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 | agpl-3.0 | 38972caf66d8aa3d3b974fbdced8bc640f48380e | 0 | NicolasEYSSERIC/Silverpeas-Core,stephaneperry/Silverpeas-Core,SilverYoCha/Silverpeas-Core,CecileBONIN/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverYoCha/Silverpeas-Core,mmoqui/Silverpeas-Core,auroreallibe/Silverpeas-Core,mmoqui/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,SilverDav/Silverpeas-Core,ebonnet/Silverpeas-Core,Silverpeas/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,ebonnet/Silverpeas-Core,auroreallibe/Silverpeas-Core,CecileBONIN/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,stephaneperry/Silverpeas-Core,SilverDav/Silverpeas-Core,Silverpeas/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,stephaneperry/Silverpeas-Core,SilverYoCha/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,CecileBONIN/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,ebonnet/Silverpeas-Core,stephaneperry/Silverpeas-Core,auroreallibe/Silverpeas-Core,CecileBONIN/Silverpeas-Core,CecileBONIN/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverDav/Silverpeas-Core,ebonnet/Silverpeas-Core,mmoqui/Silverpeas-Core,Silverpeas/Silverpeas-Core | /**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* 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/>.
*/
package com.silverpeas.jobDomainPeas.control;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.fileupload.FileItem;
import com.silverpeas.jobDomainPeas.DomainNavigationStock;
import com.silverpeas.jobDomainPeas.GroupNavigationStock;
import com.silverpeas.jobDomainPeas.JobDomainPeasDAO;
import com.silverpeas.jobDomainPeas.JobDomainPeasException;
import com.silverpeas.jobDomainPeas.JobDomainPeasTrappedException;
import com.silverpeas.jobDomainPeas.JobDomainSettings;
import com.silverpeas.jobDomainPeas.SynchroUserWebServiceItf;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.csv.CSVReader;
import com.silverpeas.util.csv.Variant;
import com.silverpeas.util.security.X509Factory;
import com.stratelia.silverpeas.authentication.Authentication;
import com.stratelia.silverpeas.peasCore.AbstractComponentSessionController;
import com.stratelia.silverpeas.peasCore.ComponentContext;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.selection.Selection;
import com.stratelia.silverpeas.selection.SelectionException;
import com.stratelia.silverpeas.selection.SelectionUsersGroups;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.silverpeas.util.PairObject;
import com.stratelia.silverpeas.util.SilverpeasSettings;
import com.stratelia.webactiv.beans.admin.AbstractDomainDriver;
import com.stratelia.webactiv.beans.admin.AdminController;
import com.stratelia.webactiv.beans.admin.Domain;
import com.stratelia.webactiv.beans.admin.DomainProperty;
import com.stratelia.webactiv.beans.admin.Group;
import com.stratelia.webactiv.beans.admin.GroupProfileInst;
import com.stratelia.webactiv.beans.admin.SynchroReport;
import com.stratelia.webactiv.beans.admin.UserDetail;
import com.stratelia.webactiv.beans.admin.UserFull;
import com.stratelia.webactiv.util.GeneralPropertiesManager;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.exception.SilverpeasException;
import com.stratelia.webactiv.util.exception.UtilException;
import com.stratelia.webactiv.util.exception.UtilTrappedException;
/**
* Class declaration
* @author
*/
public class JobDomainPeasSessionController extends AbstractComponentSessionController {
String m_TargetUserId = null;
String m_TargetDomainId = "";
DomainNavigationStock m_TargetDomain = null;
Vector<GroupNavigationStock> m_GroupsPath = new Vector<GroupNavigationStock>();
SynchroThread m_theThread = null;
Exception m_ErrorOccured = null;
String m_SynchroReport = "";
Selection sel = null;
List<UserDetail> usersToImport = null;
Hashtable<String, String> queryToImport = null;
AdminController m_AdminCtrl = null;
private ArrayList<String> listSelectedUsers = new ArrayList<String>();
// pagination de la liste des résultats
private int indexOfFirstItemToDisplay = 0;
boolean refreshDomain = true;
/**
* Standard Session Controller Constructeur
* @param mainSessionCtrl The user's profile
* @param componentContext The component's profile
* @see
*/
public JobDomainPeasSessionController(MainSessionController mainSessionCtrl,
ComponentContext componentContext) {
super(mainSessionCtrl, componentContext,
"com.silverpeas.jobDomainPeas.multilang.jobDomainPeasBundle",
"com.silverpeas.jobDomainPeas.settings.jobDomainPeasIcons",
"com.silverpeas.jobDomainPeas.settings.jobDomainPeasSettings");
setComponentRootName(URLManager.CMP_JOBDOMAINPEAS);
m_AdminCtrl = new AdminController(getUserId());
sel = getSelection();
}
public int getMinLengthLogin() {
return JobDomainSettings.m_MinLengthLogin;
}
public int getMinLengthPwd() {
return JobDomainSettings.m_MinLengthPwd;
}
public boolean isBlanksAllowedInPwd() {
return JobDomainSettings.m_BlanksAllowedInPwd;
}
public boolean isUserAddingAllowedForGroupManager() {
return JobDomainSettings.m_UserAddingAllowedForGroupManagers;
}
public boolean isAccessGranted() {
boolean accessGranted = false;
if (getUserManageableGroupIds().size() > 0) {
return true;
}
if (getUserDetail().isAccessAdmin()
|| getUserDetail().isAccessDomainManager()) {
return true;
}
return accessGranted;
}
public void setRefreshDomain(boolean refreshDomain) {
this.refreshDomain = refreshDomain;
}
/*
* USER functions
*/
public void setTargetUser(String userId) {
m_TargetUserId = userId;
}
public UserDetail getTargetUserDetail() throws JobDomainPeasException {
UserDetail valret = null;
if ((m_TargetUserId != null) && (m_TargetUserId.length() > 0)) {
valret = getOrganizationController().getUserDetail(m_TargetUserId);
if (valret == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getTargetUserDetail()",
SilverpeasException.ERROR, "jobDomainPeas.EX_USER_NOT_AVAILABLE",
"UserId=" + m_TargetUserId);
}
}
return valret;
}
public UserFull getTargetUserFull() throws JobDomainPeasException {
UserFull valret = null;
if ((m_TargetUserId != null) && (m_TargetUserId.length() > 0)) {
valret = getOrganizationController().getUserFull(m_TargetUserId);
if (valret == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getTargetUserFull()",
SilverpeasException.ERROR, "jobDomainPeas.EX_USER_NOT_AVAILABLE",
"UserId=" + m_TargetUserId);
}
}
return valret;
}
public String createUser(String userLogin, String userLastName,
String userFirstName, String userEMail, String userAccessLevel,
boolean userPasswordValid, String userPassword, HashMap<String, String> properties,
String groupId)
throws JobDomainPeasException, JobDomainPeasTrappedException {
UserDetail theNewUser = new UserDetail();
String idRet = null;
String existingUser;
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createUser()",
"root.MSG_GEN_ENTER_METHOD", "userLogin=" + userLogin
+ " userLastName=" + userLastName + " userFirstName="
+ userFirstName + " userEMail=" + userEMail + " userAccessLevel="
+ userAccessLevel);
existingUser = m_AdminCtrl.getUserIdByLoginAndDomain(userLogin,
m_TargetDomainId);
if ((existingUser != null) && (existingUser.length() > 0)) {
JobDomainPeasTrappedException te = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_LOGIN_ALREADY_USED");
te.setGoBackPage("displayUserCreate");
throw te;
}
theNewUser.setId("-1");
if ((m_TargetDomainId != null) && (m_TargetDomainId.equals("-1") == false)
&& (m_TargetDomainId.length() > 0)) {
theNewUser.setDomainId(m_TargetDomainId);
}
theNewUser.setLogin(userLogin);
theNewUser.setLastName(userLastName);
theNewUser.setFirstName(userFirstName);
theNewUser.seteMail(userEMail);
theNewUser.setAccessLevel(userAccessLevel);
idRet = m_AdminCtrl.addUser(theNewUser);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_ADD_USER");
}
refresh();
setTargetUser(idRet);
// Update UserFull informations
UserFull uf = getTargetUserFull();
if (uf != null) {
if (uf.isPasswordAvailable()) {
uf.setPasswordValid(userPasswordValid);
uf.setPassword(userPassword);
}
// process extra properties
Set<String> keys = properties.keySet();
Iterator<String> iKeys = keys.iterator();
String key = null;
String value = null;
while (iKeys.hasNext()) {
key = iKeys.next();
value = properties.get(key);
uf.setValue(key, value);
}
idRet = m_AdminCtrl.updateUserFull(uf);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER");
}
}
// regroupement de l'utilisateur dans un groupe
regroupInGroup(properties, null);
// If group is provided, add newly created user to it
if (StringUtil.isDefined(groupId)) {
m_AdminCtrl.addUserInGroup(idRet, groupId);
}
return idRet;
}
/**
* Regroupement éventuel de l'utilisateur dans un groupe (pour les domaines SQL)
* @throws JobDomainPeasException
*/
private void regroupInGroup(HashMap<String, String> properties, String lastGroupId)
throws JobDomainPeasException {
// Traitement du domaine SQL
if (!"-1".equals(getTargetDomain().getId())
&& !"0".equals(getTargetDomain().getId())
&& getTargetDomain().getDriverClassName().equals(
"com.stratelia.silverpeas.domains.sqldriver.SQLDriver")) {
ResourceLocator specificRs = new ResourceLocator(getTargetDomain().getPropFileName(), "");
int numPropertyRegroup = SilverpeasSettings.readInt(specificRs,
"property.Grouping", -1);
String nomRegroup = null;
String theUserIdToRegroup = m_TargetUserId;
String[] newUserIds;
List<String> lUserIds;
List<String> lNewUserIds;
if (numPropertyRegroup > -1) {
String nomPropertyRegroupement = SilverpeasSettings.readString(
specificRs, "property_" + numPropertyRegroup + ".Name", null);
if (nomPropertyRegroupement != null) {
// Suppression de l'appartenance de l'utilisateur au groupe auquel il
// appartenait
if (lastGroupId != null) {
Group lastGroup = m_AdminCtrl.getGroupById(lastGroupId);
lUserIds = Arrays.asList(lastGroup.getUserIds());
lNewUserIds = new ArrayList<String>(lUserIds);
lNewUserIds.remove(theUserIdToRegroup);
newUserIds = lNewUserIds.toArray(new String[lNewUserIds.size()]);
updateGroupSubUsers(lastGroupId, newUserIds);
}
// Recherche du nom du regroupement (nom du groupe)
Set<String> keys = properties.keySet();
Iterator<String> iKeys = keys.iterator();
String key = null;
String value = null;
boolean trouve = false;
while (iKeys.hasNext()) {
key = iKeys.next();
value = properties.get(key);
if (key.equals(nomPropertyRegroupement)) {
trouve = true;
break;
}
}
if (trouve) {
nomRegroup = value;
}
}
}
if (nomRegroup != null && nomRegroup.length() > 0) {
// Recherche le groupe dans le domaine
Group group = m_AdminCtrl.getGroupByNameInDomain(nomRegroup,
m_TargetDomainId);
if (group == null) {
// le groupe n'existe pas, on le crée
group = new Group();
group.setId("-1");
group.setDomainId(m_TargetDomainId);
group.setSuperGroupId(null); // groupe à la racine
group.setName(nomRegroup);
group.setDescription("");
String groupId = m_AdminCtrl.addGroup(group);
group = m_AdminCtrl.getGroupById(groupId);
}
lUserIds = Arrays.asList(group.getUserIds());
lNewUserIds = new ArrayList<String>(lUserIds);
lNewUserIds.add(theUserIdToRegroup);
newUserIds = lNewUserIds.toArray(new String[lNewUserIds.size()]);
// Ajout de l'appartenance de l'utilisateur au groupe
updateGroupSubUsers(group.getId(), newUserIds);
}
}
}
/**
* Parse the CSV file.
* @param filePart
* @throws UtilTrappedException
* @throws JobDomainPeasTrappedException
* @throws JobDomainPeasException
*/
public void importCsvUsers(FileItem filePart) throws UtilTrappedException,
JobDomainPeasTrappedException, JobDomainPeasException {
InputStream is;
try {
is = filePart.getInputStream();
} catch (IOException e) {
JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.importCsvUsers",
SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", e);
jdpe.setGoBackPage("displayUsersCsvImport");
throw jdpe;
}
CSVReader csvReader = new CSVReader(getLanguage());
csvReader.initCSVFormat(
"com.silverpeas.jobDomainPeas.settings.usersCSVFormat", "User", ";",
getTargetDomain().getPropFileName(), "property_");
// spécifique domaine Silverpeas (2 colonnes en moins (password et
// passwordValid)
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
csvReader.setM_specificNbCols(csvReader.getM_specificNbCols() - 2);
}
Variant[][] csvValues;
try {
csvValues = csvReader.parseStream(is);
} catch (UtilTrappedException ute) {
ute.setGoBackPage("displayUsersCsvImport");
throw ute;
}
StringBuilder listErrors = new StringBuilder("");
String nom;
String prenom;
String login;
String existingLogin;
String email;
String droits;
String userAccessLevel;
String motDePasse;
String title;
String company;
String position;
String boss;
String phone;
String homePhone;
String fax;
String cellularPhone;
String address;
String informationSpecifiqueString;
boolean informationSpecifiqueBoolean;
for (int i = 0; i < csvValues.length; i++) {
// Nom
nom = csvValues[i][0].getValueString();
if (nom.length() == 0) {// champ obligatoire
listErrors.append(getErrorMessage(i+1, 1, nom));
listErrors.append(getString("JDP.obligatoire")).append("<br/>");
} else if (nom.length() > 100) {// verifier 100 char max
listErrors.append(getErrorMessage(i+1, 1, nom));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").
append(getString("JDP.caracteres")).append("<br/>");
}
// Prenom
prenom = csvValues[i][1].getValueString(); // verifier 100 char max
if (prenom.length() > 100) {
listErrors.append(getErrorMessage(i+1, 2, prenom));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 "
+ getString("JDP.caracteres")).append("<br/>");
}
// Login
login = csvValues[i][2].getValueString();
if (login.length() == 0) {// champ obligatoire
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.obligatoire")).append("<br/>");
} else if (login.length() < JobDomainSettings.m_MinLengthLogin) {// verifier
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.nbCarMin")).append(" ").append(
JobDomainSettings.m_MinLengthLogin).append(" ").append(getString("JDP.caracteres")).
append("<br/>");
} else if (login.length() > 50) {// verifier 20 char max
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.nbCarMax")).append(" 50 ").append(getString(
"JDP.caracteres")).append("<br/>");
} else {// verif login unique
existingLogin = m_AdminCtrl.getUserIdByLoginAndDomain(login,
m_TargetDomainId);
if (existingLogin != null) {
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.existingLogin")).append("<br/>");
}
}
// Email
email = csvValues[i][3].getValueString(); // verifier 100 char max
if (email.length() > 100) {
listErrors.append(getErrorMessage(i+1, 4, email));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// Droits
droits = csvValues[i][4].getValueString();
if (!"".equals(droits) && !"Admin".equals(droits)
&& !"AdminPdc".equals(droits) && !"AdminDomain".equals(droits)
&& !"User".equals(droits) && !"Guest".equals(droits)) {
listErrors.append(getErrorMessage(i+1, 5, droits));
listErrors.append(getString("JDP.valeursPossibles")).append("<br/>");
}
// MotDePasse
motDePasse = csvValues[i][5].getValueString();
// password is not mandatory
if (StringUtil.isDefined(motDePasse)) {
if (!JobDomainSettings.m_BlanksAllowedInPwd
&& motDePasse.indexOf(" ") != -1) {
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.espaces")).append("<br/>");
} else if (motDePasse.length() < JobDomainSettings.m_MinLengthPwd) {// verifier
// jobDomainPeasSettings.getString("minLengthPwd")
// char
// min
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.nbCarMin")).append(" ").append(
JobDomainSettings.m_MinLengthPwd).append(" ").append(getString("JDP.caracteres")).append(
"<br/>");
} else if (motDePasse.length() > 32) {// verifier 32 char max
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.nbCarMax")).append(" 32 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
}
if (csvReader.getM_specificNbCols() > 0) {
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
// title
title = csvValues[i][6].getValueString(); // verifier 100 char max
if (title.length() > 100) {
listErrors.append(getErrorMessage(i+1, 7, title));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// company
company = csvValues[i][7].getValueString(); // verifier 100 char max
if (company.length() > 100) {
listErrors.append(getErrorMessage(i+1, 8, company));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// position
position = csvValues[i][8].getValueString(); // verifier 100 char max
if (position.length() > 100) {
listErrors.append(getErrorMessage(i+1, 9, position));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// boss
boss = csvValues[i][9].getValueString(); // verifier 100 char max
if (boss.length() > 100) {
listErrors.append(getErrorMessage(i+1, 10, boss));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// phone
phone = csvValues[i][10].getValueString(); // verifier 20 char max
if (phone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 11, phone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// homePhone
homePhone = csvValues[i][11].getValueString(); // verifier 20 char max
if (homePhone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 12, homePhone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// fax
fax = csvValues[i][12].getValueString(); // verifier 20 char max
if (fax.length() > 20) {
listErrors.append(getErrorMessage(i+1, 13, fax));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// cellularPhone
cellularPhone = csvValues[i][13].getValueString(); // verifier 20 char
// max
if (cellularPhone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 14, cellularPhone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// address
address = csvValues[i][14].getValueString(); // verifier 500 char max
if (address.length() > 500) {
listErrors.append(getErrorMessage(i+1, 15, address));
listErrors.append(getString("JDP.nbCarMax")).append(" 500 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
} else {// domaine SQL
// informations spécifiques
for (int j = 0; j < csvReader.getM_specificNbCols(); j++) {
if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueString = csvValues[i][j + 6].getValueString(); // verifier 50 char max
if (informationSpecifiqueString.length() > 50) {
listErrors.append(getErrorMessage(i+1, j + 6, informationSpecifiqueString));
listErrors.append(getString("JDP.nbCarMax")).append(" 50 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
}
}
}
}
}
if (listErrors.length() > 0) {
JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.importCsvUsers",
SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", listErrors.toString());
jdpe.setGoBackPage("displayUsersCsvImport");
throw jdpe;
}
// pas d'erreur, on importe les utilisateurs
HashMap<String, String> properties;
for (int i = 0; i < csvValues.length; i++) {
// Nom
nom = csvValues[i][0].getValueString();
// Prenom
prenom = csvValues[i][1].getValueString();
// Login
login = csvValues[i][2].getValueString();
// Email
email = csvValues[i][3].getValueString();
// Droits
droits = csvValues[i][4].getValueString();
if ("Admin".equals(droits)) {
userAccessLevel = "A";
} else if ("AdminPdc".equals(droits)) {
userAccessLevel = "K";
} else if ("AdminDomain".equals(droits)) {
userAccessLevel = "D";
} else if ("User".equals(droits)) {
userAccessLevel = "U";
} else if ("Guest".equals(droits)) {
userAccessLevel = "G";
} else {
userAccessLevel = "U";
}
// MotDePasse
motDePasse = csvValues[i][5].getValueString();
// données spécifiques
properties = new HashMap<String, String>();
if (csvReader.getM_specificNbCols() > 0) {
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
// title
title = csvValues[i][6].getValueString();
properties.put(csvReader.getM_specificParameterName(0), title);
// company
company = csvValues[i][7].getValueString();
properties.put(csvReader.getM_specificParameterName(1), company);
// position
position = csvValues[i][8].getValueString();
properties.put(csvReader.getM_specificParameterName(2), position);
// boss
boss = csvValues[i][9].getValueString();
properties.put(csvReader.getM_specificParameterName(3), boss);
// phone
phone = csvValues[i][10].getValueString();
properties.put(csvReader.getM_specificParameterName(4), phone);
// homePhone
homePhone = csvValues[i][11].getValueString();
properties.put(csvReader.getM_specificParameterName(5), homePhone);
// fax
fax = csvValues[i][12].getValueString();
properties.put(csvReader.getM_specificParameterName(6), fax);
// cellularPhone
cellularPhone = csvValues[i][13].getValueString();
properties.put(csvReader.getM_specificParameterName(7), cellularPhone);
// address
address = csvValues[i][14].getValueString();
properties.put(csvReader.getM_specificParameterName(8), address);
} else {// domaine SQL
// informations spécifiques
for (int j = 0; j < csvReader.getM_specificNbCols(); j++) {
if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueString = csvValues[i][j + 6].getValueString();
properties.put(csvReader.getM_specificParameterName(j),
informationSpecifiqueString);
} else if (Variant.TYPE_BOOLEAN.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueBoolean = csvValues[i][j + 6].getValueBoolean();
if (informationSpecifiqueBoolean) {
properties.put(csvReader.getM_specificParameterName(j), "1");
} else {
properties.put(csvReader.getM_specificParameterName(j), "0");
}
}
}
}
}
boolean passwordValid = StringUtil.isDefined(motDePasse); // password is not mandatory
createUser(login, nom, prenom, email, userAccessLevel, passwordValid, motDePasse,
properties, null); // l'id User créé est dans m_TargetUserId
}
}
private String getErrorMessage(int line, int column, String value) {
StringBuilder str = new StringBuilder();
str.append(getString("JDP.ligne")).append(" = ").append(line).append(", ");
str.append(getString("JDP.colonne")).append(" = ").append(column).append(", ");
str.append(getString("JDP.valeur")).append(" = ").append(value).append(", ");
return str.toString();
}
private String getLastGroupId(UserFull theUser) {
// Traitement du domaine SQL
if (!"-1".equals(getTargetDomain().getId())
&& !"0".equals(getTargetDomain().getId())
&& getTargetDomain().getDriverClassName().equals(
"com.stratelia.silverpeas.domains.sqldriver.SQLDriver")) {
ResourceLocator specificRs = new ResourceLocator(getTargetDomain().getPropFileName(), "");
int numPropertyRegroup = SilverpeasSettings.readInt(specificRs,
"property.Grouping", -1);
String nomLastGroup = null;
if (numPropertyRegroup > -1) {
String nomPropertyRegroupement = SilverpeasSettings.readString(
specificRs, "property_" + numPropertyRegroup + ".Name", null);
if (nomPropertyRegroupement != null) {
// Recherche du nom du regroupement (nom du groupe)
String[] keys = theUser.getPropertiesNames();
String key = null;
String value = null;
boolean trouve = false;
for (int i = 0; i < keys.length; i++) {
key = keys[i];
value = theUser.getValue(key);
if (key.equals(nomPropertyRegroupement)) {
trouve = true;
break;
}
}
if (trouve) {
nomLastGroup = value;
}
}
}
if (nomLastGroup != null && nomLastGroup.length() > 0) {
// Recherche le groupe dans le domaine
Group group = m_AdminCtrl.getGroupByNameInDomain(nomLastGroup,
m_TargetDomainId);
if (group != null) {
return group.getId();
}
}
}
return null;
}
public void modifyUser(String idUser, String userLastName,
String userFirstName, String userEMail, String userAccessLevel,
boolean userPasswordValid, String userPassword, HashMap<String, String> properties)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser + " userLastName="
+ userLastName + " userFirstName=" + userFirstName + " userEMail="
+ userEMail + " userAccessLevel=" + userAccessLevel);
UserFull theModifiedUser = m_AdminCtrl.getUserFull(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
// nom du groupe auquel était rattaché l'utilisateur
String lastGroupId = getLastGroupId(theModifiedUser);
theModifiedUser.setLastName(userLastName);
theModifiedUser.setFirstName(userFirstName);
theModifiedUser.seteMail(userEMail);
theModifiedUser.setAccessLevel(userAccessLevel);
if (theModifiedUser.isPasswordAvailable()) {
theModifiedUser.setPasswordValid(userPasswordValid);
theModifiedUser.setPassword(userPassword);
}
// process extra properties
Set<String> keys = properties.keySet();
for (String key : keys) {
String value = properties.get(key);
theModifiedUser.setValue(key, value);
}
String idRet = m_AdminCtrl.updateUserFull(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
// regroupement de l'utilisateur dans un groupe
regroupInGroup(properties, lastGroupId);
}
public void modifySynchronizedUser(String idUser, String userAccessLevel)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifySynchronizedUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
UserDetail theModifiedUser = m_AdminCtrl.getUserDetail(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySynchronizedUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
theModifiedUser.setAccessLevel(userAccessLevel);
String idRet = m_AdminCtrl.updateSynchronizedUser(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySynchronizedUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
}
public void modifyUserFull(String idUser, String userAccessLevel,
HashMap<String, String> properties)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyUserFull()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser + " userAccessLevel=" + userAccessLevel);
UserFull theModifiedUser = m_AdminCtrl.getUserFull(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUserFull()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
theModifiedUser.setAccessLevel(userAccessLevel);
// process extra properties
Set<String> keys = properties.keySet();
for (String key : keys) {
String value = properties.get(key);
theModifiedUser.setValue(key, value);
}
String idRet = m_AdminCtrl.updateUserFull(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUserFull()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
}
public void deleteUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.deleteUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
UserDetail user = getUserDetail(idUser);
boolean deleteUser = true;
// TODO : Manage deleting case for group manager
if (!"A".equals(getUserAccessLevel()) && !"D".equals(getUserAccessLevel()) && isGroupManager()) {
List<String> directGroupIds =
Arrays.asList(getOrganizationController().getDirectGroupIdsOfUser(idUser));
List<String> manageableGroupIds = getUserManageableGroupIds();
String directGroupId = null;
String rootGroupId = null;
List<String> groupIdLinksToRemove = new ArrayList<String>();
for (int g = 0; g < directGroupIds.size(); g++) {
directGroupId = directGroupIds.get(g);
// get root group of each directGroup
List<String> groupPath = m_AdminCtrl.getPathToGroup(directGroupId);
if (groupPath != null && groupPath.size() > 0) {
rootGroupId = groupPath.get(0);
} else {
rootGroupId = directGroupId;
}
// if root group is not one of manageable group, avoid deletion
// user belongs to another community
if (!manageableGroupIds.contains(rootGroupId)) {
deleteUser = false;
} else {
groupIdLinksToRemove.add(directGroupId);
}
}
if (!deleteUser) {
// removes only links between user and manageable groups
for (Iterator<String> iterator = groupIdLinksToRemove.iterator(); iterator.hasNext();) {
String groupIdLinkToRemove = iterator.next();
m_AdminCtrl.removeUserFromGroup(idUser, groupIdLinkToRemove);
}
refresh();
}
}
if (deleteUser) {
idRet = m_AdminCtrl.deleteUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.deleteUser()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_USER", "UserId="
+ idUser);
}
if (m_TargetUserId.equals(idUser)) {
m_TargetUserId = null;
}
if ((getDomainActions() & AbstractDomainDriver.ACTION_X509_USER) != 0) {
// revocate user's certificate
revocateCertificate(user);
}
refresh();
}
}
public Iterator<DomainProperty> getPropertiesToImport() throws JobDomainPeasException {
return m_AdminCtrl.getSpecificPropertiesToImportUsers(m_TargetDomainId,
getLanguage()).iterator();
}
public void importUser(String userLogin) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.importUser()",
"root.MSG_GEN_ENTER_METHOD", "userLogin=" + userLogin);
idRet = m_AdminCtrl.synchronizeImportUser(m_TargetDomainId, userLogin);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.importUser()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_USER",
"userLogin=" + userLogin);
}
refresh();
setTargetUser(idRet);
}
public void importUsers(String[] specificIds) throws JobDomainPeasException {
for (int i = 0; specificIds != null && i < specificIds.length; i++) {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.importUsers()",
"root.MSG_GEN_ENTER_METHOD", "specificId=" + specificIds[i]);
m_AdminCtrl.synchronizeImportUser(m_TargetDomainId, specificIds[i]);
}
refresh();
}
public List<UserDetail> searchUsers(Hashtable<String, String> query) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.searchUsers()",
"root.MSG_GEN_ENTER_METHOD", "query=" + query.toString());
queryToImport = query;
usersToImport = m_AdminCtrl.searchUsers(m_TargetDomainId, query);
return usersToImport;
}
public List<UserDetail> getUsersToImport() {
return usersToImport;
}
public Hashtable<String, String> getQueryToImport() {
return queryToImport;
}
public UserFull getUser(String specificId) {
return m_AdminCtrl.getUserFull(m_TargetDomainId, specificId);
}
public void synchroUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.synchroUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
idRet = m_AdminCtrl.synchronizeUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.synchroUser()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_USER");
}
refresh();
setTargetUser(idRet);
}
public void unsynchroUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.unsynchroUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
idRet = m_AdminCtrl.synchronizeRemoveUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.unsynchroUser()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_USER");
}
if (m_TargetUserId.equals(idUser)) {
m_TargetUserId = null;
}
refresh();
}
/*
* GROUP functions
*/
public void returnIntoGroup(String groupId) throws JobDomainPeasException {
int i = 0;
if (!StringUtil.isDefined(groupId)) {
m_GroupsPath.clear();
} else {
i = m_GroupsPath.size() - 1;
while ((i >= 0)
&& (m_GroupsPath.get(i).isThisGroup(groupId) == false)) {
m_GroupsPath.removeElementAt(i);
i--;
}
}
setTargetUser(null);
}
public void removeGroupFromPath(String groupId) throws JobDomainPeasException {
int i = 0;
if (StringUtil.isDefined(groupId)) {
i = 0;
while ((i < m_GroupsPath.size())
&& (m_GroupsPath.get(i).isThisGroup(groupId) == false)) {
i++;
}
if (i < m_GroupsPath.size()) {
m_GroupsPath.setSize(i); // Tunc the vector
}
}
}
public void goIntoGroup(String groupId) throws JobDomainPeasException {
if (StringUtil.isDefined(groupId)) {
if (getTargetGroup() == null
|| (getTargetGroup() != null && !getTargetGroup().getId().equals(
groupId))) {
Group targetGroup = m_AdminCtrl.getGroupById(groupId);
if (GroupNavigationStock.isGroupValid(targetGroup)) {
List<String> manageableGroupIds = null;
if (isOnlyGroupManager() && !isGroupManagerOnGroup(groupId)) {
manageableGroupIds = getUserManageableGroupIds();
}
GroupNavigationStock newSubGroup = new GroupNavigationStock(groupId,
m_AdminCtrl, manageableGroupIds);
m_GroupsPath.add(newSubGroup);
}
}
} else {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.setTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE",
"GroupId=" + groupId);
}
setTargetUser(null);
}
public Group getTargetGroup() throws JobDomainPeasException {
if (m_GroupsPath.size() <= 0) {
return null;
}
return m_GroupsPath.lastElement().getThisGroup();
}
/**
* @return a List with 2 elements. First one, a List of UserDetail. Last one, a List of Group.
* @throws JobDomainPeasException
*/
public List<List> getGroupManagers() throws JobDomainPeasException {
List<List> usersAndGroups = new ArrayList<List>();
List<UserDetail> users = new ArrayList<UserDetail>();
List<Group> groups = new ArrayList<Group>();
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
if (profile != null) {
List<String> groupIds = profile.getAllGroups();
Group group = null;
for (int nI = 0; nI < groupIds.size(); nI++) {
group = m_AdminCtrl.getGroupById(groupIds.get(nI));
groups.add(group);
}
List<String> userIds = profile.getAllUsers();
UserDetail user = null;
for (int nI = 0; nI < userIds.size(); nI++) {
user = getUserDetail(userIds.get(nI));
users.add(user);
}
}
usersAndGroups.add(users);
usersAndGroups.add(groups);
return usersAndGroups;
}
// user panel de selection de n groupes et n users
public void initUserPanelForGroupManagers(String compoURL) throws SelectionException,
JobDomainPeasException {
sel.resetAll();
sel.setHostSpaceName(getMultilang().getString("JDP.jobDomain"));
sel.setHostComponentName(new PairObject(getTargetGroup().getName(), null));
ResourceLocator generalMessage = GeneralPropertiesManager.getGeneralMultilang(getLanguage());
PairObject[] hostPath = {new PairObject(getMultilang().getString("JDP.roleManager")
+ " > " + generalMessage.getString("GML.selection"), null)};
sel.setHostPath(hostPath);
sel.setGoBackURL(compoURL + "groupManagersUpdate");
sel.setCancelURL(compoURL + "groupManagersCancel");
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
List<String> allUsers = profile.getAllUsers();
List<String> allGroups = profile.getAllGroups();
sel.setSelectedElements(allUsers.toArray(new String[allUsers.size()]));
sel.setSelectedSets(allGroups.toArray(new String[allGroups.size()]));
}
public void updateGroupProfile() throws JobDomainPeasException {
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
profile.removeAllGroups();
profile.removeAllUsers();
setGroupsAndUsers(profile, sel.getSelectedSets(), sel.getSelectedElements());
m_AdminCtrl.updateGroupProfile(profile);
}
public void deleteGroupProfile() throws JobDomainPeasException {
m_AdminCtrl.deleteGroupProfile(getTargetGroup().getId());
}
private void setGroupsAndUsers(GroupProfileInst profile, String[] groupIds,
String[] userIds) {
// groups
for (int i = 0; groupIds != null && i < groupIds.length; i++) {
if (groupIds[i] != null && groupIds[i].length() > 0) {
profile.addGroup(groupIds[i]);
}
}
// users
for (int i = 0; userIds != null && i < userIds.length; i++) {
if (userIds[i] != null && userIds[i].length() > 0) {
profile.addUser(userIds[i]);
}
}
}
public boolean isGroupRoot(String groupId) throws JobDomainPeasException {
Group gr = m_AdminCtrl.getGroupById(groupId);
if (GroupNavigationStock.isGroupValid(gr)) {
if (this.refreshDomain && (!StringUtil.isDefined(gr.getSuperGroupId()) || "-1".equals(gr.getSuperGroupId()))) {
return true;
}
return false;
}
return false;
}
public Group[] getSubGroups(boolean isParentGroup)
throws JobDomainPeasException {
Group[] groups = null;
if (isParentGroup) {
if (m_GroupsPath.size() <= 0) {
throw new JobDomainPeasException("JobDomainPeasSessionController.getTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE");
}
groups = m_GroupsPath.lastElement().getGroupPage();
} else { // Domain case
groups = m_TargetDomain.getGroupPage();
}
if (isOnlyGroupManager() && !isGroupManagerOnCurrentGroup()) {
groups = filterGroupsToGroupManager(groups);
}
for (int i = 0; i < groups.length; i++) {
if (groups[i] != null) {
groups[i].setNbUsers(getOrganizationController().getAllSubUsersNumber(
groups[i].getId()));
}
}
return groups;
}
public String[][] getSubUsers(boolean isParentGroup)
throws JobDomainPeasException {
UserDetail[] usDetails = null;
String[][] valret = null;
int i = 0;
if (isParentGroup) {
if (m_GroupsPath.size() <= 0) {
throw new JobDomainPeasException("JobDomainPeasSessionController.getTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE");
}
usDetails = m_GroupsPath.lastElement().getUserPage();
} else { // Domain case
usDetails = m_TargetDomain.getUserPage();
}
valret = new String[usDetails.length][4];
for (i = 0; i < usDetails.length; i++) {
if (usDetails[i] != null) {
valret[i][0] = getSureString(usDetails[i].getId());
valret[i][1] = EncodeHelper.javaStringToHtmlString(getSureString(usDetails[i].getLastName()));
valret[i][2] = EncodeHelper.javaStringToHtmlString(
getSureString(usDetails[i].getFirstName()));
valret[i][3] = EncodeHelper.javaStringToHtmlString(getSureString(usDetails[i].getLogin()));
} else {
valret[i][0] = "";
valret[i][1] = "";
valret[i][2] = "";
valret[i][3] = "";
}
}
return valret;
}
public String getPath(String baseURL, String toAppendAtEnd)
throws JobDomainPeasException {
StringBuilder strPath = new StringBuilder("");
Group theGroup = null;
int i;
for (i = 0; i < m_GroupsPath.size(); i++) {
theGroup = m_GroupsPath.get(i).getThisGroup();
if (strPath.length() > 0) {
strPath.append(" > ");
}
if (((i + 1) < m_GroupsPath.size()) || (m_TargetUserId != null)
|| (toAppendAtEnd != null)) {
strPath.append("<a href=\"").append(baseURL).append("groupReturn?Idgroup=").
append(theGroup.getId()).append("\">").
append(EncodeHelper.javaStringToHtmlString(theGroup.getName())).append("</a>");
} else {
strPath.append(EncodeHelper.javaStringToHtmlString(theGroup.getName()));
}
}
if (m_TargetUserId != null) {
if (strPath.length() > 0) {
strPath.append(" > ");
}
if (toAppendAtEnd != null) {
strPath.append("<a href=\"").append(baseURL).append("userContent?Iduser=").
append(m_TargetUserId).append("\">").
append(EncodeHelper.javaStringToHtmlString(getTargetUserDetail().getDisplayedName())).
append("</a>");
} else {
strPath.append(EncodeHelper.javaStringToHtmlString(getTargetUserDetail().getDisplayedName()));
}
}
if (toAppendAtEnd != null) {
if (strPath.length() > 0) {
strPath.append(" > ");
}
strPath.append(EncodeHelper.javaStringToHtmlString(toAppendAtEnd));
}
return strPath.toString();
}
public boolean createGroup(String idParent, String groupName,
String groupDescription, String groupRule) throws JobDomainPeasException {
Group theNewGroup = new Group();
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createGroup()",
"root.MSG_GEN_ENTER_METHOD", "ParentId=" + idParent + " Name="
+ groupName + " Desc=" + groupDescription);
theNewGroup.setId("-1");
if (StringUtil.isDefined(m_TargetDomainId)
&& !"-1".equals(m_TargetDomainId)) {
theNewGroup.setDomainId(m_TargetDomainId);
}
theNewGroup.setSuperGroupId(idParent);
theNewGroup.setName(groupName);
theNewGroup.setDescription(groupDescription);
theNewGroup.setRule(groupRule);
String idRet = m_AdminCtrl.addGroup(theNewGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.createGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_ADD_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean modifyGroup(String idGroup, String groupName,
String groupDescription, String groupRule) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.modifyGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup + " Desc=" + groupDescription);
Group theModifiedGroup = m_AdminCtrl.getGroupById(idGroup);
if (theModifiedGroup == null) {
throw new JobDomainPeasException("JobDomainPeasSessionController.modifyGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_GROUP");
}
theModifiedGroup.setName(groupName);
theModifiedGroup.setDescription(groupDescription);
theModifiedGroup.setRule(groupRule);
String idRet = m_AdminCtrl.updateGroup(theModifiedGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.modifyGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean updateGroupSubUsers(String idGroup, String[] userIds)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.updateGroupSubUsers()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
Group theModifiedGroup = m_AdminCtrl.getGroupById(idGroup);
if (theModifiedGroup == null) {
throw new JobDomainPeasException("JobDomainPeasSessionController.updateGroupSubUsers()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_GROUP");
}
theModifiedGroup.setUserIds(userIds);
String idRet = m_AdminCtrl.updateGroup(theModifiedGroup);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.updateGroupSubUsers()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_GROUP");
}
refresh();
return false;
}
public boolean deleteGroup(String idGroup) throws JobDomainPeasException {
boolean haveToRefreshDomain = isGroupRoot(idGroup);
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.deleteGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.deleteGroupById(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.deleteGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_GROUP");
}
removeGroupFromPath(idGroup);
refresh();
return haveToRefreshDomain;
}
public boolean synchroGroup(String idGroup) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.synchroGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.synchronizeGroup(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.synchroGroup()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean unsynchroGroup(String idGroup) throws JobDomainPeasException {
boolean haveToRefreshDomain = isGroupRoot(idGroup);
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.unsynchroGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.synchronizeRemoveGroup(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.unsynchroGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_GROUP");
}
removeGroupFromPath(idGroup);
refresh();
return haveToRefreshDomain;
}
public boolean importGroup(String groupName) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.importGroup()",
"root.MSG_GEN_ENTER_METHOD", "groupName=" + groupName);
String idRet = m_AdminCtrl.synchronizeImportGroup(m_TargetDomainId,
groupName);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.importGroup()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
/*
* DOMAIN functions
*/
public void setDefaultTargetDomain() {
UserDetail ud = getUserDetail();
if (ud.isDomainAdminRestricted()) {
setTargetDomain(ud.getDomainId());
}
}
public void setTargetDomain(String domainId) {
if (!StringUtil.isDefined(domainId)) {
m_TargetDomain = null;
m_TargetDomainId = "";
} else {
List<String> manageableGroupIds = null;
if (isOnlyGroupManager()) {
manageableGroupIds = getUserManageableGroupIds();
}
m_TargetDomain = new DomainNavigationStock(domainId, m_AdminCtrl, manageableGroupIds);
m_TargetDomainId = domainId;
}
}
public Domain getTargetDomain() {
if (m_TargetDomain == null) {
return null;
}
return m_TargetDomain.getThisDomain();
}
public long getDomainActions() {
if (m_TargetDomainId.length() > 0) {
return m_AdminCtrl.getDomainActions(m_TargetDomainId);
}
return 0;
}
public String[][] getAllDomains() {
String[][] valret = null;
UserDetail ud = getUserDetail();
if (ud.isAccessDomainManager()) {
Domain userDomain = m_AdminCtrl.getDomain(ud.getDomainId());
valret = new String[1][3];
valret[0][0] = ud.getDomainId();
valret[0][1] = EncodeHelper.javaStringToHtmlString(userDomain.getName());
if (m_TargetDomainId.equals(userDomain.getId())) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
} else if (ud.isAccessAdmin()) {
Domain[] allDomains = m_AdminCtrl.getAllDomains();
valret = new String[allDomains.length + 1][3];
// Domaine mixte
valret[0][0] = "-1";
valret[0][1] = getString("JDP.domainMixt");
if (m_TargetDomainId.equals("-1")) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
// Tous les domaines
for (int i = 1; i < valret.length; i++) {
valret[i][0] = allDomains[i - 1].getId();
valret[i][1] = EncodeHelper.javaStringToHtmlString(allDomains[i - 1].getName());
if (m_TargetDomainId.equals(allDomains[i - 1].getId())) {
valret[i][2] = "selected";
} else {
valret[i][2] = "";
}
}
} else if (isOnlyGroupManager()) {
// Domaine mixte
valret = new String[2][3];
valret[0][0] = "-1";
valret[0][1] = getString("JDP.domainMixt");
if (m_TargetDomainId.equals("-1")) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
// Domaine de l'utilisateur
Domain userDomain = m_AdminCtrl.getDomain(ud.getDomainId());
valret[1][0] = userDomain.getId();
valret[1][1] = EncodeHelper.javaStringToHtmlString(userDomain.getName());
if (m_TargetDomainId.equals(userDomain.getId())) {
valret[1][2] = "selected";
} else {
valret[1][2] = "";
}
}
return valret;
}
public boolean isOnlyGroupManager() {
return isGroupManager() && !getUserDetail().isAccessAdmin()
&& !getUserDetail().isAccessDomainManager();
}
public boolean isGroupManagerOnCurrentGroup() throws JobDomainPeasException {
if (getTargetGroup() != null) {
return isGroupManagerOnGroup(getTargetGroup().getId());
}
return false;
}
public boolean isGroupManagerOnGroup(String groupId)
throws JobDomainPeasException {
List<String> manageableGroupIds = getUserManageableGroupIds();
if (manageableGroupIds.contains(groupId)) {
// Current user is directly manager of group
return true;
} else {
List<String> groupPath = m_AdminCtrl.getPathToGroup(groupId);
groupPath.retainAll(manageableGroupIds);
if (groupPath.size() > 0) {
// Current user is at least manager of one super group of group
return true;
}
}
return false;
}
public boolean isGroupManagerDirectlyOnCurrentGroup()
throws JobDomainPeasException {
List<String> manageableGroupIds = getUserManageableGroupIds();
return manageableGroupIds.contains(getTargetGroup().getId());
}
public Group[] getAllRootGroups() {
if (m_TargetDomainId.length() <= 0) {
return new Group[0];
}
Group[] selGroupsArray = m_TargetDomain.getAllGroupPage();
if (isOnlyGroupManager()) {
selGroupsArray = filterGroupsToGroupManager(selGroupsArray);
}
JobDomainSettings.sortGroups(selGroupsArray);
return selGroupsArray;
}
private Group[] filterGroupsToGroupManager(Group[] groups) {
// get all manageable groups by current user
List<String> manageableGroupIds = getUserManageableGroupIds();
Iterator<String> itManageableGroupsIds = null;
List<Group> temp = new ArrayList<Group>();
// filter groups
Group group = null;
for (int g = 0; g < groups.length; g++) {
group = groups[g];
if (manageableGroupIds.contains(group.getId())) {
temp.add(group);
} else {
// get all subGroups of group
List<String> subGroupIds = Arrays.asList(m_AdminCtrl.getAllSubGroupIdsRecursively(group.
getId()));
// check if at least one manageable group is part of subGroupIds
itManageableGroupsIds = manageableGroupIds.iterator();
String manageableGroupId = null;
boolean find = false;
while (!find && itManageableGroupsIds.hasNext()) {
manageableGroupId = itManageableGroupsIds.next();
if (subGroupIds.contains(manageableGroupId)) {
find = true;
}
}
if (find) {
temp.add(group);
}
}
}
return temp.toArray(new Group[temp.size()]);
}
public String createDomain(String domainName, String domainDescription, String domainDriver,
String domainProperties, String domainAuthentication, String silverpeasServerURL,
String domainTimeStamp) throws JobDomainPeasException, JobDomainPeasTrappedException {
// Vérif domainName
verifCreateDomain(domainName, false);
Domain theNewDomain = new Domain();
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setId("-1");
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName(domainDriver);
theNewDomain.setPropFileName(domainProperties);
theNewDomain.setAuthenticationServer(domainAuthentication);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp(domainTimeStamp);
String idRet = m_AdminCtrl.addDomain(theNewDomain);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.createDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN");
}
refresh();
return idRet;
}
private void verifCreateDomain(String domainName, boolean domainSql)
throws JobDomainPeasTrappedException {
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
if (domainSql) {
trappedException.setGoBackPage("displayDomainSQLCreate");
} else {
trappedException.setGoBackPage("displayDomainCreate");
}
// 1-Vérif non présence d'espaces
int indexOfSpace = domainName.indexOf(" ");
if (indexOfSpace > -1) {
throw trappedException;
}
// 2-Vérif caractères alphanumériques
int i = 0;
char car;
while (i < domainName.length()) {
car = domainName.charAt(i);
if (!Character.isLetterOrDigit(car)) {
throw trappedException;
}
i++;
}
// 3-Vérif domainName unique dans la table ST_Domain
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
if (domainSql) {
// 4-Vérif domainName unique dans le fileSystem
// pour les properties
// com.stratelia.silverpeas.domains.domain<domainName>.properties
// et
// com.stratelia.silverpeas.authentication.autDomain<domainName>.properties
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
StringBuilder cheminFichierDomain = new StringBuilder(pathInitialize.substring(0,
indexOfInitialize));
cheminFichierDomain.append("properties").append(File.separator).append("com").append(
File.separator).append("stratelia").append(File.separator).append("silverpeas").append(
File.separator).append("domains");
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain.toString());
File fileDomain = new File(directoryDomain, nomFichierDomain);
if (fileDomain.exists()) {
throw trappedException;
}
StringBuilder cheminFichierAutDomain = new StringBuilder(pathInitialize.substring(0,
indexOfInitialize));
cheminFichierAutDomain.append("properties").append(File.separator).append("com").append(
File.separator).append("stratelia").append(File.separator).append("silverpeas").append(
File.separator).append("authentication");
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain.toString());
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
if (fileAutDomain.exists()) {
throw trappedException;
}
}
}
public String createSQLDomain(String domainName, String domainDescription,
String silverpeasServerURL) throws JobDomainPeasException, JobDomainPeasTrappedException {
// 0- Vérif domainName
verifCreateDomain(domainName, true);
// 1-Création sur le fileSystem du properties
// com.stratelia.silverpeas.domains.domain<domainName>
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création sur le fileSystem du properties com.stratelia.silverpeas.domains.domain<domainName>");
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
String cheminFichierDomain = pathInitialize.substring(0, indexOfInitialize)
+ "properties" + File.separator + "com" + File.separator + "stratelia"
+ File.separator + "silverpeas" + File.separator + "domains";
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain);
File fileDomain = new File(directoryDomain, nomFichierDomain);
PrintWriter sortie = null;
try {
sortie = new PrintWriter(new FileWriter(fileDomain));
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException("JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
// properties templateDomainSQL
ResourceLocator templateDomainSql = new ResourceLocator(
"com.stratelia.silverpeas.domains.templateDomainSQL", "");
String cryptMethod = SilverpeasSettings.readString(templateDomainSql,
"database.SQLPasswordEncryption", Authentication.ENC_TYPE_MD5);
boolean allowPasswordChange = SilverpeasSettings.readBoolean(
templateDomainSql, "allowPasswordChange", true);
BufferedReader readerTemplateDomainSQL = null;
try {
String cheminFichierTemplateDomainSQL = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator
+ "silverpeas"
+ File.separator
+ "domains" + File.separator + "templateDomainSQL.properties";
File fileTemplateDomainSQL = new File(cheminFichierTemplateDomainSQL);
readerTemplateDomainSQL = new BufferedReader(new FileReader(
fileTemplateDomainSQL));
} catch (FileNotFoundException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
String currentLine;
sortie.println("# SQL driver");
sortie.println("");
sortie.println("# DataBase Access");
sortie.println("# ----------------");
sortie.println("");
ResourceLocator propAdmin = new ResourceLocator(
"com.stratelia.webactiv.beans.admin.admin", "");
sortie.println("database.SQLClassName = "
+ propAdmin.getString("AdminDBDriver"));
sortie.println("database.SQLJDBCUrl = "
+ propAdmin.getString("WaProductionDb"));
sortie.println("database.SQLAccessLogin = "
+ propAdmin.getString("WaProductionUser"));
sortie.println("database.SQLAccessPasswd = "
+ propAdmin.getString("WaProductionPswd"));
sortie.println("");
sortie.println("database.SQLUserTableName = Domain" + domainName
+ "_User");
sortie.println("database.SQLGroupTableName = Domain" + domainName
+ "_Group");
sortie.println("database.SQLUserGroupTableName = Domain" + domainName
+ "_Group_User_Rel");
sortie.println("");
sortie.println("# Generic Properties");
sortie.println("# ----------------");
sortie.println("");
sortie.println("# For Users");
sortie.println("database.SQLUserSpecificIdColumnName = id");
sortie.println("database.SQLUserLoginColumnName = login");
sortie.println("database.SQLUserFirstNameColumnName = firstName");
sortie.println("database.SQLUserLastNameColumnName = lastName");
sortie.println("database.SQLUserEMailColumnName = email");
sortie.println("database.SQLUserPasswordColumnName = password");
sortie.println("database.SQLUserPasswordValidColumnName = passwordValid");
sortie.println("");
sortie.println("# For Groups");
sortie.println("database.SQLGroupSpecificIdColumnName = id");
sortie.println("database.SQLGroupNameColumnName = name");
sortie.println("database.SQLGroupDescriptionColumnName = description");
sortie.println("database.SQLGroupParentIdColumnName = superGroupId");
sortie.println("");
sortie.println("# For Users-Groups relations");
sortie.println("database.SQLUserGroupUIDColumnName = userId");
sortie.println("database.SQLUserGroupGIDColumnName = groupId");
sortie.println("");
try {
while ((currentLine = readerTemplateDomainSQL.readLine()) != null) {
if (!currentLine.startsWith("allowPasswordChange")) {
sortie.println(currentLine);
}
}
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
sortie.close();
// 2-Création sur le fileSystem du properties
// com.stratelia.silverpeas.authentication.autDomain<domainName>
SilverTrace.info(
"jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création sur le fileSystem du properties com.stratelia.silverpeas.authentication.autDomain<domainName>");
String cheminFichierAutDomain = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator + "silverpeas" + File.separator + "authentication";
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain);
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
try {
sortie = new PrintWriter(new FileWriter(fileAutDomain));
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
sortie.println("# Silverpeas default driver authentication");
sortie.println("# ----------------------------------------");
sortie.println("");
sortie.println(
"# Fallback type : could be one of the following values : none, ifNotRejected, always");
sortie.println("fallbackType = none");
sortie.println("");
sortie.println("allowPasswordChange = " + allowPasswordChange);
sortie.println("");
sortie.println("# Authentication servers");
sortie.println(
"# Available types are : com.stratelia.silverpeas.authentication.AuthenticationNT, com.stratelia.silverpeas.authentication.AuthenticationSQL and com.stratelia.silverpeas.authentication.AuthenticationLDAP");
sortie.println("");
sortie.println("autServersCount = 1");
sortie.println("");
sortie.println(
"autServer0.type = com.stratelia.silverpeas.authentication.AuthenticationSQL");
sortie.println("autServer0.enabled = true");
sortie.println("autServer0.SQLJDBCUrl = "
+ propAdmin.getString("WaProductionDb"));
sortie.println("autServer0.SQLAccessLogin = "
+ propAdmin.getString("WaProductionUser"));
sortie.println("autServer0.SQLAccessPasswd = "
+ propAdmin.getString("WaProductionPswd"));
sortie.println("autServer0.SQLDriverClass = "
+ propAdmin.getString("AdminDBDriver"));
sortie.println("autServer0.SQLUserTableName = Domain" + domainName
+ "_User");
sortie.println("autServer0.SQLUserLoginColumnName = login");
sortie.println("autServer0.SQLUserPasswordColumnName = password");
sortie.println("autServer0.SQLUserPasswordAvailableColumnName = passwordValid");
sortie.println("autServer0.SQLPasswordEncryption = " + cryptMethod);
sortie.close();
// 3-Création en base de données des 3 nouvelles tables du domaine :
// Domain<domainName>_Group, Domain<domainName>_Group_User_Rel et
// Domain<domainName>_User
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création en base de données des 3 tablse du Domain");
try {
JobDomainPeasDAO.createTableDomain_Group(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
try {
JobDomainPeasDAO.createTableDomain_User(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
try {
JobDomainPeasDAO.createTableDomain_Group_User_Rel(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
// 4-Enregistrement en base de données du nouveau Domaine dans ST_Domain
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Insertion d'une entrée dans la table ST_Domain");
Domain theNewDomain = new Domain();
String idRet = null;
theNewDomain.setId("-1");
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName("com.stratelia.silverpeas.domains.sqldriver.SQLDriver");
theNewDomain.setPropFileName("com.stratelia.silverpeas.domains.domain"
+ domainName);
theNewDomain.setAuthenticationServer("autDomain" + domainName);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp("0");
idRet = m_AdminCtrl.addDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN");
}
return idRet;
}
public String modifyDomain(String domainName, String domainDescription,
String domainDriver, String domainProperties,
String domainAuthentication, String silverpeasServerURL,
String domainTimeStamp) throws JobDomainPeasException,
JobDomainPeasTrappedException {
Domain theNewDomain = getTargetDomain();
// Vérif domainName unique dans la table ST_Domain
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
trappedException.setGoBackPage("domainContent");
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (!domain.getId().equals(theNewDomain.getId())
&& domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
String idRet = null;
if (!StringUtil.isDefined(m_TargetDomainId)
|| m_TargetDomainId.equals("-1")) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName(domainDriver);
theNewDomain.setPropFileName(domainProperties);
theNewDomain.setAuthenticationServer(domainAuthentication);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp(domainTimeStamp);
idRet = m_AdminCtrl.updateDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
refresh();
return idRet;
}
public String modifySQLDomain(String domainName, String domainDescription,
String silverpeasServerURL) throws JobDomainPeasException,
JobDomainPeasTrappedException {
Domain theNewDomain = getTargetDomain();
// Vérif domainName unique dans la table ST_Domain
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
trappedException.setGoBackPage("domainContent");
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (!domain.getId().equals(theNewDomain.getId())
&& domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
String idRet = null;
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySQLDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifySQLDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
idRet = m_AdminCtrl.updateDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySQLDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
refresh();
return idRet;
}
public void deleteDomain() throws JobDomainPeasException {
String idRet = null;
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
idRet = m_AdminCtrl.removeDomain(getTargetDomain().getId());
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
returnIntoGroup(null);
m_TargetDomain = null;
}
public void deleteSQLDomain() throws JobDomainPeasException {
String cheminProperties = getTargetDomain().getPropFileName();
String domainName = cheminProperties.substring(39);
// 1-Suppression en base de données du Domaine dans ST_Domain
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
String idRet = m_AdminCtrl.removeDomain(getTargetDomain().getId());
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
returnIntoGroup(null);
m_TargetDomain = null;
// 2-Suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 3-Suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 4-Suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 5-Suppression du fichier domain<domainName>.properties
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
String cheminFichierDomain = pathInitialize.substring(0, indexOfInitialize)
+ "properties" + File.separator + "com" + File.separator + "stratelia"
+ File.separator + "silverpeas" + File.separator + "domains";
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain);
File fileDomain = new File(directoryDomain, nomFichierDomain);
fileDomain.delete();
// 6-Suppression du fichier domain<domainName>.properties
String cheminFichierAutDomain = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator + "silverpeas" + File.separator + "authentication";
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain);
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
fileAutDomain.delete();
}
protected String getSureString(String s) {
if (s == null) {
return "";
} else {
return s;
}
}
public void refresh() {
if (m_TargetDomain != null) {
m_TargetDomain.refresh();
}
for (int i = 0; i < m_GroupsPath.size(); i++) {
m_GroupsPath.get(i).refresh();
}
setTargetUser(null);
}
/*
* Selection Peas functions
*/
public String initSelectionPeasForGroups(String compoURL)
throws JobDomainPeasException {
String hostSpaceName = getString("JDP.userPanelGroup");
PairObject hostComponentName = new PairObject(getTargetGroup().getName(),
compoURL + "groupContent");
PairObject[] hostPath = new PairObject[0];
String hostUrl = compoURL + "groupAddRemoveUsers";
String cancelUrl = compoURL + "groupContent";
Selection sel = getSelection();
sel.resetAll();
sel.setHostSpaceName(hostSpaceName);
sel.setHostPath(hostPath);
sel.setHostComponentName(hostComponentName);
sel.setGoBackURL(hostUrl);
sel.setCancelURL(cancelUrl);
if ((m_TargetDomainId != null) && (!m_TargetDomainId.equals("-1"))
&& (m_TargetDomainId.length() > 0)) {
// Add extra params
SelectionUsersGroups sug = new SelectionUsersGroups();
sug.setDomainId(m_TargetDomainId);
sel.setExtraParams(sug);
}
sel.setSelectedElements(SelectionUsersGroups.getUserIds(m_GroupsPath.lastElement().
getAllUserPage()));
// Contraintes
sel.setSetSelectable(false);
sel.setPopupMode(false);
sel.setFirstPage(Selection.FIRST_PAGE_CART);
return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
}
/*
* Appel UserPannel pour récup du user sélectionné :
*/
public String[] getSelectedUsersIds() {
return getSelection().getSelectedElements();
}
// Throws Specific Exception
public String initSelectionPeasForOneGroupOrUser(String compoURL)
throws JobDomainPeasException {
String hostSpaceName = getString("JDP.userPanelDomain");
PairObject hostComponentName = new PairObject(getTargetDomain().getName(),
compoURL + "domainContent");
PairObject[] hostPath = new PairObject[0];
String hostUrl = compoURL + "selectUserOrGroup";
String cancelUrl = compoURL + "domainContent";
Selection sel = getSelection();
sel.resetAll();
sel.setHostSpaceName(hostSpaceName);
sel.setHostPath(hostPath);
sel.setHostComponentName(hostComponentName);
sel.setGoBackURL(hostUrl);
sel.setCancelURL(cancelUrl);
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.length() <= 0)) {
sel.setElementSelectable(false);
}
// Add extra params
SelectionUsersGroups sug = new SelectionUsersGroups();
sug.setDomainId(m_TargetDomainId);
sel.setExtraParams(sug);
// Contraintes
sel.setMultiSelect(false);
sel.setPopupMode(false);
sel.setFirstPage(Selection.FIRST_PAGE_BROWSE);
return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
}
public String getSelectedUserId() {
return getSelection().getFirstSelectedElement();
}
public String getSelectedGroupId() {
return getSelection().getFirstSelectedSet();
}
// Synchro Management
// ------------------
public void synchroSQLDomain() {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO SQL DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
if (m_theThread == null) {
SynchroReport.setTraceLevel(SynchroReport.TRACE_LEVEL_INFO);
SynchroReport.setState(SynchroReport.STATE_WAITSTART);
m_theThread = new SynchroWebServiceThread(this);
m_ErrorOccured = null;
m_SynchroReport = "";
m_theThread.startTheThread();
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------THREAD SYNCHRO SQL DOMAIN LANCE-----------");
} else {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------!!!! SYNCHRO DOMAIN SQL : DEUXIEME APPEL !!!!!-----------");
}
}
protected String synchronizeSilverpeasViaWebService() {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO SQL DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
String sReport = "";
SynchroUserWebServiceItf synchroUserWebService = null;
try {
sReport = "Démarrage de la synchronisation...\n\n";
// Démarrage de la synchro avec la Popup d'affichage
SynchroReport.startSynchro();
Domain theDomain = getTargetDomain();
SynchroReport.warn("jobDomainPeas.synchronizeSilverpeasViaWebService",
"Domaine : " + theDomain.getName() + " (id : " + theDomain.getId()
+ ")", null);
// 1- Récupère la liste des groupes à synchroniser (en insert et
// update)
Collection<Group> listGroupToInsertUpdate;
try {
listGroupToInsertUpdate = JobDomainPeasDAO.selectGroupSynchroInsertUpdateTableDomain_Group(
theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 2- Traitement Domaine, appel aux webServices
String propDomainFileName = theDomain.getPropFileName();
ResourceLocator propDomainSql = new ResourceLocator(propDomainFileName,
"");
String nomClasseWebService = propDomainSql.getString("ExternalSynchroClass");
try {
synchroUserWebService = (SynchroUserWebServiceItf) Class.forName(
nomClasseWebService).newInstance();
} catch (Exception e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e);
}
synchroUserWebService.startConnection();
// Insertion / Update de la société
sReport += synchroUserWebService.insertUpdateDomainWebService(theDomain.getId(), theDomain.
getName());
// 3- Traitement groupes, appel aux webServices
if (listGroupToInsertUpdate != null && listGroupToInsertUpdate.size() > 0) {
// Insertion / Update des groupes
sReport += synchroUserWebService.insertUpdateListGroupWebService(
theDomain.getId(), theDomain.getName(), listGroupToInsertUpdate);
// Suppression des groupes
/*
* Collection listGroupSilverpeas = Arrays.asList(m_AdminCtrl.getAllGroupIds()); sReport +=
* synchroUserWebService.deleteListGroupWebService(theDomain.getId(), listGroupSilverpeas);
*/
}
// 4- Récupère la liste des users à synchroniser (en insert et update)
Collection<UserFull> listUserToInsertUpdate;
try {
listUserToInsertUpdate = JobDomainPeasDAO.selectUserSynchroInsertUpdateTableDomain_User(
theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 5- Récupère la liste des users à synchroniser (en delete)
Collection<UserDetail> listUserToDelete;
try {
listUserToDelete = JobDomainPeasDAO.selectUserSynchroDeleteTableDomain_User(theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 6-Traitement users, appel aux webServices
if ((listUserToInsertUpdate != null && listUserToInsertUpdate.size() > 0)
|| (listUserToDelete != null && listUserToDelete.size() > 0)) {
// CBO : UPDATE 09.04.2008
/*
* //Insertion / Update des users if(listUserToInsertUpdate != null &&
* listUserToInsertUpdate.size()>0) { sReport +=
* synchroUserWebService.insertUpdateListUserWebService (theDomain.getId(),
* listUserToInsertUpdate, listGroupToInsertUpdate); } //Suppression des users
* if(listUserToDelete != null && listUserToDelete.size()>0) { sReport +=
* synchroUserWebService.deleteListUserWebService(theDomain.getId(), listUserToDelete); }
*/
// Suppression des users
if (listUserToDelete != null && listUserToDelete.size() > 0) {
sReport += synchroUserWebService.deleteListUserWebService(theDomain.getId(),
listUserToDelete);
}
// Insertion / Update des users
if (listUserToInsertUpdate != null && listUserToInsertUpdate.size() > 0) {
sReport += synchroUserWebService.insertUpdateListUserWebService(
theDomain.getId(), listUserToInsertUpdate,
listGroupToInsertUpdate);
}
// CBO : FIN UPDATE 09.04.2008
}
sReport += "\n\nFin de la synchronisation...";
} catch (JobDomainPeasException e) {
SilverTrace.error("JobDomainPeasSessionController",
"JobDomainPeasSessionController.synchronizeSilverpeasViaWebService",
"admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e);
SynchroReport.error(
"JobDomainPeasSessionController.synchronizeSilverpeasViaWebService",
"Problème lors de la synchronisation : " + e.getMessage(), null);
sReport = "Erreurs lors de la synchronisation : \n" + e.getMessage();
} finally {
// Fin de synchro avec la Popup d'affichage
SynchroReport.stopSynchro();
synchroUserWebService.endConnection();
}
return sReport;
}
public void synchroDomain(int traceLevel) {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
if (m_theThread == null) {
SynchroReport.setTraceLevel(traceLevel);
SynchroReport.setState(SynchroReport.STATE_WAITSTART);
m_theThread = new SynchroLdapThread(this, m_AdminCtrl, m_TargetDomainId);
m_ErrorOccured = null;
m_SynchroReport = "";
m_theThread.startTheThread();
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------THREAD SYNCHRO DOMAIN LANCE-----------");
} else {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------!!!! SYNCHRO DOMAIN : DEUXIEME APPEL !!!!!-----------");
}
}
public boolean isEnCours() {
if (m_theThread == null) {
return false;
} else {
return m_theThread.isEnCours();
}
}
public Exception getErrorOccured() {
return m_ErrorOccured;
}
public String getSynchroReport() {
if (m_ErrorOccured != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
m_ErrorOccured.printStackTrace(pw);
return m_ErrorOccured.toString() + "\n" + sw.getBuffer().toString();
} else {
return m_SynchroReport;
}
}
public void threadFinished() {
m_ErrorOccured = m_theThread.getErrorOccured();
m_SynchroReport = m_theThread.getSynchroReport();
m_theThread = null;
}
public void getP12(String userId) throws JobDomainPeasException {
UserDetail user = getUserDetail(userId);
try {
X509Factory.buildP12(user.getId(), user.getLogin(), user.getLastName(),
user.getFirstName(), user.getDomainId());
} catch (UtilException e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getP12()", SilverpeasException.ERROR,
"admin.MSG_ERR_CANT_GET_P12", e);
}
}
private void revocateCertificate(UserDetail user)
throws JobDomainPeasException {
try {
X509Factory.revocateUserCertificate(user.getId());
} catch (UtilException e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.revocateCertificate()",
SilverpeasException.ERROR, "admin.MSG_ERR_CANT_REVOCATE_CERTIFICATE",
e);
}
}
/** PAGINATION **/
/**
* Get list of selected users Ids
*/
public ArrayList<String> getListSelectedUsers() {
SilverTrace.info("jobDomainPeas","JobDomainPeasSessionController.getListUsersSelected()", "",
"listSelectedUsers (taille) = (" + listSelectedUsers.size() + ") "
+ listSelectedUsers.toString());
return listSelectedUsers;
}
public void clearListSelectedUsers() {
listSelectedUsers.clear();
}
public void setListSelectedUsers(ArrayList<String> list) {
listSelectedUsers = list;
SilverTrace.info("jobDomainPeas","JobDomainPeasSessionController.setListSelectedUsers()", "",
"listSelectedUsers (taille) = (" + listSelectedUsers.size() + ") "
+ listSelectedUsers.toString());
}
public void setIndexOfFirstItemToDisplay(String index) {
this.indexOfFirstItemToDisplay = Integer.parseInt(index);
}
public int getIndexOfFirstItemToDisplay() {
return indexOfFirstItemToDisplay;
}
public List<Group> getUserManageableGroups() {
List<Group> groups = new ArrayList<Group>();
List<String> groupIds = getUserManageableGroupIds();
Group[] aGroups = getOrganizationController().getGroups(groupIds.toArray(new String[groupIds.
size()]));
groups = Arrays.asList(aGroups);
return groups;
}
public UserDetail checkUser(UserDetail userToCheck) {
UserDetail existingUser = null;
UserDetail[] existingUsers = m_TargetDomain.getAllUserPage();
for (int i = 0; i < existingUsers.length; i++) {
existingUser = existingUsers[i];
if (userToCheck.getLastName().equalsIgnoreCase(existingUser.getLastName())
&& userToCheck.getFirstName().equalsIgnoreCase(existingUser.getFirstName())
&& userToCheck.geteMail().equalsIgnoreCase(existingUser.geteMail())) {
return existingUser;
}
}
return null;
}
/**
* @return true if community management is activated and target user belongs to one group
* manageable by current user
*/
public boolean isUserInAtLeastOneGroupManageableByCurrentUser() {
if (!JobDomainSettings.m_UseCommunityManagement) {
return false;
}
List<String> groupIds = getUserManageableGroupIds();
for (Iterator<String> iterator = groupIds.iterator(); iterator.hasNext();) {
String groupId = iterator.next();
UserDetail[] users = getOrganizationController().getAllUsersOfGroup(groupId);
UserDetail user = getUser(m_TargetUserId, users);
if (user != null) {
return true;
}
}
return false;
}
private UserDetail getUser(String userId, UserDetail[] users) {
for (UserDetail userDetail : users) {
if (userId.equals(userDetail.getId())) {
return userDetail;
}
}
return null;
}
} | web-core/src/main/java/com/silverpeas/jobDomainPeas/control/JobDomainPeasSessionController.java | /**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* 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/>.
*/
package com.silverpeas.jobDomainPeas.control;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import org.apache.commons.fileupload.FileItem;
import com.silverpeas.jobDomainPeas.DomainNavigationStock;
import com.silverpeas.jobDomainPeas.GroupNavigationStock;
import com.silverpeas.jobDomainPeas.JobDomainPeasDAO;
import com.silverpeas.jobDomainPeas.JobDomainPeasException;
import com.silverpeas.jobDomainPeas.JobDomainPeasTrappedException;
import com.silverpeas.jobDomainPeas.JobDomainSettings;
import com.silverpeas.jobDomainPeas.SynchroUserWebServiceItf;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.StringUtil;
import com.silverpeas.util.csv.CSVReader;
import com.silverpeas.util.csv.Variant;
import com.silverpeas.util.security.X509Factory;
import com.stratelia.silverpeas.authentication.Authentication;
import com.stratelia.silverpeas.peasCore.AbstractComponentSessionController;
import com.stratelia.silverpeas.peasCore.ComponentContext;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.selection.Selection;
import com.stratelia.silverpeas.selection.SelectionException;
import com.stratelia.silverpeas.selection.SelectionUsersGroups;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.silverpeas.util.PairObject;
import com.stratelia.silverpeas.util.SilverpeasSettings;
import com.stratelia.webactiv.beans.admin.AbstractDomainDriver;
import com.stratelia.webactiv.beans.admin.AdminController;
import com.stratelia.webactiv.beans.admin.Domain;
import com.stratelia.webactiv.beans.admin.DomainProperty;
import com.stratelia.webactiv.beans.admin.Group;
import com.stratelia.webactiv.beans.admin.GroupProfileInst;
import com.stratelia.webactiv.beans.admin.SynchroReport;
import com.stratelia.webactiv.beans.admin.UserDetail;
import com.stratelia.webactiv.beans.admin.UserFull;
import com.stratelia.webactiv.util.GeneralPropertiesManager;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.exception.SilverpeasException;
import com.stratelia.webactiv.util.exception.UtilException;
import com.stratelia.webactiv.util.exception.UtilTrappedException;
/**
* Class declaration
* @author
*/
public class JobDomainPeasSessionController extends AbstractComponentSessionController {
String m_TargetUserId = null;
String m_TargetDomainId = "";
DomainNavigationStock m_TargetDomain = null;
Vector<GroupNavigationStock> m_GroupsPath = new Vector<GroupNavigationStock>();
SynchroThread m_theThread = null;
Exception m_ErrorOccured = null;
String m_SynchroReport = "";
Selection sel = null;
List<UserDetail> usersToImport = null;
Hashtable<String, String> queryToImport = null;
AdminController m_AdminCtrl = null;
private ArrayList<String> listSelectedUsers = new ArrayList<String>();
// pagination de la liste des résultats
private int indexOfFirstItemToDisplay = 0;
boolean refreshDomain = true;
/**
* Standard Session Controller Constructeur
* @param mainSessionCtrl The user's profile
* @param componentContext The component's profile
* @see
*/
public JobDomainPeasSessionController(MainSessionController mainSessionCtrl,
ComponentContext componentContext) {
super(mainSessionCtrl, componentContext,
"com.silverpeas.jobDomainPeas.multilang.jobDomainPeasBundle",
"com.silverpeas.jobDomainPeas.settings.jobDomainPeasIcons",
"com.silverpeas.jobDomainPeas.settings.jobDomainPeasSettings");
setComponentRootName(URLManager.CMP_JOBDOMAINPEAS);
m_AdminCtrl = new AdminController(getUserId());
sel = getSelection();
}
public int getMinLengthLogin() {
return JobDomainSettings.m_MinLengthLogin;
}
public int getMinLengthPwd() {
return JobDomainSettings.m_MinLengthPwd;
}
public boolean isBlanksAllowedInPwd() {
return JobDomainSettings.m_BlanksAllowedInPwd;
}
public boolean isUserAddingAllowedForGroupManager() {
return JobDomainSettings.m_UserAddingAllowedForGroupManagers;
}
public boolean isAccessGranted() {
boolean accessGranted = false;
if (getUserManageableGroupIds().size() > 0) {
return true;
}
if (getUserDetail().isAccessAdmin()
|| getUserDetail().isAccessDomainManager()) {
return true;
}
return accessGranted;
}
public void setRefreshDomain(boolean refreshDomain) {
this.refreshDomain = refreshDomain;
}
/*
* USER functions
*/
public void setTargetUser(String userId) {
m_TargetUserId = userId;
}
public UserDetail getTargetUserDetail() throws JobDomainPeasException {
UserDetail valret = null;
if ((m_TargetUserId != null) && (m_TargetUserId.length() > 0)) {
valret = getOrganizationController().getUserDetail(m_TargetUserId);
if (valret == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getTargetUserDetail()",
SilverpeasException.ERROR, "jobDomainPeas.EX_USER_NOT_AVAILABLE",
"UserId=" + m_TargetUserId);
}
}
return valret;
}
public UserFull getTargetUserFull() throws JobDomainPeasException {
UserFull valret = null;
if ((m_TargetUserId != null) && (m_TargetUserId.length() > 0)) {
valret = getOrganizationController().getUserFull(m_TargetUserId);
if (valret == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getTargetUserFull()",
SilverpeasException.ERROR, "jobDomainPeas.EX_USER_NOT_AVAILABLE",
"UserId=" + m_TargetUserId);
}
}
return valret;
}
public String createUser(String userLogin, String userLastName,
String userFirstName, String userEMail, String userAccessLevel,
boolean userPasswordValid, String userPassword, HashMap<String, String> properties,
String groupId)
throws JobDomainPeasException, JobDomainPeasTrappedException {
UserDetail theNewUser = new UserDetail();
String idRet = null;
String existingUser;
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createUser()",
"root.MSG_GEN_ENTER_METHOD", "userLogin=" + userLogin
+ " userLastName=" + userLastName + " userFirstName="
+ userFirstName + " userEMail=" + userEMail + " userAccessLevel="
+ userAccessLevel);
existingUser = m_AdminCtrl.getUserIdByLoginAndDomain(userLogin,
m_TargetDomainId);
if ((existingUser != null) && (existingUser.length() > 0)) {
JobDomainPeasTrappedException te = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_LOGIN_ALREADY_USED");
te.setGoBackPage("displayUserCreate");
throw te;
}
theNewUser.setId("-1");
if ((m_TargetDomainId != null) && (m_TargetDomainId.equals("-1") == false)
&& (m_TargetDomainId.length() > 0)) {
theNewUser.setDomainId(m_TargetDomainId);
}
theNewUser.setLogin(userLogin);
theNewUser.setLastName(userLastName);
theNewUser.setFirstName(userFirstName);
theNewUser.seteMail(userEMail);
theNewUser.setAccessLevel(userAccessLevel);
idRet = m_AdminCtrl.addUser(theNewUser);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_ADD_USER");
}
refresh();
setTargetUser(idRet);
// Update UserFull informations
UserFull uf = getTargetUserFull();
if (uf != null) {
if (uf.isPasswordAvailable()) {
uf.setPasswordValid(userPasswordValid);
uf.setPassword(userPassword);
}
// process extra properties
Set<String> keys = properties.keySet();
Iterator<String> iKeys = keys.iterator();
String key = null;
String value = null;
while (iKeys.hasNext()) {
key = iKeys.next();
value = properties.get(key);
uf.setValue(key, value);
}
idRet = m_AdminCtrl.updateUserFull(uf);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER");
}
}
// regroupement de l'utilisateur dans un groupe
regroupInGroup(properties, null);
// If group is provided, add newly created user to it
if (StringUtil.isDefined(groupId)) {
m_AdminCtrl.addUserInGroup(idRet, groupId);
}
return idRet;
}
/**
* Regroupement éventuel de l'utilisateur dans un groupe (pour les domaines SQL)
* @throws JobDomainPeasException
*/
private void regroupInGroup(HashMap<String, String> properties, String lastGroupId)
throws JobDomainPeasException {
// Traitement du domaine SQL
if (!"-1".equals(getTargetDomain().getId())
&& !"0".equals(getTargetDomain().getId())
&& getTargetDomain().getDriverClassName().equals(
"com.stratelia.silverpeas.domains.sqldriver.SQLDriver")) {
ResourceLocator specificRs = new ResourceLocator(getTargetDomain().getPropFileName(), "");
int numPropertyRegroup = SilverpeasSettings.readInt(specificRs,
"property.Grouping", -1);
String nomRegroup = null;
String theUserIdToRegroup = m_TargetUserId;
String[] newUserIds;
List<String> lUserIds;
List<String> lNewUserIds;
if (numPropertyRegroup > -1) {
String nomPropertyRegroupement = SilverpeasSettings.readString(
specificRs, "property_" + numPropertyRegroup + ".Name", null);
if (nomPropertyRegroupement != null) {
// Suppression de l'appartenance de l'utilisateur au groupe auquel il
// appartenait
if (lastGroupId != null) {
Group lastGroup = m_AdminCtrl.getGroupById(lastGroupId);
lUserIds = Arrays.asList(lastGroup.getUserIds());
lNewUserIds = new ArrayList<String>(lUserIds);
lNewUserIds.remove(theUserIdToRegroup);
newUserIds = lNewUserIds.toArray(new String[lNewUserIds.size()]);
updateGroupSubUsers(lastGroupId, newUserIds);
}
// Recherche du nom du regroupement (nom du groupe)
Set<String> keys = properties.keySet();
Iterator<String> iKeys = keys.iterator();
String key = null;
String value = null;
boolean trouve = false;
while (iKeys.hasNext()) {
key = iKeys.next();
value = properties.get(key);
if (key.equals(nomPropertyRegroupement)) {
trouve = true;
break;
}
}
if (trouve) {
nomRegroup = value;
}
}
}
if (nomRegroup != null && nomRegroup.length() > 0) {
// Recherche le groupe dans le domaine
Group group = m_AdminCtrl.getGroupByNameInDomain(nomRegroup,
m_TargetDomainId);
if (group == null) {
// le groupe n'existe pas, on le crée
group = new Group();
group.setId("-1");
group.setDomainId(m_TargetDomainId);
group.setSuperGroupId(null); // groupe à la racine
group.setName(nomRegroup);
group.setDescription("");
String groupId = m_AdminCtrl.addGroup(group);
group = m_AdminCtrl.getGroupById(groupId);
}
lUserIds = Arrays.asList(group.getUserIds());
lNewUserIds = new ArrayList<String>(lUserIds);
lNewUserIds.add(theUserIdToRegroup);
newUserIds = lNewUserIds.toArray(new String[lNewUserIds.size()]);
// Ajout de l'appartenance de l'utilisateur au groupe
updateGroupSubUsers(group.getId(), newUserIds);
}
}
}
/**
* Parse the CSV file.
* @param filePart
* @throws UtilTrappedException
* @throws JobDomainPeasTrappedException
* @throws JobDomainPeasException
*/
public void importCsvUsers(FileItem filePart) throws UtilTrappedException,
JobDomainPeasTrappedException, JobDomainPeasException {
InputStream is;
try {
is = filePart.getInputStream();
} catch (IOException e) {
JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.importCsvUsers",
SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", e);
jdpe.setGoBackPage("displayUsersCsvImport");
throw jdpe;
}
CSVReader csvReader = new CSVReader(getLanguage());
csvReader.initCSVFormat(
"com.silverpeas.jobDomainPeas.settings.usersCSVFormat", "User", ";",
getTargetDomain().getPropFileName(), "property_");
// spécifique domaine Silverpeas (2 colonnes en moins (password et
// passwordValid)
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
csvReader.setM_specificNbCols(csvReader.getM_specificNbCols() - 2);
}
Variant[][] csvValues;
try {
csvValues = csvReader.parseStream(is);
} catch (UtilTrappedException ute) {
ute.setGoBackPage("displayUsersCsvImport");
throw ute;
}
StringBuilder listErrors = new StringBuilder("");
String nom;
String prenom;
String login;
String existingLogin;
String email;
String droits;
String userAccessLevel;
String motDePasse;
String title;
String company;
String position;
String boss;
String phone;
String homePhone;
String fax;
String cellularPhone;
String address;
String informationSpecifiqueString;
boolean informationSpecifiqueBoolean;
for (int i = 0; i < csvValues.length; i++) {
// Nom
nom = csvValues[i][0].getValueString();
if (nom.length() == 0) {// champ obligatoire
listErrors.append(getErrorMessage(i+1, 1, nom));
listErrors.append(getString("JDP.obligatoire")).append("<br/>");
} else if (nom.length() > 100) {// verifier 100 char max
listErrors.append(getErrorMessage(i+1, 1, nom));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").
append(getString("JDP.caracteres")).append("<br/>");
}
// Prenom
prenom = csvValues[i][1].getValueString(); // verifier 100 char max
if (prenom.length() > 100) {
listErrors.append(getErrorMessage(i+1, 2, prenom));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 "
+ getString("JDP.caracteres")).append("<br/>");
}
// Login
login = csvValues[i][2].getValueString();
if (login.length() == 0) {// champ obligatoire
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.obligatoire")).append("<br/>");
} else if (login.length() < JobDomainSettings.m_MinLengthLogin) {// verifier
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.nbCarMin")).append(" ").append(
JobDomainSettings.m_MinLengthLogin).append(" ").append(getString("JDP.caracteres")).
append("<br/>");
} else if (login.length() > 20) {// verifier 20 char max
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
} else {// verif login unique
existingLogin = m_AdminCtrl.getUserIdByLoginAndDomain(login,
m_TargetDomainId);
if (existingLogin != null) {
listErrors.append(getErrorMessage(i+1, 3, login));
listErrors.append(getString("JDP.existingLogin")).append("<br/>");
}
}
// Email
email = csvValues[i][3].getValueString(); // verifier 100 char max
if (email.length() > 100) {
listErrors.append(getErrorMessage(i+1, 4, email));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// Droits
droits = csvValues[i][4].getValueString();
if (!"".equals(droits) && !"Admin".equals(droits)
&& !"AdminPdc".equals(droits) && !"AdminDomain".equals(droits)
&& !"User".equals(droits) && !"Guest".equals(droits)) {
listErrors.append(getErrorMessage(i+1, 5, droits));
listErrors.append(getString("JDP.valeursPossibles")).append("<br/>");
}
// MotDePasse
motDePasse = csvValues[i][5].getValueString();
// password is not mandatory
if (StringUtil.isDefined(motDePasse)) {
if (!JobDomainSettings.m_BlanksAllowedInPwd
&& motDePasse.indexOf(" ") != -1) {
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.espaces")).append("<br/>");
} else if (motDePasse.length() < JobDomainSettings.m_MinLengthPwd) {// verifier
// jobDomainPeasSettings.getString("minLengthPwd")
// char
// min
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.nbCarMin")).append(" ").append(
JobDomainSettings.m_MinLengthPwd).append(" ").append(getString("JDP.caracteres")).append(
"<br/>");
} else if (motDePasse.length() > 32) {// verifier 32 char max
listErrors.append(getErrorMessage(i+1, 6, motDePasse));
listErrors.append(getString("JDP.nbCarMax")).append(" 32 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
}
if (csvReader.getM_specificNbCols() > 0) {
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
// title
title = csvValues[i][6].getValueString(); // verifier 100 char max
if (title.length() > 100) {
listErrors.append(getErrorMessage(i+1, 7, title));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// company
company = csvValues[i][7].getValueString(); // verifier 100 char max
if (company.length() > 100) {
listErrors.append(getErrorMessage(i+1, 8, company));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// position
position = csvValues[i][8].getValueString(); // verifier 100 char max
if (position.length() > 100) {
listErrors.append(getErrorMessage(i+1, 9, position));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// boss
boss = csvValues[i][9].getValueString(); // verifier 100 char max
if (boss.length() > 100) {
listErrors.append(getErrorMessage(i+1, 10, boss));
listErrors.append(getString("JDP.nbCarMax")).append(" 100 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// phone
phone = csvValues[i][10].getValueString(); // verifier 20 char max
if (phone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 11, phone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// homePhone
homePhone = csvValues[i][11].getValueString(); // verifier 20 char max
if (homePhone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 12, homePhone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// fax
fax = csvValues[i][12].getValueString(); // verifier 20 char max
if (fax.length() > 20) {
listErrors.append(getErrorMessage(i+1, 13, fax));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// cellularPhone
cellularPhone = csvValues[i][13].getValueString(); // verifier 20 char
// max
if (cellularPhone.length() > 20) {
listErrors.append(getErrorMessage(i+1, 14, cellularPhone));
listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
// address
address = csvValues[i][14].getValueString(); // verifier 500 char max
if (address.length() > 500) {
listErrors.append(getErrorMessage(i+1, 15, address));
listErrors.append(getString("JDP.nbCarMax")).append(" 500 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
} else {// domaine SQL
// informations spécifiques
for (int j = 0; j < csvReader.getM_specificNbCols(); j++) {
if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueString = csvValues[i][j + 6].getValueString(); // verifier 50 char max
if (informationSpecifiqueString.length() > 50) {
listErrors.append(getErrorMessage(i+1, j + 6, informationSpecifiqueString));
listErrors.append(getString("JDP.nbCarMax")).append(" 50 ").append(getString(
"JDP.caracteres")).append("<br/>");
}
}
}
}
}
}
if (listErrors.length() > 0) {
JobDomainPeasTrappedException jdpe = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController.importCsvUsers",
SilverpeasException.ERROR, "jobDomainPeas.EX_CSV_FILE", listErrors.toString());
jdpe.setGoBackPage("displayUsersCsvImport");
throw jdpe;
}
// pas d'erreur, on importe les utilisateurs
HashMap<String, String> properties;
for (int i = 0; i < csvValues.length; i++) {
// Nom
nom = csvValues[i][0].getValueString();
// Prenom
prenom = csvValues[i][1].getValueString();
// Login
login = csvValues[i][2].getValueString();
// Email
email = csvValues[i][3].getValueString();
// Droits
droits = csvValues[i][4].getValueString();
if ("Admin".equals(droits)) {
userAccessLevel = "A";
} else if ("AdminPdc".equals(droits)) {
userAccessLevel = "K";
} else if ("AdminDomain".equals(droits)) {
userAccessLevel = "D";
} else if ("User".equals(droits)) {
userAccessLevel = "U";
} else if ("Guest".equals(droits)) {
userAccessLevel = "G";
} else {
userAccessLevel = "U";
}
// MotDePasse
motDePasse = csvValues[i][5].getValueString();
// données spécifiques
properties = new HashMap<String, String>();
if (csvReader.getM_specificNbCols() > 0) {
if ("-1".equals(getTargetDomain().getId())
|| "0".equals(getTargetDomain().getId())) {// domaine Silverpeas
// title
title = csvValues[i][6].getValueString();
properties.put(csvReader.getM_specificParameterName(0), title);
// company
company = csvValues[i][7].getValueString();
properties.put(csvReader.getM_specificParameterName(1), company);
// position
position = csvValues[i][8].getValueString();
properties.put(csvReader.getM_specificParameterName(2), position);
// boss
boss = csvValues[i][9].getValueString();
properties.put(csvReader.getM_specificParameterName(3), boss);
// phone
phone = csvValues[i][10].getValueString();
properties.put(csvReader.getM_specificParameterName(4), phone);
// homePhone
homePhone = csvValues[i][11].getValueString();
properties.put(csvReader.getM_specificParameterName(5), homePhone);
// fax
fax = csvValues[i][12].getValueString();
properties.put(csvReader.getM_specificParameterName(6), fax);
// cellularPhone
cellularPhone = csvValues[i][13].getValueString();
properties.put(csvReader.getM_specificParameterName(7), cellularPhone);
// address
address = csvValues[i][14].getValueString();
properties.put(csvReader.getM_specificParameterName(8), address);
} else {// domaine SQL
// informations spécifiques
for (int j = 0; j < csvReader.getM_specificNbCols(); j++) {
if (Variant.TYPE_STRING.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueString = csvValues[i][j + 6].getValueString();
properties.put(csvReader.getM_specificParameterName(j),
informationSpecifiqueString);
} else if (Variant.TYPE_BOOLEAN.equals(csvReader.getM_specificColType(j))) {
informationSpecifiqueBoolean = csvValues[i][j + 6].getValueBoolean();
if (informationSpecifiqueBoolean) {
properties.put(csvReader.getM_specificParameterName(j), "1");
} else {
properties.put(csvReader.getM_specificParameterName(j), "0");
}
}
}
}
}
boolean passwordValid = StringUtil.isDefined(motDePasse); // password is not mandatory
createUser(login, nom, prenom, email, userAccessLevel, passwordValid, motDePasse,
properties, null); // l'id User créé est dans m_TargetUserId
}
}
private String getErrorMessage(int line, int column, String value) {
StringBuilder str = new StringBuilder();
str.append(getString("JDP.ligne")).append(" = ").append(line).append(", ");
str.append(getString("JDP.colonne")).append(" = ").append(column).append(", ");
str.append(getString("JDP.valeur")).append(" = ").append(value).append(", ");
return str.toString();
}
private String getLastGroupId(UserFull theUser) {
// Traitement du domaine SQL
if (!"-1".equals(getTargetDomain().getId())
&& !"0".equals(getTargetDomain().getId())
&& getTargetDomain().getDriverClassName().equals(
"com.stratelia.silverpeas.domains.sqldriver.SQLDriver")) {
ResourceLocator specificRs = new ResourceLocator(getTargetDomain().getPropFileName(), "");
int numPropertyRegroup = SilverpeasSettings.readInt(specificRs,
"property.Grouping", -1);
String nomLastGroup = null;
if (numPropertyRegroup > -1) {
String nomPropertyRegroupement = SilverpeasSettings.readString(
specificRs, "property_" + numPropertyRegroup + ".Name", null);
if (nomPropertyRegroupement != null) {
// Recherche du nom du regroupement (nom du groupe)
String[] keys = theUser.getPropertiesNames();
String key = null;
String value = null;
boolean trouve = false;
for (int i = 0; i < keys.length; i++) {
key = keys[i];
value = theUser.getValue(key);
if (key.equals(nomPropertyRegroupement)) {
trouve = true;
break;
}
}
if (trouve) {
nomLastGroup = value;
}
}
}
if (nomLastGroup != null && nomLastGroup.length() > 0) {
// Recherche le groupe dans le domaine
Group group = m_AdminCtrl.getGroupByNameInDomain(nomLastGroup,
m_TargetDomainId);
if (group != null) {
return group.getId();
}
}
}
return null;
}
public void modifyUser(String idUser, String userLastName,
String userFirstName, String userEMail, String userAccessLevel,
boolean userPasswordValid, String userPassword, HashMap<String, String> properties)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser + " userLastName="
+ userLastName + " userFirstName=" + userFirstName + " userEMail="
+ userEMail + " userAccessLevel=" + userAccessLevel);
UserFull theModifiedUser = m_AdminCtrl.getUserFull(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
// nom du groupe auquel était rattaché l'utilisateur
String lastGroupId = getLastGroupId(theModifiedUser);
theModifiedUser.setLastName(userLastName);
theModifiedUser.setFirstName(userFirstName);
theModifiedUser.seteMail(userEMail);
theModifiedUser.setAccessLevel(userAccessLevel);
if (theModifiedUser.isPasswordAvailable()) {
theModifiedUser.setPasswordValid(userPasswordValid);
theModifiedUser.setPassword(userPassword);
}
// process extra properties
Set<String> keys = properties.keySet();
for (String key : keys) {
String value = properties.get(key);
theModifiedUser.setValue(key, value);
}
String idRet = m_AdminCtrl.updateUserFull(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
// regroupement de l'utilisateur dans un groupe
regroupInGroup(properties, lastGroupId);
}
public void modifySynchronizedUser(String idUser, String userAccessLevel)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifySynchronizedUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
UserDetail theModifiedUser = m_AdminCtrl.getUserDetail(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySynchronizedUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
theModifiedUser.setAccessLevel(userAccessLevel);
String idRet = m_AdminCtrl.updateSynchronizedUser(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySynchronizedUser()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
}
public void modifyUserFull(String idUser, String userAccessLevel,
HashMap<String, String> properties)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyUserFull()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser + " userAccessLevel=" + userAccessLevel);
UserFull theModifiedUser = m_AdminCtrl.getUserFull(idUser);
if (theModifiedUser == null) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUserFull()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_USER");
}
theModifiedUser.setAccessLevel(userAccessLevel);
// process extra properties
Set<String> keys = properties.keySet();
for (String key : keys) {
String value = properties.get(key);
theModifiedUser.setValue(key, value);
}
String idRet = m_AdminCtrl.updateUserFull(theModifiedUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyUserFull()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_USER", "UserId="
+ idUser);
}
refresh();
setTargetUser(idRet);
}
public void deleteUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.deleteUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
UserDetail user = getUserDetail(idUser);
boolean deleteUser = true;
// TODO : Manage deleting case for group manager
if (!"A".equals(getUserAccessLevel()) && !"D".equals(getUserAccessLevel()) && isGroupManager()) {
List<String> directGroupIds =
Arrays.asList(getOrganizationController().getDirectGroupIdsOfUser(idUser));
List<String> manageableGroupIds = getUserManageableGroupIds();
String directGroupId = null;
String rootGroupId = null;
List<String> groupIdLinksToRemove = new ArrayList<String>();
for (int g = 0; g < directGroupIds.size(); g++) {
directGroupId = directGroupIds.get(g);
// get root group of each directGroup
List<String> groupPath = m_AdminCtrl.getPathToGroup(directGroupId);
if (groupPath != null && groupPath.size() > 0) {
rootGroupId = groupPath.get(0);
} else {
rootGroupId = directGroupId;
}
// if root group is not one of manageable group, avoid deletion
// user belongs to another community
if (!manageableGroupIds.contains(rootGroupId)) {
deleteUser = false;
} else {
groupIdLinksToRemove.add(directGroupId);
}
}
if (!deleteUser) {
// removes only links between user and manageable groups
for (Iterator<String> iterator = groupIdLinksToRemove.iterator(); iterator.hasNext();) {
String groupIdLinkToRemove = iterator.next();
m_AdminCtrl.removeUserFromGroup(idUser, groupIdLinkToRemove);
}
refresh();
}
}
if (deleteUser) {
idRet = m_AdminCtrl.deleteUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.deleteUser()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_USER", "UserId="
+ idUser);
}
if (m_TargetUserId.equals(idUser)) {
m_TargetUserId = null;
}
if ((getDomainActions() & AbstractDomainDriver.ACTION_X509_USER) != 0) {
// revocate user's certificate
revocateCertificate(user);
}
refresh();
}
}
public Iterator<DomainProperty> getPropertiesToImport() throws JobDomainPeasException {
return m_AdminCtrl.getSpecificPropertiesToImportUsers(m_TargetDomainId,
getLanguage()).iterator();
}
public void importUser(String userLogin) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.importUser()",
"root.MSG_GEN_ENTER_METHOD", "userLogin=" + userLogin);
idRet = m_AdminCtrl.synchronizeImportUser(m_TargetDomainId, userLogin);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.importUser()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_USER",
"userLogin=" + userLogin);
}
refresh();
setTargetUser(idRet);
}
public void importUsers(String[] specificIds) throws JobDomainPeasException {
for (int i = 0; specificIds != null && i < specificIds.length; i++) {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.importUsers()",
"root.MSG_GEN_ENTER_METHOD", "specificId=" + specificIds[i]);
m_AdminCtrl.synchronizeImportUser(m_TargetDomainId, specificIds[i]);
}
refresh();
}
public List<UserDetail> searchUsers(Hashtable<String, String> query) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.searchUsers()",
"root.MSG_GEN_ENTER_METHOD", "query=" + query.toString());
queryToImport = query;
usersToImport = m_AdminCtrl.searchUsers(m_TargetDomainId, query);
return usersToImport;
}
public List<UserDetail> getUsersToImport() {
return usersToImport;
}
public Hashtable<String, String> getQueryToImport() {
return queryToImport;
}
public UserFull getUser(String specificId) {
return m_AdminCtrl.getUserFull(m_TargetDomainId, specificId);
}
public void synchroUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.synchroUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
idRet = m_AdminCtrl.synchronizeUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.synchroUser()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_USER");
}
refresh();
setTargetUser(idRet);
}
public void unsynchroUser(String idUser) throws JobDomainPeasException {
String idRet = null;
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.unsynchroUser()",
"root.MSG_GEN_ENTER_METHOD", "UserId=" + idUser);
idRet = m_AdminCtrl.synchronizeRemoveUser(idUser);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.unsynchroUser()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_USER");
}
if (m_TargetUserId.equals(idUser)) {
m_TargetUserId = null;
}
refresh();
}
/*
* GROUP functions
*/
public void returnIntoGroup(String groupId) throws JobDomainPeasException {
int i = 0;
if (!StringUtil.isDefined(groupId)) {
m_GroupsPath.clear();
} else {
i = m_GroupsPath.size() - 1;
while ((i >= 0)
&& (m_GroupsPath.get(i).isThisGroup(groupId) == false)) {
m_GroupsPath.removeElementAt(i);
i--;
}
}
setTargetUser(null);
}
public void removeGroupFromPath(String groupId) throws JobDomainPeasException {
int i = 0;
if (StringUtil.isDefined(groupId)) {
i = 0;
while ((i < m_GroupsPath.size())
&& (m_GroupsPath.get(i).isThisGroup(groupId) == false)) {
i++;
}
if (i < m_GroupsPath.size()) {
m_GroupsPath.setSize(i); // Tunc the vector
}
}
}
public void goIntoGroup(String groupId) throws JobDomainPeasException {
if (StringUtil.isDefined(groupId)) {
if (getTargetGroup() == null
|| (getTargetGroup() != null && !getTargetGroup().getId().equals(
groupId))) {
Group targetGroup = m_AdminCtrl.getGroupById(groupId);
if (GroupNavigationStock.isGroupValid(targetGroup)) {
List<String> manageableGroupIds = null;
if (isOnlyGroupManager() && !isGroupManagerOnGroup(groupId)) {
manageableGroupIds = getUserManageableGroupIds();
}
GroupNavigationStock newSubGroup = new GroupNavigationStock(groupId,
m_AdminCtrl, manageableGroupIds);
m_GroupsPath.add(newSubGroup);
}
}
} else {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.setTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE",
"GroupId=" + groupId);
}
setTargetUser(null);
}
public Group getTargetGroup() throws JobDomainPeasException {
if (m_GroupsPath.size() <= 0) {
return null;
}
return m_GroupsPath.lastElement().getThisGroup();
}
/**
* @return a List with 2 elements. First one, a List of UserDetail. Last one, a List of Group.
* @throws JobDomainPeasException
*/
public List<List> getGroupManagers() throws JobDomainPeasException {
List<List> usersAndGroups = new ArrayList<List>();
List<UserDetail> users = new ArrayList<UserDetail>();
List<Group> groups = new ArrayList<Group>();
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
if (profile != null) {
List<String> groupIds = profile.getAllGroups();
Group group = null;
for (int nI = 0; nI < groupIds.size(); nI++) {
group = m_AdminCtrl.getGroupById(groupIds.get(nI));
groups.add(group);
}
List<String> userIds = profile.getAllUsers();
UserDetail user = null;
for (int nI = 0; nI < userIds.size(); nI++) {
user = getUserDetail(userIds.get(nI));
users.add(user);
}
}
usersAndGroups.add(users);
usersAndGroups.add(groups);
return usersAndGroups;
}
// user panel de selection de n groupes et n users
public void initUserPanelForGroupManagers(String compoURL) throws SelectionException,
JobDomainPeasException {
sel.resetAll();
sel.setHostSpaceName(getMultilang().getString("JDP.jobDomain"));
sel.setHostComponentName(new PairObject(getTargetGroup().getName(), null));
ResourceLocator generalMessage = GeneralPropertiesManager.getGeneralMultilang(getLanguage());
PairObject[] hostPath = {new PairObject(getMultilang().getString("JDP.roleManager")
+ " > " + generalMessage.getString("GML.selection"), null)};
sel.setHostPath(hostPath);
sel.setGoBackURL(compoURL + "groupManagersUpdate");
sel.setCancelURL(compoURL + "groupManagersCancel");
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
List<String> allUsers = profile.getAllUsers();
List<String> allGroups = profile.getAllGroups();
sel.setSelectedElements(allUsers.toArray(new String[allUsers.size()]));
sel.setSelectedSets(allGroups.toArray(new String[allGroups.size()]));
}
public void updateGroupProfile() throws JobDomainPeasException {
GroupProfileInst profile = m_AdminCtrl.getGroupProfile(getTargetGroup().getId());
profile.removeAllGroups();
profile.removeAllUsers();
setGroupsAndUsers(profile, sel.getSelectedSets(), sel.getSelectedElements());
m_AdminCtrl.updateGroupProfile(profile);
}
public void deleteGroupProfile() throws JobDomainPeasException {
m_AdminCtrl.deleteGroupProfile(getTargetGroup().getId());
}
private void setGroupsAndUsers(GroupProfileInst profile, String[] groupIds,
String[] userIds) {
// groups
for (int i = 0; groupIds != null && i < groupIds.length; i++) {
if (groupIds[i] != null && groupIds[i].length() > 0) {
profile.addGroup(groupIds[i]);
}
}
// users
for (int i = 0; userIds != null && i < userIds.length; i++) {
if (userIds[i] != null && userIds[i].length() > 0) {
profile.addUser(userIds[i]);
}
}
}
public boolean isGroupRoot(String groupId) throws JobDomainPeasException {
Group gr = m_AdminCtrl.getGroupById(groupId);
if (GroupNavigationStock.isGroupValid(gr)) {
if (this.refreshDomain && (!StringUtil.isDefined(gr.getSuperGroupId()) || "-1".equals(gr.getSuperGroupId()))) {
return true;
}
return false;
}
return false;
}
public Group[] getSubGroups(boolean isParentGroup)
throws JobDomainPeasException {
Group[] groups = null;
if (isParentGroup) {
if (m_GroupsPath.size() <= 0) {
throw new JobDomainPeasException("JobDomainPeasSessionController.getTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE");
}
groups = m_GroupsPath.lastElement().getGroupPage();
} else { // Domain case
groups = m_TargetDomain.getGroupPage();
}
if (isOnlyGroupManager() && !isGroupManagerOnCurrentGroup()) {
groups = filterGroupsToGroupManager(groups);
}
for (int i = 0; i < groups.length; i++) {
if (groups[i] != null) {
groups[i].setNbUsers(getOrganizationController().getAllSubUsersNumber(
groups[i].getId()));
}
}
return groups;
}
public String[][] getSubUsers(boolean isParentGroup)
throws JobDomainPeasException {
UserDetail[] usDetails = null;
String[][] valret = null;
int i = 0;
if (isParentGroup) {
if (m_GroupsPath.size() <= 0) {
throw new JobDomainPeasException("JobDomainPeasSessionController.getTargetGroup()",
SilverpeasException.ERROR, "jobDomainPeas.EX_GROUP_NOT_AVAILABLE");
}
usDetails = m_GroupsPath.lastElement().getUserPage();
} else { // Domain case
usDetails = m_TargetDomain.getUserPage();
}
valret = new String[usDetails.length][4];
for (i = 0; i < usDetails.length; i++) {
if (usDetails[i] != null) {
valret[i][0] = getSureString(usDetails[i].getId());
valret[i][1] = EncodeHelper.javaStringToHtmlString(getSureString(usDetails[i].getLastName()));
valret[i][2] = EncodeHelper.javaStringToHtmlString(
getSureString(usDetails[i].getFirstName()));
valret[i][3] = EncodeHelper.javaStringToHtmlString(getSureString(usDetails[i].getLogin()));
} else {
valret[i][0] = "";
valret[i][1] = "";
valret[i][2] = "";
valret[i][3] = "";
}
}
return valret;
}
public String getPath(String baseURL, String toAppendAtEnd)
throws JobDomainPeasException {
StringBuilder strPath = new StringBuilder("");
Group theGroup = null;
int i;
for (i = 0; i < m_GroupsPath.size(); i++) {
theGroup = m_GroupsPath.get(i).getThisGroup();
if (strPath.length() > 0) {
strPath.append(" > ");
}
if (((i + 1) < m_GroupsPath.size()) || (m_TargetUserId != null)
|| (toAppendAtEnd != null)) {
strPath.append("<a href=\"").append(baseURL).append("groupReturn?Idgroup=").
append(theGroup.getId()).append("\">").
append(EncodeHelper.javaStringToHtmlString(theGroup.getName())).append("</a>");
} else {
strPath.append(EncodeHelper.javaStringToHtmlString(theGroup.getName()));
}
}
if (m_TargetUserId != null) {
if (strPath.length() > 0) {
strPath.append(" > ");
}
if (toAppendAtEnd != null) {
strPath.append("<a href=\"").append(baseURL).append("userContent?Iduser=").
append(m_TargetUserId).append("\">").
append(EncodeHelper.javaStringToHtmlString(getTargetUserDetail().getDisplayedName())).
append("</a>");
} else {
strPath.append(EncodeHelper.javaStringToHtmlString(getTargetUserDetail().getDisplayedName()));
}
}
if (toAppendAtEnd != null) {
if (strPath.length() > 0) {
strPath.append(" > ");
}
strPath.append(EncodeHelper.javaStringToHtmlString(toAppendAtEnd));
}
return strPath.toString();
}
public boolean createGroup(String idParent, String groupName,
String groupDescription, String groupRule) throws JobDomainPeasException {
Group theNewGroup = new Group();
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createGroup()",
"root.MSG_GEN_ENTER_METHOD", "ParentId=" + idParent + " Name="
+ groupName + " Desc=" + groupDescription);
theNewGroup.setId("-1");
if (StringUtil.isDefined(m_TargetDomainId)
&& !"-1".equals(m_TargetDomainId)) {
theNewGroup.setDomainId(m_TargetDomainId);
}
theNewGroup.setSuperGroupId(idParent);
theNewGroup.setName(groupName);
theNewGroup.setDescription(groupDescription);
theNewGroup.setRule(groupRule);
String idRet = m_AdminCtrl.addGroup(theNewGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.createGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_ADD_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean modifyGroup(String idGroup, String groupName,
String groupDescription, String groupRule) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.modifyGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup + " Desc=" + groupDescription);
Group theModifiedGroup = m_AdminCtrl.getGroupById(idGroup);
if (theModifiedGroup == null) {
throw new JobDomainPeasException("JobDomainPeasSessionController.modifyGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_GROUP");
}
theModifiedGroup.setName(groupName);
theModifiedGroup.setDescription(groupDescription);
theModifiedGroup.setRule(groupRule);
String idRet = m_AdminCtrl.updateGroup(theModifiedGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.modifyGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean updateGroupSubUsers(String idGroup, String[] userIds)
throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.updateGroupSubUsers()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
Group theModifiedGroup = m_AdminCtrl.getGroupById(idGroup);
if (theModifiedGroup == null) {
throw new JobDomainPeasException("JobDomainPeasSessionController.updateGroupSubUsers()",
SilverpeasException.ERROR, "admin.EX_ERR_UNKNOWN_GROUP");
}
theModifiedGroup.setUserIds(userIds);
String idRet = m_AdminCtrl.updateGroup(theModifiedGroup);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.updateGroupSubUsers()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_GROUP");
}
refresh();
return false;
}
public boolean deleteGroup(String idGroup) throws JobDomainPeasException {
boolean haveToRefreshDomain = isGroupRoot(idGroup);
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.deleteGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.deleteGroupById(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.deleteGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_GROUP");
}
removeGroupFromPath(idGroup);
refresh();
return haveToRefreshDomain;
}
public boolean synchroGroup(String idGroup) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.synchroGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.synchronizeGroup(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.synchroGroup()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
public boolean unsynchroGroup(String idGroup) throws JobDomainPeasException {
boolean haveToRefreshDomain = isGroupRoot(idGroup);
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.unsynchroGroup()",
"root.MSG_GEN_ENTER_METHOD", "GroupId=" + idGroup);
String idRet = m_AdminCtrl.synchronizeRemoveGroup(idGroup);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.unsynchroGroup()",
SilverpeasException.ERROR, "admin.EX_ERR_DELETE_GROUP");
}
removeGroupFromPath(idGroup);
refresh();
return haveToRefreshDomain;
}
public boolean importGroup(String groupName) throws JobDomainPeasException {
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.importGroup()",
"root.MSG_GEN_ENTER_METHOD", "groupName=" + groupName);
String idRet = m_AdminCtrl.synchronizeImportGroup(m_TargetDomainId,
groupName);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.importGroup()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_GROUP");
}
refresh();
return isGroupRoot(idRet);
}
/*
* DOMAIN functions
*/
public void setDefaultTargetDomain() {
UserDetail ud = getUserDetail();
if (ud.isDomainAdminRestricted()) {
setTargetDomain(ud.getDomainId());
}
}
public void setTargetDomain(String domainId) {
if (!StringUtil.isDefined(domainId)) {
m_TargetDomain = null;
m_TargetDomainId = "";
} else {
List<String> manageableGroupIds = null;
if (isOnlyGroupManager()) {
manageableGroupIds = getUserManageableGroupIds();
}
m_TargetDomain = new DomainNavigationStock(domainId, m_AdminCtrl, manageableGroupIds);
m_TargetDomainId = domainId;
}
}
public Domain getTargetDomain() {
if (m_TargetDomain == null) {
return null;
}
return m_TargetDomain.getThisDomain();
}
public long getDomainActions() {
if (m_TargetDomainId.length() > 0) {
return m_AdminCtrl.getDomainActions(m_TargetDomainId);
}
return 0;
}
public String[][] getAllDomains() {
String[][] valret = null;
UserDetail ud = getUserDetail();
if (ud.isAccessDomainManager()) {
Domain userDomain = m_AdminCtrl.getDomain(ud.getDomainId());
valret = new String[1][3];
valret[0][0] = ud.getDomainId();
valret[0][1] = EncodeHelper.javaStringToHtmlString(userDomain.getName());
if (m_TargetDomainId.equals(userDomain.getId())) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
} else if (ud.isAccessAdmin()) {
Domain[] allDomains = m_AdminCtrl.getAllDomains();
valret = new String[allDomains.length + 1][3];
// Domaine mixte
valret[0][0] = "-1";
valret[0][1] = getString("JDP.domainMixt");
if (m_TargetDomainId.equals("-1")) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
// Tous les domaines
for (int i = 1; i < valret.length; i++) {
valret[i][0] = allDomains[i - 1].getId();
valret[i][1] = EncodeHelper.javaStringToHtmlString(allDomains[i - 1].getName());
if (m_TargetDomainId.equals(allDomains[i - 1].getId())) {
valret[i][2] = "selected";
} else {
valret[i][2] = "";
}
}
} else if (isOnlyGroupManager()) {
// Domaine mixte
valret = new String[2][3];
valret[0][0] = "-1";
valret[0][1] = getString("JDP.domainMixt");
if (m_TargetDomainId.equals("-1")) {
valret[0][2] = "selected";
} else {
valret[0][2] = "";
}
// Domaine de l'utilisateur
Domain userDomain = m_AdminCtrl.getDomain(ud.getDomainId());
valret[1][0] = userDomain.getId();
valret[1][1] = EncodeHelper.javaStringToHtmlString(userDomain.getName());
if (m_TargetDomainId.equals(userDomain.getId())) {
valret[1][2] = "selected";
} else {
valret[1][2] = "";
}
}
return valret;
}
public boolean isOnlyGroupManager() {
return isGroupManager() && !getUserDetail().isAccessAdmin()
&& !getUserDetail().isAccessDomainManager();
}
public boolean isGroupManagerOnCurrentGroup() throws JobDomainPeasException {
if (getTargetGroup() != null) {
return isGroupManagerOnGroup(getTargetGroup().getId());
}
return false;
}
public boolean isGroupManagerOnGroup(String groupId)
throws JobDomainPeasException {
List<String> manageableGroupIds = getUserManageableGroupIds();
if (manageableGroupIds.contains(groupId)) {
// Current user is directly manager of group
return true;
} else {
List<String> groupPath = m_AdminCtrl.getPathToGroup(groupId);
groupPath.retainAll(manageableGroupIds);
if (groupPath.size() > 0) {
// Current user is at least manager of one super group of group
return true;
}
}
return false;
}
public boolean isGroupManagerDirectlyOnCurrentGroup()
throws JobDomainPeasException {
List<String> manageableGroupIds = getUserManageableGroupIds();
return manageableGroupIds.contains(getTargetGroup().getId());
}
public Group[] getAllRootGroups() {
if (m_TargetDomainId.length() <= 0) {
return new Group[0];
}
Group[] selGroupsArray = m_TargetDomain.getAllGroupPage();
if (isOnlyGroupManager()) {
selGroupsArray = filterGroupsToGroupManager(selGroupsArray);
}
JobDomainSettings.sortGroups(selGroupsArray);
return selGroupsArray;
}
private Group[] filterGroupsToGroupManager(Group[] groups) {
// get all manageable groups by current user
List<String> manageableGroupIds = getUserManageableGroupIds();
Iterator<String> itManageableGroupsIds = null;
List<Group> temp = new ArrayList<Group>();
// filter groups
Group group = null;
for (int g = 0; g < groups.length; g++) {
group = groups[g];
if (manageableGroupIds.contains(group.getId())) {
temp.add(group);
} else {
// get all subGroups of group
List<String> subGroupIds = Arrays.asList(m_AdminCtrl.getAllSubGroupIdsRecursively(group.
getId()));
// check if at least one manageable group is part of subGroupIds
itManageableGroupsIds = manageableGroupIds.iterator();
String manageableGroupId = null;
boolean find = false;
while (!find && itManageableGroupsIds.hasNext()) {
manageableGroupId = itManageableGroupsIds.next();
if (subGroupIds.contains(manageableGroupId)) {
find = true;
}
}
if (find) {
temp.add(group);
}
}
}
return temp.toArray(new Group[temp.size()]);
}
public String createDomain(String domainName, String domainDescription, String domainDriver,
String domainProperties, String domainAuthentication, String silverpeasServerURL,
String domainTimeStamp) throws JobDomainPeasException, JobDomainPeasTrappedException {
// Vérif domainName
verifCreateDomain(domainName, false);
Domain theNewDomain = new Domain();
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setId("-1");
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName(domainDriver);
theNewDomain.setPropFileName(domainProperties);
theNewDomain.setAuthenticationServer(domainAuthentication);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp(domainTimeStamp);
String idRet = m_AdminCtrl.addDomain(theNewDomain);
if (!StringUtil.isDefined(idRet)) {
throw new JobDomainPeasException("JobDomainPeasSessionController.createDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN");
}
refresh();
return idRet;
}
private void verifCreateDomain(String domainName, boolean domainSql)
throws JobDomainPeasTrappedException {
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
if (domainSql) {
trappedException.setGoBackPage("displayDomainSQLCreate");
} else {
trappedException.setGoBackPage("displayDomainCreate");
}
// 1-Vérif non présence d'espaces
int indexOfSpace = domainName.indexOf(" ");
if (indexOfSpace > -1) {
throw trappedException;
}
// 2-Vérif caractères alphanumériques
int i = 0;
char car;
while (i < domainName.length()) {
car = domainName.charAt(i);
if (!Character.isLetterOrDigit(car)) {
throw trappedException;
}
i++;
}
// 3-Vérif domainName unique dans la table ST_Domain
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
if (domainSql) {
// 4-Vérif domainName unique dans le fileSystem
// pour les properties
// com.stratelia.silverpeas.domains.domain<domainName>.properties
// et
// com.stratelia.silverpeas.authentication.autDomain<domainName>.properties
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
StringBuilder cheminFichierDomain = new StringBuilder(pathInitialize.substring(0,
indexOfInitialize));
cheminFichierDomain.append("properties").append(File.separator).append("com").append(
File.separator).append("stratelia").append(File.separator).append("silverpeas").append(
File.separator).append("domains");
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain.toString());
File fileDomain = new File(directoryDomain, nomFichierDomain);
if (fileDomain.exists()) {
throw trappedException;
}
StringBuilder cheminFichierAutDomain = new StringBuilder(pathInitialize.substring(0,
indexOfInitialize));
cheminFichierAutDomain.append("properties").append(File.separator).append("com").append(
File.separator).append("stratelia").append(File.separator).append("silverpeas").append(
File.separator).append("authentication");
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain.toString());
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
if (fileAutDomain.exists()) {
throw trappedException;
}
}
}
public String createSQLDomain(String domainName, String domainDescription,
String silverpeasServerURL) throws JobDomainPeasException, JobDomainPeasTrappedException {
// 0- Vérif domainName
verifCreateDomain(domainName, true);
// 1-Création sur le fileSystem du properties
// com.stratelia.silverpeas.domains.domain<domainName>
SilverTrace.info("jobDomainPeas", "JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création sur le fileSystem du properties com.stratelia.silverpeas.domains.domain<domainName>");
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
String cheminFichierDomain = pathInitialize.substring(0, indexOfInitialize)
+ "properties" + File.separator + "com" + File.separator + "stratelia"
+ File.separator + "silverpeas" + File.separator + "domains";
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain);
File fileDomain = new File(directoryDomain, nomFichierDomain);
PrintWriter sortie = null;
try {
sortie = new PrintWriter(new FileWriter(fileDomain));
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException("JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
// properties templateDomainSQL
ResourceLocator templateDomainSql = new ResourceLocator(
"com.stratelia.silverpeas.domains.templateDomainSQL", "");
String cryptMethod = SilverpeasSettings.readString(templateDomainSql,
"database.SQLPasswordEncryption", Authentication.ENC_TYPE_MD5);
boolean allowPasswordChange = SilverpeasSettings.readBoolean(
templateDomainSql, "allowPasswordChange", true);
BufferedReader readerTemplateDomainSQL = null;
try {
String cheminFichierTemplateDomainSQL = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator
+ "silverpeas"
+ File.separator
+ "domains" + File.separator + "templateDomainSQL.properties";
File fileTemplateDomainSQL = new File(cheminFichierTemplateDomainSQL);
readerTemplateDomainSQL = new BufferedReader(new FileReader(
fileTemplateDomainSQL));
} catch (FileNotFoundException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
String currentLine;
sortie.println("# SQL driver");
sortie.println("");
sortie.println("# DataBase Access");
sortie.println("# ----------------");
sortie.println("");
ResourceLocator propAdmin = new ResourceLocator(
"com.stratelia.webactiv.beans.admin.admin", "");
sortie.println("database.SQLClassName = "
+ propAdmin.getString("AdminDBDriver"));
sortie.println("database.SQLJDBCUrl = "
+ propAdmin.getString("WaProductionDb"));
sortie.println("database.SQLAccessLogin = "
+ propAdmin.getString("WaProductionUser"));
sortie.println("database.SQLAccessPasswd = "
+ propAdmin.getString("WaProductionPswd"));
sortie.println("");
sortie.println("database.SQLUserTableName = Domain" + domainName
+ "_User");
sortie.println("database.SQLGroupTableName = Domain" + domainName
+ "_Group");
sortie.println("database.SQLUserGroupTableName = Domain" + domainName
+ "_Group_User_Rel");
sortie.println("");
sortie.println("# Generic Properties");
sortie.println("# ----------------");
sortie.println("");
sortie.println("# For Users");
sortie.println("database.SQLUserSpecificIdColumnName = id");
sortie.println("database.SQLUserLoginColumnName = login");
sortie.println("database.SQLUserFirstNameColumnName = firstName");
sortie.println("database.SQLUserLastNameColumnName = lastName");
sortie.println("database.SQLUserEMailColumnName = email");
sortie.println("database.SQLUserPasswordColumnName = password");
sortie.println("database.SQLUserPasswordValidColumnName = passwordValid");
sortie.println("");
sortie.println("# For Groups");
sortie.println("database.SQLGroupSpecificIdColumnName = id");
sortie.println("database.SQLGroupNameColumnName = name");
sortie.println("database.SQLGroupDescriptionColumnName = description");
sortie.println("database.SQLGroupParentIdColumnName = superGroupId");
sortie.println("");
sortie.println("# For Users-Groups relations");
sortie.println("database.SQLUserGroupUIDColumnName = userId");
sortie.println("database.SQLUserGroupGIDColumnName = groupId");
sortie.println("");
try {
while ((currentLine = readerTemplateDomainSQL.readLine()) != null) {
if (!currentLine.startsWith("allowPasswordChange")) {
sortie.println(currentLine);
}
}
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
sortie.close();
// 2-Création sur le fileSystem du properties
// com.stratelia.silverpeas.authentication.autDomain<domainName>
SilverTrace.info(
"jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création sur le fileSystem du properties com.stratelia.silverpeas.authentication.autDomain<domainName>");
String cheminFichierAutDomain = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator + "silverpeas" + File.separator + "authentication";
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain);
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
try {
sortie = new PrintWriter(new FileWriter(fileAutDomain));
} catch (IOException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
sortie.println("# Silverpeas default driver authentication");
sortie.println("# ----------------------------------------");
sortie.println("");
sortie.println(
"# Fallback type : could be one of the following values : none, ifNotRejected, always");
sortie.println("fallbackType = none");
sortie.println("");
sortie.println("allowPasswordChange = " + allowPasswordChange);
sortie.println("");
sortie.println("# Authentication servers");
sortie.println(
"# Available types are : com.stratelia.silverpeas.authentication.AuthenticationNT, com.stratelia.silverpeas.authentication.AuthenticationSQL and com.stratelia.silverpeas.authentication.AuthenticationLDAP");
sortie.println("");
sortie.println("autServersCount = 1");
sortie.println("");
sortie.println(
"autServer0.type = com.stratelia.silverpeas.authentication.AuthenticationSQL");
sortie.println("autServer0.enabled = true");
sortie.println("autServer0.SQLJDBCUrl = "
+ propAdmin.getString("WaProductionDb"));
sortie.println("autServer0.SQLAccessLogin = "
+ propAdmin.getString("WaProductionUser"));
sortie.println("autServer0.SQLAccessPasswd = "
+ propAdmin.getString("WaProductionPswd"));
sortie.println("autServer0.SQLDriverClass = "
+ propAdmin.getString("AdminDBDriver"));
sortie.println("autServer0.SQLUserTableName = Domain" + domainName
+ "_User");
sortie.println("autServer0.SQLUserLoginColumnName = login");
sortie.println("autServer0.SQLUserPasswordColumnName = password");
sortie.println("autServer0.SQLUserPasswordAvailableColumnName = passwordValid");
sortie.println("autServer0.SQLPasswordEncryption = " + cryptMethod);
sortie.close();
// 3-Création en base de données des 3 nouvelles tables du domaine :
// Domain<domainName>_Group, Domain<domainName>_Group_User_Rel et
// Domain<domainName>_User
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Création en base de données des 3 tablse du Domain");
try {
JobDomainPeasDAO.createTableDomain_Group(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
try {
JobDomainPeasDAO.createTableDomain_User(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
try {
JobDomainPeasDAO.createTableDomain_Group_User_Rel(domainName);
} catch (SQLException e) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e);
}
// 4-Enregistrement en base de données du nouveau Domaine dans ST_Domain
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.createSQLDomain()",
"root.MSG_GEN_ENTER_METHOD",
"Insertion d'une entrée dans la table ST_Domain");
Domain theNewDomain = new Domain();
String idRet = null;
theNewDomain.setId("-1");
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName("com.stratelia.silverpeas.domains.sqldriver.SQLDriver");
theNewDomain.setPropFileName("com.stratelia.silverpeas.domains.domain"
+ domainName);
theNewDomain.setAuthenticationServer("autDomain" + domainName);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp("0");
idRet = m_AdminCtrl.addDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
// suppression du fichier domain<domainName>.properties
fileDomain.delete();
// suppression du fichier domain<domainName>.properties
fileAutDomain.delete();
// suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
// suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN", e1);
}
throw new JobDomainPeasException(
"JobDomainPeasSessionController.createSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_ADD_DOMAIN");
}
return idRet;
}
public String modifyDomain(String domainName, String domainDescription,
String domainDriver, String domainProperties,
String domainAuthentication, String silverpeasServerURL,
String domainTimeStamp) throws JobDomainPeasException,
JobDomainPeasTrappedException {
Domain theNewDomain = getTargetDomain();
// Vérif domainName unique dans la table ST_Domain
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
trappedException.setGoBackPage("domainContent");
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (!domain.getId().equals(theNewDomain.getId())
&& domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
String idRet = null;
if (!StringUtil.isDefined(m_TargetDomainId)
|| m_TargetDomainId.equals("-1")) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifyDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setDriverClassName(domainDriver);
theNewDomain.setPropFileName(domainProperties);
theNewDomain.setAuthenticationServer(domainAuthentication);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
theNewDomain.setTheTimeStamp(domainTimeStamp);
idRet = m_AdminCtrl.updateDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifyDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
refresh();
return idRet;
}
public String modifySQLDomain(String domainName, String domainDescription,
String silverpeasServerURL) throws JobDomainPeasException,
JobDomainPeasTrappedException {
Domain theNewDomain = getTargetDomain();
// Vérif domainName unique dans la table ST_Domain
JobDomainPeasTrappedException trappedException = new JobDomainPeasTrappedException(
"JobDomainPeasSessionController", SilverpeasException.WARNING,
"jobDomainPeas.WARN_DOMAIN_SQL_NAME");
trappedException.setGoBackPage("domainContent");
Domain[] tabDomain = m_AdminCtrl.getAllDomains();
Domain domain;
for (int j = 0; j < tabDomain.length; j++) {
domain = tabDomain[j];
if (!domain.getId().equals(theNewDomain.getId())
&& domain.getName().toLowerCase().equals(domainName.toLowerCase())) {
throw trappedException;
}
}
String idRet = null;
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySQLDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.modifySQLDomain()",
"root.MSG_GEN_ENTER_METHOD", "domainName=" + domainName);
theNewDomain.setName(domainName);
theNewDomain.setDescription(domainDescription);
theNewDomain.setSilverpeasServerURL(silverpeasServerURL);
idRet = m_AdminCtrl.updateDomain(theNewDomain);
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.modifySQLDomain()",
SilverpeasException.ERROR, "admin.EX_ERR_UPDATE_DOMAIN");
}
refresh();
return idRet;
}
public void deleteDomain() throws JobDomainPeasException {
String idRet = null;
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
idRet = m_AdminCtrl.removeDomain(getTargetDomain().getId());
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
returnIntoGroup(null);
m_TargetDomain = null;
}
public void deleteSQLDomain() throws JobDomainPeasException {
String cheminProperties = getTargetDomain().getPropFileName();
String domainName = cheminProperties.substring(39);
// 1-Suppression en base de données du Domaine dans ST_Domain
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.equals("0")) || (m_TargetDomainId.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
String idRet = m_AdminCtrl.removeDomain(getTargetDomain().getId());
if ((idRet == null) || (idRet.length() <= 0)) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN");
}
returnIntoGroup(null);
m_TargetDomain = null;
// 2-Suppresion de la table Domain<domainName>_Group
try {
JobDomainPeasDAO.dropTableDomain_Group(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 3-Suppresion de la table Domain<domainName>_User
try {
JobDomainPeasDAO.dropTableDomain_User(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 4-Suppresion de la table Domain<domainName>_Group_User_Rel
try {
JobDomainPeasDAO.dropTableDomain_Group_User_Rel(domainName);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.deleteSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_DELETE_DOMAIN", e1);
}
// 5-Suppression du fichier domain<domainName>.properties
ResourceLocator propInitialize = new ResourceLocator(
"com.stratelia.silverpeas._silverpeasinitialize.settings._silverpeasinitializeSettings",
"");
String pathInitialize = propInitialize.getString("pathInitialize");
int indexOfInitialize = pathInitialize.indexOf("initialize");
String cheminFichierDomain = pathInitialize.substring(0, indexOfInitialize)
+ "properties" + File.separator + "com" + File.separator + "stratelia"
+ File.separator + "silverpeas" + File.separator + "domains";
String nomFichierDomain = "domain" + domainName + ".properties";
File directoryDomain = new File(cheminFichierDomain);
File fileDomain = new File(directoryDomain, nomFichierDomain);
fileDomain.delete();
// 6-Suppression du fichier domain<domainName>.properties
String cheminFichierAutDomain = pathInitialize.substring(0,
indexOfInitialize)
+ "properties"
+ File.separator
+ "com"
+ File.separator
+ "stratelia"
+ File.separator + "silverpeas" + File.separator + "authentication";
String nomFichierAutDomain = "autDomain" + domainName + ".properties";
File directoryAutDomain = new File(cheminFichierAutDomain);
File fileAutDomain = new File(directoryAutDomain, nomFichierAutDomain);
fileAutDomain.delete();
}
protected String getSureString(String s) {
if (s == null) {
return "";
} else {
return s;
}
}
public void refresh() {
if (m_TargetDomain != null) {
m_TargetDomain.refresh();
}
for (int i = 0; i < m_GroupsPath.size(); i++) {
m_GroupsPath.get(i).refresh();
}
setTargetUser(null);
}
/*
* Selection Peas functions
*/
public String initSelectionPeasForGroups(String compoURL)
throws JobDomainPeasException {
String hostSpaceName = getString("JDP.userPanelGroup");
PairObject hostComponentName = new PairObject(getTargetGroup().getName(),
compoURL + "groupContent");
PairObject[] hostPath = new PairObject[0];
String hostUrl = compoURL + "groupAddRemoveUsers";
String cancelUrl = compoURL + "groupContent";
Selection sel = getSelection();
sel.resetAll();
sel.setHostSpaceName(hostSpaceName);
sel.setHostPath(hostPath);
sel.setHostComponentName(hostComponentName);
sel.setGoBackURL(hostUrl);
sel.setCancelURL(cancelUrl);
if ((m_TargetDomainId != null) && (!m_TargetDomainId.equals("-1"))
&& (m_TargetDomainId.length() > 0)) {
// Add extra params
SelectionUsersGroups sug = new SelectionUsersGroups();
sug.setDomainId(m_TargetDomainId);
sel.setExtraParams(sug);
}
sel.setSelectedElements(SelectionUsersGroups.getUserIds(m_GroupsPath.lastElement().
getAllUserPage()));
// Contraintes
sel.setSetSelectable(false);
sel.setPopupMode(false);
sel.setFirstPage(Selection.FIRST_PAGE_CART);
return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
}
/*
* Appel UserPannel pour récup du user sélectionné :
*/
public String[] getSelectedUsersIds() {
return getSelection().getSelectedElements();
}
// Throws Specific Exception
public String initSelectionPeasForOneGroupOrUser(String compoURL)
throws JobDomainPeasException {
String hostSpaceName = getString("JDP.userPanelDomain");
PairObject hostComponentName = new PairObject(getTargetDomain().getName(),
compoURL + "domainContent");
PairObject[] hostPath = new PairObject[0];
String hostUrl = compoURL + "selectUserOrGroup";
String cancelUrl = compoURL + "domainContent";
Selection sel = getSelection();
sel.resetAll();
sel.setHostSpaceName(hostSpaceName);
sel.setHostPath(hostPath);
sel.setHostComponentName(hostComponentName);
sel.setGoBackURL(hostUrl);
sel.setCancelURL(cancelUrl);
if ((m_TargetDomainId == null) || (m_TargetDomainId.equals("-1"))
|| (m_TargetDomainId.length() <= 0)) {
sel.setElementSelectable(false);
}
// Add extra params
SelectionUsersGroups sug = new SelectionUsersGroups();
sug.setDomainId(m_TargetDomainId);
sel.setExtraParams(sug);
// Contraintes
sel.setMultiSelect(false);
sel.setPopupMode(false);
sel.setFirstPage(Selection.FIRST_PAGE_BROWSE);
return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
}
public String getSelectedUserId() {
return getSelection().getFirstSelectedElement();
}
public String getSelectedGroupId() {
return getSelection().getFirstSelectedSet();
}
// Synchro Management
// ------------------
public void synchroSQLDomain() {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO SQL DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
if (m_theThread == null) {
SynchroReport.setTraceLevel(SynchroReport.TRACE_LEVEL_INFO);
SynchroReport.setState(SynchroReport.STATE_WAITSTART);
m_theThread = new SynchroWebServiceThread(this);
m_ErrorOccured = null;
m_SynchroReport = "";
m_theThread.startTheThread();
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------THREAD SYNCHRO SQL DOMAIN LANCE-----------");
} else {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------!!!! SYNCHRO DOMAIN SQL : DEUXIEME APPEL !!!!!-----------");
}
}
protected String synchronizeSilverpeasViaWebService() {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroSQLDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO SQL DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
String sReport = "";
SynchroUserWebServiceItf synchroUserWebService = null;
try {
sReport = "Démarrage de la synchronisation...\n\n";
// Démarrage de la synchro avec la Popup d'affichage
SynchroReport.startSynchro();
Domain theDomain = getTargetDomain();
SynchroReport.warn("jobDomainPeas.synchronizeSilverpeasViaWebService",
"Domaine : " + theDomain.getName() + " (id : " + theDomain.getId()
+ ")", null);
// 1- Récupère la liste des groupes à synchroniser (en insert et
// update)
Collection<Group> listGroupToInsertUpdate;
try {
listGroupToInsertUpdate = JobDomainPeasDAO.selectGroupSynchroInsertUpdateTableDomain_Group(
theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 2- Traitement Domaine, appel aux webServices
String propDomainFileName = theDomain.getPropFileName();
ResourceLocator propDomainSql = new ResourceLocator(propDomainFileName,
"");
String nomClasseWebService = propDomainSql.getString("ExternalSynchroClass");
try {
synchroUserWebService = (SynchroUserWebServiceItf) Class.forName(
nomClasseWebService).newInstance();
} catch (Exception e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e);
}
synchroUserWebService.startConnection();
// Insertion / Update de la société
sReport += synchroUserWebService.insertUpdateDomainWebService(theDomain.getId(), theDomain.
getName());
// 3- Traitement groupes, appel aux webServices
if (listGroupToInsertUpdate != null && listGroupToInsertUpdate.size() > 0) {
// Insertion / Update des groupes
sReport += synchroUserWebService.insertUpdateListGroupWebService(
theDomain.getId(), theDomain.getName(), listGroupToInsertUpdate);
// Suppression des groupes
/*
* Collection listGroupSilverpeas = Arrays.asList(m_AdminCtrl.getAllGroupIds()); sReport +=
* synchroUserWebService.deleteListGroupWebService(theDomain.getId(), listGroupSilverpeas);
*/
}
// 4- Récupère la liste des users à synchroniser (en insert et update)
Collection<UserFull> listUserToInsertUpdate;
try {
listUserToInsertUpdate = JobDomainPeasDAO.selectUserSynchroInsertUpdateTableDomain_User(
theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 5- Récupère la liste des users à synchroniser (en delete)
Collection<UserDetail> listUserToDelete;
try {
listUserToDelete = JobDomainPeasDAO.selectUserSynchroDeleteTableDomain_User(theDomain);
} catch (SQLException e1) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.synchroSQLDomain()",
SilverpeasException.ERROR, "admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e1);
}
// 6-Traitement users, appel aux webServices
if ((listUserToInsertUpdate != null && listUserToInsertUpdate.size() > 0)
|| (listUserToDelete != null && listUserToDelete.size() > 0)) {
// CBO : UPDATE 09.04.2008
/*
* //Insertion / Update des users if(listUserToInsertUpdate != null &&
* listUserToInsertUpdate.size()>0) { sReport +=
* synchroUserWebService.insertUpdateListUserWebService (theDomain.getId(),
* listUserToInsertUpdate, listGroupToInsertUpdate); } //Suppression des users
* if(listUserToDelete != null && listUserToDelete.size()>0) { sReport +=
* synchroUserWebService.deleteListUserWebService(theDomain.getId(), listUserToDelete); }
*/
// Suppression des users
if (listUserToDelete != null && listUserToDelete.size() > 0) {
sReport += synchroUserWebService.deleteListUserWebService(theDomain.getId(),
listUserToDelete);
}
// Insertion / Update des users
if (listUserToInsertUpdate != null && listUserToInsertUpdate.size() > 0) {
sReport += synchroUserWebService.insertUpdateListUserWebService(
theDomain.getId(), listUserToInsertUpdate,
listGroupToInsertUpdate);
}
// CBO : FIN UPDATE 09.04.2008
}
sReport += "\n\nFin de la synchronisation...";
} catch (JobDomainPeasException e) {
SilverTrace.error("JobDomainPeasSessionController",
"JobDomainPeasSessionController.synchronizeSilverpeasViaWebService",
"admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e);
SynchroReport.error(
"JobDomainPeasSessionController.synchronizeSilverpeasViaWebService",
"Problème lors de la synchronisation : " + e.getMessage(), null);
sReport = "Erreurs lors de la synchronisation : \n" + e.getMessage();
} finally {
// Fin de synchro avec la Popup d'affichage
SynchroReport.stopSynchro();
synchroUserWebService.endConnection();
}
return sReport;
}
public void synchroDomain(int traceLevel) {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------SYNCHRO DOMAIN APPELE----------- domainId="
+ m_TargetDomainId);
if (m_theThread == null) {
SynchroReport.setTraceLevel(traceLevel);
SynchroReport.setState(SynchroReport.STATE_WAITSTART);
m_theThread = new SynchroLdapThread(this, m_AdminCtrl, m_TargetDomainId);
m_ErrorOccured = null;
m_SynchroReport = "";
m_theThread.startTheThread();
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------THREAD SYNCHRO DOMAIN LANCE-----------");
} else {
SilverTrace.info("jobDomainPeas",
"JobDomainPeasSessionController.synchroDomain()",
"root.MSG_GEN_PARAM_VALUE",
"------------!!!! SYNCHRO DOMAIN : DEUXIEME APPEL !!!!!-----------");
}
}
public boolean isEnCours() {
if (m_theThread == null) {
return false;
} else {
return m_theThread.isEnCours();
}
}
public Exception getErrorOccured() {
return m_ErrorOccured;
}
public String getSynchroReport() {
if (m_ErrorOccured != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
m_ErrorOccured.printStackTrace(pw);
return m_ErrorOccured.toString() + "\n" + sw.getBuffer().toString();
} else {
return m_SynchroReport;
}
}
public void threadFinished() {
m_ErrorOccured = m_theThread.getErrorOccured();
m_SynchroReport = m_theThread.getSynchroReport();
m_theThread = null;
}
public void getP12(String userId) throws JobDomainPeasException {
UserDetail user = getUserDetail(userId);
try {
X509Factory.buildP12(user.getId(), user.getLogin(), user.getLastName(),
user.getFirstName(), user.getDomainId());
} catch (UtilException e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.getP12()", SilverpeasException.ERROR,
"admin.MSG_ERR_CANT_GET_P12", e);
}
}
private void revocateCertificate(UserDetail user)
throws JobDomainPeasException {
try {
X509Factory.revocateUserCertificate(user.getId());
} catch (UtilException e) {
throw new JobDomainPeasException(
"JobDomainPeasSessionController.revocateCertificate()",
SilverpeasException.ERROR, "admin.MSG_ERR_CANT_REVOCATE_CERTIFICATE",
e);
}
}
/** PAGINATION **/
/**
* Get list of selected users Ids
*/
public ArrayList<String> getListSelectedUsers() {
SilverTrace.info("jobDomainPeas","JobDomainPeasSessionController.getListUsersSelected()", "",
"listSelectedUsers (taille) = (" + listSelectedUsers.size() + ") "
+ listSelectedUsers.toString());
return listSelectedUsers;
}
public void clearListSelectedUsers() {
listSelectedUsers.clear();
}
public void setListSelectedUsers(ArrayList<String> list) {
listSelectedUsers = list;
SilverTrace.info("jobDomainPeas","JobDomainPeasSessionController.setListSelectedUsers()", "",
"listSelectedUsers (taille) = (" + listSelectedUsers.size() + ") "
+ listSelectedUsers.toString());
}
public void setIndexOfFirstItemToDisplay(String index) {
this.indexOfFirstItemToDisplay = Integer.parseInt(index);
}
public int getIndexOfFirstItemToDisplay() {
return indexOfFirstItemToDisplay;
}
public List<Group> getUserManageableGroups() {
List<Group> groups = new ArrayList<Group>();
List<String> groupIds = getUserManageableGroupIds();
Group[] aGroups = getOrganizationController().getGroups(groupIds.toArray(new String[groupIds.
size()]));
groups = Arrays.asList(aGroups);
return groups;
}
public UserDetail checkUser(UserDetail userToCheck) {
UserDetail existingUser = null;
UserDetail[] existingUsers = m_TargetDomain.getAllUserPage();
for (int i = 0; i < existingUsers.length; i++) {
existingUser = existingUsers[i];
if (userToCheck.getLastName().equalsIgnoreCase(existingUser.getLastName())
&& userToCheck.getFirstName().equalsIgnoreCase(existingUser.getFirstName())
&& userToCheck.geteMail().equalsIgnoreCase(existingUser.geteMail())) {
return existingUser;
}
}
return null;
}
/**
* @return true if community management is activated and target user belongs to one group
* manageable by current user
*/
public boolean isUserInAtLeastOneGroupManageableByCurrentUser() {
if (!JobDomainSettings.m_UseCommunityManagement) {
return false;
}
List<String> groupIds = getUserManageableGroupIds();
for (Iterator<String> iterator = groupIds.iterator(); iterator.hasNext();) {
String groupId = iterator.next();
UserDetail[] users = getOrganizationController().getAllUsersOfGroup(groupId);
UserDetail user = getUser(m_TargetUserId, users);
if (user != null) {
return true;
}
}
return false;
}
private UserDetail getUser(String userId, UserDetail[] users) {
for (UserDetail userDetail : users) {
if (userId.equals(userDetail.getId())) {
return userDetail;
}
}
return null;
}
} | Updating the login max size limitation to 50
| web-core/src/main/java/com/silverpeas/jobDomainPeas/control/JobDomainPeasSessionController.java | Updating the login max size limitation to 50 | <ide><path>eb-core/src/main/java/com/silverpeas/jobDomainPeas/control/JobDomainPeasSessionController.java
<ide>
<ide> return accessGranted;
<ide> }
<del>
<add>
<ide> public void setRefreshDomain(boolean refreshDomain) {
<ide> this.refreshDomain = refreshDomain;
<ide> }
<ide> * @param filePart
<ide> * @throws UtilTrappedException
<ide> * @throws JobDomainPeasTrappedException
<del> * @throws JobDomainPeasException
<add> * @throws JobDomainPeasException
<ide> */
<ide> public void importCsvUsers(FileItem filePart) throws UtilTrappedException,
<ide> JobDomainPeasTrappedException, JobDomainPeasException {
<ide> listErrors.append(getString("JDP.nbCarMin")).append(" ").append(
<ide> JobDomainSettings.m_MinLengthLogin).append(" ").append(getString("JDP.caracteres")).
<ide> append("<br/>");
<del> } else if (login.length() > 20) {// verifier 20 char max
<add> } else if (login.length() > 50) {// verifier 20 char max
<ide> listErrors.append(getErrorMessage(i+1, 3, login));
<del> listErrors.append(getString("JDP.nbCarMax")).append(" 20 ").append(getString(
<add> listErrors.append(getString("JDP.nbCarMax")).append(" 50 ").append(getString(
<ide> "JDP.caracteres")).append("<br/>");
<ide> } else {// verif login unique
<ide> existingLogin = m_AdminCtrl.getUserIdByLoginAndDomain(login,
<ide> properties, null); // l'id User créé est dans m_TargetUserId
<ide> }
<ide> }
<del>
<add>
<ide> private String getErrorMessage(int line, int column, String value) {
<ide> StringBuilder str = new StringBuilder();
<ide> str.append(getString("JDP.ligne")).append(" = ").append(line).append(", ");
<ide> refresh();
<ide> setTargetUser(idRet);
<ide> }
<del>
<add>
<ide> public void modifyUserFull(String idUser, String userAccessLevel,
<ide> HashMap<String, String> properties)
<ide> throws JobDomainPeasException { |
|
Java | apache-2.0 | a4b428323b699460ccd67a079a938a7d4a4b4fde | 0 | strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.reindex;
import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.test.junit.annotations.TestLogging;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.elasticsearch.action.DocWriteRequest.OpType.CREATE;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
/**
* Tests failure capturing and abort-on-failure behavior of reindex.
*/
@TestLogging("_root:DEBUG")
public class ReindexFailureTests extends ReindexTestCase {
public void testFailuresCauseAbortDefault() throws Exception {
/*
* Create the destination index such that the copy will cause a mapping
* conflict on every request.
*/
indexRandom(true,
client().prepareIndex("dest", "test", "test").setSource("test", 10) /* Its a string in the source! */);
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest");
/*
* Set the search size to something very small to cause there to be
* multiple batches for this request so we can assert that we abort on
* the first batch.
*/
copy.source().setSize(1);
BulkByScrollResponse response = copy.get();
assertThat(response, matcher()
.batches(1)
.failures(both(greaterThan(0)).and(lessThanOrEqualTo(maximumNumberOfShards()))));
for (Failure failure: response.getBulkFailures()) {
assertThat(failure.getMessage(), containsString("IllegalArgumentException[For input string: \"words words\"]"));
}
}
public void testAbortOnVersionConflict() throws Exception {
// Just put something in the way of the copy.
indexRandom(true,
client().prepareIndex("dest", "test", "1").setSource("test", "test"));
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest").abortOnVersionConflict(true);
// CREATE will cause the conflict to prevent the write.
copy.destination().setOpType(CREATE);
BulkByScrollResponse response = copy.get();
assertThat(response, matcher().batches(1).versionConflicts(1).failures(1).created(99));
for (Failure failure: response.getBulkFailures()) {
assertThat(failure.getMessage(), containsString("VersionConflictEngineException[[test]["));
}
}
/**
* Make sure that search failures get pushed back to the user as failures of
* the whole process. We do lose some information about how far along the
* process got, but its important that they see these failures.
*/
public void testResponseOnSearchFailure() throws Exception {
/*
* Attempt to trigger a reindex failure by deleting the source index out
* from under it.
*/
int attempt = 1;
while (attempt < 5) {
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest");
copy.source().setSize(10);
Future<BulkByScrollResponse> response = copy.execute();
client().admin().indices().prepareDelete("source").get();
try {
response.get();
logger.info("Didn't trigger a reindex failure on the {} attempt", attempt);
attempt++;
/*
* In the past we've seen the delete of the source index
* actually take effect *during* the `indexDocs` call in
* the next step. This breaks things pretty disasterously
* so we *try* and wait for the delete to be fully
* complete here.
*/
assertBusy(() -> assertFalse(client().admin().indices().prepareExists("source").get().isExists()));
} catch (ExecutionException e) {
logger.info("Triggered a reindex failure on the {} attempt: {}", attempt, e.getMessage());
assertThat(e.getMessage(),
either(containsString("all shards failed"))
.or(containsString("No search context found"))
.or(containsString("no such index"))
);
return;
}
}
assumeFalse("Wasn't able to trigger a reindex failure in " + attempt + " attempts.", true);
}
private void indexDocs(int count) throws Exception {
List<IndexRequestBuilder> docs = new ArrayList<IndexRequestBuilder>(count);
for (int i = 0; i < count; i++) {
docs.add(client().prepareIndex("source", "test", Integer.toString(i)).setSource("test", "words words"));
}
indexRandom(true, docs);
}
}
| modules/reindex/src/test/java/org/elasticsearch/index/reindex/ReindexFailureTests.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.reindex;
import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.test.junit.annotations.TestLogging;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.elasticsearch.action.DocWriteRequest.OpType.CREATE;
import static org.hamcrest.Matchers.both;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
/**
* Tests failure capturing and abort-on-failure behavior of reindex.
*/
@TestLogging("_root:DEBUG")
public class ReindexFailureTests extends ReindexTestCase {
public void testFailuresCauseAbortDefault() throws Exception {
/*
* Create the destination index such that the copy will cause a mapping
* conflict on every request.
*/
indexRandom(true,
client().prepareIndex("dest", "test", "test").setSource("test", 10) /* Its a string in the source! */);
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest");
/*
* Set the search size to something very small to cause there to be
* multiple batches for this request so we can assert that we abort on
* the first batch.
*/
copy.source().setSize(1);
BulkByScrollResponse response = copy.get();
assertThat(response, matcher()
.batches(1)
.failures(both(greaterThan(0)).and(lessThanOrEqualTo(maximumNumberOfShards()))));
for (Failure failure: response.getBulkFailures()) {
assertThat(failure.getMessage(), containsString("IllegalArgumentException[For input string: \"words words\"]"));
}
}
public void testAbortOnVersionConflict() throws Exception {
// Just put something in the way of the copy.
indexRandom(true,
client().prepareIndex("dest", "test", "1").setSource("test", "test"));
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest").abortOnVersionConflict(true);
// CREATE will cause the conflict to prevent the write.
copy.destination().setOpType(CREATE);
BulkByScrollResponse response = copy.get();
assertThat(response, matcher().batches(1).versionConflicts(1).failures(1).created(99));
for (Failure failure: response.getBulkFailures()) {
assertThat(failure.getMessage(), containsString("VersionConflictEngineException[[test]["));
}
}
/**
* Make sure that search failures get pushed back to the user as failures of
* the whole process. We do lose some information about how far along the
* process got, but its important that they see these failures.
*/
public void testResponseOnSearchFailure() throws Exception {
/*
* Attempt to trigger a reindex failure by deleting the source index out
* from under it.
*/
int attempt = 1;
while (attempt < 5) {
indexDocs(100);
ReindexRequestBuilder copy = reindex().source("source").destination("dest");
copy.source().setSize(10);
Future<BulkByScrollResponse> response = copy.execute();
client().admin().indices().prepareDelete("source").get();
try {
response.get();
logger.info("Didn't trigger a reindex failure on the {} attempt", attempt);
attempt++;
} catch (ExecutionException e) {
logger.info("Triggered a reindex failure on the {} attempt: {}", attempt, e.getMessage());
assertThat(e.getMessage(),
either(containsString("all shards failed"))
.or(containsString("No search context found"))
.or(containsString("no such index"))
);
return;
}
}
assumeFalse("Wasn't able to trigger a reindex failure in " + attempt + " attempts.", true);
}
private void indexDocs(int count) throws Exception {
List<IndexRequestBuilder> docs = new ArrayList<IndexRequestBuilder>(count);
for (int i = 0; i < count; i++) {
docs.add(client().prepareIndex("source", "test", Integer.toString(i)).setSource("test", "words words"));
}
indexRandom(true, docs);
}
}
| Reindex: Wait for deletion in test
The test failure tracked by #28053 occurs because we fail to get the
failure response from the reindex on the first try and on our second try
the delete index API call that was supposed to trigger the failure
actually deletes the index during document creation. This causes the
test to fail catastrophically.
This PR attempts to wait for the failure to finish before the test moves
on to the second attempt. The failure doesn't reproduce locally for me
so I can't be sure that this helps at all with the failure, but it
certainly feels like it should help some. Here is hoping this prevents
similar failures in the future.
| modules/reindex/src/test/java/org/elasticsearch/index/reindex/ReindexFailureTests.java | Reindex: Wait for deletion in test | <ide><path>odules/reindex/src/test/java/org/elasticsearch/index/reindex/ReindexFailureTests.java
<ide> response.get();
<ide> logger.info("Didn't trigger a reindex failure on the {} attempt", attempt);
<ide> attempt++;
<add> /*
<add> * In the past we've seen the delete of the source index
<add> * actually take effect *during* the `indexDocs` call in
<add> * the next step. This breaks things pretty disasterously
<add> * so we *try* and wait for the delete to be fully
<add> * complete here.
<add> */
<add> assertBusy(() -> assertFalse(client().admin().indices().prepareExists("source").get().isExists()));
<ide> } catch (ExecutionException e) {
<ide> logger.info("Triggered a reindex failure on the {} attempt: {}", attempt, e.getMessage());
<ide> assertThat(e.getMessage(), |
|
Java | mit | 94a90cac33832cd576804e0f44b2f9e19b33341a | 0 | nalabelle/senior-design-project | /**
* Author: Alex Swanson 103706731?
* Date started: Early Sept
* Date Completed: IP
* Peer Review: IP
* Date: You mean today?
* Team members: Buddy Corp
* Contribution: IP
*
* Working Calendar... no functionality
* TODO
* Fix broken button/header texy issues
* Move New Event button out of header section.
* Find a way to stretch calendar on large screens... new day_button xml? relative layout fill?
* Sprint 2: add event tracking, add events,
* scrolling (back/forward in time), day detail popup
*
*/
package com.comp490.studybuddy.calendar;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import com.comp490.studybuddy.R;
public class CalenActivity extends Activity {
private Calendar calendar;
private int month, year;
private TextView currentMonth;
//Days of week, add events. TODO
private TextView calHeader;
private Button newEvent; //IP
private GridView calendarGrid;
private GridCellAdapter adapter;
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";
//testing git and stash... nothing todo with project
private int testline;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcal);
//testing stahs/git
testline = 808;
calendar = Calendar.getInstance(Locale.getDefault());
month = calendar.get(Calendar.MONTH) + 1;
year = calendar.get(Calendar.YEAR);
currentMonth = (TextView) this.findViewById(R.id.curr_month);
currentMonth.setText(dateFormatter.format(dateTemplate, calendar.getTime()));
//How to align to columns? Option for Su->Sa || M -> Su TODO
calHeader = (TextView) this.findViewById(R.id.cal_header);
calHeader.setText("New Event"); //Esthetic bug fix for now
calendarGrid = (GridView) this.findViewById(R.id.gridView1);
// Grid --> Calendar
adapter = new GridCellAdapter(getApplicationContext(), R.id.grid_day, month, year);
adapter.notifyDataSetChanged();
calendarGrid.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.calen, menu);
return true;
}//Autogen
@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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}//Autogen
//Grid --> Calendar
public class GridCellAdapter extends BaseAdapter implements OnClickListener
{
private final Context context;
private final List<String> list;
private static final int DAY_OFFSET = 1;
private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private final int month, year;
private int daysInMonth;
private int currDayOfMonth;
private int currWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
//better way? Locale based
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");
public GridCellAdapter(Context context, int cellID, int month, int year)
{
super();
this.context = context;
this.list = new ArrayList<String>();
this.month = month;
this.year = year;
Calendar calendar = Calendar.getInstance();
setCurrDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
// Print Month
printMonth(month, year);
// Find Number of Events
eventsPerMonthMap = findEventsMonth(year, month);
}
//print to cells
private void printMonth(int m, int y)
{
int prevMonthPadding = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = m - 1;
daysInMonth = getDaysinMonth(currentMonth);
GregorianCalendar cal = new GregorianCalendar(y, currentMonth, 1);
if (currentMonth == 11) //Dec
{
prevMonth = currentMonth - 1;
daysInPrevMonth = getDaysinMonth(prevMonth);
nextMonth = 0;
prevYear = y;
nextYear = y + 1;
}
else if (currentMonth == 0) // Jan
{
prevMonth = 11;
prevYear = y - 1;
nextYear = y;
daysInPrevMonth = getDaysinMonth(prevMonth);
nextMonth = 1;
}
else //Not dec && Not jan
{
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = y;
prevYear = y;
daysInPrevMonth = getDaysinMonth(prevMonth);
}
//Pad front of month
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
prevMonthPadding = currentWeekDay;
if (cal.isLeapYear(cal.get(Calendar.YEAR)) && m == 1)
{
++daysInMonth;
}
// Previous Month days, fill in beginning of curr month if necessary
for (int i = 0; i < prevMonthPadding; i++)
{
list.add(String.valueOf((daysInPrevMonth - prevMonthPadding + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthString(prevMonth) + "-" + prevYear);
}
// Current Month Days
for (int i = 1; i <= daysInMonth; i++)
{
if (i == getCurrDayOfMonth())
{
list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthString(currentMonth) + "-" + y);
}
else
{
list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthString(currentMonth) + "-" + y);
}
}
// Fill in end of curr months, if necessary
for (int i = 0; i < list.size() % 7; i++)
{
list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthString(nextMonth) + "-" + nextYear);
}
} //End print Month
public String getMonthString(int i)
{
return months[i];
}
public int getDaysinMonth(int i)
{
return daysOfMonth[i];
}
public String getItem(int position)
{
return list.get(position);
}
public int getCurrDayOfMonth()
{
return currDayOfMonth;
}
public void setCurrDayOfMonth(int currDayOfMonth)
{
this.currDayOfMonth = currDayOfMonth;
}
public int getCurrWeekDay()
{
return currWeekDay;
}
public void setCurrWeekDay(int currWeekDay)
{
this.currWeekDay = currWeekDay;
}
@Override
public int getCount()
{
return list.size();
}
@Override
public long getItemId(int position)
{
return position;
}
//Where to store/ retrieve events?
private HashMap<String, Integer> findEventsMonth(int year, int month)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.day_button, parent, false);
}
// day cells, button action
gridcell = (Button) row.findViewById(R.id.grid_day);
gridcell.setOnClickListener(this);
// Parse print month information
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
//Add number of events per day from HashMap.
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null))
{
if (eventsPerMonthMap.containsKey(theday))
{
num_events_per_day = (TextView) row.findViewById(R.id.num_events);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
// Set the Day in each GridCell, date as tag
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
//Colorize days on calendar
//Sandwiching months days
if (day_color[1].equals("GREY"))
{
gridcell.setTextColor(Color.LTGRAY);
}
//Current Month
if (day_color[1].equals("WHITE"))
{
gridcell.setTextColor(Color.WHITE);
}
//Day
if (day_color[1].equals("BLUE"))
{
gridcell.setTextColor(Color.BLUE);
}
return row;
}
//TODO setpopup day detail
@Override
public void onClick(View view)
{
//Get info for day poked
String date_month_year = (String) view.getTag();
}
} //End GridCellAdapter
}// End CalenActivity
| src/com/comp490/studybuddy/calendar/CalenActivity.java | /**
* Author: Alex Swanson 103706731?
* Date started: Early Sept
* Date Completed: IP
* Peer Review: IP
* Date: You mean today?
* Team members: Buddy Corp
* Contribution: IP
*
* Working Calendar... no functionality
* TODO
* Fix broken button/header texy issues
* Move New Event button out of header section.
* Find a way to stretch calendar on large screens... new day_button xml? relative layout fill?
* Sprint 2: add event tracking, add events,
* scrolling (back/forward in time), day detail popup
*
*/
package com.comp490.studybuddy.calendar;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import com.comp490.studybuddy.R;
public class CalenActivity extends Activity {
private Calendar calendar;
private int month, year;
private TextView currentMonth;
//Days of week, add events. TODO
private TextView calHeader;
private Button newEvent; //IP
private GridView calendarGrid;
private GridCellAdapter adapter;
private final DateFormat dateFormatter = new DateFormat();
private static final String dateTemplate = "MMMM yyyy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcal);
calendar = Calendar.getInstance(Locale.getDefault());
month = calendar.get(Calendar.MONTH) + 1;
year = calendar.get(Calendar.YEAR);
currentMonth = (TextView) this.findViewById(R.id.curr_month);
currentMonth.setText(dateFormatter.format(dateTemplate, calendar.getTime()));
//How to align to columns? Option for Su->Sa || M -> Su TODO
calHeader = (TextView) this.findViewById(R.id.cal_header);
calHeader.setText("New Event"); //Esthetic bug fix for now
calendarGrid = (GridView) this.findViewById(R.id.gridView1);
// Grid --> Calendar
adapter = new GridCellAdapter(getApplicationContext(), R.id.grid_day, month, year);
adapter.notifyDataSetChanged();
calendarGrid.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.calen, menu);
return true;
}//Autogen
@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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}//Autogen
//Grid --> Calendar
public class GridCellAdapter extends BaseAdapter implements OnClickListener
{
private final Context context;
private final List<String> list;
private static final int DAY_OFFSET = 1;
private final String[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
private final int[] daysOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private final int month, year;
private int daysInMonth;
private int currDayOfMonth;
private int currWeekDay;
private Button gridcell;
private TextView num_events_per_day;
private final HashMap<String, Integer> eventsPerMonthMap;
//better way? Locale based
private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy");
public GridCellAdapter(Context context, int cellID, int month, int year)
{
super();
this.context = context;
this.list = new ArrayList<String>();
this.month = month;
this.year = year;
Calendar calendar = Calendar.getInstance();
setCurrDayOfMonth(calendar.get(Calendar.DAY_OF_MONTH));
setCurrWeekDay(calendar.get(Calendar.DAY_OF_WEEK));
// Print Month
printMonth(month, year);
// Find Number of Events
eventsPerMonthMap = findEventsMonth(year, month);
}
//print to cells
private void printMonth(int m, int y)
{
int prevMonthPadding = 0;
int daysInPrevMonth = 0;
int prevMonth = 0;
int prevYear = 0;
int nextMonth = 0;
int nextYear = 0;
int currentMonth = m - 1;
daysInMonth = getDaysinMonth(currentMonth);
GregorianCalendar cal = new GregorianCalendar(y, currentMonth, 1);
if (currentMonth == 11) //Dec
{
prevMonth = currentMonth - 1;
daysInPrevMonth = getDaysinMonth(prevMonth);
nextMonth = 0;
prevYear = y;
nextYear = y + 1;
}
else if (currentMonth == 0) // Jan
{
prevMonth = 11;
prevYear = y - 1;
nextYear = y;
daysInPrevMonth = getDaysinMonth(prevMonth);
nextMonth = 1;
}
else //Not dec && Not jan
{
prevMonth = currentMonth - 1;
nextMonth = currentMonth + 1;
nextYear = y;
prevYear = y;
daysInPrevMonth = getDaysinMonth(prevMonth);
}
//Pad front of month
int currentWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
prevMonthPadding = currentWeekDay;
if (cal.isLeapYear(cal.get(Calendar.YEAR)) && m == 1)
{
++daysInMonth;
}
// Previous Month days, fill in beginning of curr month if necessary
for (int i = 0; i < prevMonthPadding; i++)
{
list.add(String.valueOf((daysInPrevMonth - prevMonthPadding + DAY_OFFSET) + i) + "-GREY" + "-" + getMonthString(prevMonth) + "-" + prevYear);
}
// Current Month Days
for (int i = 1; i <= daysInMonth; i++)
{
if (i == getCurrDayOfMonth())
{
list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthString(currentMonth) + "-" + y);
}
else
{
list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthString(currentMonth) + "-" + y);
}
}
// Fill in end of curr months, if necessary
for (int i = 0; i < list.size() % 7; i++)
{
list.add(String.valueOf(i + 1) + "-GREY" + "-" + getMonthString(nextMonth) + "-" + nextYear);
}
} //End print Month
public String getMonthString(int i)
{
return months[i];
}
public int getDaysinMonth(int i)
{
return daysOfMonth[i];
}
public String getItem(int position)
{
return list.get(position);
}
public int getCurrDayOfMonth()
{
return currDayOfMonth;
}
public void setCurrDayOfMonth(int currDayOfMonth)
{
this.currDayOfMonth = currDayOfMonth;
}
public int getCurrWeekDay()
{
return currWeekDay;
}
public void setCurrWeekDay(int currWeekDay)
{
this.currWeekDay = currWeekDay;
}
@Override
public int getCount()
{
return list.size();
}
@Override
public long getItemId(int position)
{
return position;
}
//Where to store/ retrieve events?
private HashMap<String, Integer> findEventsMonth(int year, int month)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
return map;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.day_button, parent, false);
}
// day cells, button action
gridcell = (Button) row.findViewById(R.id.grid_day);
gridcell.setOnClickListener(this);
// Parse print month information
String[] day_color = list.get(position).split("-");
String theday = day_color[0];
String themonth = day_color[2];
String theyear = day_color[3];
//Add number of events per day from HashMap.
if ((!eventsPerMonthMap.isEmpty()) && (eventsPerMonthMap != null))
{
if (eventsPerMonthMap.containsKey(theday))
{
num_events_per_day = (TextView) row.findViewById(R.id.num_events);
Integer numEvents = (Integer) eventsPerMonthMap.get(theday);
num_events_per_day.setText(numEvents.toString());
}
}
// Set the Day in each GridCell, date as tag
gridcell.setText(theday);
gridcell.setTag(theday + "-" + themonth + "-" + theyear);
//Colorize days on calendar
//Sandwiching months days
if (day_color[1].equals("GREY"))
{
gridcell.setTextColor(Color.LTGRAY);
}
//Current Month
if (day_color[1].equals("WHITE"))
{
gridcell.setTextColor(Color.WHITE);
}
//Day
if (day_color[1].equals("BLUE"))
{
gridcell.setTextColor(Color.BLUE);
}
return row;
}
//TODO setpopup day detail
@Override
public void onClick(View view)
{
//Get info for day poked
String date_month_year = (String) view.getTag();
}
} //End GridCellAdapter
}// End CalenActivity
| Added some junk code. Want to see if pushes goto Git or Stash or
hopefully Both
| src/com/comp490/studybuddy/calendar/CalenActivity.java | Added some junk code. Want to see if pushes goto Git or Stash or hopefully Both | <ide><path>rc/com/comp490/studybuddy/calendar/CalenActivity.java
<ide>
<ide> private final DateFormat dateFormatter = new DateFormat();
<ide> private static final String dateTemplate = "MMMM yyyy";
<add>
<add> //testing git and stash... nothing todo with project
<add> private int testline;
<ide>
<ide> @Override
<ide> protected void onCreate(Bundle savedInstanceState) {
<ide> super.onCreate(savedInstanceState);
<ide> setContentView(R.layout.activity_customcal);
<add>
<add> //testing stahs/git
<add> testline = 808;
<ide>
<ide> calendar = Calendar.getInstance(Locale.getDefault());
<ide> month = calendar.get(Calendar.MONTH) + 1; |
|
JavaScript | mit | af72fd3260c8e3d7d7d196e13694f5b32180e0c0 | 0 | ForbesLindesay/babel-plugin-transform-react-pug,pugjs/babel-plugin-transform-react-pug | import assert from 'assert';
import error from 'pug-error';
// Mising "types"
// - Comment
// - BlockComment
// - &attributes
// - InterpolatedTag
// - Code(buffer: false + block)
// - Each(object)
function addLocToAst(ast, line) {
if (ast.loc) {
ast.loc = {
start: {line: line + ast.loc.start.line, column: 0},
end: {line: line + ast.loc.end.line, column: 0},
};
Object.keys(ast).forEach(key => {
if (Array.isArray(ast[key])) {
ast[key].forEach(n => addLocToAst(n, line));
} else if (ast[key] && typeof ast[key] === 'object') {
addLocToAst(ast[key], line);
}
});
}
}
export default function ({babel, parse, helpers, ast, path, code}) {
const {types} = babel;
const baseLine = path.node.loc.start.line;
let lastLine = 0;
const t = {};
function getFn(key) {
return (...args) => {
const res = types[key](...args);
const loc = {line: baseLine + lastLine, column: 0};
res.loc = {start: loc, end: loc};
return res;
};
}
for (const key in types) {
if (/^is|^assert/.test(key)) {
t[key] = types[key];
} else {
t[key] = getFn(key);
}
}
const nodes = t.identifier('pug_nodes');
function withString(node, stringLiteral) {
t.assertStringLiteral(stringLiteral);
if (t.isStringLiteral(node)) {
return t.stringLiteral(node.value + stringLiteral.value);
}
if (t.isBinaryExpression(node, {operator: '+'}) && t.isStringLiteral(node.right)) {
return t.binaryExpression('+', node.left, withString(node.right, stringLiteral));
}
return t.binaryExpression('+', node, stringLiteral);
}
let staticBlockID = 0;
const compiler = {
baseBlock() {
return {
_id: 'base',
getKey(fn) {
fn(t.stringLiteral('pug'));
},
handleAttributes(attrs) {},
end() {},
};
},
staticBlock(parent) {
let enabled = false;
let parentEnabled = false;
let key = null;
const pending = [];
let index = 0;
parent.getKey(parentKey => {
parentEnabled = true;
key = withString(parentKey, t.stringLiteral(':' + (staticBlockID++)));
onUpdate();
});
function onUpdate() {
if (enabled && parentEnabled) {
while (pending.length) {
pending.shift()(withString(key, t.stringLiteral(':' + (index++))));
}
}
}
return {
getKey(fn) {
if (pending.indexOf(fn) === -1) {
pending.push(fn);
}
onUpdate();
},
handleAttributes(attrs) {
for (const attr of attrs) {
if (
t.isJSXAttribute(attr) &&
t.isJSXIdentifier(attr.name, {name: 'key'})
) {
return;
}
}
this.getKey(key => {
if (t.isStringLiteral(key)) key = key; // t.jSXText(key.value);
else key = t.jSXExpressionContainer(key);
attrs.push(t.jSXAttribute(
t.jSXIdentifier('key'),
key,
));
});
},
end() {
enabled = true;
onUpdate();
},
};
},
dynamicBlock(parent, lineNumber) {
let enabled = false;
let localKey = null;
let parentEnabled = false;
let parentKey = null;
const pending = [];
let index = 0;
function join(left, right) {
return t.binaryExpression('+', left, right);
}
parent.getKey(_parentKey => {
parentEnabled = true;
parentKey = withString(_parentKey, t.stringLiteral(':'));
onUpdate();
});
function onUpdate() {
if (enabled && parentEnabled && localKey) {
while (pending.length) {
pending.shift()(withString(join(parentKey, localKey), t.stringLiteral(':' + (index++))));
}
} else if (enabled && parentEnabled) {
const err = error('MISSING_KEY', 'You must specify a key for the first item in any loops.', {
line: path.node.loc.start.line + lineNumber,
filename: 'pug',
src: code,
});
throw err;
}
}
return {
getKey(fn) {
if (pending.indexOf(fn) === -1) {
pending.push(fn);
}
onUpdate();
},
handleAttributes(attrs) {
for (const attr of attrs) {
if (
t.isJSXAttribute(attr) &&
t.isJSXIdentifier(attr.name, {name: 'key'})
) {
if (localKey === null && t.isJSXExpressionContainer(attr.value) && attr.value.expression) {
localKey = attr.value.expression;
onUpdate();
// remove the attribute and replace with the properly nested version
attrs.splice(attrs.indexOf(attr), 1);
} else {
return;
}
}
}
this.getKey(key => {
if (t.isStringLiteral(key)) key = key; // t.jSXText(key.value);
else key = t.jSXExpressionContainer(key);
attrs.push(t.jSXAttribute(
t.jSXIdentifier('key'),
key,
));
});
},
end() {
enabled = true;
onUpdate();
},
};
},
parseExpression(src) {
const val = parse('x = (' + src + ');').program.body;
assert(val.length === 1);
// TODO: add the correct column number
addLocToAst(val, baseLine + lastLine);
return val[0].expression.right;
},
parseStatement(src) {
const val = parse(src).program.body;
assert(val.length === 1);
// TODO: add the correct column number
addLocToAst(val, baseLine + lastLine);
return val[0];
},
wrapExpressionInJSX(value) { // returns ["JSX"]
if (t.isJSX(value)) {
return value;
} else if (t.isStringLiteral(value)) {
return t.jSXText(value.value);
} else {
return t.jSXExpressionContainer(value);
}
},
joinJsExpressions(values) {
const vals = [];
// flatten one level
for (const val of values) {
if (t.isArrayExpression(val)) {
for (const e of val.entries) {
vals.push(e);
}
} else {
vals.push(val);
}
}
if (vals.length === 0) {
return t.nullLiteral();
} else if (vals.length === 1) {
return vals[0];
} else {
return t.arrayExpression(vals);
}
},
joinJsStatements(values) {
const vals = [];
// flatten one level
for (const val of values) {
if (Array.isArray(val)) {
for (const e of val) {
vals.push(e);
}
} else {
vals.push(val);
}
}
return vals;
},
getPushStatement(arg) {
return t.expressionStatement(
t.callExpression(
t.memberExpression(
nodes,
t.identifier('push'),
),
[arg],
),
);
},
visit(node, mode, block) {
if (typeof this['visit' + node.type] === 'function') {
lastLine = node.line - 1;
return this['visit' + node.type](node, mode, block);
} else {
throw new Error(node.type + ' is not yet supported');
}
},
// [ "JSXExpressionContainer", "ConditionalExpression", "IfStatement" ]
visitCase(node, mode, block) {
// compile the case/when into a series of conditionals then compile that down to jsx
const base = {alternate: null};
let parent = base;
let defaultValue = {type: 'Block', nodes: []};
node.block.nodes.forEach(whenNode => {
if (whenNode.expr === 'default') {
defaultValue = whenNode.block;
} else {
parent.alternate = {
type: 'Conditional',
test: node.expr + ' === ' + whenNode.expr,
consequent: whenNode.block,
alternate: null,
};
parent = parent.alternate;
}
});
if (!base.alternate) {
throw new Error('Empty case blocks are not supported');
}
parent.alternate = defaultValue;
return this.visit(base.alternate, mode, block);
},
// [ "JSX", "Expression", "Statement" ]
visitCode(node, mode, block) {
if (node.buffer && !node.mustEscape) {
throw new Error('Unescaped, buffered code is not supported in react-pug');
}
switch (mode) {
case 'jsx':
return this.wrapExpressionInJSX(this.visitCode(node, 'jsExpression', block));
case 'jsExpression':
if (node.buffer) {
return this.parseExpression(node.val);
}
// TODO: hoist and rename `const` and `let` variables
return t.doExpression(
t.blockStatement([
this.parseStatement(node.val),
t.expressionStatement(t.nullLiteral()),
]),
);
case 'jsStatements':
if (node.buffer) {
return [this.getPushStatement(this.parseExpression(node.val))];
}
return [this.parseStatement(node.val)];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "ConditionalExpression", "IfStatement" ]
visitConditional(node, mode, block) {
if (node.alternate && node.alternate.type === 'Conditional') {
node.alternate = {nodes: [node.alternate]};
}
const test = this.parseExpression(node.test);
switch (mode) {
case 'jsx':
return t.jSXExpressionContainer(this.visitConditional(node, 'jsExpression', block));
case 'jsExpression':
const condConsequentBlock = this.staticBlock(block);
const condConsequent = this.joinJsExpressions(
node.consequent.nodes.map(
node => this.visit(node, 'jsExpression', condConsequentBlock),
).filter(Boolean),
);
condConsequentBlock.end();
let condAlternate = t.nullLiteral();
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
condAlternate = this.joinJsExpressions(
node.alternate.nodes.map(
node => this.visit(node, 'jsExpression', alternateBlock),
).filter(Boolean),
);
alternateBlock.end();
}
return t.conditionalExpression(
test,
condConsequent,
condAlternate,
);
case 'jsStatements':
const ifConsequentBlock = this.staticBlock(block);
const ifConsequent = t.blockStatement(
this.joinJsStatements(
node.consequent.nodes.map(
node => this.visit(node, 'jsStatements', ifConsequentBlock),
),
),
);
ifConsequentBlock.end();
let ifAlternate = null;
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
ifAlternate = t.blockStatement(
this.joinJsStatements(
node.alternate.nodes.map(
node => this.visit(node, 'jsStatements', alternateBlock),
),
),
);
alternateBlock.end();
}
return [
t.ifStatement(
test,
ifConsequent,
ifAlternate,
),
];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "DoExpression", "WhileStatement" ]
visitEach(node, mode, block) {
if (mode === 'jsx') {
return this.wrapExpressionInJSX(this.visitEach(node, 'jsExpression', block));
}
if (mode === 'jsExpression') {
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
nodes,
t.arrayExpression([]),
),
],
);
const end = t.expressionStatement(nodes);
return t.doExpression(
t.blockStatement([variableDeclaration, ...(this.visitEach(node, 'jsStatements', block)), end]),
);
}
const childBlock = this.dynamicBlock(block, node.line);
const obj = path.scope.generateUidIdentifier('pug_arr');
const objLength = t.memberExpression(
obj,
t.identifier('length'),
);
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
obj,
this.parseExpression(node.obj),
),
],
);
const index = node.key ? t.identifier(node.key) : path.scope.generateUidIdentifier('pug_index');
const init = t.variableDeclaration(
'let',
[
t.variableDeclarator(
index,
t.numericLiteral(0),
),
],
);
const test = t.binaryExpression(
'<',
index,
objLength,
);
const update = t.updateExpression(
'++',
index
);
let loop = t.forStatement(init, test, update, t.blockStatement(
[
t.variableDeclaration(
'const',
[
t.variableDeclarator(
t.identifier(node.val),
t.memberExpression(
obj,
index,
true,
),
),
],
),
].concat(
this.joinJsStatements(
node.block.nodes.map(
node => this.visit(node, 'jsStatements', childBlock),
),
),
),
));
childBlock.end();
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
const alternate = t.blockStatement(this.joinJsStatements(
node.alternate.nodes.map(
node => this.visit(node, 'jsStatements', alternateBlock),
).filter(Boolean),
));
alternateBlock.end();
loop = t.ifStatement(
objLength,
loop,
alternate,
);
}
return [
variableDeclaration,
t.ifStatement(
t.callExpression(
t.memberExpression(
t.identifier('Array'),
t.identifier('isArray'),
),
[obj],
),
t.blockStatement([loop]),
t.blockStatement([
t.throwStatement(
t.newExpression(
t.identifier('TypeError'),
[t.stringLiteral('Expected ' + node.obj + ' to be an array.')],
),
),
]),
),
];
},
// returns ["JSXElement", "JSXElement", "PushStatement"] ]
visitTag(node, mode, block) {
const name = t.jSXIdentifier(node.name);
const children = (
(
node.code ?
[this.visitCode(node.code, 'jsx', this.baseBlock())] :
[]
).concat(node.block.nodes.map(
node => this.visit(node, 'jsx', this.baseBlock())
).filter(Boolean))
// TODO: assert that these are all valid jsx things
);
if (node.attributeBlocks.length) {
throw new Error('Attribute blocks are not yet supported in react-pug');
}
const classes = [];
const attrs = node.attrs.map(
({name, val, mustEscape}) => {
if (/\.\.\./.test(name) && val === true) {
return t.jSXSpreadAttribute(this.parseExpression(name.substr(3)));
}
switch (name) {
case 'for':
name = 'htmlFor';
break;
case 'maxlength':
name = 'maxLength';
break;
case 'class':
name = 'className';
break;
}
const expr = this.parseExpression(val === true ? 'true' : val);
if (!mustEscape && (!t.isStringLiteral(expr) || /(\<\>\&)/.test(val))) {
throw new Error('Unescaped attributes are not supported in react-pug');
}
if (name === 'className') {
classes.push(expr);
return null;
}
const jsxValue = (
t.isStringLiteral(expr) || t.isJSXElement(expr)
? expr
: t.jSXExpressionContainer(expr)
);
if (/\.\.\./.test(name)) {
throw new Error('spread attributes must not have a value');
}
return t.jSXAttribute(
t.jSXIdentifier(name),
jsxValue,
);
},
).filter(Boolean);
if (classes.length) {
const value = (
classes.every(cls => t.isStringLiteral(cls))
? t.stringLiteral(classes.map(cls => cls.value).join(' '))
: (
t.jSXExpressionContainer(
t.callExpression(
t.memberExpression(
t.arrayExpression(classes),
t.identifier('join'),
),
[
t.stringLiteral(' '),
],
),
)
)
);
attrs.push(t.jSXAttribute(t.jSXIdentifier('className'), value));
}
block.handleAttributes(attrs);
const open = t.jSXOpeningElement(
name,
attrs, // Array<JSXAttribute | JSXSpreadAttribute>
children.length === 0,
);
const close = (
children.length === 0
? null
: t.jSXClosingElement(name)
);
const element = t.jSXElement(
open,
close,
children, // ["StringLiteral","JSXExpressionContainer","JSXElement"]
children.length === 0
);
switch (mode) {
case 'jsx':
case 'jsExpression':
return element;
case 'jsStatements':
return [this.getPushStatement(element)];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXText", "StringLiteral", "PushStatement"]
visitText(node, mode, block) {
switch (mode) {
case 'jsx':
return t.jSXText(node.val);
case 'jsExpression':
return t.stringLiteral(node.val);
case 'jsStatements':
return [this.getPushStatement(this.visitText(node, 'jsExpression', block))];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "DoExpression", "WhileStatement" ]
visitWhile(node, mode, block) {
if (mode === 'jsx') {
return this.wrapExpressionInJSX(this.visitWhile(node, 'jsExpression', block));
}
if (mode === 'jsExpression') {
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
nodes,
t.arrayExpression([]),
),
],
);
const end = t.expressionStatement(nodes);
return t.doExpression(
t.blockStatement([variableDeclaration, ...(this.visitWhile(node, 'jsStatements', block)), end]),
);
}
const childBlock = this.dynamicBlock(block, node.line);
const test = this.parseExpression(node.test);
const body = t.blockStatement(
this.joinJsStatements(
node.block.nodes.map(
node => this.visit(node, 'jsStatements', childBlock),
).filter(Boolean),
),
);
childBlock.end();
return [t.whileStatement(test, body)];
},
};
return ast.nodes.map(node => compiler.visit(node, 'jsExpression', compiler.baseBlock()));
}
| src/code-gen.js | import assert from 'assert';
import error from 'pug-error';
// Mising "types"
// - Comment
// - BlockComment
// - &attributes
// - InterpolatedTag
// - Code(buffer: false + block)
// - Each(object)
export default function ({babel, parse, helpers, ast, path, code}) {
const {types} = babel;
const baseLine = path.node.loc.start.line;
let lastLine = 0;
const t = {};
function getFn(key) {
return (...args) => {
const res = types[key](...args);
const loc = {line: baseLine + lastLine, column: 0};
res.loc = {start: loc, end: loc};
return res;
};
}
for (const key in types) {
if (/^is|^assert/.test(key)) {
t[key] = types[key];
} else {
t[key] = getFn(key);
}
}
const nodes = t.identifier('pug_nodes');
function withString(node, stringLiteral) {
t.assertStringLiteral(stringLiteral);
if (t.isStringLiteral(node)) {
return t.stringLiteral(node.value + stringLiteral.value);
}
if (t.isBinaryExpression(node, {operator: '+'}) && t.isStringLiteral(node.right)) {
return t.binaryExpression('+', node.left, withString(node.right, stringLiteral));
}
return t.binaryExpression('+', node, stringLiteral);
}
let staticBlockID = 0;
const compiler = {
baseBlock() {
return {
_id: 'base',
getKey(fn) {
fn(t.stringLiteral('pug'));
},
handleAttributes(attrs) {},
end() {},
};
},
staticBlock(parent) {
let enabled = false;
let parentEnabled = false;
let key = null;
const pending = [];
let index = 0;
parent.getKey(parentKey => {
parentEnabled = true;
key = withString(parentKey, t.stringLiteral(':' + (staticBlockID++)));
onUpdate();
});
function onUpdate() {
if (enabled && parentEnabled) {
while (pending.length) {
pending.shift()(withString(key, t.stringLiteral(':' + (index++))));
}
}
}
return {
getKey(fn) {
if (pending.indexOf(fn) === -1) {
pending.push(fn);
}
onUpdate();
},
handleAttributes(attrs) {
for (const attr of attrs) {
if (
t.isJSXAttribute(attr) &&
t.isJSXIdentifier(attr.name, {name: 'key'})
) {
return;
}
}
this.getKey(key => {
if (t.isStringLiteral(key)) key = key; // t.jSXText(key.value);
else key = t.jSXExpressionContainer(key);
attrs.push(t.jSXAttribute(
t.jSXIdentifier('key'),
key,
));
});
},
end() {
enabled = true;
onUpdate();
},
};
},
dynamicBlock(parent, lineNumber) {
let enabled = false;
let localKey = null;
let parentEnabled = false;
let parentKey = null;
const pending = [];
let index = 0;
function join(left, right) {
return t.binaryExpression('+', left, right);
}
parent.getKey(_parentKey => {
parentEnabled = true;
parentKey = withString(_parentKey, t.stringLiteral(':'));
onUpdate();
});
function onUpdate() {
if (enabled && parentEnabled && localKey) {
while (pending.length) {
pending.shift()(withString(join(parentKey, localKey), t.stringLiteral(':' + (index++))));
}
} else if (enabled && parentEnabled) {
const err = error('MISSING_KEY', 'You must specify a key for the first item in any loops.', {
line: path.node.loc.start.line + lineNumber,
filename: 'pug',
src: code,
});
throw err;
}
}
return {
getKey(fn) {
if (pending.indexOf(fn) === -1) {
pending.push(fn);
}
onUpdate();
},
handleAttributes(attrs) {
for (const attr of attrs) {
if (
t.isJSXAttribute(attr) &&
t.isJSXIdentifier(attr.name, {name: 'key'})
) {
if (localKey === null && t.isJSXExpressionContainer(attr.value) && attr.value.expression) {
localKey = attr.value.expression;
onUpdate();
// remove the attribute and replace with the properly nested version
attrs.splice(attrs.indexOf(attr), 1);
} else {
return;
}
}
}
this.getKey(key => {
if (t.isStringLiteral(key)) key = key; // t.jSXText(key.value);
else key = t.jSXExpressionContainer(key);
attrs.push(t.jSXAttribute(
t.jSXIdentifier('key'),
key,
));
});
},
end() {
enabled = true;
onUpdate();
},
};
},
parseExpression(src) {
const val = parse('x = (' + src + ');').program.body;
assert(val.length === 1);
return val[0].expression.right;
},
parseStatement(src) {
const val = parse(src).program.body;
assert(val.length === 1);
return val[0];
},
wrapExpressionInJSX(value) { // returns ["JSX"]
if (t.isJSX(value)) {
return value;
} else if (t.isStringLiteral(value)) {
return t.jSXText(value.value);
} else {
return t.jSXExpressionContainer(value);
}
},
joinJsExpressions(values) {
const vals = [];
// flatten one level
for (const val of values) {
if (t.isArrayExpression(val)) {
for (const e of val.entries) {
vals.push(e);
}
} else {
vals.push(val);
}
}
if (vals.length === 0) {
return t.nullLiteral();
} else if (vals.length === 1) {
return vals[0];
} else {
return t.arrayExpression(vals);
}
},
joinJsStatements(values) {
const vals = [];
// flatten one level
for (const val of values) {
if (Array.isArray(val)) {
for (const e of val) {
vals.push(e);
}
} else {
vals.push(val);
}
}
return vals;
},
getPushStatement(arg) {
return t.expressionStatement(
t.callExpression(
t.memberExpression(
nodes,
t.identifier('push'),
),
[arg],
),
);
},
visit(node, mode, block) {
if (typeof this['visit' + node.type] === 'function') {
lastLine = node.line - 1;
return this['visit' + node.type](node, mode, block);
} else {
throw new Error(node.type + ' is not yet supported');
}
},
// [ "JSXExpressionContainer", "ConditionalExpression", "IfStatement" ]
visitCase(node, mode, block) {
// compile the case/when into a series of conditionals then compile that down to jsx
const base = {alternate: null};
let parent = base;
let defaultValue = {type: 'Block', nodes: []};
node.block.nodes.forEach(whenNode => {
if (whenNode.expr === 'default') {
defaultValue = whenNode.block;
} else {
parent.alternate = {
type: 'Conditional',
test: node.expr + ' === ' + whenNode.expr,
consequent: whenNode.block,
alternate: null,
};
parent = parent.alternate;
}
});
if (!base.alternate) {
throw new Error('Empty case blocks are not supported');
}
parent.alternate = defaultValue;
return this.visit(base.alternate, mode, block);
},
// [ "JSX", "Expression", "Statement" ]
visitCode(node, mode, block) {
if (node.buffer && !node.mustEscape) {
throw new Error('Unescaped, buffered code is not supported in react-pug');
}
switch (mode) {
case 'jsx':
return this.wrapExpressionInJSX(this.visitCode(node, 'jsExpression', block));
case 'jsExpression':
if (node.buffer) {
return this.parseExpression(node.val);
}
// TODO: hoist and rename `const` and `let` variables
return t.doExpression(
t.blockStatement([
this.parseStatement(node.val),
t.expressionStatement(t.nullLiteral()),
]),
);
case 'jsStatements':
if (node.buffer) {
return [this.getPushStatement(this.parseExpression(node.val))];
}
return [this.parseStatement(node.val)];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "ConditionalExpression", "IfStatement" ]
visitConditional(node, mode, block) {
if (node.alternate && node.alternate.type === 'Conditional') {
node.alternate = {nodes: [node.alternate]};
}
const test = this.parseExpression(node.test);
switch (mode) {
case 'jsx':
return t.jSXExpressionContainer(this.visitConditional(node, 'jsExpression', block));
case 'jsExpression':
const condConsequentBlock = this.staticBlock(block);
const condConsequent = this.joinJsExpressions(
node.consequent.nodes.map(
node => this.visit(node, 'jsExpression', condConsequentBlock),
).filter(Boolean),
);
condConsequentBlock.end();
let condAlternate = t.nullLiteral();
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
condAlternate = this.joinJsExpressions(
node.alternate.nodes.map(
node => this.visit(node, 'jsExpression', alternateBlock),
).filter(Boolean),
);
alternateBlock.end();
}
return t.conditionalExpression(
test,
condConsequent,
condAlternate,
);
case 'jsStatements':
const ifConsequentBlock = this.staticBlock(block);
const ifConsequent = t.blockStatement(
this.joinJsStatements(
node.consequent.nodes.map(
node => this.visit(node, 'jsStatements', ifConsequentBlock),
),
),
);
ifConsequentBlock.end();
let ifAlternate = null;
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
ifAlternate = t.blockStatement(
this.joinJsStatements(
node.alternate.nodes.map(
node => this.visit(node, 'jsStatements', alternateBlock),
),
),
);
alternateBlock.end();
}
return [
t.ifStatement(
test,
ifConsequent,
ifAlternate,
),
];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "DoExpression", "WhileStatement" ]
visitEach(node, mode, block) {
if (mode === 'jsx') {
return this.wrapExpressionInJSX(this.visitEach(node, 'jsExpression', block));
}
if (mode === 'jsExpression') {
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
nodes,
t.arrayExpression([]),
),
],
);
const end = t.expressionStatement(nodes);
return t.doExpression(
t.blockStatement([variableDeclaration, ...(this.visitEach(node, 'jsStatements', block)), end]),
);
}
const childBlock = this.dynamicBlock(block, node.line);
const obj = path.scope.generateUidIdentifier('pug_arr');
const objLength = t.memberExpression(
obj,
t.identifier('length'),
);
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
obj,
this.parseExpression(node.obj),
),
],
);
const index = node.key ? t.identifier(node.key) : path.scope.generateUidIdentifier('pug_index');
const init = t.variableDeclaration(
'let',
[
t.variableDeclarator(
index,
t.numericLiteral(0),
),
],
);
const test = t.binaryExpression(
'<',
index,
objLength,
);
const update = t.updateExpression(
'++',
index
);
let loop = t.forStatement(init, test, update, t.blockStatement(
[
t.variableDeclaration(
'const',
[
t.variableDeclarator(
t.identifier(node.val),
t.memberExpression(
obj,
index,
true,
),
),
],
),
].concat(
this.joinJsStatements(
node.block.nodes.map(
node => this.visit(node, 'jsStatements', childBlock),
),
),
),
));
childBlock.end();
if (node.alternate) {
const alternateBlock = this.staticBlock(block);
const alternate = t.blockStatement(this.joinJsStatements(
node.alternate.nodes.map(
node => this.visit(node, 'jsStatements', alternateBlock),
).filter(Boolean),
));
alternateBlock.end();
loop = t.ifStatement(
objLength,
loop,
alternate,
);
}
return [
variableDeclaration,
t.ifStatement(
t.callExpression(
t.memberExpression(
t.identifier('Array'),
t.identifier('isArray'),
),
[obj],
),
t.blockStatement([loop]),
t.blockStatement([
t.throwStatement(
t.newExpression(
t.identifier('TypeError'),
[t.stringLiteral('Expected ' + node.obj + ' to be an array.')],
),
),
]),
),
];
},
// returns ["JSXElement", "JSXElement", "PushStatement"] ]
visitTag(node, mode, block) {
const name = t.jSXIdentifier(node.name);
const children = (
(
node.code ?
[this.visitCode(node.code, 'jsx', this.baseBlock())] :
[]
).concat(node.block.nodes.map(
node => this.visit(node, 'jsx', this.baseBlock())
).filter(Boolean))
// TODO: assert that these are all valid jsx things
);
if (node.attributeBlocks.length) {
throw new Error('Attribute blocks are not yet supported in react-pug');
}
const classes = [];
const attrs = node.attrs.map(
({name, val, mustEscape}) => {
if (/\.\.\./.test(name) && val === true) {
return t.jSXSpreadAttribute(this.parseExpression(name.substr(3)));
}
switch (name) {
case 'for':
name = 'htmlFor';
break;
case 'maxlength':
name = 'maxLength';
break;
case 'class':
name = 'className';
break;
}
const expr = this.parseExpression(val === true ? 'true' : val);
if (!mustEscape && (!t.isStringLiteral(expr) || /(\<\>\&)/.test(val))) {
throw new Error('Unescaped attributes are not supported in react-pug');
}
if (name === 'className') {
classes.push(expr);
return null;
}
const jsxValue = (
t.isStringLiteral(expr) || t.isJSXElement(expr)
? expr
: t.jSXExpressionContainer(expr)
);
if (/\.\.\./.test(name)) {
throw new Error('spread attributes must not have a value');
}
return t.jSXAttribute(
t.jSXIdentifier(name),
jsxValue,
);
},
).filter(Boolean);
if (classes.length) {
const value = (
classes.every(cls => t.isStringLiteral(cls))
? t.stringLiteral(classes.map(cls => cls.value).join(' '))
: (
t.jSXExpressionContainer(
t.callExpression(
t.memberExpression(
t.arrayExpression(classes),
t.identifier('join'),
),
[
t.stringLiteral(' '),
],
),
)
)
);
attrs.push(t.jSXAttribute(t.jSXIdentifier('className'), value));
}
block.handleAttributes(attrs);
const open = t.jSXOpeningElement(
name,
attrs, // Array<JSXAttribute | JSXSpreadAttribute>
children.length === 0,
);
const close = (
children.length === 0
? null
: t.jSXClosingElement(name)
);
const element = t.jSXElement(
open,
close,
children, // ["StringLiteral","JSXExpressionContainer","JSXElement"]
children.length === 0
);
switch (mode) {
case 'jsx':
case 'jsExpression':
return element;
case 'jsStatements':
return [this.getPushStatement(element)];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXText", "StringLiteral", "PushStatement"]
visitText(node, mode, block) {
switch (mode) {
case 'jsx':
return t.jSXText(node.val);
case 'jsExpression':
return t.stringLiteral(node.val);
case 'jsStatements':
return [this.getPushStatement(this.visitText(node, 'jsExpression', block))];
default:
throw new Error('Unexpected mode "' + mode + '" should be "jsx", "jsStatement" or "jsExpression"');
}
},
// [ "JSXExpressionContainer", "DoExpression", "WhileStatement" ]
visitWhile(node, mode, block) {
if (mode === 'jsx') {
return this.wrapExpressionInJSX(this.visitWhile(node, 'jsExpression', block));
}
if (mode === 'jsExpression') {
const variableDeclaration = t.variableDeclaration(
'const',
[
t.variableDeclarator(
nodes,
t.arrayExpression([]),
),
],
);
const end = t.expressionStatement(nodes);
return t.doExpression(
t.blockStatement([variableDeclaration, ...(this.visitWhile(node, 'jsStatements', block)), end]),
);
}
const childBlock = this.dynamicBlock(block, node.line);
const test = this.parseExpression(node.test);
const body = t.blockStatement(
this.joinJsStatements(
node.block.nodes.map(
node => this.visit(node, 'jsStatements', childBlock),
).filter(Boolean),
),
);
childBlock.end();
return [t.whileStatement(test, body)];
},
};
return ast.nodes.map(node => compiler.visit(node, 'jsExpression', compiler.baseBlock()));
}
| Add locations to parsed JavaScript
| src/code-gen.js | Add locations to parsed JavaScript | <ide><path>rc/code-gen.js
<ide> // - Code(buffer: false + block)
<ide> // - Each(object)
<ide>
<add>function addLocToAst(ast, line) {
<add> if (ast.loc) {
<add> ast.loc = {
<add> start: {line: line + ast.loc.start.line, column: 0},
<add> end: {line: line + ast.loc.end.line, column: 0},
<add> };
<add> Object.keys(ast).forEach(key => {
<add> if (Array.isArray(ast[key])) {
<add> ast[key].forEach(n => addLocToAst(n, line));
<add> } else if (ast[key] && typeof ast[key] === 'object') {
<add> addLocToAst(ast[key], line);
<add> }
<add> });
<add> }
<add>}
<ide> export default function ({babel, parse, helpers, ast, path, code}) {
<ide> const {types} = babel;
<ide> const baseLine = path.node.loc.start.line;
<ide> parseExpression(src) {
<ide> const val = parse('x = (' + src + ');').program.body;
<ide> assert(val.length === 1);
<add> // TODO: add the correct column number
<add> addLocToAst(val, baseLine + lastLine);
<ide> return val[0].expression.right;
<ide> },
<ide> parseStatement(src) {
<ide> const val = parse(src).program.body;
<ide> assert(val.length === 1);
<add> // TODO: add the correct column number
<add> addLocToAst(val, baseLine + lastLine);
<ide> return val[0];
<ide> },
<ide> |
|
JavaScript | mit | 5c7400baba60c7a138310162d436bff67cfb60f3 | 0 | robianmcd/image-server | var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
var images = [
{url: 'http://i.imgur.com/DuMqW96.jpg', description: 'Owl Creek Pass, Colorado by Stuart Gordon'},
{url: 'http://i.imgur.com/2CCGvhw.jpg', description: 'This owl is appears enamored with a leaf'},
{url: 'http//i.imgur.com/ZM2xE1A.jpg', description: 'This stop sign has a sign under it to remind you that the above stop sign is a stop sign'},
{url: 'http://i.imgur.com/j18XC9i.jpg', description: 'The most boring superhero ever'}
];
app.get('/', function (req, res) {
res.send(images);
});
app.post('/', function(req, res) {
if(req.body.url && req.body.description && typeof req.body.url === 'string' && typeof req.body.description === 'string') {
images.unshift({url: req.body.url, description: req.body.description});
while(images.length > 20) {
images.pop();
}
res.send(200);
} else {
res.send(400, 'Post body must contain a url and a description and they must be strings');
}
});
var server = app.listen(3000, function () {
console.log('Listening');
}); | server.js | var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var images = [
{url: 'http://i.imgur.com/DuMqW96.jpg', description: 'Owl Creek Pass, Colorado by Stuart Gordon'},
{url: 'http://i.imgur.com/2CCGvhw.jpg', description: 'This owl is appears enamored with a leaf'},
{url: 'http//i.imgur.com/ZM2xE1A.jpg', description: 'This stop sign has a sign under it to remind you that the above stop sign is a stop sign'},
{url: 'http://i.imgur.com/j18XC9i.jpg', description: 'The most boring superhero ever'}
];
app.get('/', function (req, res) {
res.send(images);
});
app.post('/', function(req, res) {
if(req.body.url && req.body.description && typeof req.body.url === 'string' && typeof req.body.description === 'string') {
images.unshift({url: req.body.url, description: req.body.description});
while(images.length > 20) {
images.pop();
}
res.send(200);
} else {
res.send(400, 'Post body must contain a url and a description and they must be strings');
}
});
var server = app.listen(3000, function () {
console.log('Listening');
}); | test heroku deploy
| server.js | test heroku deploy | <ide><path>erver.js
<ide> var express = require('express');
<ide> var app = express();
<ide> var bodyParser = require('body-parser');
<del>app.use( bodyParser.json() ); // to support JSON-encoded bodies
<del>app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
<add>app.use( bodyParser.json() );
<add>app.use(bodyParser.urlencoded({
<ide> extended: true
<ide> }));
<ide> |
|
Java | apache-2.0 | a39ea1208433dbdea66ad889426048460ec64e30 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.startup.impl;
import com.intellij.diagnostic.*;
import com.intellij.diagnostic.StartUpMeasurer.Activities;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.lightEdit.LightEdit;
import com.intellij.ide.lightEdit.LightEditCompatible;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.plugins.cl.PluginClassLoader;
import com.intellij.ide.startup.ServiceNotReadyException;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionNotApplicableException;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.extensions.impl.ExtensionPointImpl;
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.impl.ProjectManagerExImplKt;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.GuiUtils;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.concurrency.AppExecutorUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("IncorrectParentDisposable")
@ApiStatus.Internal
public class StartupManagerImpl extends StartupManagerEx {
private static final Logger LOG = Logger.getInstance(StartupManagerImpl.class);
private static final long EDT_WARN_THRESHOLD_IN_NANO = TimeUnit.MILLISECONDS.toNanos(100);
private final Object myLock = new Object();
private final Deque<Runnable> startupActivities = new ArrayDeque<>();
private final Deque<Runnable> postStartupActivities = new ArrayDeque<>();
@MagicConstant(intValues = {0, DUMB_AWARE_PASSED, ALL_PASSED})
private volatile int postStartupActivitiesPassed;
private final CompletableFuture<Object> allActivitiesPassed = new CompletableFuture<>();
private static final int DUMB_AWARE_PASSED = 1;
private static final int ALL_PASSED = 2;
private volatile boolean myStartupActivitiesPassed;
private final Project myProject;
public StartupManagerImpl(@NotNull Project project) {
myProject = project;
}
private void checkNonDefaultProject() {
LOG.assertTrue(!myProject.isDefault(), "Please don't register startup activities for the default project: they won't ever be run");
}
@Override
public void registerStartupActivity(@NotNull Runnable runnable) {
checkNonDefaultProject();
LOG.assertTrue(!myStartupActivitiesPassed, "Registering startup activity that will never be run");
synchronized (myLock) {
startupActivities.add(runnable);
}
}
@Override
public void registerPostStartupActivity(@NotNull Runnable runnable) {
if (DumbService.isDumbAware(runnable)) {
runAfterOpened(runnable);
return;
}
checkNonDefaultProject();
checkThatPostActivitiesNotPassed();
LOG.warn("Activities registered via registerPostStartupActivity must be dumb-aware: " + runnable);
synchronized (myLock) {
checkThatPostActivitiesNotPassed();
postStartupActivities.add((DumbAwareRunnable)() -> {
DumbService.getInstance(myProject).unsafeRunWhenSmart(runnable);
});
}
}
private void checkThatPostActivitiesNotPassed() {
if (postStartupActivityPassed()) {
LOG.error("Registering post-startup activity that will never be run:" +
" disposed=" + myProject.isDisposed() + "; open=" + myProject.isOpen() +
"; passed=" + myStartupActivitiesPassed);
}
}
@Override
public boolean startupActivityPassed() {
return myStartupActivitiesPassed;
}
@Override
public boolean postStartupActivityPassed() {
return postStartupActivitiesPassed == ALL_PASSED;
}
@Override
public @NotNull Future<Object> getAllActivitiesPassedFuture() {
return allActivitiesPassed;
}
public final void projectOpened(@Nullable ProgressIndicator indicator) {
Application app = ApplicationManager.getApplication();
if (indicator != null && app.isInternal()) {
indicator.setText(IdeBundle.message("startup.indicator.text.running.startup.activities"));
}
runStartUpActivities(indicator);
if (indicator != null) {
indicator.checkCanceled();
}
LoadingState phase = DumbService.isDumb(myProject) ? LoadingState.PROJECT_OPENED : LoadingState.INDEXING_FINISHED;
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, phase);
if (app.isUnitTestMode() && !app.isDispatchThread()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, this::runPostStartupActivities);
}
else {
AppExecutorUtil.getAppExecutorService().execute(() -> {
if (!myProject.isDisposed()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, this::runPostStartupActivities);
}
});
if (app.isUnitTestMode()) {
LOG.assertTrue(app.isDispatchThread());
ProjectManagerExImplKt.waitAndProcessInvocationEventsInIdeEventQueue(this);
}
}
}
private void runStartUpActivities(@Nullable ProgressIndicator indicator) {
LOG.assertTrue(!myStartupActivitiesPassed);
Activity activity = StartUpMeasurer.startMainActivity("project startup");
runActivities(startupActivities, indicator, null);
ExtensionsAreaImpl area = (ExtensionsAreaImpl)ApplicationManager.getApplication().getExtensionArea();
executeActivitiesFromExtensionPoint(indicator, area.getExtensionPoint("com.intellij.startupActivity"));
myStartupActivitiesPassed = true;
activity.end();
}
private void executeActivitiesFromExtensionPoint(@Nullable ProgressIndicator indicator,
@SuppressWarnings("SameParameterValue") @NotNull ExtensionPointImpl<StartupActivity> extensionPoint) {
// use processImplementations to not even create extension if not white-listed
extensionPoint.processImplementations(/* shouldBeSorted = */ true, (supplier, pluginDescriptor) -> {
if (myProject.isDisposed()) {
return;
}
PluginId id = pluginDescriptor.getPluginId();
if (!(id == PluginManagerCore.CORE_ID ||
id == PluginManagerCore.JAVA_PLUGIN_ID ||
id.getIdString().equals("com.jetbrains.performancePlugin") ||
id.getIdString().equals("com.intellij.kotlinNative.platformDeps"))) {
LOG.error("Only bundled plugin can define " + extensionPoint.getName() + ": " + pluginDescriptor);
return;
}
if (indicator != null) {
indicator.checkCanceled();
}
try {
runActivity(null, supplier.get(), pluginDescriptor, indicator);
}
catch (ExtensionNotApplicableException ignore) {
}
});
}
// Must be executed in a pooled thread outside of project loading modal task. The only exclusion - test mode.
private void runPostStartupActivities() {
LOG.assertTrue(myStartupActivitiesPassed);
PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot();
// strictly speaking, the activity is not sequential, because sub-activities are performed in different threads
// (depending on dumb-awareness), but because there is no other concurrent phase,ur
// we measure it as a sequential activity to put it on the timeline and make clear what's going on the end (avoid last "unknown" phase)
Activity dumbAwareActivity = StartUpMeasurer.startMainActivity(Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES);
AtomicReference<Activity> edtActivity = new AtomicReference<>();
AtomicBoolean uiFreezeWarned = new AtomicBoolean();
AtomicInteger counter = new AtomicInteger();
DumbService dumbService = DumbService.getInstance(myProject);
StartupActivity.POST_STARTUP_ACTIVITY.processWithPluginDescriptor((extension, pluginDescriptor) -> {
if (myProject.isDisposed()) {
return;
}
if (DumbService.isDumbAware(extension)) {
runActivity(null, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
return;
}
if (edtActivity.get() == null) {
edtActivity.set(StartUpMeasurer.startMainActivity("project post-startup edt activities"));
}
counter.incrementAndGet();
dumbService.unsafeRunWhenSmart(() -> {
runActivity(uiFreezeWarned, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
dumbUnawarePostActivitiesPassed(edtActivity, counter.decrementAndGet());
});
});
dumbUnawarePostActivitiesPassed(edtActivity, counter.get());
if (myProject.isDisposed()) {
return;
}
runPostStartupActivitiesRegisteredDynamically();
dumbAwareActivity.end();
snapshot.logResponsivenessSinceCreation("Post-startup activities under progress");
if (!myProject.isDisposed() && !ApplicationManager.getApplication().isUnitTestMode()) {
scheduleBackgroundPostStartupActivities();
//noinspection TestOnlyProblems
addActivityEpListener(myProject);
}
}
@TestOnly
public static void addActivityEpListener(@NotNull Project project) {
StartupActivity.POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull StartupActivity extension, @NotNull PluginDescriptor pluginDescriptor) {
StartupManagerImpl startupManager = ((StartupManagerImpl)getInstance(project));
if (DumbService.isDumbAware(extension)) {
AppExecutorUtil.getAppExecutorService().execute(() -> {
if (!project.isDisposed()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(project, () -> {
startupManager.runActivity(null, extension, pluginDescriptor, ProgressManager.getInstance().getProgressIndicator());
});
}
});
}
else {
DumbService.getInstance(project).unsafeRunWhenSmart(() -> {
startupManager.runActivity(null, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
});
}
}
}, project);
}
private static void dumbUnawarePostActivitiesPassed(@NotNull AtomicReference<Activity> edtActivity, int count) {
if (count != 0) {
return;
}
Activity activity = edtActivity.getAndSet(null);
if (activity != null) {
activity.end();
}
}
private void runActivity(@Nullable AtomicBoolean uiFreezeWarned, @NotNull StartupActivity extension, @NotNull PluginDescriptor pluginDescriptor, @Nullable ProgressIndicator indicator) {
if (indicator != null) {
indicator.pushState();
}
long startTime = StartUpMeasurer.getCurrentTime();
try {
runStartupActivity(extension);
}
catch (ServiceNotReadyException e) {
LOG.error(new Exception(e));
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error(e);
}
finally {
if (indicator != null) {
indicator.popState();
}
}
String pluginId = pluginDescriptor.getPluginId().getIdString();
long duration = StartUpMeasurer.addCompletedActivity(startTime, extension.getClass(), ActivityCategory.POST_STARTUP_ACTIVITY, pluginId, StartUpMeasurer.MEASURE_THRESHOLD);
if (uiFreezeWarned != null && duration > EDT_WARN_THRESHOLD_IN_NANO) {
reportUiFreeze(uiFreezeWarned);
}
}
private void runStartupActivity(@NotNull StartupActivity activity) {
if (!LightEdit.owns(myProject) || activity instanceof LightEditCompatible) {
activity.runActivity(myProject);
}
}
private static void reportUiFreeze(@NotNull AtomicBoolean uiFreezeWarned) {
Application app = ApplicationManager.getApplication();
if (!app.isUnitTestMode() && app.isDispatchThread() && uiFreezeWarned.compareAndSet(false, true)) {
LOG.info(
"Some post-startup activities freeze UI for noticeable time. Please consider making them DumbAware to run them in background" +
" under modal progress, or just making them faster to speed up project opening.");
}
}
private void runPostStartupActivitiesRegisteredDynamically() {
runActivities(postStartupActivities, null, "project post-startup");
postStartupActivitiesPassed = DUMB_AWARE_PASSED;
DumbService.getInstance(myProject).unsafeRunWhenSmart(new Runnable() {
@Override
public void run() {
synchronized (myLock) {
if (postStartupActivities.isEmpty()) {
postStartupActivitiesPassed = ALL_PASSED;
allActivitiesPassed.complete(null);
return;
}
}
runActivities(postStartupActivities, null, null);
DumbService dumbService = DumbService.getInstance(myProject);
if (dumbService.isDumb()) {
// return here later to process newly submitted activities (if any) and set postStartupActivitiesPassed
dumbService.unsafeRunWhenSmart(this);
}
else {
postStartupActivitiesPassed = ALL_PASSED;
allActivitiesPassed.complete(null);
}
}
});
}
private void runActivities(@NotNull Deque<? extends Runnable> activities, @Nullable ProgressIndicator indicator, @Nullable String activityName) {
synchronized (myLock) {
if (activities.isEmpty()) {
return;
}
}
Activity activity = activityName == null ? null : StartUpMeasurer.startMainActivity(activityName);
while (true) {
Runnable runnable;
synchronized (myLock) {
runnable = activities.pollFirst();
}
if (indicator != null) {
indicator.checkCanceled();
}
if (runnable == null) {
break;
}
long startTime = StartUpMeasurer.getCurrentTime();
ClassLoader loader = runnable.getClass().getClassLoader();
String pluginId = loader instanceof PluginClassLoader
? ((PluginClassLoader)loader).getPluginId().getIdString()
: PluginManagerCore.CORE_ID.getIdString();
runActivity(runnable);
StartUpMeasurer.addCompletedActivity(startTime, runnable.getClass(), ActivityCategory.POST_STARTUP_ACTIVITY, pluginId, StartUpMeasurer.MEASURE_THRESHOLD);
}
if (activity != null) {
activity.end();
}
}
private void scheduleBackgroundPostStartupActivities() {
ScheduledFuture<?> scheduledFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
if (myProject.isDisposed()) {
return;
}
long startTimeNano = System.nanoTime();
StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull StartupActivity.Background extension, @NotNull PluginDescriptor pluginDescriptor) {
runStartupActivity(extension);
}
}, myProject);
List<StartupActivity.Background> activities = StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.getExtensionList();
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, () -> {
for (StartupActivity activity : activities) {
ProgressManager.checkCanceled();
if (myProject.isDisposed()) {
return;
}
runStartupActivity(activity);
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("Background post-startup activities done in " + TimeoutUtil.getDurationMillis(startTimeNano) + "ms");
}
}, Registry.intValue("ide.background.post.startup.activity.delay"), TimeUnit.MILLISECONDS);
Disposer.register(myProject, () -> {
scheduledFuture.cancel(false);
});
}
public static void runActivity(@NotNull Runnable runnable) {
ProgressManager.checkCanceled();
try {
runnable.run();
}
catch (ServiceNotReadyException e) {
LOG.error(new Exception(e));
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error(e);
}
}
@Override
public void runWhenProjectIsInitialized(@NotNull Runnable action) {
if (DumbService.isDumbAware(action)) {
runAfterOpened(() -> {
GuiUtils.invokeLaterIfNeeded(action, ModalityState.NON_MODAL, myProject.getDisposed());
});
}
else {
runAfterOpened(() -> {
DumbService.getInstance(myProject).unsafeRunWhenSmart(action);
});
}
}
@Override
public void runAfterOpened(@NotNull Runnable runnable) {
checkNonDefaultProject();
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
synchronized (myLock) {
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
postStartupActivities.add(runnable);
return;
}
}
}
runnable.run();
}
@TestOnly
public synchronized void prepareForNextTest() {
synchronized (myLock) {
startupActivities.clear();
postStartupActivities.clear();
}
}
@TestOnly
public synchronized void checkCleared() {
try {
synchronized (myLock) {
assert startupActivities.isEmpty() : "Activities: " + startupActivities;
assert postStartupActivities.isEmpty() : "DumbAware Post Activities: " + postStartupActivities;
}
}
finally {
prepareForNextTest();
}
}
} | platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.startup.impl;
import com.intellij.diagnostic.*;
import com.intellij.diagnostic.StartUpMeasurer.Activities;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.ide.plugins.cl.PluginClassLoader;
import com.intellij.ide.startup.ServiceNotReadyException;
import com.intellij.ide.startup.StartupManagerEx;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionNotApplicableException;
import com.intellij.openapi.extensions.ExtensionPointListener;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.extensions.impl.ExtensionPointImpl;
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.BackgroundTaskUtil;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.impl.ProjectManagerExImplKt;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.GuiUtils;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.concurrency.AppExecutorUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
@SuppressWarnings("IncorrectParentDisposable")
@ApiStatus.Internal
public class StartupManagerImpl extends StartupManagerEx {
private static final Logger LOG = Logger.getInstance(StartupManagerImpl.class);
private static final long EDT_WARN_THRESHOLD_IN_NANO = TimeUnit.MILLISECONDS.toNanos(100);
private final Object myLock = new Object();
private final Deque<Runnable> startupActivities = new ArrayDeque<>();
private final Deque<Runnable> postStartupActivities = new ArrayDeque<>();
@MagicConstant(intValues = {0, DUMB_AWARE_PASSED, ALL_PASSED})
private volatile int postStartupActivitiesPassed;
private final CompletableFuture<Object> allActivitiesPassed = new CompletableFuture<>();
private static final int DUMB_AWARE_PASSED = 1;
private static final int ALL_PASSED = 2;
private volatile boolean myStartupActivitiesPassed;
private final Project myProject;
public StartupManagerImpl(@NotNull Project project) {
myProject = project;
}
private void checkNonDefaultProject() {
LOG.assertTrue(!myProject.isDefault(), "Please don't register startup activities for the default project: they won't ever be run");
}
@Override
public void registerStartupActivity(@NotNull Runnable runnable) {
checkNonDefaultProject();
LOG.assertTrue(!myStartupActivitiesPassed, "Registering startup activity that will never be run");
synchronized (myLock) {
startupActivities.add(runnable);
}
}
@Override
public void registerPostStartupActivity(@NotNull Runnable runnable) {
if (DumbService.isDumbAware(runnable)) {
runAfterOpened(runnable);
return;
}
checkNonDefaultProject();
checkThatPostActivitiesNotPassed();
LOG.warn("Activities registered via registerPostStartupActivity must be dumb-aware: " + runnable);
synchronized (myLock) {
checkThatPostActivitiesNotPassed();
postStartupActivities.add((DumbAwareRunnable)() -> {
DumbService.getInstance(myProject).unsafeRunWhenSmart(runnable);
});
}
}
private void checkThatPostActivitiesNotPassed() {
if (postStartupActivityPassed()) {
LOG.error("Registering post-startup activity that will never be run:" +
" disposed=" + myProject.isDisposed() + "; open=" + myProject.isOpen() +
"; passed=" + myStartupActivitiesPassed);
}
}
@Override
public boolean startupActivityPassed() {
return myStartupActivitiesPassed;
}
@Override
public boolean postStartupActivityPassed() {
return postStartupActivitiesPassed == ALL_PASSED;
}
@Override
public @NotNull Future<Object> getAllActivitiesPassedFuture() {
return allActivitiesPassed;
}
public final void projectOpened(@Nullable ProgressIndicator indicator) {
Application app = ApplicationManager.getApplication();
if (indicator != null && app.isInternal()) {
indicator.setText(IdeBundle.message("startup.indicator.text.running.startup.activities"));
}
runStartUpActivities(indicator);
if (indicator != null) {
indicator.checkCanceled();
}
LoadingState phase = DumbService.isDumb(myProject) ? LoadingState.PROJECT_OPENED : LoadingState.INDEXING_FINISHED;
StartUpMeasurer.compareAndSetCurrentState(LoadingState.COMPONENTS_LOADED, phase);
if (app.isUnitTestMode() && !app.isDispatchThread()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, this::runPostStartupActivities);
}
else {
AppExecutorUtil.getAppExecutorService().execute(() -> {
if (!myProject.isDisposed()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, this::runPostStartupActivities);
}
});
if (app.isUnitTestMode()) {
LOG.assertTrue(app.isDispatchThread());
ProjectManagerExImplKt.waitAndProcessInvocationEventsInIdeEventQueue(this);
}
}
}
private void runStartUpActivities(@Nullable ProgressIndicator indicator) {
LOG.assertTrue(!myStartupActivitiesPassed);
Activity activity = StartUpMeasurer.startMainActivity("project startup");
runActivities(startupActivities, indicator, null);
ExtensionsAreaImpl area = (ExtensionsAreaImpl)ApplicationManager.getApplication().getExtensionArea();
executeActivitiesFromExtensionPoint(indicator, area.getExtensionPoint("com.intellij.startupActivity"));
myStartupActivitiesPassed = true;
activity.end();
}
private void executeActivitiesFromExtensionPoint(@Nullable ProgressIndicator indicator,
@SuppressWarnings("SameParameterValue") @NotNull ExtensionPointImpl<StartupActivity> extensionPoint) {
// use processImplementations to not even create extension if not white-listed
extensionPoint.processImplementations(/* shouldBeSorted = */ true, (supplier, pluginDescriptor) -> {
if (myProject.isDisposed()) {
return;
}
PluginId id = pluginDescriptor.getPluginId();
if (!(id == PluginManagerCore.CORE_ID ||
id == PluginManagerCore.JAVA_PLUGIN_ID ||
id.getIdString().equals("com.jetbrains.performancePlugin") ||
id.getIdString().equals("com.intellij.kotlinNative.platformDeps"))) {
LOG.error("Only bundled plugin can define " + extensionPoint.getName() + ": " + pluginDescriptor);
return;
}
if (indicator != null) {
indicator.checkCanceled();
}
try {
runActivity(null, supplier.get(), pluginDescriptor, indicator);
}
catch (ExtensionNotApplicableException ignore) {
}
});
}
// Must be executed in a pooled thread outside of project loading modal task. The only exclusion - test mode.
private void runPostStartupActivities() {
LOG.assertTrue(myStartupActivitiesPassed);
PerformanceWatcher.Snapshot snapshot = PerformanceWatcher.takeSnapshot();
// strictly speaking, the activity is not sequential, because sub-activities are performed in different threads
// (depending on dumb-awareness), but because there is no other concurrent phase,ur
// we measure it as a sequential activity to put it on the timeline and make clear what's going on the end (avoid last "unknown" phase)
Activity dumbAwareActivity = StartUpMeasurer.startMainActivity(Activities.PROJECT_DUMB_POST_START_UP_ACTIVITIES);
AtomicReference<Activity> edtActivity = new AtomicReference<>();
AtomicBoolean uiFreezeWarned = new AtomicBoolean();
AtomicInteger counter = new AtomicInteger();
DumbService dumbService = DumbService.getInstance(myProject);
StartupActivity.POST_STARTUP_ACTIVITY.processWithPluginDescriptor((extension, pluginDescriptor) -> {
if (myProject.isDisposed()) {
return;
}
if (DumbService.isDumbAware(extension)) {
runActivity(null, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
return;
}
if (edtActivity.get() == null) {
edtActivity.set(StartUpMeasurer.startMainActivity("project post-startup edt activities"));
}
counter.incrementAndGet();
dumbService.unsafeRunWhenSmart(() -> {
runActivity(uiFreezeWarned, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
dumbUnawarePostActivitiesPassed(edtActivity, counter.decrementAndGet());
});
});
dumbUnawarePostActivitiesPassed(edtActivity, counter.get());
if (myProject.isDisposed()) {
return;
}
runPostStartupActivitiesRegisteredDynamically();
dumbAwareActivity.end();
snapshot.logResponsivenessSinceCreation("Post-startup activities under progress");
if (!myProject.isDisposed() && !ApplicationManager.getApplication().isUnitTestMode()) {
scheduleBackgroundPostStartupActivities();
//noinspection TestOnlyProblems
addActivityEpListener(myProject);
}
}
@TestOnly
public static void addActivityEpListener(@NotNull Project project) {
StartupActivity.POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull StartupActivity extension, @NotNull PluginDescriptor pluginDescriptor) {
StartupManagerImpl startupManager = ((StartupManagerImpl)getInstance(project));
if (DumbService.isDumbAware(extension)) {
AppExecutorUtil.getAppExecutorService().execute(() -> {
if (!project.isDisposed()) {
BackgroundTaskUtil.runUnderDisposeAwareIndicator(project, () -> {
startupManager.runActivity(null, extension, pluginDescriptor, ProgressManager.getInstance().getProgressIndicator());
});
}
});
}
else {
DumbService.getInstance(project).unsafeRunWhenSmart(() -> {
startupManager.runActivity(null, extension, pluginDescriptor, ProgressIndicatorProvider.getGlobalProgressIndicator());
});
}
}
}, project);
}
private static void dumbUnawarePostActivitiesPassed(@NotNull AtomicReference<Activity> edtActivity, int count) {
if (count != 0) {
return;
}
Activity activity = edtActivity.getAndSet(null);
if (activity != null) {
activity.end();
}
}
private void runActivity(@Nullable AtomicBoolean uiFreezeWarned, @NotNull StartupActivity extension, @NotNull PluginDescriptor pluginDescriptor, @Nullable ProgressIndicator indicator) {
if (indicator != null) {
indicator.pushState();
}
long startTime = StartUpMeasurer.getCurrentTime();
try {
extension.runActivity(myProject);
}
catch (ServiceNotReadyException e) {
LOG.error(new Exception(e));
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error(e);
}
finally {
if (indicator != null) {
indicator.popState();
}
}
String pluginId = pluginDescriptor.getPluginId().getIdString();
long duration = StartUpMeasurer.addCompletedActivity(startTime, extension.getClass(), ActivityCategory.POST_STARTUP_ACTIVITY, pluginId, StartUpMeasurer.MEASURE_THRESHOLD);
if (uiFreezeWarned != null && duration > EDT_WARN_THRESHOLD_IN_NANO) {
reportUiFreeze(uiFreezeWarned);
}
}
private static void reportUiFreeze(@NotNull AtomicBoolean uiFreezeWarned) {
Application app = ApplicationManager.getApplication();
if (!app.isUnitTestMode() && app.isDispatchThread() && uiFreezeWarned.compareAndSet(false, true)) {
LOG.info(
"Some post-startup activities freeze UI for noticeable time. Please consider making them DumbAware to run them in background" +
" under modal progress, or just making them faster to speed up project opening.");
}
}
private void runPostStartupActivitiesRegisteredDynamically() {
runActivities(postStartupActivities, null, "project post-startup");
postStartupActivitiesPassed = DUMB_AWARE_PASSED;
DumbService.getInstance(myProject).unsafeRunWhenSmart(new Runnable() {
@Override
public void run() {
synchronized (myLock) {
if (postStartupActivities.isEmpty()) {
postStartupActivitiesPassed = ALL_PASSED;
allActivitiesPassed.complete(null);
return;
}
}
runActivities(postStartupActivities, null, null);
DumbService dumbService = DumbService.getInstance(myProject);
if (dumbService.isDumb()) {
// return here later to process newly submitted activities (if any) and set postStartupActivitiesPassed
dumbService.unsafeRunWhenSmart(this);
}
else {
postStartupActivitiesPassed = ALL_PASSED;
allActivitiesPassed.complete(null);
}
}
});
}
private void runActivities(@NotNull Deque<? extends Runnable> activities, @Nullable ProgressIndicator indicator, @Nullable String activityName) {
synchronized (myLock) {
if (activities.isEmpty()) {
return;
}
}
Activity activity = activityName == null ? null : StartUpMeasurer.startMainActivity(activityName);
while (true) {
Runnable runnable;
synchronized (myLock) {
runnable = activities.pollFirst();
}
if (indicator != null) {
indicator.checkCanceled();
}
if (runnable == null) {
break;
}
long startTime = StartUpMeasurer.getCurrentTime();
ClassLoader loader = runnable.getClass().getClassLoader();
String pluginId = loader instanceof PluginClassLoader
? ((PluginClassLoader)loader).getPluginId().getIdString()
: PluginManagerCore.CORE_ID.getIdString();
runActivity(runnable);
StartUpMeasurer.addCompletedActivity(startTime, runnable.getClass(), ActivityCategory.POST_STARTUP_ACTIVITY, pluginId, StartUpMeasurer.MEASURE_THRESHOLD);
}
if (activity != null) {
activity.end();
}
}
private void scheduleBackgroundPostStartupActivities() {
ScheduledFuture<?> scheduledFuture = AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> {
if (myProject.isDisposed()) {
return;
}
long startTimeNano = System.nanoTime();
StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<>() {
@Override
public void extensionAdded(@NotNull StartupActivity.Background extension, @NotNull PluginDescriptor pluginDescriptor) {
extension.runActivity(myProject);
}
}, myProject);
List<StartupActivity.Background> activities = StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.getExtensionList();
BackgroundTaskUtil.runUnderDisposeAwareIndicator(myProject, () -> {
for (StartupActivity activity : activities) {
ProgressManager.checkCanceled();
if (myProject.isDisposed()) {
return;
}
activity.runActivity(myProject);
}
});
if (LOG.isDebugEnabled()) {
LOG.debug("Background post-startup activities done in " + TimeoutUtil.getDurationMillis(startTimeNano) + "ms");
}
}, Registry.intValue("ide.background.post.startup.activity.delay"), TimeUnit.MILLISECONDS);
Disposer.register(myProject, () -> {
scheduledFuture.cancel(false);
});
}
public static void runActivity(@NotNull Runnable runnable) {
ProgressManager.checkCanceled();
try {
runnable.run();
}
catch (ServiceNotReadyException e) {
LOG.error(new Exception(e));
}
catch (ProcessCanceledException e) {
throw e;
}
catch (Throwable e) {
LOG.error(e);
}
}
@Override
public void runWhenProjectIsInitialized(@NotNull Runnable action) {
if (DumbService.isDumbAware(action)) {
runAfterOpened(() -> {
GuiUtils.invokeLaterIfNeeded(action, ModalityState.NON_MODAL, myProject.getDisposed());
});
}
else {
runAfterOpened(() -> {
DumbService.getInstance(myProject).unsafeRunWhenSmart(action);
});
}
}
@Override
public void runAfterOpened(@NotNull Runnable runnable) {
checkNonDefaultProject();
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
synchronized (myLock) {
if (postStartupActivitiesPassed < DUMB_AWARE_PASSED) {
postStartupActivities.add(runnable);
return;
}
}
}
runnable.run();
}
@TestOnly
public synchronized void prepareForNextTest() {
synchronized (myLock) {
startupActivities.clear();
postStartupActivities.clear();
}
}
@TestOnly
public synchronized void checkCleared() {
try {
synchronized (myLock) {
assert startupActivities.isEmpty() : "Activities: " + startupActivities;
assert postStartupActivities.isEmpty() : "DumbAware Post Activities: " + postStartupActivities;
}
}
finally {
prepareForNextTest();
}
}
} | light edit: run StartupActivity at startup in LightEdit mode too if the activity is LightEditCompatible (IDEA-233987)
GitOrigin-RevId: 363e94b9a491edb70512ca4ed2e8802a36509807 | platform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java | light edit: run StartupActivity at startup in LightEdit mode too if the activity is LightEditCompatible (IDEA-233987) | <ide><path>latform/platform-impl/src/com/intellij/ide/startup/impl/StartupManagerImpl.java
<ide> import com.intellij.diagnostic.*;
<ide> import com.intellij.diagnostic.StartUpMeasurer.Activities;
<ide> import com.intellij.ide.IdeBundle;
<add>import com.intellij.ide.lightEdit.LightEdit;
<add>import com.intellij.ide.lightEdit.LightEditCompatible;
<ide> import com.intellij.ide.plugins.PluginManagerCore;
<ide> import com.intellij.ide.plugins.cl.PluginClassLoader;
<ide> import com.intellij.ide.startup.ServiceNotReadyException;
<ide> }
<ide> long startTime = StartUpMeasurer.getCurrentTime();
<ide> try {
<del> extension.runActivity(myProject);
<add> runStartupActivity(extension);
<ide> }
<ide> catch (ServiceNotReadyException e) {
<ide> LOG.error(new Exception(e));
<ide> long duration = StartUpMeasurer.addCompletedActivity(startTime, extension.getClass(), ActivityCategory.POST_STARTUP_ACTIVITY, pluginId, StartUpMeasurer.MEASURE_THRESHOLD);
<ide> if (uiFreezeWarned != null && duration > EDT_WARN_THRESHOLD_IN_NANO) {
<ide> reportUiFreeze(uiFreezeWarned);
<add> }
<add> }
<add>
<add> private void runStartupActivity(@NotNull StartupActivity activity) {
<add> if (!LightEdit.owns(myProject) || activity instanceof LightEditCompatible) {
<add> activity.runActivity(myProject);
<ide> }
<ide> }
<ide>
<ide> StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.addExtensionPointListener(new ExtensionPointListener<>() {
<ide> @Override
<ide> public void extensionAdded(@NotNull StartupActivity.Background extension, @NotNull PluginDescriptor pluginDescriptor) {
<del> extension.runActivity(myProject);
<add> runStartupActivity(extension);
<ide> }
<ide> }, myProject);
<ide> List<StartupActivity.Background> activities = StartupActivity.BACKGROUND_POST_STARTUP_ACTIVITY.getExtensionList();
<ide> return;
<ide> }
<ide>
<del> activity.runActivity(myProject);
<add> runStartupActivity(activity);
<ide> }
<ide> });
<ide> if (LOG.isDebugEnabled()) { |
|
Java | apache-2.0 | 9b1353fe88aa0199ceec37eea4139064a7fcd9c6 | 0 | babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble | // JSArray.java
package ed.js;
import java.util.*;
import ed.js.func.*;
import ed.js.engine.*;
import static ed.js.JSInternalFunctions.*;
/**
* http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Iteration_methods
*
* TODO:
* reduce
* redeceRight
* concat
* indexOf (JS 1.6+)
* join
* lastIndexOf (JS 1.6+)
* slice
* toSource
* valueOf
* pop
* reverse
* shift
* unshift
*/
public class JSArray extends JSObjectBase implements Iterable {
public final static JSFunction _cons = new JSArrayCons();
static class JSArrayCons extends JSFunctionCalls0{
public Object call( Scope s , Object[] args ){
throw new RuntimeException( "can't be here" );
}
protected void init(){
_prototype.set( "splice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = ((Number)startObj).intValue();
int num = numObj == null ? 0 : ((Number)numObj).intValue();
for ( int i=start; i<a._array.size() && ( num == 0 || i < start + num ); i++ ){
n.add( a._array.get( i ) );
}
return n;
}
} );
_prototype.set( "remove" , new JSFunctionCalls1() {
public Object call( Scope s , Object idxObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int idx = ((Number)idxObj).intValue();
if ( idx >= a._array.size() )
return null;
return a._array.remove( idx );
}
} );
_prototype.set( "push" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a.add( o );
return a.size();
}
} );
_prototype.set( "concat" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
if ( o == null )
return a;
if ( ! ( o instanceof JSArray ) )
throw new RuntimeException( "trying to concat a non-array");
JSArray tempArray = (JSArray)o;
for ( Object temp : tempArray._array )
a.add( temp );
return a;
}
} );
_prototype.set( "filter" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
n.add( o );
return n;
}
} );
_prototype.set( "unique" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
Set seen = new HashSet();
for ( Object o : a._array ){
if ( seen.contains( o ) )
continue;
seen.add( o );
n.add( o );
}
return n;
}
} );
_prototype.set( "forEach" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( int i=0; i<a._array.size(); i++ )
f.call( s , a._array.get( i ) , i , a._array.size() );
return null;
}
} );
_prototype.set( "every" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( ! JS_evalToBool( f.call( s , o ) ) )
return false;
return true;
}
} );
_prototype.set( "some" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
return true;
return false;
}
} );
_prototype.set( "map" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
n.add( f.call( s , o ) );
return n;
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
for ( Object o : a._array )
if ( JSInternalFunctions.JS_eq( o , test ) )
return true;
return false;
}
} );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
for ( int i=start; i<a._array.size(); i++ )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "sort" , new JSFunctionCalls1() {
public Object call( Scope s , Object func , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( func == null )
Collections.sort( a._array , _normalComparator );
else
Collections.sort( a._array , new MyComparator( s , (JSFunction)func ) );
return a;
}
} );
}
}
public static JSArray create( Object ... obj ){
return new JSArray( obj );
}
public JSArray(){
this( 0 );
}
public JSArray( int init ){
super( _cons );
_array = new ArrayList( Math.max( 16 , init ) );
for ( int i=0; i<init; i++ )
_array.add( null );
}
public JSArray( Object ... obj ){
super( _cons );
_array = new ArrayList( obj.length );
for ( Object o : obj )
_array.add( o );
}
public JSArray( List lst ){
super( _cons );
_array = lst == null ? new ArrayList() : lst;
}
public Object setInt( int pos , Object v ){
while ( _array.size() <= pos )
_array.add( null );
_array.set( pos , v );
return v;
}
public Object getInt( int pos ){
if ( pos >= _array.size() ){
return null;
}
return _array.get( pos );
}
public int size(){
return _array.size();
}
public Object get( Object n ){
if ( n != null )
if ( n instanceof JSString || n instanceof String )
if ( n.toString().equals( "length" ) )
return _array.size();
int idx = _getInt( n );
if ( idx >=0 )
return getInt( idx );
return super.get( n );
}
public Object set( Object n , Object v ){
if ( n.toString().equals( "" ) ){
_array.add( v );
return v;
}
int idx = _getInt( n );
if ( idx < 0 )
return super.set( n , v );
return setInt( idx , v );
}
public Collection<String> keySet(){
Collection<String> p = super.keySet();
List<String> keys = new ArrayList<String>( p.size() + _array.size() );
for ( int i=0; i<_array.size(); i++ )
keys.add( String.valueOf( i ) );
keys.addAll( p );
return keys;
}
public String toString(){
StringBuilder buf = new StringBuilder();
for ( int i=0; i<_array.size(); i++ ){
if ( i > 0 )
buf.append( "," );
buf.append( _array.get( i ) );
}
return buf.toString();
}
public void add( Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
_array.add( o );
}
public void addAll( Collection c ){
_array.addAll( c );
}
public Iterator iterator(){
return _array.iterator();
}
int _getInt( Object o ){
if ( o == null )
return -1;
if ( o instanceof JSString )
o = o.toString();
if ( ! ( o instanceof String ) )
return -1;
String str = o.toString();
for ( int i=0; i<str.length(); i++ )
if ( ! Character.isDigit( str.charAt( i ) ) )
return -1;
return Integer.parseInt( str );
}
public void shuffle(){
Collections.shuffle( _array );
}
public void lock(){
_locked = true;
}
public void clear(){
_array.clear();
}
public boolean isLocked(){
return _locked;
}
private boolean _locked = false;
final List<Object> _array;
static class MyComparator implements Comparator {
MyComparator( Scope s , JSFunction func ){
_scope = s;
_func = func;
}
public int compare( Object l , Object r ){
if ( _func == null ){
if ( l == null && r == null )
return 0;
if ( l == null )
return 1;
if ( r == null )
return -1;
return l.toString().compareTo( r.toString() );
}
return ((Number)(_func.call( _scope , l , r , null ))).intValue();
}
private final Scope _scope;
private final JSFunction _func;
}
static final MyComparator _normalComparator = new MyComparator( null , null );
}
| src/main/ed/js/JSArray.java | // JSArray.java
package ed.js;
import java.util.*;
import ed.js.func.*;
import ed.js.engine.*;
import static ed.js.JSInternalFunctions.*;
/**
* http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array#Iteration_methods
*
* TODO:
* reduce
* redeceRight
* concat
* indexOf (JS 1.6+)
* join
* lastIndexOf (JS 1.6+)
* slice
* toSource
* valueOf
* pop
* reverse
* shift
* unshift
*/
public class JSArray extends JSObjectBase implements Iterable {
public final static JSFunction _cons = new JSArrayCons();
static class JSArrayCons extends JSFunctionCalls0{
public Object call( Scope s , Object[] args ){
throw new RuntimeException( "can't be here" );
}
protected void init(){
_prototype.set( "splice" , new JSFunctionCalls2() {
public Object call( Scope s , Object startObj , Object numObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
int start = ((Number)startObj).intValue();
int num = numObj == null ? 0 : ((Number)numObj).intValue();
for ( int i=start; i<a._array.size() && ( num == 0 || i < start + num ); i++ ){
n.add( a._array.get( i ) );
}
return n;
}
} );
_prototype.set( "remove" , new JSFunctionCalls1() {
public Object call( Scope s , Object idxObj , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int idx = ((Number)idxObj).intValue();
if ( idx >= a._array.size() )
return null;
return a._array.remove( idx );
}
} );
_prototype.set( "push" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
a.add( o );
return a.size();
}
} );
_prototype.set( "concat" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( a == null )
throw new RuntimeException( "this shouldn't be possible. scope id = " + s._id );
if ( o == null )
return a;
if ( ! ( o instanceof JSArray ) )
throw new RuntimeException( "trying to concat a non-array");
JSArray tempArray = (JSArray)o;
for ( Object temp : tempArray._array )
a.add( temp );
return a;
}
} );
_prototype.set( "filter" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
n.add( o );
return n;
}
} );
_prototype.set( "unique" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSArray n = new JSArray();
Set seen = new HashSet();
for ( Object o : a._array ){
if ( seen.contains( o ) )
continue;
seen.add( o );
n.add( o );
}
return n;
}
} );
_prototype.set( "forEach" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( int i=0; i<a._array.size(); i++ )
f.call( s , a._array.get( i ) , i , a._array.size() );
return null;
}
} );
_prototype.set( "every" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( ! JS_evalToBool( f.call( s , o ) ) )
return false;
return true;
}
} );
_prototype.set( "some" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
for ( Object o : a._array )
if ( JS_evalToBool( f.call( s , o ) ) )
return true;
return false;
}
} );
_prototype.set( "map" , new JSFunctionCalls1() {
public Object call( Scope s , Object fo , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
JSFunction f = (JSFunction)fo;
JSArray n = new JSArray();
for ( Object o : a._array )
n.add( f.call( s , o ) );
return n;
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
for ( Object o : a._array )
if ( JSInternalFunctions.JS_eq( o , test ) )
return true;
return false;
}
} );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object test , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] instanceof Number )
start = ((Number)foo[0]).intValue();
for ( int i=start; i<a._array.size(); i++ )
if ( JSInternalFunctions.JS_sheq( test , a._array.get( i ) ) )
return i;
return -1;
}
} );
_prototype.set( "sort" , new JSFunctionCalls1() {
public Object call( Scope s , Object func , Object foo[] ){
JSArray a = (JSArray)(s.getThis());
if ( func == null )
Collections.sort( a._array , _normalComparator );
else
Collections.sort( a._array , new MyComparator( s , (JSFunction)func ) );
return a;
}
} );
}
}
public static JSArray create( Object ... obj ){
return new JSArray( obj );
}
public JSArray(){
this( 0 );
}
public JSArray( int init ){
super( _cons );
_array = new ArrayList( Math.max( 16 , init ) );
for ( int i=0; i<init; i++ )
_array.add( null );
}
public JSArray( Object ... obj ){
super( _cons );
_array = new ArrayList( obj.length );
for ( Object o : obj )
_array.add( o );
}
public JSArray( List lst ){
super( _cons );
_array = lst == null ? new ArrayList() : lst;
}
public Object setInt( int pos , Object v ){
while ( _array.size() <= pos )
_array.add( null );
_array.set( pos , v );
return v;
}
public Object getInt( int pos ){
if ( pos >= _array.size() ){
return null;
}
return _array.get( pos );
}
public int size(){
return _array.size();
}
public Object get( Object n ){
if ( n != null )
if ( n instanceof JSString || n instanceof String )
if ( n.toString().equals( "length" ) )
return _array.size();
int idx = _getInt( n );
if ( idx >=0 )
return getInt( idx );
return super.get( n );
}
public Object set( Object n , Object v ){
if ( n.toString().equals( "" ) ){
_array.add( v );
return v;
}
int idx = _getInt( n );
if ( idx < 0 )
return super.set( n , v );
return setInt( idx , v );
}
public Collection<String> keySet(){
Collection<String> p = super.keySet();
List<String> keys = new ArrayList<String>( p.size() + _array.size() );
for ( int i=0; i<_array.size(); i++ )
keys.add( String.valueOf( i ) );
keys.addAll( p );
return keys;
}
public String toString(){
StringBuilder buf = new StringBuilder();
for ( int i=0; i<_array.size(); i++ ){
if ( i > 0 )
buf.append( "," );
buf.append( _array.get( i ) );
}
return buf.toString();
}
public void add( Object o ){
if ( _locked )
throw new RuntimeException( "array locked" );
_array.add( o );
}
public void addAll( Collection c ){
_array.addAll( c );
}
public Iterator iterator(){
return _array.iterator();
}
int _getInt( Object o ){
if ( o == null )
return -1;
if ( o instanceof JSString )
o = o.toString();
if ( ! ( o instanceof String ) )
return -1;
String str = o.toString();
for ( int i=0; i<str.length(); i++ )
if ( ! Character.isDigit( str.charAt( i ) ) )
return -1;
return Integer.parseInt( str );
}
public void shuffle(){
Collections.shuffle( _array );
}
public void lock(){
_locked = true;
}
public void clear(){
_array.clear();
}
private boolean _locked = false;
final List<Object> _array;
static class MyComparator implements Comparator {
MyComparator( Scope s , JSFunction func ){
_scope = s;
_func = func;
}
public int compare( Object l , Object r ){
if ( _func == null ){
if ( l == null && r == null )
return 0;
if ( l == null )
return 1;
if ( r == null )
return -1;
return l.toString().compareTo( r.toString() );
}
return ((Number)(_func.call( _scope , l , r , null ))).intValue();
}
private final Scope _scope;
private final JSFunction _func;
}
static final MyComparator _normalComparator = new MyComparator( null , null );
}
| isLocked
| src/main/ed/js/JSArray.java | isLocked | <ide><path>rc/main/ed/js/JSArray.java
<ide> _array.clear();
<ide> }
<ide>
<add> public boolean isLocked(){
<add> return _locked;
<add> }
<add>
<ide> private boolean _locked = false;
<ide> final List<Object> _array;
<ide> |
|
Java | apache-2.0 | 128e8c8784b4717a275d55118f96f5726159c156 | 0 | operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver | /*
Copyright 2008-2011 Opera Software ASA
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.opera.core.systems.scope.stp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriverException;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.opera.core.systems.scope.handlers.AbstractEventHandler;
import com.opera.core.systems.scope.handlers.IConnectionHandler;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.scope.protos.UmsProtos;
import com.opera.core.systems.scope.protos.UmsProtos.Command;
import com.opera.core.systems.scope.protos.UmsProtos.Error;
import com.opera.core.systems.scope.protos.UmsProtos.Event;
import com.opera.core.systems.scope.protos.UmsProtos.Response;
import com.opera.core.systems.util.SocketListener;
import com.opera.core.systems.util.SocketMonitor;
public class StpConnection implements SocketListener {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private SocketChannel socketChannel;
// Outgoing send queue
private final ArrayBlockingQueue<ByteBuffer> requests;
private ByteBuffer recvBuffer;
// For STP1
final byte[] prefix = { 'S', 'T', 'P', 1 };
private ByteString stpPrefix = ByteString.copyFrom(prefix);
private AbstractEventHandler eventHandler;
private UmsEventParser stp1EventHandler;
private IConnectionHandler connectionHandler;
public enum State {
SERVICELIST, HANDSHAKE, EMPTY, STP;
}
private State state = State.SERVICELIST;
private void setState(State state) {
// logger.fine("Setting state: " + state.toString());
this.state = state;
}
public boolean isConnected() {
if (socketChannel == null) return false;
return true;
}
/*
@Override
public void finalize() throws Throwable {
logger.severe("STPConnection cleanup");
if (socketChannel != null && socketChannel.isOpen()) {
close();
}
super.finalize();
}
*/
/**
* Initializes variables in object scope, sets 'count known' to false to read
* byte count (STP/0).
*
* @param socket
* @param handler
* @param eventHandler
* @throws IOException
*/
public StpConnection(SocketChannel socket, IConnectionHandler handler,
AbstractEventHandler eventHandler) throws IOException {
connectionHandler = handler;
socketChannel = socket;
this.eventHandler = eventHandler;
requests = new ArrayBlockingQueue<ByteBuffer>(1024);
recvBuffer = ByteBuffer.allocateDirect(65536);
recvBuffer.limit(0);
socket.configureBlocking(false);
SocketMonitor.instance().add(socket, this, SelectionKey.OP_READ);
if (!handler.onConnected(this)) {
close();
throw new IOException(
"Connection not allowed from IConnectionHandler (already connected)");
}
}
private void switchToStp1() {
stp1EventHandler = new UmsEventParser(eventHandler);
sendEnableStp1();
setState(State.HANDSHAKE);
}
/**
* Queues up an STP/1 message sent from another thread and wakes up selector
* to register it to the key
*
* @param command to add to the request queue
* @throws IOException
*/
public void send(Command command) {
logger.log(Level.FINEST, command.toString());
byte[] payload = command.toByteArray();
int totalSize = payload.length + 1; // increment 1 for message type
ByteBuffer outMessageSize = encodeMessageSize(totalSize);
// create the message
ByteBuffer buffer = ByteBuffer.allocateDirect(prefix.length
+ outMessageSize.position() + 1 + payload.length);
buffer.put(prefix, 0, prefix.length);
outMessageSize.flip();
buffer.put(outMessageSize);
buffer.put((byte) 1);
buffer.put(payload);
// log what is being sent.
logger.fine("SEND: " + command.toString());
requests.add(buffer);
SocketMonitor.instance().modify(socketChannel, this,
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public void sendEnableStp1() {
// temporary fix for CORE-33057
try {
Thread.sleep(OperaIntervals.EXEC_SLEEP.getValue());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
send("*enable stp-1");
}
public void sendQuit() {
send("*quit");
}
/**
* Queues up an STP/0 message sent from another thread and wakes up selector
* to register it to the key
*
* @param message to add to the request queue
*/
private void send(String message) {
String scopeMessage = message.length() + " " + message;
logger.fine("WRITE : " + scopeMessage);
byte[] bytes = null;
try {
bytes = scopeMessage.getBytes("UTF-16BE");
} catch (UnsupportedEncodingException e) {
close();
connectionHandler.onException(e);
return;
}
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
requests.add(buffer);
SocketMonitor.instance().modify(socketChannel, this,
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public boolean canRead(SelectableChannel channel) throws IOException {
logger.fine("canRead");
if (!channel.isOpen()) return false;
if (socketChannel == null) throw new IOException(
"We dont have a socket :-)");
// read as much data as possible into buffer!
ByteBuffer readBuffer = ByteBuffer.allocateDirect(1000);
int readSize = 0;
// continue to read data and read messages until there are no messages
boolean didNotFindAnyMessage = false;
while (!didNotFindAnyMessage) {
logger.fine("canReadLoop!");
// read as much data as possible (until recvBuffer is full OR we don't get
// any more data)
do {
readBuffer.clear();
try {
// do we have a socket
if (socketChannel == null) {
readSize = -1;
// do we have room in our buffer?
} else {
readSize = socketChannel.read(readBuffer);
if (readSize > 0) {
readBuffer.limit(readSize);
readBuffer.position(0);
}
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Channel closed, causing exception",
ex.getMessage());
readSize = -1;// same as error from socketChannel.read
}
if (readSize < 0) {
try {
logger.log(Level.FINE, "Channel closed: {0}",
socketChannel.socket().getInetAddress().getHostName());
} catch (NullPointerException e) {
// ignore
}
connectionHandler.onDisconnect();
SocketMonitor.instance().remove(socketChannel);
return false;
} else if (readSize > 0) {
// double buffer size if needed!
if (recvBuffer.limit() + readBuffer.limit() >= recvBuffer.capacity()) {
logger.fine("Doubled the size of our recv buffer!");
ByteBuffer newRecvBuffer = ByteBuffer.allocate(recvBuffer.capacity() * 2);
newRecvBuffer.clear();
recvBuffer.position(0);
newRecvBuffer.limit(recvBuffer.limit());
newRecvBuffer.position(0);
newRecvBuffer.put(recvBuffer);
newRecvBuffer.position(0);
recvBuffer = newRecvBuffer;
}
recvBuffer.position(recvBuffer.limit());
recvBuffer.limit(recvBuffer.limit() + readSize);// increase limit!
recvBuffer.put(readBuffer);
logger.fine("did read " + readSize + " bytes, new buffer size = "
+ recvBuffer.limit());
}
} while (readSize > 0);
// read as many messages as possible, and only
didNotFindAnyMessage = true;
while (readMessage(recvBuffer)) {
didNotFindAnyMessage = false;
}
}
return true;
}
public boolean canWrite(SelectableChannel channel) throws IOException {
logger.fine("canWrite");
if (socketChannel == null) throw new IOException(
"We dont have a socket :-)");
int totalWritten = 0;
while (!requests.isEmpty()) {
ByteBuffer buffer = requests.poll();
buffer.flip();
int written = 0;
do {
written = socketChannel.write(buffer);
if (written <= 0) break;
if (written > 0) totalWritten += written;
} while (buffer.hasRemaining());
}
logger.fine("Wrote " + totalWritten + " bytes");
return (!requests.isEmpty());
}
/**
* Switches the wait state and wakes up the selector to process
*/
public void close() {
if (socketChannel == null) return;
SocketMonitor.instance().remove(socketChannel);
try {
socketChannel.close();
} catch (IOException ignored) {
/* nothing to be done */
} finally {
socketChannel = null;
}
}
/**
* Processes an incoming message and passes it to event handler if needed, the
* following events are to our interest: Runtime-Started : ecmascript runtime
* starts in Opera (that we can inject to) Runtime-Stopped : ecmascript
* runtime stops (not used, buggy) Message: fired from console log event
* Updated-Window: a window is updated OR created (opener-id=0) Active-Window:
* window focus changed Window-Closed: self explanatory If message matches
* none it is added to the response queue (probably response to command)
*
* @param message
*/
public void parseServiceList(String message) {
logger.fine("parseServiceList: \"" + message + "\"");
int split = message.indexOf(" ");
if (split < 0) {
connectionHandler.onException(new WebDriverException(
"Invalid service list received."));
return;
}
List<String> services = Arrays.asList(message.substring(split + 1).split(
","));
connectionHandler.onServiceList(services);
logger.fine("Service List OK.");
if (!services.contains("stp-1")) {
connectionHandler.onException(new WebDriverException(
"STP/0 is not supported!"));
return;
}
switchToStp1();
}
private void signalResponse(int tag, Response response) {
connectionHandler.onResponseReceived(tag, response);
}
private void signalEvent(Event event) {
logger.fine("EVENT " + event.toString());
stp1EventHandler.handleEvent(event);
}
/**
* reads a message from the buffer, and pops the used data out of the buffer!
*
* @param buffer the buffer containing messages
* @return true if we got a message from the buffer!
*/
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenreading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenreading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start!
buffer.get(dst);
buffer.position(0);// reset position!
bytesWeHaveBeenreading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Handshake"));
} else {
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
}
break;
case EMPTY: // read 4 byte header: STP\0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenreading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Header"));
}
}
break;
case STP:
// try to read size,
buffer.position(0);
if (buffer.limit() <= 0) {
logger.fine("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenreading = buffer.position();
buffer.position(0);
// if we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenreading + messageSize) {
buffer.position(bytesWeHaveBeenreading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenreading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenreading += messageSize;// 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new WebDriverException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.fine("tried to read a message, but expected " + (4 + messageSize)
+ " bytes, and only got " + buffer.limit());
buffer.position(0);
bytesWeHaveBeenreading = 0;
}
break;
}
// pop number of read bytes from
if (bytesWeHaveBeenreading > 0) {
// pop X bytes, and keep message for the rest!
int rest = buffer.limit() - bytesWeHaveBeenreading;
if (rest == 0) {
buffer.clear();
buffer.limit(0);
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenreading);
buffer.get(temp, 0, rest);
buffer.clear();
buffer.limit(rest);
buffer.position(0);
buffer.put(temp, 0, rest);
buffer.position(0);// set position back to start!
}
logger.fine("did read message of " + bytesWeHaveBeenreading
+ " bytes, new buffer size = " + buffer.limit());
return true; // we did read a message :-)
} else {
if (buffer.limit() > 0) {
logger.fine("did NOT read message from buffer of size = "
+ buffer.limit());
} else {
logger.fine("no messages in empty buffer");
}
return false;
}
}
private void processMessage(int stpType, byte[] payload) throws IOException {
logger.finest("processMessage: " + stpType);
switch (stpType) {
/*
* case 1://command //commands are not supposed to be received
* throw new WebDriverException("Received command from host?");
*/
case 2:// response
// log what is being sent.
Response response = Response.parseFrom(payload);
logger.fine("RECV RESPONSE: " + response.toString());
signalResponse(response.getTag(), response);
break;
case 3:// event
Event event = Event.parseFrom(payload);
logger.fine("RECV EVENT: " + event.toString());
signalEvent(event);
break;
case 4:// error
Error error = Error.parseFrom(payload);
logger.fine("RECV ERROR: " + error.toString());
if (error.getService().equals("ecmascript-debugger")
&& error.getStatus() == UmsProtos.Status.INTERNAL_ERROR.getNumber()) {
signalResponse(error.getTag(), null);
} else {
logger.log(Level.SEVERE, "Error : {0}", error.toString());
connectionHandler.onException(new WebDriverException(
"Error on command : " + error.toString()));
}
break;
default:
connectionHandler.onException(new WebDriverException(
"Unhandled STP type: " + stpType));
}
}
// protobuf methods, taken from the protobuf library by Google
// explained: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
private int readRawVarint32(ByteBuffer bytes) {
byte tmp = bytes.get();
if (tmp >= 0) {
return tmp;
}
int result = tmp & 0x7f;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = bytes.get()) << 28;
if (tmp < 0) {
// Discard upper 32 bits.
for (int i = 0; i < 5; i++) {
if (bytes.get() >= 0) return result;
}
connectionHandler.onException(new WebDriverException(
"Error while reading raw int"));
}
}
}
}
return result;
}
private ByteBuffer encodeMessageSize(int value) {
ByteBuffer buffer = ByteBuffer.allocateDirect(CodedOutputStream.computeRawVarint32Size(value));
while (true) {
if ((value & ~0x7F) == 0) {
buffer.put((byte) (value));
return buffer;
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
}
}
| src/com/opera/core/systems/scope/stp/StpConnection.java | /*
Copyright 2008-2011 Opera Software ASA
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.opera.core.systems.scope.stp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriverException;
import com.google.protobuf.ByteString;
import com.google.protobuf.CodedOutputStream;
import com.opera.core.systems.scope.handlers.AbstractEventHandler;
import com.opera.core.systems.scope.handlers.IConnectionHandler;
import com.opera.core.systems.scope.internal.OperaIntervals;
import com.opera.core.systems.scope.protos.UmsProtos;
import com.opera.core.systems.scope.protos.UmsProtos.Command;
import com.opera.core.systems.scope.protos.UmsProtos.Error;
import com.opera.core.systems.scope.protos.UmsProtos.Event;
import com.opera.core.systems.scope.protos.UmsProtos.Response;
import com.opera.core.systems.util.SocketListener;
import com.opera.core.systems.util.SocketMonitor;
public class StpConnection implements SocketListener {
private final Logger logger = Logger.getLogger(this.getClass().getName());
private SocketChannel socketChannel;
// Outgoing send queue
private final ArrayBlockingQueue<ByteBuffer> requests;
private ByteBuffer recvBuffer;
// For STP1
final byte[] prefix = { 'S', 'T', 'P', 1 };
private ByteString stpPrefix = ByteString.copyFrom(prefix);
private AbstractEventHandler eventHandler;
private UmsEventParser stp1EventHandler;
private IConnectionHandler connectionHandler;
public enum State {
SERVICELIST, HANDSHAKE, EMPTY, STP;
}
private State state = State.SERVICELIST;
private void setState(State state) {
// logger.fine("Setting state: " + state.toString());
this.state = state;
}
public boolean isConnected() {
if (socketChannel == null) return false;
return true;
}
/*
@Override
public void finalize() throws Throwable {
logger.severe("STPConnection cleanup");
if (socketChannel != null && socketChannel.isOpen()) {
close();
}
super.finalize();
}
*/
/**
* Initializes variables in object scope, sets 'count known' to false to read
* byte count (STP/0).
*
* @param socket
* @param handler
* @param eventHandler
* @throws IOException
*/
public StpConnection(SocketChannel socket, IConnectionHandler handler,
AbstractEventHandler eventHandler) throws IOException {
connectionHandler = handler;
socketChannel = socket;
this.eventHandler = eventHandler;
requests = new ArrayBlockingQueue<ByteBuffer>(1024);
recvBuffer = ByteBuffer.allocateDirect(65536);
recvBuffer.limit(0);
socket.configureBlocking(false);
SocketMonitor.instance().add(socket, this, SelectionKey.OP_READ);
if (!handler.onConnected(this)) {
close();
throw new IOException(
"Connection not allowed from IConnectionHandler (already connected)");
}
}
private void switchToStp1() {
stp1EventHandler = new UmsEventParser(eventHandler);
sendEnableStp1();
setState(State.HANDSHAKE);
}
/**
* Queues up an STP/1 message sent from another thread and wakes up selector
* to register it to the key
*
* @param command to add to the request queue
* @throws IOException
*/
public void send(Command command) {
logger.log(Level.FINEST, command.toString());
byte[] payload = command.toByteArray();
int totalSize = payload.length + 1; // increment 1 for message type
ByteBuffer outMessageSize = encodeMessageSize(totalSize);
// create the message
ByteBuffer buffer = ByteBuffer.allocateDirect(prefix.length
+ outMessageSize.position() + 1 + payload.length);
buffer.put(prefix, 0, prefix.length);
outMessageSize.flip();
buffer.put(outMessageSize);
buffer.put((byte) 1);
buffer.put(payload);
// log what is being sent.
logger.fine("SEND: " + command.toString());
requests.add(buffer);
SocketMonitor.instance().modify(socketChannel, this,
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public void sendEnableStp1() {
// temporary fix for CORE-33057
try {
Thread.sleep(OperaIntervals.EXEC_SLEEP.getValue());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
send("*enable stp-1");
}
public void sendQuit() {
send("*quit");
}
/**
* Queues up an STP/0 message sent from another thread and wakes up selector
* to register it to the key
*
* @param message to add to the request queue
*/
private void send(String message) {
String scopeMessage = message.length() + " " + message;
logger.fine("WRITE : " + scopeMessage);
byte[] bytes = null;
try {
bytes = scopeMessage.getBytes("UTF-16BE");
} catch (UnsupportedEncodingException e) {
close();
connectionHandler.onException(e);
return;
}
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
requests.add(buffer);
SocketMonitor.instance().modify(socketChannel, this,
SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public boolean canRead(SelectableChannel channel) throws IOException {
logger.fine("canRead");
if (!channel.isOpen()) return false;
if (socketChannel == null) throw new IOException(
"We dont have a socket :-)");
// read as much data as possible into buffer!
ByteBuffer readBuffer = ByteBuffer.allocateDirect(1000);
int readSize = 0;
// continue to read data and read messages until there are no messages
boolean didNotFindAnyMessage = false;
while (!didNotFindAnyMessage) {
logger.fine("canReadLoop!");
// read as much data as possible (until recvBuffer is full OR we don't get
// any more data)
do {
readBuffer.clear();
try {
// do we have a socket
if (socketChannel == null) {
readSize = -1;
// do we have room in our buffer?
} else {
readSize = socketChannel.read(readBuffer);
if (readSize > 0) {
readBuffer.limit(readSize);
readBuffer.position(0);
}
}
} catch (IOException ex) {
logger.log(Level.WARNING, "Channel closed, causing exception",
ex.getMessage());
readSize = -1;// same as error from socketChannel.read
}
if (readSize < 0) {
try {
logger.log(Level.INFO, "Channel closed : {0}",
socketChannel.socket().getInetAddress().getHostName());
} catch (NullPointerException e) {
// ignore
}
connectionHandler.onDisconnect();
SocketMonitor.instance().remove(socketChannel);
return false;
} else if (readSize > 0) {
// double buffer size if needed!
if (recvBuffer.limit() + readBuffer.limit() >= recvBuffer.capacity()) {
logger.fine("Doubled the size of our recv buffer!");
ByteBuffer newRecvBuffer = ByteBuffer.allocate(recvBuffer.capacity() * 2);
newRecvBuffer.clear();
recvBuffer.position(0);
newRecvBuffer.limit(recvBuffer.limit());
newRecvBuffer.position(0);
newRecvBuffer.put(recvBuffer);
newRecvBuffer.position(0);
recvBuffer = newRecvBuffer;
}
recvBuffer.position(recvBuffer.limit());
recvBuffer.limit(recvBuffer.limit() + readSize);// increase limit!
recvBuffer.put(readBuffer);
logger.fine("did read " + readSize + " bytes, new buffer size = "
+ recvBuffer.limit());
}
} while (readSize > 0);
// read as many messages as possible, and only
didNotFindAnyMessage = true;
while (readMessage(recvBuffer)) {
didNotFindAnyMessage = false;
}
}
return true;
}
public boolean canWrite(SelectableChannel channel) throws IOException {
logger.fine("canWrite");
if (socketChannel == null) throw new IOException(
"We dont have a socket :-)");
int totalWritten = 0;
while (!requests.isEmpty()) {
ByteBuffer buffer = requests.poll();
buffer.flip();
int written = 0;
do {
written = socketChannel.write(buffer);
if (written <= 0) break;
if (written > 0) totalWritten += written;
} while (buffer.hasRemaining());
}
logger.fine("Wrote " + totalWritten + " bytes");
return (!requests.isEmpty());
}
/**
* Switches the wait state and wakes up the selector to process
*/
public void close() {
if (socketChannel == null) return;
SocketMonitor.instance().remove(socketChannel);
try {
socketChannel.close();
} catch (IOException ignored) {
/* nothing to be done */
} finally {
socketChannel = null;
}
}
/**
* Processes an incoming message and passes it to event handler if needed, the
* following events are to our interest: Runtime-Started : ecmascript runtime
* starts in Opera (that we can inject to) Runtime-Stopped : ecmascript
* runtime stops (not used, buggy) Message: fired from console log event
* Updated-Window: a window is updated OR created (opener-id=0) Active-Window:
* window focus changed Window-Closed: self explanatory If message matches
* none it is added to the response queue (probably response to command)
*
* @param message
*/
public void parseServiceList(String message) {
logger.fine("parseServiceList: \"" + message + "\"");
int split = message.indexOf(" ");
if (split < 0) {
connectionHandler.onException(new WebDriverException(
"Invalid service list received."));
return;
}
List<String> services = Arrays.asList(message.substring(split + 1).split(
","));
connectionHandler.onServiceList(services);
logger.fine("Service List OK.");
if (!services.contains("stp-1")) {
connectionHandler.onException(new WebDriverException(
"STP/0 is not supported!"));
return;
}
switchToStp1();
}
private void signalResponse(int tag, Response response) {
connectionHandler.onResponseReceived(tag, response);
}
private void signalEvent(Event event) {
logger.fine("EVENT " + event.toString());
stp1EventHandler.handleEvent(event);
}
/**
* reads a message from the buffer, and pops the used data out of the buffer!
*
* @param buffer the buffer containing messages
* @return true if we got a message from the buffer!
*/
private boolean readMessage(ByteBuffer buffer) {
// logger.finest("readMessage: " + bytesRead + " bytes read, remaining=" +
// remainingBytes.length + ", state=" + state.toString() + ", recurse=" +
// recurse);
buffer.position(0);
int bytesWeHaveBeenreading = 0;
switch (state) {
case SERVICELIST:
StringBuilder builder = new StringBuilder();
builder.append(buffer.asCharBuffer());
parseServiceList(builder.toString());
buffer.position(0);// reset position!
bytesWeHaveBeenreading = buffer.limit(); // bytesWeHaveBeenreading = all
// bytes in buffer!
break;
case HANDSHAKE:
if (buffer.limit() >= 6) {
byte[] dst = new byte[6];
buffer.position(0);// read from start!
buffer.get(dst);
buffer.position(0);// reset position!
bytesWeHaveBeenreading = 6; // 6 bytes will be removed from buffer
String handShake = new String(dst);
if (!handShake.equals("STP/1\n")) {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Handshake"));
} else {
setState(State.EMPTY);
connectionHandler.onHandshake(true);
}
}
break;
case EMPTY: // read 4 byte header: STP\0
if (buffer.limit() >= 4) {
byte[] headerPrefix = new byte[4];
buffer.get(headerPrefix);
buffer.position(0);
bytesWeHaveBeenreading = 4;
ByteString incomingPrefix = ByteString.copyFrom(headerPrefix);
if (stpPrefix.equals(incomingPrefix)) {
setState(State.STP);
/*
if(buffer.hasRemaining()){
buffer.compact();
readMessage(buffer, buffer.position(), true);
} else {
buffer.clear();
}
*/
} else {
close();
connectionHandler.onException(new WebDriverException(
"Scope Transport Protocol Error : Header"));
}
}
break;
case STP:
// try to read size,
buffer.position(0);
if (buffer.limit() <= 0) {
logger.fine("STP: Empty buffer");
break;
}
int messageSize = readRawVarint32(buffer);// read part of buffer
bytesWeHaveBeenreading = buffer.position();
buffer.position(0);
// if we got size, read more, if not just leave it!
if (buffer.limit() >= bytesWeHaveBeenreading + messageSize) {
buffer.position(bytesWeHaveBeenreading);
// Read type and Payload!
int messageType = buffer.get();
bytesWeHaveBeenreading += 1;
byte[] payload = new byte[--messageSize];
buffer.get(payload);
buffer.position(0);
bytesWeHaveBeenreading += messageSize;// 32 bits = 4 bytes :-)
setState(State.EMPTY);
try {
processMessage(messageType, payload);
} catch (IOException e) {
close();
connectionHandler.onException(new WebDriverException(
"Error while processing the message: " + e.getMessage()));
}
} else {
// 4 + messageSize because of the int at the beginning
logger.fine("tried to read a message, but expected " + (4 + messageSize)
+ " bytes, and only got " + buffer.limit());
buffer.position(0);
bytesWeHaveBeenreading = 0;
}
break;
}
// pop number of read bytes from
if (bytesWeHaveBeenreading > 0) {
// pop X bytes, and keep message for the rest!
int rest = buffer.limit() - bytesWeHaveBeenreading;
if (rest == 0) {
buffer.clear();
buffer.limit(0);
} else {
byte[] temp = new byte[rest];
buffer.position(bytesWeHaveBeenreading);
buffer.get(temp, 0, rest);
buffer.clear();
buffer.limit(rest);
buffer.position(0);
buffer.put(temp, 0, rest);
buffer.position(0);// set position back to start!
}
logger.fine("did read message of " + bytesWeHaveBeenreading
+ " bytes, new buffer size = " + buffer.limit());
return true; // we did read a message :-)
} else {
if (buffer.limit() > 0) {
logger.fine("did NOT read message from buffer of size = "
+ buffer.limit());
} else {
logger.fine("no messages in empty buffer");
}
return false;
}
}
private void processMessage(int stpType, byte[] payload) throws IOException {
logger.finest("processMessage: " + stpType);
switch (stpType) {
/*
* case 1://command //commands are not supposed to be received
* throw new WebDriverException("Received command from host?");
*/
case 2:// response
// log what is being sent.
Response response = Response.parseFrom(payload);
logger.fine("RECV RESPONSE: " + response.toString());
signalResponse(response.getTag(), response);
break;
case 3:// event
Event event = Event.parseFrom(payload);
logger.fine("RECV EVENT: " + event.toString());
signalEvent(event);
break;
case 4:// error
Error error = Error.parseFrom(payload);
logger.fine("RECV ERROR: " + error.toString());
if (error.getService().equals("ecmascript-debugger")
&& error.getStatus() == UmsProtos.Status.INTERNAL_ERROR.getNumber()) {
signalResponse(error.getTag(), null);
} else {
logger.log(Level.SEVERE, "Error : {0}", error.toString());
connectionHandler.onException(new WebDriverException(
"Error on command : " + error.toString()));
}
break;
default:
connectionHandler.onException(new WebDriverException(
"Unhandled STP type: " + stpType));
}
}
// protobuf methods, taken from the protobuf library by Google
// explained: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints
private int readRawVarint32(ByteBuffer bytes) {
byte tmp = bytes.get();
if (tmp >= 0) {
return tmp;
}
int result = tmp & 0x7f;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 7;
} else {
result |= (tmp & 0x7f) << 7;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 14;
} else {
result |= (tmp & 0x7f) << 14;
if ((tmp = bytes.get()) >= 0) {
result |= tmp << 21;
} else {
result |= (tmp & 0x7f) << 21;
result |= (tmp = bytes.get()) << 28;
if (tmp < 0) {
// Discard upper 32 bits.
for (int i = 0; i < 5; i++) {
if (bytes.get() >= 0) return result;
}
connectionHandler.onException(new WebDriverException(
"Error while reading raw int"));
}
}
}
}
return result;
}
private ByteBuffer encodeMessageSize(int value) {
ByteBuffer buffer = ByteBuffer.allocateDirect(CodedOutputStream.computeRawVarint32Size(value));
while (true) {
if ((value & ~0x7F) == 0) {
buffer.put((byte) (value));
return buffer;
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
value >>>= 7;
}
}
}
}
| Reducing log message to FINE
| src/com/opera/core/systems/scope/stp/StpConnection.java | Reducing log message to FINE | <ide><path>rc/com/opera/core/systems/scope/stp/StpConnection.java
<ide>
<ide> if (readSize < 0) {
<ide> try {
<del> logger.log(Level.INFO, "Channel closed : {0}",
<del> socketChannel.socket().getInetAddress().getHostName());
<add> logger.log(Level.FINE, "Channel closed: {0}",
<add> socketChannel.socket().getInetAddress().getHostName());
<ide> } catch (NullPointerException e) {
<ide> // ignore
<ide> } |
|
Java | apache-2.0 | 9ba4e3f5b554cac2cf61e977e439f61531095123 | 0 | freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM | /*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.
*/
/**
* @author Nikolay A. Kuznetsov
* @version $Revision: 1.4.2.2 $
*/
package java.util.regex;
/**
* Non-capturing group closing node.
*
* @author Nikolay A. Kuznetsov
* @version $Revision: 1.4.2.2 $
*/
class NonCapFSet extends FSet {
public NonCapFSet(int groupIndex) {
super(groupIndex);
}
public int matches(int stringIndex, CharSequence testString,
MatchResultImpl matchResult) {
int gr = getGroupIndex();
matchResult.setConsumed(gr, stringIndex - matchResult.getConsumed(gr));
return next.matches(stringIndex, testString, matchResult);
}
protected String getName() {
return "NonCapFSet";
}
public boolean hasConsumed(MatchResultImpl mr) {
return false;
}
}
| modules/regex/src/main/java/java/util/regex/NonCapFSet.java | /*
* Copyright 2005 The Apache Software Foundation or its licensors, as applicable.
*
* 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.
*/
/**
* @author Nikolay A. Kuznetsov
* @version $Revision: 1.4.2.2 $
*/
package java.util.regex;
/**
* Non-capturing group closing node.
*
* @author Nikolay A. Kuznetsov
* @version $Revision: 1.4.2.2 $
*/
class NonCapFSet extends FSet {
public NonCapFSet(int groupIndex) {
super(groupIndex);
}
public int matches(int stringIndex, CharSequence testString,
MatchResultImpl matchResult) {
int gr = getGroupIndex();
int end = matchResult.getEnd(gr);
matchResult.setConsumed(gr, stringIndex - matchResult.getConsumed(gr));
int shift = next.matches(stringIndex, testString, matchResult);
if (shift < 0)
matchResult.setEnd(gr, end);
return shift;
}
protected String getName() {
return "NonCapFSet";
}
public boolean hasConsumed(MatchResultImpl mr) {
return false;
}
} | Apply patch HARMONY-674 (Pattern throws ArrayIndexOutOfBoundsException when mathching regexp)
svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=418840
| modules/regex/src/main/java/java/util/regex/NonCapFSet.java | Apply patch HARMONY-674 (Pattern throws ArrayIndexOutOfBoundsException when mathching regexp) | <ide><path>odules/regex/src/main/java/java/util/regex/NonCapFSet.java
<ide> MatchResultImpl matchResult) {
<ide>
<ide> int gr = getGroupIndex();
<del> int end = matchResult.getEnd(gr);
<ide> matchResult.setConsumed(gr, stringIndex - matchResult.getConsumed(gr));
<ide>
<del> int shift = next.matches(stringIndex, testString, matchResult);
<del>
<del> if (shift < 0)
<del> matchResult.setEnd(gr, end);
<del> return shift;
<add> return next.matches(stringIndex, testString, matchResult);
<ide> }
<ide>
<ide> protected String getName() { |
|
Java | lgpl-2.1 | f5fca4ac2b3545dfe513798c3f08a9c76d483539 | 0 | pentaho/pentaho-commons-xul | package org.pentaho.ui.xul.swt.tags;
import java.beans.Expression;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.containers.XulListbox;
import org.pentaho.ui.xul.dnd.DropEffectType;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swt.AbstractSwtXulContainer;
public class SwtListbox extends AbstractSwtXulContainer implements XulListbox{
private static final long serialVersionUID = 3064125049914932493L;
private static final Log logger = LogFactory.getLog(SwtListbox.class);
private List listBox;
private boolean disabled = false;
private String selType;
private int rowsToDisplay = 0;
String onSelect = null;
private XulDomContainer container;
private String binding;
private Collection elements;
private String command;
private int[] curSelectedIndices = null;
private int curSelectedIndex = -1;
private Object prevSelectedObject;
public SwtListbox(Element self, XulComponent parent, XulDomContainer container, String tagName) {
super(tagName);
this.container = container;
int style = SWT.BORDER | SWT.V_SCROLL;
if(self.getAttributeValue("seltype") != null && self.getAttributeValue("seltype").equals("multi")){
style |= SWT.MULTI;
} else {
style |= SWT.SINGLE;
}
listBox = new List((Composite)parent.getManagedObject(), style);
listBox.addSelectionListener(new SelectionAdapter(){
@Override
public void widgetSelected(SelectionEvent arg0) {
fireSelectedEvents();
}
});
setManagedObject(listBox);
}
private void fireSelectedEvents(){
int[] indices = listBox.getSelectionIndices();
SwtListbox.this.changeSupport.firePropertyChange("selectedIndices", curSelectedIndices, indices);
curSelectedIndices = indices;
SwtListbox.this.changeSupport.firePropertyChange("selectedIndex", curSelectedIndex, getSelectedIndex());
curSelectedIndex = getSelectedIndex();
if(elements != null){
Object newSelectedObject = getSelectedItem();
SwtListbox.this.changeSupport.firePropertyChange("selectedItem", prevSelectedObject, newSelectedObject);
prevSelectedObject = newSelectedObject;
Object[] newSelectedObjectList = getSelectedItems();
SwtListbox.this.changeSupport.firePropertyChange("selectedItems", null, newSelectedObjectList);
}
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
if (!listBox.isDisposed()) listBox.setEnabled( !disabled );
}
public void setDisabled(String dis) {
this.disabled = Boolean.parseBoolean(dis);
if (!listBox.isDisposed()) listBox.setEnabled( !disabled );
}
public int getRows() {
return rowsToDisplay;
}
public void setRows(int rowsToDisplay) {
this.rowsToDisplay = rowsToDisplay;
if ((!listBox.isDisposed()) && (rowsToDisplay > 0)){
int ht = rowsToDisplay * listBox.getItemHeight();
//listBox.setSize(listBox.getSize().x,height);
if (listBox.getLayoutData() != null){
((GridData)listBox.getLayoutData()).heightHint = ht;
((GridData)listBox.getLayoutData()).minimumHeight = ht;
}
}
}
public String getSeltype() {
return selType;
}
/**
* TODO: PARTIAL IMPL: Because this is needed on construction,
* we need to rework this class a bit to allow setting of
* multiple selection.
*/
public void setSeltype(String selType) {
this.selType = selType;
}
public void addItem(Object item) {
// SWT limitation - these can only be strings ...
// We could still attempt to load the object using
// its toString() method, but then what you recieved
// back from getItem() or getSelection() would
// be inconsistent with what you put into the list...
// TODO: Could possibly simulate a model
// by holding onto real objects and syncing them
// with the listbox.
if (!(item instanceof String)){
// log error... only strings supported...
}
listBox.add((String)item);
}
public void removeItems(){
listBox.removeAll();
}
public String getOnselect() {
return onSelect;
}
public void setOnselect(final String method) {
onSelect = method;
listBox.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(org.eclipse.swt.events.SelectionEvent arg0){
invoke(method);
}
});
}
public Object getSelectedItem() {
if (listBox.getSelection()==null ||
listBox.getSelectionCount()<=0){
return null;
}
// If there's a bound collection return the model object.
int selIdx = getSelectedIndex();
if(elements != null && selIdx >= 0 && selIdx < elements.size()){
return elements.toArray()[selIdx];
}
// otherwise return String value
return listBox.getSelection()[0];
}
public Object[] getSelectedItems() {
// If there's a bound collection return the model object.
int[] selIndices = getSelectedIndices();
if(elements != null && selIndices.length > 0){
Object[] returnArray = new Object[selIndices.length];
Object[] valueArray = elements.toArray();
for(int i=0;i<selIndices.length;i++) {
returnArray[i] = valueArray[selIndices[i]];
}
return returnArray;
}
// otherwise return String value
return listBox.getSelection();
}
public int getSelectedIndex(){
return listBox.getSelectionIndex();
}
public int[] getSelectedIndices(){
return listBox.getSelectionIndices();
}
public void setSelectedItem(Object item) {
setSelectedItems(new Object[] {item});
}
public void setSelectedItems(Object[] items) {
if(elements != null){
// If bound collection get idx and use that.
int[] indices = new int[items.length];
int pos = 0;
for(Object o : items){
int index = getIndex(o);
if(index >= 0) {
indices[pos++] = index;
}
}
setSelectedIndices(indices);
} else {
for (Object object : items) {
if (!(object instanceof String)){
// TODO log error... only strings supported...
}
}
String[] sel = new String[items.length];
System.arraycopy(items, 0, sel, 0, items.length);
listBox.setSelection(sel);
// SWT doesn't seem to fire this event when the selection
// is made via code, only with a mouse or keyboard action.
listBox.notifyListeners(SWT.Selection, new Event());
}
}
private int getIndex(Object o) {
Object[] elementArray = elements.toArray();
for(int i=0;i<elementArray.length;i++) {
if(elementArray[i] == o) {
return i;
}
}
return -1;
}
public int getRowCount() {
return (!listBox.isDisposed()) ? listBox.getItemCount() : 0;
}
public void setSelectedIndex(int index) {
if(index > listBox.getItemCount()){
return;
}
if (listBox.isDisposed()){
// TODO log error ..
}
listBox.setSelection(index);
}
public void setSelectedindex(String index) {
if (listBox.isDisposed()){
// TODO log error ..
}
listBox.setSelection(Integer.parseInt(index));
}
public <T> Collection<T> getElements() {
return this.elements;
}
public <T> void setElements(Collection<T> elements) {
if(elements != null) {
logger.info("SetElements on listbox called: collection has "+elements.size()+" rows");
this.elements = elements;
this.prevSelectedObject = null;
this.curSelectedIndex = -1;
this.curSelectedIndices = null;
listBox.removeAll();
for (T t : elements) {
SwtListitem item = null;
try {
item = (SwtListitem) container.getDocumentRoot().createElement("listitem");
} catch (XulException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// SwtListitem item = new SwtListitem(null, this, container, null);
this.addChild(item);
item.setLabel(extractLabel(t));
}
layout();
}
}
public void setSelectedIndices(int[] indices) {
listBox.deselectAll();
listBox.select(indices);
fireSelectedEvents();
}
public void setBinding(String binding) {
this.binding = binding;
}
public String getBinding() {
return binding;
}
private <T> String extractLabel(T t) {
if(t == null){
return "";
}
String attribute = getBinding();
if (StringUtils.isEmpty(attribute)) {
return t.toString();
} else {
String getter = "get" + (String.valueOf(attribute.charAt(0)).toUpperCase()) + attribute.substring(1);
try {
return ""+ (new Expression(t, getter, null).getValue());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//
// SwtListbox supports drag bindings, but not drop bindings
//
@Override
protected java.util.List<Object> getSwtDragData() {
java.util.List<Object> list = new ArrayList<Object>();
if (elements != null && elements instanceof java.util.List) {
int[] indices = listBox.getSelectionIndices();
for (int i = 0; i < indices.length; i++) {
list.add(((java.util.List)elements).get(indices[i]));
}
} else {
for (String str: listBox.getSelection()) {
list.add(str);
}
}
return list;
}
@Override
protected void onSwtDragFinished(DropEffectType effect) {
if (effect == DropEffectType.MOVE) {
if (elements != null) {
throw new UnsupportedOperationException("Bindings not yet supported in drag with move");
} else {
// remove both from xul and from list
int[] indices = listBox.getSelectionIndices();
for (int i = indices.length - 1; i >= 0; i--) {
removeChild(getChildNodes().get(indices[i]));
}
listBox.remove(indices);
// need to link to bindings
}
}
}
@Override
protected void onSwtDragDropAccepted(DropEvent event) {
if (elements != null) {
throw new UnsupportedOperationException("Bindings not yet supported on drop");
} else {
java.util.List<Object> data = event.getDataTransfer().getData();
for (int i = 0; i < data.size(); i++) {
SwtListitem item = null;
try {
item = (SwtListitem) container.getDocumentRoot().createElement("listitem");
} catch (XulException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.addChild(item);
item.setLabel(data.get(i).toString());
}
layout();
}
}
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
super.enableDrop();
}
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
// TODO: once listBox is initialized lazily, we also need to move this
// this exact logic is in setDrageffect because both need to be set for
// enable dragging
if (getDrageffect() != null) {
super.enableDrag(DropEffectType.valueOfIgnoreCase(getDrageffect()));
}
}
public void setDrageffect(String drageffect) {
super.setDrageffect(drageffect);
// TODO: once listBox is initialized lazily, we also need to move this
// this exact logic is in setOndrag because both need to be set for
// enable dragging
if (getOndrag() != null) {
super.enableDrag(DropEffectType.valueOfIgnoreCase(getDrageffect()));
}
}
public String getCommand() {
return command;
}
public void setCommand(final String command) {
this.command = command;
listBox.addMouseListener(new MouseAdapter(){
public void mouseDoubleClick(MouseEvent arg0) {
invoke(command);
}
});
}
}
| pentaho-xul-swt/src/org/pentaho/ui/xul/swt/tags/SwtListbox.java | package org.pentaho.ui.xul.swt.tags;
import java.beans.Expression;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.List;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.containers.XulListbox;
import org.pentaho.ui.xul.dnd.DropEffectType;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swt.AbstractSwtXulContainer;
public class SwtListbox extends AbstractSwtXulContainer implements XulListbox{
private static final long serialVersionUID = 3064125049914932493L;
private static final Log logger = LogFactory.getLog(SwtListbox.class);
private List listBox;
private boolean disabled = false;
private String selType;
private int rowsToDisplay = 0;
String onSelect = null;
private XulDomContainer container;
private String binding;
private Collection elements;
private String command;
private int[] curSelectedIndices = null;
private int curSelectedIndex = -1;
private Object prevSelectedObject;
public SwtListbox(Element self, XulComponent parent, XulDomContainer container, String tagName) {
super(tagName);
this.container = container;
int style = SWT.BORDER | SWT.V_SCROLL;
if(self.getAttributeValue("seltype") != null && self.getAttributeValue("seltype").equals("multi")){
style |= SWT.MULTI;
} else {
style |= SWT.SINGLE;
}
listBox = new List((Composite)parent.getManagedObject(), style);
listBox.addSelectionListener(new SelectionAdapter(){
@Override
public void widgetSelected(SelectionEvent arg0) {
int[] indices = listBox.getSelectionIndices();
SwtListbox.this.changeSupport.firePropertyChange("selectedIndices", curSelectedIndices, indices);
curSelectedIndices = indices;
SwtListbox.this.changeSupport.firePropertyChange("selectedIndex", curSelectedIndex, getSelectedIndex());
curSelectedIndex = getSelectedIndex();
if(elements != null){
Object newSelectedObject = getSelectedItem();
SwtListbox.this.changeSupport.firePropertyChange("selectedItem", prevSelectedObject, newSelectedObject);
prevSelectedObject = newSelectedObject;
Object[] newSelectedObjectList = getSelectedItems();
SwtListbox.this.changeSupport.firePropertyChange("selectedItems", null, newSelectedObjectList);
}
}
});
setManagedObject(listBox);
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
if (!listBox.isDisposed()) listBox.setEnabled( !disabled );
}
public void setDisabled(String dis) {
this.disabled = Boolean.parseBoolean(dis);
if (!listBox.isDisposed()) listBox.setEnabled( !disabled );
}
public int getRows() {
return rowsToDisplay;
}
public void setRows(int rowsToDisplay) {
this.rowsToDisplay = rowsToDisplay;
if ((!listBox.isDisposed()) && (rowsToDisplay > 0)){
int ht = rowsToDisplay * listBox.getItemHeight();
//listBox.setSize(listBox.getSize().x,height);
if (listBox.getLayoutData() != null){
((GridData)listBox.getLayoutData()).heightHint = ht;
((GridData)listBox.getLayoutData()).minimumHeight = ht;
}
}
}
public String getSeltype() {
return selType;
}
/**
* TODO: PARTIAL IMPL: Because this is needed on construction,
* we need to rework this class a bit to allow setting of
* multiple selection.
*/
public void setSeltype(String selType) {
this.selType = selType;
}
public void addItem(Object item) {
// SWT limitation - these can only be strings ...
// We could still attempt to load the object using
// its toString() method, but then what you recieved
// back from getItem() or getSelection() would
// be inconsistent with what you put into the list...
// TODO: Could possibly simulate a model
// by holding onto real objects and syncing them
// with the listbox.
if (!(item instanceof String)){
// log error... only strings supported...
}
listBox.add((String)item);
}
public void removeItems(){
listBox.removeAll();
}
public String getOnselect() {
return onSelect;
}
public void setOnselect(final String method) {
onSelect = method;
listBox.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(org.eclipse.swt.events.SelectionEvent arg0){
invoke(method);
}
});
}
public Object getSelectedItem() {
if (listBox.getSelection()==null ||
listBox.getSelectionCount()<=0){
return null;
}
// If there's a bound collection return the model object.
int selIdx = getSelectedIndex();
if(elements != null && selIdx >= 0 && selIdx < elements.size()){
return elements.toArray()[selIdx];
}
// otherwise return String value
return listBox.getSelection()[0];
}
public Object[] getSelectedItems() {
// If there's a bound collection return the model object.
int[] selIndices = getSelectedIndices();
if(elements != null && selIndices.length > 0){
Object[] returnArray = new Object[selIndices.length];
Object[] valueArray = elements.toArray();
for(int i=0;i<selIndices.length;i++) {
returnArray[i] = valueArray[selIndices[i]];
}
return returnArray;
}
// otherwise return String value
return listBox.getSelection();
}
public int getSelectedIndex(){
return listBox.getSelectionIndex();
}
public int[] getSelectedIndices(){
return listBox.getSelectionIndices();
}
public void setSelectedItem(Object item) {
setSelectedItems(new Object[] {item});
}
public void setSelectedItems(Object[] items) {
if(elements != null){
// If bound collection get idx and use that.
int[] indices = new int[items.length];
int pos = 0;
for(Object o : items){
int index = getIndex(o);
if(index >= 0) {
indices[pos++] = index;
}
}
setSelectedIndices(indices);
} else {
for (Object object : items) {
if (!(object instanceof String)){
// TODO log error... only strings supported...
}
}
String[] sel = new String[items.length];
System.arraycopy(items, 0, sel, 0, items.length);
listBox.setSelection(sel);
// SWT doesn't seem to fire this event when the selection
// is made via code, only with a mouse or keyboard action.
listBox.notifyListeners(SWT.Selection, new Event());
}
}
private int getIndex(Object o) {
Object[] elementArray = elements.toArray();
for(int i=0;i<elementArray.length;i++) {
if(elementArray[i] == o) {
return i;
}
}
return -1;
}
public int getRowCount() {
return (!listBox.isDisposed()) ? listBox.getItemCount() : 0;
}
public void setSelectedIndex(int index) {
if(index > listBox.getItemCount()){
return;
}
if (listBox.isDisposed()){
// TODO log error ..
}
listBox.setSelection(index);
}
public void setSelectedindex(String index) {
if (listBox.isDisposed()){
// TODO log error ..
}
listBox.setSelection(Integer.parseInt(index));
}
public <T> Collection<T> getElements() {
return this.elements;
}
public <T> void setElements(Collection<T> elements) {
if(elements != null) {
logger.info("SetElements on listbox called: collection has "+elements.size()+" rows");
this.elements = elements;
this.prevSelectedObject = null;
this.curSelectedIndex = -1;
this.curSelectedIndices = null;
listBox.removeAll();
for (T t : elements) {
SwtListitem item = null;
try {
item = (SwtListitem) container.getDocumentRoot().createElement("listitem");
} catch (XulException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// SwtListitem item = new SwtListitem(null, this, container, null);
this.addChild(item);
item.setLabel(extractLabel(t));
}
layout();
}
}
public void setSelectedIndices(int[] indices) {
listBox.deselectAll();
listBox.select(indices);
}
public void setBinding(String binding) {
this.binding = binding;
}
public String getBinding() {
return binding;
}
private <T> String extractLabel(T t) {
if(t == null){
return "";
}
String attribute = getBinding();
if (StringUtils.isEmpty(attribute)) {
return t.toString();
} else {
String getter = "get" + (String.valueOf(attribute.charAt(0)).toUpperCase()) + attribute.substring(1);
try {
return ""+ (new Expression(t, getter, null).getValue());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//
// SwtListbox supports drag bindings, but not drop bindings
//
@Override
protected java.util.List<Object> getSwtDragData() {
java.util.List<Object> list = new ArrayList<Object>();
if (elements != null && elements instanceof java.util.List) {
int[] indices = listBox.getSelectionIndices();
for (int i = 0; i < indices.length; i++) {
list.add(((java.util.List)elements).get(indices[i]));
}
} else {
for (String str: listBox.getSelection()) {
list.add(str);
}
}
return list;
}
@Override
protected void onSwtDragFinished(DropEffectType effect) {
if (effect == DropEffectType.MOVE) {
if (elements != null) {
throw new UnsupportedOperationException("Bindings not yet supported in drag with move");
} else {
// remove both from xul and from list
int[] indices = listBox.getSelectionIndices();
for (int i = indices.length - 1; i >= 0; i--) {
removeChild(getChildNodes().get(indices[i]));
}
listBox.remove(indices);
// need to link to bindings
}
}
}
@Override
protected void onSwtDragDropAccepted(DropEvent event) {
if (elements != null) {
throw new UnsupportedOperationException("Bindings not yet supported on drop");
} else {
java.util.List<Object> data = event.getDataTransfer().getData();
for (int i = 0; i < data.size(); i++) {
SwtListitem item = null;
try {
item = (SwtListitem) container.getDocumentRoot().createElement("listitem");
} catch (XulException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.addChild(item);
item.setLabel(data.get(i).toString());
}
layout();
}
}
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
super.enableDrop();
}
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
// TODO: once listBox is initialized lazily, we also need to move this
// this exact logic is in setDrageffect because both need to be set for
// enable dragging
if (getDrageffect() != null) {
super.enableDrag(DropEffectType.valueOfIgnoreCase(getDrageffect()));
}
}
public void setDrageffect(String drageffect) {
super.setDrageffect(drageffect);
// TODO: once listBox is initialized lazily, we also need to move this
// this exact logic is in setOndrag because both need to be set for
// enable dragging
if (getOndrag() != null) {
super.enableDrag(DropEffectType.valueOfIgnoreCase(getDrageffect()));
}
}
public String getCommand() {
return command;
}
public void setCommand(final String command) {
this.command = command;
listBox.addMouseListener(new MouseAdapter(){
public void mouseDoubleClick(MouseEvent arg0) {
invoke(command);
}
});
}
}
| [AGILEBI-406] firing selectedIndex events on programatic selection
| pentaho-xul-swt/src/org/pentaho/ui/xul/swt/tags/SwtListbox.java | [AGILEBI-406] firing selectedIndex events on programatic selection | <ide><path>entaho-xul-swt/src/org/pentaho/ui/xul/swt/tags/SwtListbox.java
<ide>
<ide> @Override
<ide> public void widgetSelected(SelectionEvent arg0) {
<del> int[] indices = listBox.getSelectionIndices();
<del> SwtListbox.this.changeSupport.firePropertyChange("selectedIndices", curSelectedIndices, indices);
<del> curSelectedIndices = indices;
<del>
<del>
<del> SwtListbox.this.changeSupport.firePropertyChange("selectedIndex", curSelectedIndex, getSelectedIndex());
<del> curSelectedIndex = getSelectedIndex();
<del>
<del> if(elements != null){
<del> Object newSelectedObject = getSelectedItem();
<del> SwtListbox.this.changeSupport.firePropertyChange("selectedItem", prevSelectedObject, newSelectedObject);
<del> prevSelectedObject = newSelectedObject;
<del>
<del> Object[] newSelectedObjectList = getSelectedItems();
<del> SwtListbox.this.changeSupport.firePropertyChange("selectedItems", null, newSelectedObjectList);
<del> }
<add> fireSelectedEvents();
<ide> }
<ide>
<ide> });
<ide>
<ide> setManagedObject(listBox);
<add> }
<add>
<add> private void fireSelectedEvents(){
<add>
<add> int[] indices = listBox.getSelectionIndices();
<add> SwtListbox.this.changeSupport.firePropertyChange("selectedIndices", curSelectedIndices, indices);
<add> curSelectedIndices = indices;
<add>
<add>
<add> SwtListbox.this.changeSupport.firePropertyChange("selectedIndex", curSelectedIndex, getSelectedIndex());
<add> curSelectedIndex = getSelectedIndex();
<add>
<add> if(elements != null){
<add> Object newSelectedObject = getSelectedItem();
<add> SwtListbox.this.changeSupport.firePropertyChange("selectedItem", prevSelectedObject, newSelectedObject);
<add> prevSelectedObject = newSelectedObject;
<add>
<add> Object[] newSelectedObjectList = getSelectedItems();
<add> SwtListbox.this.changeSupport.firePropertyChange("selectedItems", null, newSelectedObjectList);
<add> }
<ide> }
<ide>
<ide> public boolean isDisabled() {
<ide> public void setSelectedIndices(int[] indices) {
<ide> listBox.deselectAll();
<ide> listBox.select(indices);
<add> fireSelectedEvents();
<ide> }
<ide>
<ide> public void setBinding(String binding) { |
|
Java | mit | 10e96b93501b57741a7e24f65a8b752ee47f0405 | 0 | conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5 | package com.conveyal.r5.streets;
import com.conveyal.r5.api.util.LegMode;
import com.conveyal.r5.profile.StreetMode;
import com.conveyal.r5.profile.ProfileRequest;
import com.conveyal.r5.transit.TransitLayer;
import com.conveyal.r5.util.TIntObjectHashMultimap;
import com.conveyal.r5.util.TIntObjectMultimap;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
/**
* This routes over the street layer of a TransitNetwork.
* It is a throw-away calculator object that retains routing state and after the search is finished.
* Additional functions are called to retrieve the routing results from that state.
*/
public class StreetRouter {
private static final Logger LOG = LoggerFactory.getLogger(StreetRouter.class);
private static final boolean DEBUG_OUTPUT = false;
public static final int ALL_VERTICES = -1;
public final StreetLayer streetLayer;
// TODO don't hardwire drive-on-right
private TurnCostCalculator turnCostCalculator;
/**
* It uses all nonzero limit as a limit whichever gets hit first
* For example if distanceLimitMeters > 0 it is used as a limit. But if it isn't
* timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set
* warning is shown and both are used.
*/
public int distanceLimitMeters = 0;
public int timeLimitSeconds = 0;
/**
* Store the best state at the end of each edge. We store states at the ends of edges, rather than at vertices, so
* that we can apply turn costs. You can't apply turn costs (which are vertex costs) when you are storing a single state
* per vertex, because the vertex cost is not applied until leaving the vertex. This means that a state that must make
* an expensive U-turn to reach the destination may beat out a state that is slightly less costly _at that vertex_ but
* will complete the search with a cheap straight-through movement. We use the ends rather than the beginnings of edges
* to avoid state proliferation (otherwise after traversing an edge you'd have to create states, many of which would
* be dominated pretty quickly, for every outgoing edge at the to vertex).
*
* Storing states per edge is mathematically equivalent to creating a so-called edge-based graph in which all of the
* street segments have been represented as nodes and all of the intersections/turn possibilities as edges, but that
* is a very theoretical view and creates a semantic nightmare because it's hard to think about nodes that represent
* things with dimension (not to mention never being sure whether you're talking about the original, standard graph
* or the transformed, edge-based graph). We had a nightmarish time trying to keep this straight in OTP, and eventually
* removed it. Using edge-based graphs to represent turn costs/restrictions is documented at http://geo.fsv.cvut.cz/gdata/2013/pin2/d/dokumentace/line_graph_teorie.pdf
*
* This would seem to obviate the need to have incomparable states at all, but it in fact does not, because of the existence
* of complex turn restrictions that have via ways. This could be a simple U-turn on a dual carriageway, but could also be
* something more complex (no right turn after left &c.). In these cases, we still have to have incomparable states when
* we are partway through the restriction.
*
* When determining the weight at a vertex, one should just grab all the incoming edges, and take the minimum. However,
* it's a bit more complicated to properly determine the time/weight at a split, because of turn costs. Suppose that
* the best state at a particular vertex require a left turn onto the split edge; it is important to apply that left
* turn costs. Even more important is to make sure that the split edge is not the end of a restricted turn; if it is,
* one must reach the split via an alternate state.
*/
// TODO we might be able to make this more efficient by taking advantage of the fact that we almost always have a
// single state per edge (the only time we don't is when we're in the middle of a turn restriction).
TIntObjectMultimap<State> bestStatesAtEdge = new TIntObjectHashMultimap<>();
PriorityQueue<State> queue = new PriorityQueue<>((s0, s1) -> s0.weight - s1.weight);
// If you set this to a non-negative number, the search will be directed toward that vertex .
public int toVertex = ALL_VERTICES;
/** Set individual properties here, or an entirely new request */
public ProfileRequest profileRequest = new ProfileRequest();
/** Search mode: we need a single mode, it is up to the caller to disentagle the modes set in the profile request */
public StreetMode streetMode = StreetMode.WALK;
private RoutingVisitor routingVisitor;
private Split originSplit;
private Split destinationSplit;
private int bestWeightAtDestination = Integer.MAX_VALUE;
/**
* Here is previous streetRouter in multi router search
* For example if we are searching for P+R we need 2 street searches
* First from start to all car parks and next from all the car parks to transit stops
* <p>
* Second street router has first one in previous. This is needed so the paths can be reconstructed in response
**/
public StreetRouter previous;
public void setRoutingVisitor(RoutingVisitor routingVisitor) {
this.routingVisitor = routingVisitor;
}
/** Currently used for debugging snapping to vertices
* TODO: API should probably be nicer
* setOrigin on split or setOrigin that would return split
* @return
*/
public Split getOriginSplit() {
return originSplit;
}
/**
* @return a map from transit stop indexes to their distances from the origin.
* Note that the TransitLayer contains all the information about which street vertices are transit stops.
*/
public TIntIntMap getReachedStops() {
TIntIntMap result = new TIntIntHashMap();
TransitLayer transitLayer = streetLayer.parentNetwork.transitLayer;
transitLayer.stopForStreetVertex.forEachEntry((streetVertex, stop) -> {
if (streetVertex == -1) return true;
State state = getStateAtVertex(streetVertex);
// TODO should this be time?
if (state != null) result.put(stop, state.weight);
return true; // continue iteration
});
return result;
}
/** Return a map where the keys are all the reached vertices, and the values are their distances from the origin. */
public TIntIntMap getReachedVertices () {
TIntIntMap result = new TIntIntHashMap();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor();
bestStatesAtEdge.forEachEntry((eidx, states) -> {
if (eidx < 0) return true;
State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
e.seek(eidx);
int vidx = e.getToVertex();
if (!result.containsKey(vidx) || result.get(vidx) > state.weight)
result.put(vidx, state.weight);
return true; // continue iteration
});
return result;
}
/**
* @return a map where all the keys are vertex indexes with the particular flag and all the values are states.
*/
public TIntObjectMap<State> getReachedVertices (VertexStore.VertexFlag flag) {
TIntObjectMap<State> result = new TIntObjectHashMap<>();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor();
VertexStore.Vertex v = streetLayer.vertexStore.getCursor();
bestStatesAtEdge.forEachEntry((eidx, states) -> {
if (eidx < 0) return true;
State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
e.seek(eidx);
int vidx = e.getToVertex();
v.seek(vidx);
if (v.getFlag(flag)) {
if (!result.containsKey(vidx) || result.get(vidx).weight > state.weight) {
result.put(vidx, state);
}
}
return true; // continue iteration
});
return result;
}
/**
* Get a distance table to all street vertices touched by the last search operation on this StreetRouter.
* @return A packed list of (vertex, distance) for every reachable street vertex.
* This is currently returning the weight, which is the distance in meters.
*/
public int[] getStopTree () {
TIntIntMap states = getReachedVertices();
TIntList result = new TIntArrayList(states.size() * 2);
// Convert stop vertex indexes in street layer to transit layer stop indexes.
states.forEachEntry((vertexIndex, weight) -> {
result.add(vertexIndex);
result.add(weight);
return true; // continue iteration
});
return result.toArray();
}
public StreetRouter (StreetLayer streetLayer) {
this.streetLayer = streetLayer;
// TODO one of two things: 1) don't hardwire drive-on-right, or 2) https://en.wikipedia.org/wiki/Dagen_H
this.turnCostCalculator = new TurnCostCalculator(streetLayer, true);
}
/**
* Finds closest vertex which has streetMode permissions
*
* @param lat Latitude in floating point (not fixed int) degrees.
* @param lon Longitude in flating point (not fixed int) degrees.
* @return true if edge was found near wanted coordinate
*/
public boolean setOrigin (double lat, double lon) {
Split split = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
if (split == null) {
LOG.info("No street was found near the specified origin point of {}, {}.", lat, lon);
return false;
}
originSplit = split;
bestStatesAtEdge.clear();
queue.clear();
// from vertex is at end of back edge. Set edge correctly so that turn restrictions/costs are applied correctly
// at the origin.
State startState0 = new State(split.vertex0, split.edge + 1, streetMode);
State startState1 = new State(split.vertex1, split.edge, streetMode);
// TODO walk speed, assuming 1 m/sec currently.
startState0.weight = split.distance0_mm / 1000;
startState1.weight = split.distance1_mm / 1000;
// NB not adding to bestStates, as it will be added when it comes out of the queue
queue.add(startState0);
queue.add(startState1);
return true;
}
public void setOrigin (int fromVertex) {
bestStatesAtEdge.clear();
queue.clear();
// NB backEdge of -1 is no problem as it is a special case that indicates that the origin was a vertex.
State startState = new State(fromVertex, -1, streetMode);
queue.add(startState);
}
/**
* Adds multiple origins.
*
* Each state is one origin. Weight, durationSeconds and distance is copied from state.
* If legMode is LegMode.BICYCLE_RENT state.isBikeShare is set to true
*
* @param previousStates map of bikeshares/P+Rs vertexIndexes and states Return of {@link #getReachedVertices(VertexStore.VertexFlag)}}
* @param switchTime How many ms is added to state time (this is used when switching modes, renting bike, parking a car etc.)
* @param switchCost This is added to the weight and is a cost of switching modes
* @param legMode What origin search is this bike share or P+R
*/
public void setOrigin(TIntObjectMap<State> previousStates, int switchTime, int switchCost, LegMode legMode) {
bestStatesAtEdge.clear();
queue.clear();
previousStates.forEachEntry((vertexIdx, previousState) -> {
// backEdge needs to be unique for each start state or they will wind up dominating each other.
// subtract 1 from -vertexIdx because -0 == 0
State state = new State(vertexIdx, -vertexIdx - 1, streetMode);
state.weight = previousState.weight+switchCost;
state.durationSeconds = previousState.durationSeconds+switchTime;
if (legMode == LegMode.BICYCLE_RENT) {
state.isBikeShare = true;
}
state.distance = previousState.distance;
queue.add(state);
return true;
});
}
/**
* Finds closest vertex which has streetMode permissions
*
* @param lat Latitude in floating point (not fixed int) degrees.
* @param lon Longitude in flating point (not fixed int) degrees.
* @return true if edge was found near wanted coordinate
*/
public boolean setDestination (double lat, double lon) {
this.destinationSplit = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
return this.destinationSplit != null;
}
public void setDestination (Split split) {
this.destinationSplit = split;
}
/**
* Call one of the setOrigin functions first.
*
* It uses all nonzero limit as a limit whichever gets hit first
* For example if distanceLimitMeters > 0 it is used a limit. But if it isn't
* timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set
* warning is shown and both are used.
*/
public void route () {
final int distanceLimitMm;
//This is needed otherwise timeLimitSeconds gets changed and
// on next call of route on same streetRouter wrong warnings are returned
// (since timeLimitSeconds is MAX_INTEGER not 0)
final int tmpTimeLimitSeconds;
if (distanceLimitMeters > 0) {
//Distance in State is in mm wanted distance is in meters which means that conversion is necessary
distanceLimitMm = distanceLimitMeters * 1000;
} else {
//We need to set distance limit to largest possible value otherwise nothing would get routed
//since first edge distance would be larger then 0 m and routing would stop
distanceLimitMm = Integer.MAX_VALUE;
}
if (timeLimitSeconds > 0) {
tmpTimeLimitSeconds = timeLimitSeconds;
} else {
//Same issue with time limit
tmpTimeLimitSeconds = Integer.MAX_VALUE;
}
if (timeLimitSeconds > 0 && distanceLimitMeters > 0) {
LOG.warn("Both distance limit of {}m and time limit of {}s are set in streetrouter", distanceLimitMeters, timeLimitSeconds);
} else if (timeLimitSeconds == 0 && distanceLimitMeters == 0) {
LOG.warn("Distance and time limit are set to 0 in streetrouter. This means NO LIMIT in searching so WHOLE of street graph will be searched. This can be slow.");
} else if (distanceLimitMeters > 0) {
LOG.debug("Using distance limit of {}m", distanceLimitMeters);
} else if (timeLimitSeconds > 0) {
LOG.debug("Using time limit of {}s", timeLimitSeconds);
}
if (queue.size() == 0) {
LOG.warn("Routing without first setting an origin, no search will happen.");
}
PrintStream printStream = null; // for debug output
if (DEBUG_OUTPUT) {
File debugFile = new File(String.format("street-router-debug.csv"));
OutputStream outputStream;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(debugFile));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
printStream = new PrintStream(outputStream);
printStream.println("lat,lon,weight");
}
EdgeStore.Edge edge = streetLayer.edgeStore.getCursor();
QUEUE: while (!queue.isEmpty()) {
State s0 = queue.poll();
if (DEBUG_OUTPUT) {
VertexStore.Vertex v = streetLayer.vertexStore.getCursor(s0.vertex);
double lat = v.getLat();
double lon = v.getLon();
if (s0.backEdge != -1) {
EdgeStore.Edge e = streetLayer.edgeStore.getCursor(s0.backEdge);
v.seek(e.getFromVertex());
lat = (lat + v.getLat()) / 2;
lon = (lon + v.getLon()) / 2;
}
printStream.println(String.format("%.6f,%.6f,%d", v.getLat(), v.getLon(), s0.weight));
}
// Don't do any domination for states at the origin
if (s0.backEdge >= 0) {
if (bestStatesAtEdge.containsKey(s0.backEdge)) {
for (State state : bestStatesAtEdge.get(s0.backEdge)) {
// states in turn restrictions don't dominate anything
if (state.turnRestrictions == null)
continue QUEUE;
else if (s0.turnRestrictions != null && s0.turnRestrictions.size() == state.turnRestrictions.size()) {
// if they have the same turn restrictions, dominate this state with the one in the queue.
// if we make all turn-restricted states strictly incomparable we can get infinite loops with adjacent turn
// restrictions, see #88.
boolean[] same = new boolean[]{true};
s0.turnRestrictions.forEachEntry((ridx, pos) -> {
if (!state.turnRestrictions.containsKey(ridx) || state.turnRestrictions.get(ridx) != pos)
same[0] = false;
return same[0]; // shortcut iteration if they're not the same
});
if (same[0]) continue QUEUE;
}
}
}
// non-dominated state coming off the pqueue is by definition the best way to get to that vertex
// but states in turn restrictions don't dominate anything, to avoid resource limiting issues
if (s0.turnRestrictions != null)
bestStatesAtEdge.put(s0.backEdge, s0);
else {
// we might need to save an existing state that is in a turn restriction so is codominant
for (Iterator<State> it = bestStatesAtEdge.get(s0.backEdge).iterator(); it.hasNext(); ) {
State other = it.next();
// avoid a ton of codominant states when there is e.g. duplicated OSM data
// However, save this state if it is not in a turn restriction and the other state is
if (s0.weight == other.weight && !(other.turnRestrictions != null && s0.turnRestrictions == null))
continue QUEUE;
}
bestStatesAtEdge.put(s0.backEdge, s0);
}
}
if (toVertex > 0 && toVertex == s0.vertex) {
// found destination
break;
}
if (s0.weight > bestWeightAtDestination) break;
if (routingVisitor != null) {
routingVisitor.visitVertex(s0);
}
// if this state is at the destination, figure out the cost at the destination and use it for target pruning
// by using getState(split) we include turn restrictions and turn costs. We've already addded this state
// to bestStates so getState will be correct
if (destinationSplit != null && (s0.vertex == destinationSplit.vertex0 || s0.vertex == destinationSplit.vertex1)) {
State atDest = getState(destinationSplit);
// atDest could be null even though we've found a nearby vertex because of a turn restriction
if (atDest != null && bestWeightAtDestination > atDest.weight) bestWeightAtDestination = atDest.weight;
}
// explore edges leaving this vertex
streetLayer.outgoingEdges.get(s0.vertex).forEach(eidx -> {
edge.seek(eidx);
State s1 = edge.traverse(s0, streetMode, profileRequest, turnCostCalculator);
if (s1 != null && s1.distance <= distanceLimitMm && s1.getDurationSeconds() < tmpTimeLimitSeconds) {
queue.add(s1);
}
return true; // iteration over edges should continue
});
}
if (DEBUG_OUTPUT) {
printStream.close();
}
}
/** get a single best state at the end of an edge. There can be more than one state at the end of an edge due to turn restrictions */
public State getStateAtEdge (int edgeIndex) {
Collection<State> states = bestStatesAtEdge.get(edgeIndex);
if (states.isEmpty()) {
return null; // Unreachable
}
// get the lowest weight, even if it's in the middle of a turn restriction
return states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
}
/**
* Get a single best state at a vertex. NB this should not be used for propagating to samples, as you need to apply
* turn costs/restrictions during propagation.
*/
public State getStateAtVertex (int vertexIndex) {
State ret = null;
for (TIntIterator it = streetLayer.incomingEdges.get(vertexIndex).iterator(); it.hasNext();) {
int eidx = it.next();
State state = getStateAtEdge(eidx);
if (state == null) continue;
if (ret == null) ret = state;
else if (ret.weight > state.weight) ret = state;
}
return ret;
}
public int getTravelTimeToVertex (int vertexIndex) {
State state = getStateAtVertex(vertexIndex);
return state != null ? state.weight : Integer.MAX_VALUE;
}
/**
* Returns state with smaller weight to vertex0 or vertex1
*
* If state to only one vertex exists return that vertex.
* If state to none of the vertices exists returns null
* @param split
* @return
*/
public State getState(Split split) {
// get all the states at all the vertices
List<State> relevantStates = new ArrayList<>();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor(split.edge);
for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex0).iterator(); it.hasNext();) {
Collection<State> states = bestStatesAtEdge.get(it.next());
states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge, s)))
.map(s -> {
State ret = new State(-1, split.edge, s);
ret.streetMode = s.streetMode;
// figure out the turn cost
int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge, s.streetMode);
int traversalCost = (int) Math.round(split.distance0_mm / 1000d / e.calculateSpeed(profileRequest, s.streetMode));
// TODO length of perpendicular
ret.incrementWeight(turnCost + traversalCost);
ret.incrementTimeInSeconds(turnCost + traversalCost);
return ret;
})
.forEach(relevantStates::add);
}
// advance to back edge
e.advance();
for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex1).iterator(); it.hasNext();) {
Collection<State> states = bestStatesAtEdge.get(it.next());
states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge + 1, s)))
.map(s -> {
State ret = new State(-1, split.edge + 1, s);
ret.streetMode = s.streetMode;
// figure out the turn cost
int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge + 1, s.streetMode);
int traversalCost = (int) Math.round(split.distance1_mm / 1000d / e.calculateSpeed(profileRequest, s.streetMode));
// TODO length of perpendicular
ret.incrementWeight(turnCost + traversalCost);
ret.incrementTimeInSeconds(turnCost + traversalCost);
return ret;
})
.forEach(relevantStates::add);
}
return relevantStates.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).orElse(null);
}
public Split getDestinationSplit() {
return destinationSplit;
}
/**
* Returns state with smaller weight to vertex0 or vertex1
*
* First split is called with streetMode Mode
*
* If state to only one vertex exists return that vertex.
* If state to none of the vertices exists returns null
* @return
*/
public State getState(double lat, double lon) {
Split split = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
if (split == null) {
LOG.info("No street was found near the specified origin point of {}, {}.", lat, lon);
return null;
}
return getState(split);
}
public static class State implements Cloneable {
public int vertex;
public int weight;
public int backEdge;
protected int durationSeconds;
//Distance in mm
public int distance;
public StreetMode streetMode;
public State backState; // previous state in the path chain
public boolean isBikeShare = false; //is true if vertex in this state is Bike sharing station where mode switching occurs
/**
* turn restrictions we are in the middle of.
* Value is how many edges of this turn restriction we have traversed so far, so if 1 we have traversed only the from edge, etc.
*/
public TIntIntMap turnRestrictions;
public State(int atVertex, int viaEdge, State backState) {
this.vertex = atVertex;
this.backEdge = viaEdge;
//This makes sure that new states don't have non-geographic states as backStates
//non geographic states are states with negative edges since they aren't made from vertices on graph
if (backState.backEdge >= 0) {
this.backState = backState;
}
this.distance = backState.distance;
this.durationSeconds = backState.durationSeconds;
this.weight = backState.weight;
}
public State(int atVertex, int viaEdge, StreetMode streetMode) {
this.vertex = atVertex;
this.backEdge = viaEdge;
this.backState = null;
this.distance = 0;
this.streetMode = streetMode;
this.durationSeconds = 0;
}
public void incrementTimeInSeconds(long seconds) {
if (seconds < 0) {
LOG.warn("A state's time is being incremented by a negative amount while traversing edge "
);
//defectiveTraversal = true;
return;
}
durationSeconds += seconds;
}
public int getDurationSeconds() {
return durationSeconds;
}
public void incrementWeight(float weight) {
this.weight+=(int)weight;
}
public String dump() {
State state = this;
StringBuilder out = new StringBuilder();
out.append("BEGIN PATH DUMP\n");
while (state != null) {
out.append(String.format("%s at %s via %s\n", state.vertex, state.weight, state.backEdge));
state = state.backState;
}
out.append("END PATH DUMP\n");
return out.toString();
}
}
}
| src/main/java/com/conveyal/r5/streets/StreetRouter.java | package com.conveyal.r5.streets;
import com.conveyal.r5.api.util.LegMode;
import com.conveyal.r5.profile.StreetMode;
import com.conveyal.r5.profile.ProfileRequest;
import com.conveyal.r5.transit.TransitLayer;
import com.conveyal.r5.util.TIntObjectHashMultimap;
import com.conveyal.r5.util.TIntObjectMultimap;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
/**
* This routes over the street layer of a TransitNetwork.
* It is a throw-away calculator object that retains routing state and after the search is finished.
* Additional functions are called to retrieve the routing results from that state.
*/
public class StreetRouter {
private static final Logger LOG = LoggerFactory.getLogger(StreetRouter.class);
private static final boolean DEBUG_OUTPUT = false;
public static final int ALL_VERTICES = -1;
public final StreetLayer streetLayer;
// TODO don't hardwire drive-on-right
private TurnCostCalculator turnCostCalculator;
/**
* It uses all nonzero limit as a limit whichever gets hit first
* For example if distanceLimitMeters > 0 it is used as a limit. But if it isn't
* timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set
* warning is shown and both are used.
*/
public int distanceLimitMeters = 0;
public int timeLimitSeconds = 0;
/**
* Store the best state at the end of each edge. We store states at the ends of edges, rather than at vertices, so
* that we can apply turn costs. You can't apply turn costs (which are vertex costs) when you are storing a single state
* per vertex, because the vertex cost is not applied until leaving the vertex. This means that a state that must make
* an expensive U-turn to reach the destination may beat out a state that is slightly less costly _at that vertex_ but
* will complete the search with a cheap straight-through movement. We use the ends rather than the beginnings of edges
* to avoid state proliferation (otherwise after traversing an edge you'd have to create states, many of which would
* be dominated pretty quickly, for every outgoing edge at the to vertex).
*
* Storing states per edge is mathematically equivalent to creating a so-called edge-based graph in which all of the
* street segments have been represented as nodes and all of the intersections/turn possibilities as edges, but that
* is a very theoretical view and creates a semantic nightmare because it's hard to think about nodes that represent
* things with dimension (not to mention never being sure whether you're talking about the original, standard graph
* or the transformed, edge-based graph). We had a nightmarish time trying to keep this straight in OTP, and eventually
* removed it. Using edge-based graphs to represent turn costs/restrictions is documented at http://geo.fsv.cvut.cz/gdata/2013/pin2/d/dokumentace/line_graph_teorie.pdf
*
* This would seem to obviate the need to have incomparable states at all, but it in fact does not, because of the existence
* of complex turn restrictions that have via ways. This could be a simple U-turn on a dual carriageway, but could also be
* something more complex (no right turn after left &c.). In these cases, we still have to have incomparable states when
* we are partway through the restriction.
*
* When determining the weight at a vertex, one should just grab all the incoming edges, and take the minimum. However,
* it's a bit more complicated to properly determine the time/weight at a split, because of turn costs. Suppose that
* the best state at a particular vertex require a left turn onto the split edge; it is important to apply that left
* turn costs. Even more important is to make sure that the split edge is not the end of a restricted turn; if it is,
* one must reach the split via an alternate state.
*/
// TODO we might be able to make this more efficient by taking advantage of the fact that we almost always have a
// single state per edge (the only time we don't is when we're in the middle of a turn restriction).
TIntObjectMultimap<State> bestStatesAtEdge = new TIntObjectHashMultimap<>();
PriorityQueue<State> queue = new PriorityQueue<>((s0, s1) -> s0.weight - s1.weight);
// If you set this to a non-negative number, the search will be directed toward that vertex .
public int toVertex = ALL_VERTICES;
/** Set individual properties here, or an entirely new request */
public ProfileRequest profileRequest = new ProfileRequest();
/** Search mode: we need a single mode, it is up to the caller to disentagle the modes set in the profile request */
public StreetMode streetMode = StreetMode.WALK;
private RoutingVisitor routingVisitor;
private Split originSplit;
private Split destinationSplit;
private int bestWeightAtDestination = Integer.MAX_VALUE;
/**
* Here is previous streetRouter in multi router search
* For example if we are searching for P+R we need 2 street searches
* First from start to all car parks and next from all the car parks to transit stops
* <p>
* Second street router has first one in previous. This is needed so the paths can be reconstructed in response
**/
public StreetRouter previous;
public void setRoutingVisitor(RoutingVisitor routingVisitor) {
this.routingVisitor = routingVisitor;
}
/** Currently used for debugging snapping to vertices
* TODO: API should probably be nicer
* setOrigin on split or setOrigin that would return split
* @return
*/
public Split getOriginSplit() {
return originSplit;
}
/**
* @return a map from transit stop indexes to their distances from the origin.
* Note that the TransitLayer contains all the information about which street vertices are transit stops.
*/
public TIntIntMap getReachedStops() {
TIntIntMap result = new TIntIntHashMap();
TransitLayer transitLayer = streetLayer.parentNetwork.transitLayer;
transitLayer.stopForStreetVertex.forEachEntry((streetVertex, stop) -> {
if (streetVertex == -1) return true;
State state = getStateAtVertex(streetVertex);
// TODO should this be time?
if (state != null) result.put(stop, state.weight);
return true; // continue iteration
});
return result;
}
/** Return a map where the keys are all the reached vertices, and the values are their distances from the origin. */
public TIntIntMap getReachedVertices () {
TIntIntMap result = new TIntIntHashMap();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor();
bestStatesAtEdge.forEachEntry((eidx, states) -> {
if (eidx < 0) return true;
State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
e.seek(eidx);
int vidx = e.getToVertex();
if (!result.containsKey(vidx) || result.get(vidx) > state.weight)
result.put(vidx, state.weight);
return true; // continue iteration
});
return result;
}
/**
* @return a map where all the keys are vertex indexes with the particular flag and all the values are states.
*/
public TIntObjectMap<State> getReachedVertices (VertexStore.VertexFlag flag) {
TIntObjectMap<State> result = new TIntObjectHashMap<>();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor();
VertexStore.Vertex v = streetLayer.vertexStore.getCursor();
bestStatesAtEdge.forEachEntry((eidx, states) -> {
if (eidx < 0) return true;
State state = states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
e.seek(eidx);
int vidx = e.getToVertex();
v.seek(vidx);
if (v.getFlag(flag)) {
if (!result.containsKey(vidx) || result.get(vidx).weight > state.weight) {
result.put(vidx, state);
}
}
return true; // continue iteration
});
return result;
}
/**
* Get a distance table to all street vertices touched by the last search operation on this StreetRouter.
* @return A packed list of (vertex, distance) for every reachable street vertex.
* This is currently returning the weight, which is the distance in meters.
*/
public int[] getStopTree () {
TIntIntMap states = getReachedVertices();
TIntList result = new TIntArrayList(states.size() * 2);
// Convert stop vertex indexes in street layer to transit layer stop indexes.
states.forEachEntry((vertexIndex, weight) -> {
result.add(vertexIndex);
result.add(weight);
return true; // continue iteration
});
return result.toArray();
}
public StreetRouter (StreetLayer streetLayer) {
this.streetLayer = streetLayer;
// TODO one of two things: 1) don't hardwire drive-on-right, or 2) https://en.wikipedia.org/wiki/Dagen_H
this.turnCostCalculator = new TurnCostCalculator(streetLayer, true);
}
/**
* Finds closest vertex which has streetMode permissions
*
* @param lat Latitude in floating point (not fixed int) degrees.
* @param lon Longitude in flating point (not fixed int) degrees.
* @return true if edge was found near wanted coordinate
*/
public boolean setOrigin (double lat, double lon) {
Split split = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
if (split == null) {
LOG.info("No street was found near the specified origin point of {}, {}.", lat, lon);
return false;
}
originSplit = split;
bestStatesAtEdge.clear();
queue.clear();
// from vertex is at end of back edge. Set edge correctly so that turn restrictions/costs are applied correctly
// at the origin.
State startState0 = new State(split.vertex0, split.edge + 1, streetMode);
State startState1 = new State(split.vertex1, split.edge, streetMode);
// TODO walk speed, assuming 1 m/sec currently.
startState0.weight = split.distance0_mm / 1000;
startState1.weight = split.distance1_mm / 1000;
// NB not adding to bestStates, as it will be added when it comes out of the queue
queue.add(startState0);
queue.add(startState1);
return true;
}
public void setOrigin (int fromVertex) {
bestStatesAtEdge.clear();
queue.clear();
// NB backEdge of -1 is no problem as it is a special case that indicates that the origin was a vertex.
State startState = new State(fromVertex, -1, streetMode);
queue.add(startState);
}
/**
* Adds multiple origins.
*
* Each state is one origin. Weight, durationSeconds and distance is copied from state.
* If legMode is LegMode.BICYCLE_RENT state.isBikeShare is set to true
*
* @param previousStates map of bikeshares/P+Rs vertexIndexes and states Return of {@link #getReachedVertices(VertexStore.VertexFlag)}}
* @param switchTime How many ms is added to state time (this is used when switching modes, renting bike, parking a car etc.)
* @param switchCost This is added to the weight and is a cost of switching modes
* @param legMode What origin search is this bike share or P+R
*/
public void setOrigin(TIntObjectMap<State> previousStates, int switchTime, int switchCost, LegMode legMode) {
bestStatesAtEdge.clear();
queue.clear();
previousStates.forEachEntry((vertexIdx, previousState) -> {
// backEdge needs to be unique for each start state or they will wind up dominating each other.
// subtract 1 from -vertexIdx because -0 == 0
State state = new State(vertexIdx, -vertexIdx - 1, streetMode);
state.weight = previousState.weight+switchCost;
state.durationSeconds = previousState.durationSeconds+switchTime;
if (legMode == LegMode.BICYCLE_RENT) {
state.isBikeShare = true;
}
state.distance = previousState.distance;
queue.add(state);
return true;
});
}
/**
* Finds closest vertex which has streetMode permissions
*
* @param lat Latitude in floating point (not fixed int) degrees.
* @param lon Longitude in flating point (not fixed int) degrees.
* @return true if edge was found near wanted coordinate
*/
public boolean setDestination (double lat, double lon) {
this.destinationSplit = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
return this.destinationSplit != null;
}
public void setDestination (Split split) {
this.destinationSplit = split;
}
/**
* Call one of the setOrigin functions first.
*
* It uses all nonzero limit as a limit whichever gets hit first
* For example if distanceLimitMeters > 0 it is used a limit. But if it isn't
* timeLimitSeconds is used if it is bigger then 0. If both limits are 0 or both are set
* warning is shown and both are used.
*/
public void route () {
final int distanceLimitMm;
//This is needed otherwise timeLimitSeconds gets changed and
// on next call of route on same streetRouter wrong warnings are returned
// (since timeLimitSeconds is MAX_INTEGER not 0)
final int tmpTimeLimitSeconds;
if (distanceLimitMeters > 0) {
//Distance in State is in mm wanted distance is in meters which means that conversion is necessary
distanceLimitMm = distanceLimitMeters * 1000;
} else {
//We need to set distance limit to largest possible value otherwise nothing would get routed
//since first edge distance would be larger then 0 m and routing would stop
distanceLimitMm = Integer.MAX_VALUE;
}
if (timeLimitSeconds > 0) {
tmpTimeLimitSeconds = timeLimitSeconds;
} else {
//Same issue with time limit
tmpTimeLimitSeconds = Integer.MAX_VALUE;
}
if (timeLimitSeconds > 0 && distanceLimitMeters > 0) {
LOG.warn("Both distance limit of {}m and time limit of {}s are set in streetrouter", distanceLimitMeters, timeLimitSeconds);
} else if (timeLimitSeconds == 0 && distanceLimitMeters == 0) {
LOG.warn("Distance and time limit are set to 0 in streetrouter. This means NO LIMIT in searching so WHOLE of street graph will be searched. This can be slow.");
} else if (distanceLimitMeters > 0) {
LOG.debug("Using distance limit of {}m", distanceLimitMeters);
} else if (timeLimitSeconds > 0) {
LOG.debug("Using time limit of {}s", timeLimitSeconds);
}
if (queue.size() == 0) {
LOG.warn("Routing without first setting an origin, no search will happen.");
}
PrintStream printStream = null; // for debug output
if (DEBUG_OUTPUT) {
File debugFile = new File(String.format("street-router-debug.csv"));
OutputStream outputStream;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(debugFile));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
printStream = new PrintStream(outputStream);
printStream.println("lat,lon,weight");
}
EdgeStore.Edge edge = streetLayer.edgeStore.getCursor();
QUEUE: while (!queue.isEmpty()) {
State s0 = queue.poll();
if (DEBUG_OUTPUT) {
VertexStore.Vertex v = streetLayer.vertexStore.getCursor(s0.vertex);
double lat = v.getLat();
double lon = v.getLon();
if (s0.backEdge != -1) {
EdgeStore.Edge e = streetLayer.edgeStore.getCursor(s0.backEdge);
v.seek(e.getFromVertex());
lat = (lat + v.getLat()) / 2;
lon = (lon + v.getLon()) / 2;
}
printStream.println(String.format("%.6f,%.6f,%d", v.getLat(), v.getLon(), s0.weight));
}
if (bestStatesAtEdge.containsKey(s0.backEdge)) {
for (State state : bestStatesAtEdge.get(s0.backEdge)) {
// states in turn restrictions don't dominate anything
if (state.turnRestrictions == null)
continue QUEUE;
else if (s0.turnRestrictions != null && s0.turnRestrictions.size() == state.turnRestrictions.size()) {
// if they have the same turn restrictions, dominate this state with the one in the queue.
// if we make all turn-restricted states strictly incomparable we can get infinite loops with adjacent turn
// restrictions, see #88.
boolean[] same = new boolean [] { true };
s0.turnRestrictions.forEachEntry((ridx, pos) -> {
if (!state.turnRestrictions.containsKey(ridx) || state.turnRestrictions.get(ridx) != pos) same[0] = false;
return same[0]; // shortcut iteration if they're not the same
});
if (same[0]) continue QUEUE;
}
}
}
if (toVertex > 0 && toVertex == s0.vertex) {
// found destination
break;
}
if (s0.weight > bestWeightAtDestination) break;
// non-dominated state coming off the pqueue is by definition the best way to get to that vertex
// but states in turn restrictions don't dominate anything, to avoid resource limiting issues
if (s0.turnRestrictions != null)
bestStatesAtEdge.put(s0.backEdge, s0);
else {
// we might need to save an existing state that is in a turn restriction so is codominant
for (Iterator<State> it = bestStatesAtEdge.get(s0.backEdge).iterator(); it.hasNext();) {
State other = it.next();
if (s0.weight < other.weight) it.remove();
// avoid a ton of codominant states when there is e.g. duplicated OSM data
// However, save this state if it is not in a turn restriction and the other state is
else if (s0.weight == other.weight && !(other.turnRestrictions != null && s0.turnRestrictions == null))
continue QUEUE;
}
bestStatesAtEdge.put(s0.backEdge, s0);
}
if (routingVisitor != null) {
routingVisitor.visitVertex(s0);
}
// if this state is at the destination, figure out the cost at the destination and use it for target pruning
// by using getState(split) we include turn restrictions and turn costs. We've already addded this state
// to bestStates so getState will be correct
if (destinationSplit != null && (s0.vertex == destinationSplit.vertex0 || s0.vertex == destinationSplit.vertex1)) {
State atDest = getState(destinationSplit);
// atDest could be null even though we've found a nearby vertex because of a turn restriction
if (atDest != null && bestWeightAtDestination > atDest.weight) bestWeightAtDestination = atDest.weight;
}
// explore edges leaving this vertex
streetLayer.outgoingEdges.get(s0.vertex).forEach(eidx -> {
edge.seek(eidx);
State s1 = edge.traverse(s0, streetMode, profileRequest, turnCostCalculator);
if (s1 != null && s1.distance <= distanceLimitMm && s1.getDurationSeconds() < tmpTimeLimitSeconds) {
queue.add(s1);
}
return true; // iteration over edges should continue
});
}
if (DEBUG_OUTPUT) {
printStream.close();
}
}
/** get a single best state at the end of an edge. There can be more than one state at the end of an edge due to turn restrictions */
public State getStateAtEdge (int edgeIndex) {
Collection<State> states = bestStatesAtEdge.get(edgeIndex);
if (states.isEmpty()) {
return null; // Unreachable
}
// get the lowest weight, even if it's in the middle of a turn restriction
return states.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).get();
}
/**
* Get a single best state at a vertex. NB this should not be used for propagating to samples, as you need to apply
* turn costs/restrictions during propagation.
*/
public State getStateAtVertex (int vertexIndex) {
State ret = null;
for (TIntIterator it = streetLayer.incomingEdges.get(vertexIndex).iterator(); it.hasNext();) {
int eidx = it.next();
State state = getStateAtEdge(eidx);
if (state == null) continue;
if (ret == null) ret = state;
else if (ret.weight > state.weight) ret = state;
}
return ret;
}
public int getTravelTimeToVertex (int vertexIndex) {
State state = getStateAtVertex(vertexIndex);
return state != null ? state.weight : Integer.MAX_VALUE;
}
/**
* Returns state with smaller weight to vertex0 or vertex1
*
* If state to only one vertex exists return that vertex.
* If state to none of the vertices exists returns null
* @param split
* @return
*/
public State getState(Split split) {
// get all the states at all the vertices
List<State> relevantStates = new ArrayList<>();
EdgeStore.Edge e = streetLayer.edgeStore.getCursor(split.edge);
for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex0).iterator(); it.hasNext();) {
Collection<State> states = bestStatesAtEdge.get(it.next());
states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge, s)))
.map(s -> {
State ret = new State(-1, split.edge, s);
ret.streetMode = s.streetMode;
// figure out the turn cost
int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge, s.streetMode);
int traversalCost = (int) Math.round(split.distance0_mm / 1000d / e.calculateSpeed(profileRequest, s.streetMode));
// TODO length of perpendicular
ret.incrementWeight(turnCost + traversalCost);
ret.incrementTimeInSeconds(turnCost + traversalCost);
return ret;
})
.forEach(relevantStates::add);
}
// advance to back edge
e.advance();
for (TIntIterator it = streetLayer.incomingEdges.get(split.vertex1).iterator(); it.hasNext();) {
Collection<State> states = bestStatesAtEdge.get(it.next());
states.stream().filter(s -> e.canTurnFrom(s, new State(-1, split.edge + 1, s)))
.map(s -> {
State ret = new State(-1, split.edge + 1, s);
ret.streetMode = s.streetMode;
// figure out the turn cost
int turnCost = this.turnCostCalculator.computeTurnCost(s.backEdge, split.edge + 1, s.streetMode);
int traversalCost = (int) Math.round(split.distance1_mm / 1000d / e.calculateSpeed(profileRequest, s.streetMode));
// TODO length of perpendicular
ret.incrementWeight(turnCost + traversalCost);
ret.incrementTimeInSeconds(turnCost + traversalCost);
return ret;
})
.forEach(relevantStates::add);
}
return relevantStates.stream().reduce((s0, s1) -> s0.weight < s1.weight ? s0 : s1).orElse(null);
}
public Split getDestinationSplit() {
return destinationSplit;
}
/**
* Returns state with smaller weight to vertex0 or vertex1
*
* First split is called with streetMode Mode
*
* If state to only one vertex exists return that vertex.
* If state to none of the vertices exists returns null
* @return
*/
public State getState(double lat, double lon) {
Split split = streetLayer.findSplit(lat, lon, StreetLayer.LINK_RADIUS_METERS, streetMode);
if (split == null) {
LOG.info("No street was found near the specified origin point of {}, {}.", lat, lon);
return null;
}
return getState(split);
}
public static class State implements Cloneable {
public int vertex;
public int weight;
public int backEdge;
protected int durationSeconds;
//Distance in mm
public int distance;
public StreetMode streetMode;
public State backState; // previous state in the path chain
public boolean isBikeShare = false; //is true if vertex in this state is Bike sharing station where mode switching occurs
/**
* turn restrictions we are in the middle of.
* Value is how many edges of this turn restriction we have traversed so far, so if 1 we have traversed only the from edge, etc.
*/
public TIntIntMap turnRestrictions;
public State(int atVertex, int viaEdge, State backState) {
this.vertex = atVertex;
this.backEdge = viaEdge;
//This makes sure that new states don't have non-geographic states as backStates
//non geographic states are states with negative edges since they aren't made from vertices on graph
if (backState.backEdge >= 0) {
this.backState = backState;
}
this.distance = backState.distance;
this.durationSeconds = backState.durationSeconds;
this.weight = backState.weight;
}
public State(int atVertex, int viaEdge, StreetMode streetMode) {
this.vertex = atVertex;
this.backEdge = viaEdge;
this.backState = null;
this.distance = 0;
this.streetMode = streetMode;
this.durationSeconds = 0;
}
public void incrementTimeInSeconds(long seconds) {
if (seconds < 0) {
LOG.warn("A state's time is being incremented by a negative amount while traversing edge "
);
//defectiveTraversal = true;
return;
}
durationSeconds += seconds;
}
public int getDurationSeconds() {
return durationSeconds;
}
public void incrementWeight(float weight) {
this.weight+=(int)weight;
}
public String dump() {
State state = this;
StringBuilder out = new StringBuilder();
out.append("BEGIN PATH DUMP\n");
while (state != null) {
out.append(String.format("%s at %s via %s\n", state.vertex, state.weight, state.backEdge));
state = state.backState;
}
out.append("END PATH DUMP\n");
return out.toString();
}
}
}
| don't put negative edges in bestStates map.
| src/main/java/com/conveyal/r5/streets/StreetRouter.java | don't put negative edges in bestStates map. | <ide><path>rc/main/java/com/conveyal/r5/streets/StreetRouter.java
<ide>
<ide> printStream.println(String.format("%.6f,%.6f,%d", v.getLat(), v.getLon(), s0.weight));
<ide> }
<del> if (bestStatesAtEdge.containsKey(s0.backEdge)) {
<del> for (State state : bestStatesAtEdge.get(s0.backEdge)) {
<del> // states in turn restrictions don't dominate anything
<del> if (state.turnRestrictions == null)
<del> continue QUEUE;
<del> else if (s0.turnRestrictions != null && s0.turnRestrictions.size() == state.turnRestrictions.size()) {
<del> // if they have the same turn restrictions, dominate this state with the one in the queue.
<del> // if we make all turn-restricted states strictly incomparable we can get infinite loops with adjacent turn
<del> // restrictions, see #88.
<del> boolean[] same = new boolean [] { true };
<del> s0.turnRestrictions.forEachEntry((ridx, pos) -> {
<del> if (!state.turnRestrictions.containsKey(ridx) || state.turnRestrictions.get(ridx) != pos) same[0] = false;
<del> return same[0]; // shortcut iteration if they're not the same
<del> });
<del>
<del> if (same[0]) continue QUEUE;
<add>
<add> // Don't do any domination for states at the origin
<add> if (s0.backEdge >= 0) {
<add> if (bestStatesAtEdge.containsKey(s0.backEdge)) {
<add> for (State state : bestStatesAtEdge.get(s0.backEdge)) {
<add> // states in turn restrictions don't dominate anything
<add> if (state.turnRestrictions == null)
<add> continue QUEUE;
<add> else if (s0.turnRestrictions != null && s0.turnRestrictions.size() == state.turnRestrictions.size()) {
<add> // if they have the same turn restrictions, dominate this state with the one in the queue.
<add> // if we make all turn-restricted states strictly incomparable we can get infinite loops with adjacent turn
<add> // restrictions, see #88.
<add> boolean[] same = new boolean[]{true};
<add> s0.turnRestrictions.forEachEntry((ridx, pos) -> {
<add> if (!state.turnRestrictions.containsKey(ridx) || state.turnRestrictions.get(ridx) != pos)
<add> same[0] = false;
<add> return same[0]; // shortcut iteration if they're not the same
<add> });
<add>
<add> if (same[0]) continue QUEUE;
<add> }
<ide> }
<add> }
<add>
<add> // non-dominated state coming off the pqueue is by definition the best way to get to that vertex
<add> // but states in turn restrictions don't dominate anything, to avoid resource limiting issues
<add> if (s0.turnRestrictions != null)
<add> bestStatesAtEdge.put(s0.backEdge, s0);
<add> else {
<add> // we might need to save an existing state that is in a turn restriction so is codominant
<add> for (Iterator<State> it = bestStatesAtEdge.get(s0.backEdge).iterator(); it.hasNext(); ) {
<add> State other = it.next();
<add> // avoid a ton of codominant states when there is e.g. duplicated OSM data
<add> // However, save this state if it is not in a turn restriction and the other state is
<add> if (s0.weight == other.weight && !(other.turnRestrictions != null && s0.turnRestrictions == null))
<add> continue QUEUE;
<add> }
<add> bestStatesAtEdge.put(s0.backEdge, s0);
<ide> }
<ide> }
<ide>
<ide> }
<ide>
<ide> if (s0.weight > bestWeightAtDestination) break;
<del>
<del> // non-dominated state coming off the pqueue is by definition the best way to get to that vertex
<del> // but states in turn restrictions don't dominate anything, to avoid resource limiting issues
<del> if (s0.turnRestrictions != null)
<del> bestStatesAtEdge.put(s0.backEdge, s0);
<del> else {
<del> // we might need to save an existing state that is in a turn restriction so is codominant
<del> for (Iterator<State> it = bestStatesAtEdge.get(s0.backEdge).iterator(); it.hasNext();) {
<del> State other = it.next();
<del> if (s0.weight < other.weight) it.remove();
<del> // avoid a ton of codominant states when there is e.g. duplicated OSM data
<del> // However, save this state if it is not in a turn restriction and the other state is
<del> else if (s0.weight == other.weight && !(other.turnRestrictions != null && s0.turnRestrictions == null))
<del> continue QUEUE;
<del> }
<del> bestStatesAtEdge.put(s0.backEdge, s0);
<del> }
<ide>
<ide> if (routingVisitor != null) {
<ide> routingVisitor.visitVertex(s0); |
|
JavaScript | mit | 27285843118f1e405ac57cfb137c05e8c22f3a07 | 0 | GreenImp/rpg-dice-roller | /*global beforeEach, describe, DiceRoller, expect, jasmine, it */
;(function(){
'use strict';
var utils = {
/**
* Reduces an array to a single value
*
* @param obj
* @returns {*}
*/
reduceArray: function(obj){
if(Array.isArray(obj)){
return obj.reduce(function(a, b){
return utils.reduceArray(a) + utils.reduceArray(b);
}, 0);
}else{
return obj;
}
},
getMin: function(obj){
return Math.min.apply(this, obj);
},
getMax: function(obj){
return Math.max.apply(this, obj);
}
};
var customMatchers = {
toBeWithinRange: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {};
if((actual < expected.min) || (actual > expected.max)){
result.pass = false;
result.message = 'Expected ' + actual + ' to be within range: ' + expected.min + ' - ' + expected.max;
}else{
result.pass = true;
result.message = 'Expected ' + actual + ' NOT to be within range: ' + expected.min + ' - ' + expected.max;
}
return result;
}
};
},
toHaveValuesWithinRange: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true},
i;
if(!Array.isArray(actual)){
result.pass = false;
result.message = 'Expected ' + actual + ' to be an Array';
}else{
for(i = 0; i < actual.length; i++){
if((actual[i] < expected.min) || (actual[i] > expected.max)){
result.pass = false;
result.message = 'Expected ' + actual[i] + ' to be within range: ' + expected.min + ' - ' + expected.max;
// end loop
i = actual.length;
}
}
}
return result;
}
};
},
toArraySumEqualTo: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
sum = utils.reduceArray(actual);
if(sum !== expected){
result.pass = false;
result.message = 'Expected Array sum ' + sum + ' to equal ' + expected;
}else{
result.pass = true;
result.message = 'Expected Array sum ' + sum + ' NOT to equal ' + expected;
}
return result;
}
};
},
toHaveRolls: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" Not to have rolls'},
rolls = actual.rolls,
rollsReq = expected ? expected.rolls : null,
rollI;
if(!rolls.length) {
result.pass = false;
result.message = 'Expected "' + actual + '" to have rolls';
}else if(rollsReq && (rollsReq.length !== rolls.length)){
result.pass = false;
result.message = 'Expected "' + actual + '" to have ' + rollsReq.length + ' rolls';
}else{
// loop through each roll and ensure that it has rolls (multiples for exploded)
for(rollI = 0; rollI < rolls.length; rollI++){
if(!rolls[rollI].length){
result.pass = false;
result.message = 'Expected "' + actual + '" roll index "' + rollI + '" to have roll values';
}else if(rollsReq && rollsReq[rollI] && (rollsReq[rollI] !== '*') && (rollsReq[rollI] !== rolls[rollI].length)){
// roll length doesn't match expected (Ignore *, which means unlimited)
result.pass = false;
result.message = 'Expected "' + actual + '" index "' + rollI + '" (' + rolls[rollI].length + ') to have ' + rollsReq[rollI] + ' roll values';
}
if(!result.pass){
// end the loop
rollI = rolls.length;
}
}
}
return result;
}
};
},
toExplode: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" NOT to explode'},
rollList = actual,
rollI,
max = expected.max || null,
min = expected.min || null,
comparePoint = expected.comparePoint || {operator: '=', value: max},
penetrating = !!expected.penetrate;
if(!max || !min){
result.pass = false;
result.message = "Expected explode argument to provide max and min";
}else{
for(rollI = 0; rollI < rollList.length; rollList++){
var value = rollList[rollI];
if(penetrating && (rollI === 1)){
// we need to compensate for the -1 on consecutive rolls when penetrating
max--;
min--;
}
if(value > max){
// rolled over max
result.pass = false;
result.message = "Expected " + value + ' to be less than or equal to max (' + max + ')';
}else if (value < min){
// rolled under min
result.pass = false;
result.message = "Expected " + value + ' to be greater than or equal to min (' + min + ')';
}else{
var didExplode = rollList.length > (rollI+1),
shouldExplode = false;
switch(comparePoint.operator){
case '=':
case '==':
shouldExplode = value === comparePoint.value;
break;
case '<':
shouldExplode = value < comparePoint.value;
break;
case '>':
shouldExplode = value > comparePoint.value;
break;
case '<=':
shouldExplode = value <= comparePoint.value;
break;
case '>=':
shouldExplode = value >= comparePoint.value;
break;
case '!':
case '!=':
shouldExplode = value !== comparePoint.value;
break;
}
if(shouldExplode && !didExplode){
// met comparison, but didn't explode
result.pass = false;
result.message = "Expected " + value + ' to explode at ' + comparePoint.operator + ' ' + comparePoint.value;
}else if(!shouldExplode && didExplode){
// didn't meet comparison, but exploded
result.pass = false;
result.message = "Expected " + value + ' to NOT explode at ' + comparePoint.operator + ' ' + comparePoint.value;
}
}
if(!result.pass){
// end the loop
rollI = rollList.length;
}
}
}
return result;
}
};
},
toMatchParsedNotation: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
toMatch = expected.notation + ': ' + expected.rolls + ' = ' + expected.total;
if(''+actual !== toMatch){
result.pass = false;
result.message = 'Expected "' + actual + '" to match parsed notation "' + toMatch + '"';
}else{
result.pass = true;
result.message = 'Expected "' + actual + '" NOT to match parsed notation "' + toMatch + '"';
}
return result;
}
};
},
toHaveLogLength: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
logLength = actual.getLog().length;
if(typeof expected !== 'number'){
// no length specified - just check if it has a length
if(!logLength){
// no length
result.pass = false;
result.message = 'Expected log to have a length';
}else{
// no length
result.pass = true;
result.message = 'Expected log to NOT have a length';
}
}else if(logLength === expected){
result.pass = true;
result.message = 'Expected log length ' + logLength + ' NOT to be ' + expected;
}else{
result.pass = false;
result.message = 'Expected log length ' + logLength + ' to be ' + expected;
}
return result;
}
};
},
toBeDiceRoll: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" to NOT be a Dice Roll'},
resultT,
roll = actual,
total = roll.getTotal();
// check value is within allowed range
resultT = customMatchers.toBeWithinRange().compare(total, {min: expected.totalRange.min, max: expected.totalRange.max});
if(!resultT.pass){
result = resultT;
}
// check the rolls list is correct
resultT = customMatchers.toHaveRolls().compare(roll, {rolls: expected.rolls});
if(!resultT.pass){
result = resultT;
}
resultT = customMatchers.toHaveValuesWithinRange().compare(roll.rolls[0], {min: expected.dieRange.min, max: expected.dieRange.max});
if(!resultT.pass){
result = resultT;
}
resultT = customMatchers.toArraySumEqualTo().compare(roll.rolls, total);
if(!resultT.pass){
result = resultT;
}
// check the output string
resultT = customMatchers.toMatchParsedNotation().compare(roll, {notation: expected.notation, rolls: '[' + roll.rolls[0].join(',') + ']', total: total});
if(!resultT.pass){
result = resultT;
}
return result;
}
};
}
};
describe('basic dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = [4, 6, 10, 20, '%'],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
// loop through and run the tests for the dice
for(i = 0; i < dice.length; i++){
var die = dice[i],
sides = die === '%' ? 100 : die,
notation = 'd' + die;
it('should return between 1 and ' + sides + ' for `' + notation + '`', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: 1,
max: sides
},
totalRange: {
min: 1,
max: sides
},
rolls: [1],
notation: notation
});
}
});
}
});
describe('fudge dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = ['dF', 'dF.2', 'dF.1'],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
// loop through and run the tests for the dice
for(i = 0; i < dice.length; i++){
var die = dice[i],
notation = die;
// Fudge dice always provide a value between -1 and 1
it('should be between -1 and 1 for `' + notation + '`', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: -1,
max: 1
},
totalRange: {
min: -1,
max: 1
},
rolls: [1],
notation: notation
});
}
});
}
});
describe('multiple dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = [
{sides: 6, rolls: 4},
{sides: 10, rolls: 8},
{sides: 20, rolls: 5}
],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
for(i = 0; i < dice.length; i++){
var die = dice[i],
notation = die.rolls + 'd' + die.sides;
it('should roll a ' + die.sides + ' sided die ' + die.rolls + ' times', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: 1,
max: die.sides
},
totalRange: {
min: die.rolls,
max: die.rolls*die.sides
},
rolls: [die.rolls],
notation: notation
});
}
});
}
it('should compute multiple dice rolls for `1d6+2d10`', function(){
var notation = '1d6+2d10',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 26});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 10});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']+[' + roll.rolls[1].join(',') + ']', total: total});
});
it('should compute multiple dice rolls for `3d6*2d10-L`', function(){
var notation = '3d6*2d10-L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 180});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [3,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 10});
expect(utils.reduceArray(roll.rolls[0]) * (utils.reduceArray(roll.rolls[1]) - utils.getMin(roll.rolls[1]))).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']*[' + roll.rolls[1].join(',') + ']-L', total: total});
});
it('should compute multiple dice rolls for `4d6/2d3`', function(){
var notation = '4d6/2d3',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 0.66, max: 12});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 3});
expect(utils.reduceArray(roll.rolls[0]) / utils.reduceArray(roll.rolls[1])).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']/[' + roll.rolls[1].join(',') + ']', total: total});
});
});
describe('exploding, compounding, and penetrating', function(){
// create a new instance of the DiceRoller
var diceRoller,
loopCount = 1000,
i;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
});
it('should explode for `1d2!`', function(){
var notation = '1d2!',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should compound explode for `1d2!!`', function(){
var notation = '1d2!!',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should penetrate for `1d2!p`', function(){
var notation = '1d2!p',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++) {
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2, penetrate: true});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should penetrate compound for `1d2!!p`', function(){
var notation = '1d2!!p',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (check for total >= 2, as penetrating subtracts 1, so a second roll of one, would be zero)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total >= 2) ? '!!p' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total >= 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should explode if higher than 1 for `1d6!>1`', function(){
var notation = '1d6!>1',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 6, comparePoint: {operator: '>', value: 1}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should explode if less than 2 for `1d2!<2`', function(){
var notation = '1d2!<2',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2, comparePoint: {operator: '<', value: 2}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should explode if equal to 2 for `1d3!=2`', function(){
var notation = '1d3!=2',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 3, comparePoint: {operator: '=', value: 2}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should compound if higher than 1 for `1d6!!>1`', function(){
var notation = '1d6!!>1',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds if over 1, so any total of 2 or more means that it must have compounded)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total >= 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total >= 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should compound if less than 2 for `1d2!!<2`', function(){
var notation = '1d2!!<2',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds only on a roll of 1 - if we roll a 1, we roll again;
// if we then roll a 2, we get a total of 3, if we roll a 1 we get 2 and roll again - so a minimum of 3 if compounding)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should compound if equal to 2 for `1d2!!=2`', function(){
var notation = '1d2!!=2',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds only on a roll of 2 - if we roll a 2, we roll again;
// if we then roll a 1, we get a total of 3, if we roll a 2 we get 4 and roll again - so a minimum of 5 if compounding)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 4) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 4);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
});
describe('basic equations', function(){
// create a new instance of the DiceRoller
var diceRoller;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
});
it('should return between 3 and 8 for `1d6+2`', function(){
var notation = '1d6+2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 8});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total-2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total-2) + ']+2', total: total});
});
it('should return between -1 and 2 for `1d4-2`', function(){
var notation = '1d4-2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: -1, max: 2});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total+2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total+2) + ']-2', total: total});
});
it('should return between 2 and 20 for `1d10*2`', function(){
var notation = '1d10*2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 2, max: 20});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total/2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total/2) + ']*2', total: total});
});
it('should return between 0.5 and 4 for `1d8/2`', function(){
var notation = '1d8/2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 0.5, max: 4});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total*2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total*2) + ']/2', total: total});
});
it('should subtract the LOWEST roll for `4d6-L', function(){
var notation = '4d6-L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 18});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']-L', total: total});
});
it('should add the LOWEST roll for `4d6+L', function(){
var notation = '4d6+L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 5, max: 30});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before lowest is added) is equal to the total, with the lowest subtracted
expect(roll.rolls).toArraySumEqualTo(total - utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']+L', total: total});
});
it('should multiply by the LOWEST roll for `4d6*L', function(){
var notation = '4d6*L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 144});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before multiplied by lowest) is equal to the total, divided by the lowest
expect(roll.rolls).toArraySumEqualTo(total / utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']*L', total: total});
});
it('should divide by the LOWEST roll for `4d6/L', function(){
var notation = '4d6/L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 19});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before divided by lowest) is equal to the total, multiplied by the lowest
expect(roll.rolls).toArraySumEqualTo(total * utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']/L', total: total});
});
it('should subtract the HIGHEST roll for `4d6-H', function(){
var notation = '4d6-H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 18});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before highest is subtracted) is equal to the total, with the highest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']-H', total: total});
});
it('should add the HIGHEST roll for `4d6+H', function(){
var notation = '4d6+H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 5, max: 30});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before highest is added) is equal to the total, with the highest subtracted
expect(roll.rolls).toArraySumEqualTo(total - utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']+H', total: total});
});
it('should multiply by the HIGHEST roll for `4d6*H', function(){
var notation = '4d6*H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 144});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before multiplied by highest) is equal to the total, divided by the highest
expect(roll.rolls).toArraySumEqualTo(total / utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']*H', total: total});
});
it('should divide by the HIGHEST roll for `4d6/H', function(){
var notation = '4d6/H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 1.5, max: 4});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before divided by highest) is equal to the total, multiplied by the highest
expect(roll.rolls).toArraySumEqualTo(total * utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']/H', total: total});
});
it('should subtract the LOWEST explode roll for `d6!-L`', function(){
var notation = 'd6!-L',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']-L', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the Highest explode roll for `d6!-H`', function(){
var notation = 'd6!-H',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']-H', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the LOWEST compound roll for `d6!!-L`', function(){
var notation = 'd6!!-L',
hasCompounded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toEqual(0);
// check if the rolls actually exist
expect(roll.rolls).toBeGreaterThan(0);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0][0] + (roll.rolls[0][0] > 6 ? '!!' : '') + ']-L', total: total});
// determine whether this roll exploded by checking if the value is greater than the max
hasCompounded = hasCompounded || (roll.rolls[0][0] > 6);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasCompounded).toBeTruthy();
});
it('should subtract the HIGHEST compound roll for `d6!!-H`', function(){
var notation = 'd6!!-H',
hasCompounded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toEqual(0);
// check if the rolls actually exist
expect(roll.rolls).toBeGreaterThan(0);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0][0] + (roll.rolls[0][0] > 6 ? '!!' : '') + ']-H', total: total});
// determine whether this roll exploded by checking if the value is greater than the max
hasCompounded = hasCompounded || (roll.rolls[0][0] > 6);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasCompounded).toBeTruthy();
});
it('should subtract the LOWEST penetrating roll for `d6!p-L`', function(){
var notation = 'd6!p-L',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']-L', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the HIGHEST penetrating roll for `d6!p-H`', function(){
var notation = 'd6!p-H',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']-H', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
});
describe('roll log', function(){
// create a new instance of the DiceRoller
var diceRoller = new DiceRoller();
beforeEach(function(){
jasmine.addMatchers(customMatchers);
});
it('should be no dice rolled', function(){
expect(diceRoller).not.toHaveLogLength();
expect(diceRoller.getNotation()).toEqual('');
});
it('should have 1 dice rolled', function(){
diceRoller.roll('d6');
expect(diceRoller).toHaveLogLength(1);
});
it('should be cleared log', function(){
diceRoller.roll('d6');
diceRoller.clearLog();
expect(diceRoller).not.toHaveLogLength();
expect(diceRoller.getNotation()).toEqual('');
});
it('should have 2 dice rolled', function(){
diceRoller.roll('1d6');
diceRoller.roll('d10');
expect(diceRoller).toHaveLogLength(2);
});
});
}());
| tests/dice-roll.test.js | /*global beforeEach, describe, DiceRoller, expect, jasmine, it */
;(function(){
'use strict';
var utils = {
/**
* Reduces an array to a single value
*
* @param obj
* @returns {*}
*/
reduceArray: function(obj){
if(Array.isArray(obj)){
return obj.reduce(function(a, b){
return utils.reduceArray(a) + utils.reduceArray(b);
}, 0);
}else{
return obj;
}
},
getMin: function(obj){
return Math.min.apply(this, obj);
},
getMax: function(obj){
return Math.max.apply(this, obj);
}
};
var customMatchers = {
toBeWithinRange: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {};
if((actual < expected.min) || (actual > expected.max)){
result.pass = false;
result.message = 'Expected ' + actual + ' to be within range: ' + expected.min + ' - ' + expected.max;
}else{
result.pass = true;
result.message = 'Expected ' + actual + ' NOT to be within range: ' + expected.min + ' - ' + expected.max;
}
return result;
}
};
},
toHaveValuesWithinRange: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true},
i;
if(!Array.isArray(actual)){
result.pass = false;
result.message = 'Expected ' + actual + ' to be an Array';
}else{
for(i = 0; i < actual.length; i++){
if((actual[i] < expected.min) || (actual[i] > expected.max)){
result.pass = false;
result.message = 'Expected ' + actual[i] + ' to be within range: ' + expected.min + ' - ' + expected.max;
// end loop
i = actual.length;
}
}
}
return result;
}
};
},
toArraySumEqualTo: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
sum = utils.reduceArray(actual);
if(sum !== expected){
result.pass = false;
result.message = 'Expected Array sum ' + sum + ' to equal ' + expected;
}else{
result.pass = true;
result.message = 'Expected Array sum ' + sum + ' NOT to equal ' + expected;
}
return result;
}
};
},
toHaveRolls: function(util,customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" Not to have rolls'},
rolls = actual.rolls,
rollsReq = expected ? expected.rolls : null,
rollI;
if(!rolls.length) {
result.pass = false;
result.message = 'Expected "' + actual + '" to have rolls';
}else if(rollsReq && (rollsReq.length !== rolls.length)){
result.pass = false;
result.message = 'Expected "' + actual + '" to have ' + rollsReq.length + ' rolls';
}else{
// loop through each roll and ensure that it has rolls (multiples for exploded)
for(rollI = 0; rollI < rolls.length; rollI++){
if(!rolls[rollI].length){
result.pass = false;
result.message = 'Expected "' + actual + '" roll index "' + rollI + '" to have roll values';
}else if(rollsReq && rollsReq[rollI] && (rollsReq[rollI] !== '*') && (rollsReq[rollI] !== rolls[rollI].length)){
// roll length doesn't match expected (Ignore *, which means unlimited)
result.pass = false;
result.message = 'Expected "' + actual + '" index "' + rollI + '" (' + rolls[rollI].length + ') to have ' + rollsReq[rollI] + ' roll values';
}
if(!result.pass){
// end the loop
rollI = rolls.length;
}
}
}
return result;
}
};
},
toExplode: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" NOT to explode'},
rollList = actual,
rollI,
max = expected.max || null,
min = expected.min || null,
comparePoint = expected.comparePoint || {operator: '=', value: max},
penetrating = !!expected.penetrate;
if(!max || !min){
result.pass = false;
result.message = "Expected explode argument to provide max and min";
}else{
for(rollI = 0; rollI < rollList.length; rollList++){
var value = rollList[rollI];
if(penetrating && (rollI === 1)){
// we need to compensate for the -1 on consecutive rolls when penetrating
max--;
min--;
}
if(value > max){
// rolled over max
result.pass = false;
result.message = "Expected " + value + ' to be less than or equal to max (' + max + ')';
}else if (value < min){
// rolled under min
result.pass = false;
result.message = "Expected " + value + ' to be greater than or equal to min (' + min + ')';
}else{
var didExplode = rollList.length > (rollI+1),
shouldExplode = false;
switch(comparePoint.operator){
case '=':
case '==':
shouldExplode = value === comparePoint.value;
break;
case '<':
shouldExplode = value < comparePoint.value;
break;
case '>':
shouldExplode = value > comparePoint.value;
break;
case '<=':
shouldExplode = value <= comparePoint.value;
break;
case '>=':
shouldExplode = value >= comparePoint.value;
break;
case '!':
case '!=':
shouldExplode = value !== comparePoint.value;
break;
}
if(shouldExplode && !didExplode){
// met comparison, but didn't explode
result.pass = false;
result.message = "Expected " + value + ' to explode at ' + comparePoint.operator + ' ' + comparePoint.value;
}else if(!shouldExplode && didExplode){
// didn't meet comparison, but exploded
result.pass = false;
result.message = "Expected " + value + ' to NOT explode at ' + comparePoint.operator + ' ' + comparePoint.value;
}
}
if(!result.pass){
// end the loop
rollI = rollList.length;
}
}
}
return result;
}
};
},
toMatchParsedNotation: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
toMatch = expected.notation + ': ' + expected.rolls + ' = ' + expected.total;
if(''+actual !== toMatch){
result.pass = false;
result.message = 'Expected "' + actual + '" to match parsed notation "' + toMatch + '"';
}else{
result.pass = true;
result.message = 'Expected "' + actual + '" NOT to match parsed notation "' + toMatch + '"';
}
return result;
}
};
},
toHaveLogLength: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {},
logLength = actual.getLog().length;
if(typeof expected !== 'number'){
// no length specified - just check if it has a length
if(!logLength){
// no length
result.pass = false;
result.message = 'Expected log to have a length';
}else{
// no length
result.pass = true;
result.message = 'Expected log to NOT have a length';
}
}else if(logLength === expected){
result.pass = true;
result.message = 'Expected log length ' + logLength + ' NOT to be ' + expected;
}else{
result.pass = false;
result.message = 'Expected log length ' + logLength + ' to be ' + expected;
}
return result;
}
};
},
toBeDiceRoll: function(util, customEqualityTesters){
return {
compare: function(actual, expected){
var result = {pass: true, message: 'Expected "' + actual + '" to NOT be a Dice Roll'},
resultT,
roll = actual,
total = roll.getTotal();
// check value is within allowed range
resultT = customMatchers.toBeWithinRange().compare(total, {min: expected.totalRange.min, max: expected.totalRange.max});
if(!resultT.pass){
result = resultT;
}
// check the rolls list is correct
resultT = customMatchers.toHaveRolls().compare(roll, {rolls: expected.rolls});
if(!resultT.pass){
result = resultT;
}
resultT = customMatchers.toHaveValuesWithinRange().compare(roll.rolls[0], {min: expected.dieRange.min, max: expected.dieRange.max});
if(!resultT.pass){
result = resultT;
}
resultT = customMatchers.toArraySumEqualTo().compare(roll.rolls, total);
if(!resultT.pass){
result = resultT;
}
// check the output string
resultT = customMatchers.toMatchParsedNotation().compare(roll, {notation: expected.notation, rolls: '[' + roll.rolls[0].join(',') + ']', total: total});
if(!resultT.pass){
result = resultT;
}
return result;
}
};
}
};
describe('basic dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = [4, 6, 10, 20, '%'],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
// loop through and run the tests for the dice
for(i = 0; i < dice.length; i++){
var die = dice[i],
sides = die === '%' ? 100 : die,
notation = 'd' + die;
it('should return between 1 and ' + sides + ' for `' + notation + '`', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: 1,
max: sides
},
totalRange: {
min: 1,
max: sides
},
rolls: [1],
notation: notation
});
}
});
}
});
describe('fudge dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = ['dF', 'dF.2', 'dF.1'],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
// loop through and run the tests for the dice
for(i = 0; i < dice.length; i++){
var die = dice[i],
notation = die;
// Fudge dice always provide a value between -1 and 1
it('should be between -1 and 1 for `' + notation + '`', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: -1,
max: 1
},
totalRange: {
min: -1,
max: 1
},
rolls: [1],
notation: notation
});
}
});
}
});
describe('multiple dice', function(){
// create a new instance of the DiceRoller
var diceRoller,
dice = [
{sides: 6, rolls: 4},
{sides: 10, rolls: 8},
{sides: 20, rolls: 5}
],
loopCount = 1000,
i, j;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
j = 0;
});
for(i = 0; i < dice.length; i++){
var die = dice[i],
notation = die.rolls + 'd' + die.sides;
it('should roll a ' + die.sides + ' sided die ' + die.rolls + ' times', function(){
// run the tests multiple times for consistency
for(j = 0; j < loopCount; j++){
expect(diceRoller.roll(notation)).toBeDiceRoll({
dieRange: {
min: 1,
max: die.sides
},
totalRange: {
min: die.rolls,
max: die.rolls*die.sides
},
rolls: [die.rolls],
notation: notation
});
}
});
}
it('should compute multiple dice rolls for `1d6+2d10`', function(){
var notation = '1d6+2d10',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 26});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 10});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']+[' + roll.rolls[1].join(',') + ']', total: total});
});
it('should compute multiple dice rolls for `3d6*2d10-L`', function(){
var notation = '3d6*2d10-L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 180});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [3,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 10});
expect(utils.reduceArray(roll.rolls[0]) * (utils.reduceArray(roll.rolls[1]) - utils.getMin(roll.rolls[1]))).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']*[' + roll.rolls[1].join(',') + ']-L', total: total});
});
it('should compute multiple dice rolls for `4d6/2d3`', function(){
var notation = '4d6/2d3',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 0.66, max: 12});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4,2]});
expect(roll.rolls[0]).toHaveValuesWithinRange({min: 1, max: 6});
expect(roll.rolls[1]).toHaveValuesWithinRange({min: 1, max: 3});
expect(utils.reduceArray(roll.rolls[0]) / utils.reduceArray(roll.rolls[1])).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join(',') + ']/[' + roll.rolls[1].join(',') + ']', total: total});
});
});
describe('exploding, compounding, and penetrating', function(){
// create a new instance of the DiceRoller
var diceRoller,
loopCount = 1000,
i;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
i = 0;
});
it('should explode for `1d2!`', function(){
var notation = '1d2!',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should compound explode for `1d2!!`', function(){
var notation = '1d2!!',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should penetrate for `1d2!p`', function(){
var notation = '1d2!p',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++) {
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2, penetrate: true});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should penetrate compound for `1d2!!p`', function(){
var notation = '1d2!!p',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (check for total >= 2, as penetrating subtracts 1, so a second roll of one, would be zero)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total >= 2) ? '!!p' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total >= 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should explode if higher than 1 for `1d6!>1`', function(){
var notation = '1d6!>1',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 6, comparePoint: {operator: '>', value: 1}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should explode if less than 2 for `1d2!<2`', function(){
var notation = '1d2!<2',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 2, comparePoint: {operator: '<', value: 2}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should explode if equal to 2 for `1d3!=2`', function(){
var notation = '1d3!=2',
hasExploded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: ['*']});
expect(roll.rolls).toArraySumEqualTo(total);
expect(roll.rolls[0]).toExplode({min: 1, max: 3, comparePoint: {operator: '=', value: 2}});
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should compound if higher than 1 for `1d6!!>1`', function(){
var notation = '1d6!!>1',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds if over 1, so any total of 2 or more means that it must have compounded)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total >= 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total >= 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should compound if less than 2 for `1d2!!<2`', function(){
var notation = '1d2!!<2',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds only on a roll of 1 - if we roll a 1, we roll again;
// if we then roll a 2, we get a total of 3, if we roll a 1 we get 2 and roll again - so a minimum of 3 if compounding)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 2) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 2);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
it('should compound if equal to 2 for `1d2!!=2`', function(){
var notation = '1d2!!=2',
hasCompounded = false;
// loop this roll for consistency
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(0);
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total);
// check the output string (Compounds only on a roll of 2 - if we roll a 2, we roll again;
// if we then roll a 1, we get a total of 3, if we roll a 2 we get 4 and roll again - so a minimum of 5 if compounding)
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + total + ((total > 4) ? '!!' : '') + ']', total: total});
// determine whether this roll compounded by checking the value of the roll
hasCompounded = hasCompounded || (total > 4);
}
// if we run many rolls, we should expect at least one to have compounded
expect(hasCompounded).toBeTruthy();
});
});
describe('basic equations', function(){
// create a new instance of the DiceRoller
var diceRoller;
beforeEach(function(){
jasmine.addMatchers(customMatchers);
diceRoller = new DiceRoller();
});
it('should return between 3 and 8 for `1d6+2`', function(){
var notation = '1d6+2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 8});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total-2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total-2) + ']+2', total: total});
});
it('should return between -1 and 2 for `1d4-2`', function(){
var notation = '1d4-2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: -1, max: 2});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total+2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total+2) + ']-2', total: total});
});
it('should return between 2 and 20 for `1d10*2`', function(){
var notation = '1d10*2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 2, max: 20});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total/2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total/2) + ']*2', total: total});
});
it('should return between 0.5 and 4 for `1d8/2`', function(){
var notation = '1d8/2',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 0.5, max: 4});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [1]});
expect(roll.rolls).toArraySumEqualTo(total*2);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (total*2) + ']/2', total: total});
});
it('should subtract the LOWEST roll for `4d6-L', function(){
var notation = '4d6-L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 18});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']-L', total: total});
});
it('should add the LOWEST roll for `4d6+L', function(){
var notation = '4d6+L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 5, max: 30});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before lowest is added) is equal to the total, with the lowest subtracted
expect(roll.rolls).toArraySumEqualTo(total - utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']+L', total: total});
});
it('should multiply by the LOWEST roll for `4d6*L', function(){
var notation = '4d6*L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 144});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before multiplied by lowest) is equal to the total, divided by the lowest
expect(roll.rolls).toArraySumEqualTo(total / utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']*L', total: total});
});
it('should divide by the LOWEST roll for `4d6/L', function(){
var notation = '4d6/L',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 19});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before divided by lowest) is equal to the total, multiplied by the lowest
expect(roll.rolls).toArraySumEqualTo(total * utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']/L', total: total});
});
it('should subtract the HIGHEST roll for `4d6-H', function(){
var notation = '4d6-H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 3, max: 18});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before highest is subtracted) is equal to the total, with the highest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']-H', total: total});
});
it('should add the HIGHEST roll for `4d6+H', function(){
var notation = '4d6+H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 5, max: 30});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before highest is added) is equal to the total, with the highest subtracted
expect(roll.rolls).toArraySumEqualTo(total - utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']+H', total: total});
});
it('should multiply by the HIGHEST roll for `4d6*H', function(){
var notation = '4d6*H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 4, max: 144});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before multiplied by highest) is equal to the total, divided by the highest
expect(roll.rolls).toArraySumEqualTo(total / utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']*H', total: total});
});
it('should divide by the HIGHEST roll for `4d6/H', function(){
var notation = '4d6/H',
roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeWithinRange({min: 1.5, max: 4});
// check the rolls list is correct
expect(roll).toHaveRolls({rolls: [4]});
// check if the sum of the rolls (before divided by highest) is equal to the total, multiplied by the highest
expect(roll.rolls).toArraySumEqualTo(total * utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + (roll.rolls[0].join(',')) + ']/H', total: total});
});
it('should subtract the LOWEST explode roll for `d6!-L`', function(){
var notation = 'd6!-L',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']-L', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the Highest explode roll for `d6!-H`', function(){
var notation = 'd6!-H',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!,') + ']-H', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the LOWEST compound roll for `d6!!-L`', function(){
var notation = 'd6!!-L',
hasCompounded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toEqual(0);
// check if the rolls actually exist
expect(roll.rolls).toBeGreaterThan(0);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0][0] + (roll.rolls[0][0] > 6 ? '!!' : '') + ']-L', total: total});
// determine whether this roll exploded by checking if the value is greater than the max
hasCompounded = hasCompounded || (roll.rolls[0][0] > 6);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasCompounded).toBeTruthy();
});
it('should subtract the HIGHEST compound roll for `d6!!-H`', function(){
var notation = 'd6!!-H',
hasCompounded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toEqual(0);
// check if the rolls actually exist
expect(roll.rolls).toBeGreaterThan(0);
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0][0] + (roll.rolls[0][0] > 6 ? '!!' : '') + ']-H', total: total});
// determine whether this roll exploded by checking if the value is greater than the max
hasCompounded = hasCompounded || (roll.rolls[0][0] > 6);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasCompounded).toBeTruthy();
});
it('should subtract the LOWEST penetrating roll for `d6!p-L`', function(){
var notation = 'd6!p-L',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMin(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']-L', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
it('should subtract the HIGHEST penetrating roll for `d6!p-H`', function(){
var notation = 'd6!p-H',
hasExploded = false,
loopCount = 1000,
i;
// loop this roll for consistency (We need it to have exploded at least once)
for(i = 0; i < loopCount; i++){
var roll = diceRoller.roll(notation),
total = roll.getTotal();
// check value is within allowed range
expect(total).toBeGreaterThan(-1);
// check if the sum of the rolls (before lowest is subtracted) is equal to the total, with the lowest added
expect(roll.rolls).toArraySumEqualTo(total + utils.getMax(roll.rolls[0]));
// check the output string
expect(roll).toMatchParsedNotation({notation: notation, rolls: '[' + roll.rolls[0].join('!p,') + ']-H', total: total});
// determine whether this roll exploded by checking the amount of rolls
hasExploded = hasExploded || (roll.rolls[0].length > 1);
}
// if we run many rolls, we should expect at least one to have exploded
expect(hasExploded).toBeTruthy();
});
});
describe('roll log', function(){
// create a new instance of the DiceRoller
var diceRoller = new DiceRoller();
beforeEach(function(){
jasmine.addMatchers(customMatchers);
});
it('should be no dice rolled', function(){
expect(diceRoller).not.toHaveLogLength();
expect(diceRoller + '').toEqual('No dice rolled');
});
it('should have 1 dice rolled', function(){
diceRoller.roll('d6');
expect(diceRoller).toHaveLogLength(1);
});
it('should be cleared log', function(){
diceRoller.roll('d6');
diceRoller.clearLog();
expect(diceRoller).not.toHaveLogLength();
expect(diceRoller + '').toEqual('No dice rolled');
});
it('should have 2 dice rolled', function(){
diceRoller.roll('1d6');
diceRoller.roll('d10');
expect(diceRoller).toHaveLogLength(2);
});
});
}());
| Updates empty log test
| tests/dice-roll.test.js | Updates empty log test | <ide><path>ests/dice-roll.test.js
<ide>
<ide> it('should be no dice rolled', function(){
<ide> expect(diceRoller).not.toHaveLogLength();
<del> expect(diceRoller + '').toEqual('No dice rolled');
<add> expect(diceRoller.getNotation()).toEqual('');
<ide> });
<ide>
<ide> it('should have 1 dice rolled', function(){
<ide> diceRoller.clearLog();
<ide>
<ide> expect(diceRoller).not.toHaveLogLength();
<del> expect(diceRoller + '').toEqual('No dice rolled');
<add> expect(diceRoller.getNotation()).toEqual('');
<ide> });
<ide>
<ide> it('should have 2 dice rolled', function(){ |
|
Java | lgpl-2.1 | 32dc59d4838476b092960340687f4858f66fb2ea | 0 | simoc/mapyrus,simoc/mapyrus,simoc/mapyrus | /*
* This file is part of Mapyrus, software for plotting maps.
* Copyright (C) 2003 - 2011 Simon Chenery.
*
* Mapyrus 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 of the License, or
* (at your option) any later version.
*
* Mapyrus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Mapyrus; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* @(#) $Id$
*/
package org.mapyrus.function;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Manages all available functions. Provides function name
* lookup function.
*/
public class FunctionTable
{
static Hashtable<String, Function> mFunctions = new Hashtable<String, Function>();
/*
* Load all internal functions and any additional functions defined by user.
*/
static
{
Function f;
f = new Abs();
mFunctions.put(f.getName(), f);
f = new Axis();
mFunctions.put(f.getName(), f);
f = new Ceil();
mFunctions.put(f.getName(), f);
f = new Chr();
mFunctions.put(f.getName(), f);
f = new Cos();
mFunctions.put(f.getName(), f);
f = new Dir();
mFunctions.put(f.getName(), f);
f = new Floor();
mFunctions.put(f.getName(), f);
f = new Format();
mFunctions.put(f.getName(), f);
f = new Interpolate();
mFunctions.put(f.getName(), f);
f = new Length();
mFunctions.put(f.getName(), f);
f = new Lower();
mFunctions.put(f.getName(), f);
f = new Lpad();
mFunctions.put(f.getName(), f);
f = new Log10();
mFunctions.put(f.getName(), f);
f = new Match();
mFunctions.put(f.getName(), f);
f = new Max();
mFunctions.put(f.getName(), f);
f = new Min();
mFunctions.put(f.getName(), f);
f = new Parsegeo();
mFunctions.put(f.getName(), f);
f = new Pow();
mFunctions.put(f.getName(), f);
f = new Protected();
mFunctions.put(f.getName(), f);
f = new Random();
mFunctions.put(f.getName(), f);
f = new Readable();
mFunctions.put(f.getName(), f);
f = new Replace();
mFunctions.put(f.getName(), f);
f = new Roman();
mFunctions.put(f.getName(), f);
f = new Round();
mFunctions.put(f.getName(), f);
f = new Rpad();
mFunctions.put(f.getName(), f);
f = new Sin();
mFunctions.put(f.getName(), f);
f = new Split();
mFunctions.put(f.getName(), f);
f = new Spool();
mFunctions.put(f.getName(), f);
f = new Sqrt();
mFunctions.put(f.getName(), f);
f = new Stringascent();
mFunctions.put(f.getName(), f);
f = new Stringdescent();
mFunctions.put(f.getName(), f);
f = new Stringheight();
mFunctions.put(f.getName(), f);
f = new Stringwidth();
mFunctions.put(f.getName(), f);
f = new Substr();
mFunctions.put(f.getName(), f);
f = new Sum();
mFunctions.put(f.getName(), f);
f = new Tan();
mFunctions.put(f.getName(), f);
f = new Tempname();
mFunctions.put(f.getName(), f);
f = new Timestamp();
mFunctions.put(f.getName(), f);
f = new Topage();
mFunctions.put(f.getName(), f);
f = new Toworlds();
mFunctions.put(f.getName(), f);
f = new Trim();
mFunctions.put(f.getName(), f);
f = new Upper();
mFunctions.put(f.getName(), f);
f = new Wordwrap();
mFunctions.put(f.getName(), f);
try
{
/*
* Java Topology Suite functions are only available if the
* JTS JAR file is available in the classpath.
*/
f = new Buffer();
mFunctions.put(f.getName(), f);
f = new Contains();
mFunctions.put(f.getName(), f);
f = new ConvexHull();
mFunctions.put(f.getName(), f);
f = new Crosses();
mFunctions.put(f.getName(), f);
f = new Difference();
mFunctions.put(f.getName(), f);
f = new Intersection();
mFunctions.put(f.getName(), f);
f = new Overlaps();
mFunctions.put(f.getName(), f);
f = new Union();
mFunctions.put(f.getName(), f);
}
catch (NoClassDefFoundError e)
{
/*
* Add dummy placeholder functions instead.
* They'll fail if they are ever called though.
*/
mFunctions.put("buffer", new DummyFunction("buffer"));
mFunctions.put("contains", new DummyFunction("contains"));
mFunctions.put("convexhull", new DummyFunction("convexhull"));
mFunctions.put("difference", new DummyFunction("difference"));
mFunctions.put("intersection", new DummyFunction("intersection"));
mFunctions.put("overlaps", new DummyFunction("overlaps"));
mFunctions.put("union", new DummyFunction("union"));
}
try
{
/*
* Reprojection only available if jhlabs.com PROJ.4 JAR file is in classpath.
*/
f = new Reproject();
mFunctions.put(f.getName(), f);
}
catch (NoClassDefFoundError e)
{
mFunctions.put("reproject", new DummyFunction("reproject"));
}
}
/**
* Lookup Java method using reflection.
* @param funcName name of class and method to lookup.
* @return function for calling this method, or null if no method found.
*/
private static Function getJavaFunction(String funcName, int dotIndex)
{
String methodName = funcName.substring(dotIndex + 1);
String className = funcName.substring(0, dotIndex);
Function retval = null;
try
{
/*
* Try to find Java class.
*/
Class clazz = Class.forName(className);
/*
* Now try to find method in the Java class.
*/
Method[] methods = clazz.getDeclaredMethods();
ArrayList<Method> possibleMethods = new ArrayList<Method>();
for (int i = 0; i < methods.length; i++)
{
int modifiers = methods[i].getModifiers();
if ((modifiers & Modifier.STATIC) != 0 &&
(modifiers & Modifier.PUBLIC) != 0 &&
methodName.equals(methods[i].getName()))
{
possibleMethods.add(methods[i]);
}
}
if (!possibleMethods.isEmpty())
{
retval = new JavaFunction(className, methodName, possibleMethods);
/*
* Add function to standard function table to avoid having to search
* for it again next time it is used.
*/
mFunctions.put(funcName, retval);
}
}
catch (ClassNotFoundException e)
{
}
return(retval);
}
/**
* Lookup function from name and return object
* @param name name of function to lookup.
* @return object for evaluating this function, or null if not found.
*/
public static Function getFunction(String funcName)
{
Function retval = mFunctions.get(funcName);
if (retval == null)
{
/*
* Try and find a Java method with this name instead.
*/
int index = funcName.lastIndexOf('.');
if (index >= 0)
retval = getJavaFunction(funcName, index);
}
return(retval);
}
}
| src/org/mapyrus/function/FunctionTable.java | /*
* This file is part of Mapyrus, software for plotting maps.
* Copyright (C) 2003 - 2011 Simon Chenery.
*
* Mapyrus 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 of the License, or
* (at your option) any later version.
*
* Mapyrus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Mapyrus; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* @(#) $Id$
*/
package org.mapyrus.function;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Hashtable;
/**
* Manages all available functions. Provides function name
* lookup function.
*/
public class FunctionTable
{
static Hashtable<String, Function> mFunctions = new Hashtable<String, Function>();
/*
* Load all internal functions and any additional functions defined by user.
*/
static
{
Function f;
f = new Abs();
mFunctions.put(f.getName(), f);
f = new Axis();
mFunctions.put(f.getName(), f);
f = new Ceil();
mFunctions.put(f.getName(), f);
f = new Cos();
mFunctions.put(f.getName(), f);
f = new Dir();
mFunctions.put(f.getName(), f);
f = new Floor();
mFunctions.put(f.getName(), f);
f = new Format();
mFunctions.put(f.getName(), f);
f = new Interpolate();
mFunctions.put(f.getName(), f);
f = new Length();
mFunctions.put(f.getName(), f);
f = new Lower();
mFunctions.put(f.getName(), f);
f = new Lpad();
mFunctions.put(f.getName(), f);
f = new Log10();
mFunctions.put(f.getName(), f);
f = new Match();
mFunctions.put(f.getName(), f);
f = new Max();
mFunctions.put(f.getName(), f);
f = new Min();
mFunctions.put(f.getName(), f);
f = new Parsegeo();
mFunctions.put(f.getName(), f);
f = new Pow();
mFunctions.put(f.getName(), f);
f = new Protected();
mFunctions.put(f.getName(), f);
f = new Random();
mFunctions.put(f.getName(), f);
f = new Readable();
mFunctions.put(f.getName(), f);
f = new Replace();
mFunctions.put(f.getName(), f);
f = new Roman();
mFunctions.put(f.getName(), f);
f = new Round();
mFunctions.put(f.getName(), f);
f = new Rpad();
mFunctions.put(f.getName(), f);
f = new Sin();
mFunctions.put(f.getName(), f);
f = new Split();
mFunctions.put(f.getName(), f);
f = new Spool();
mFunctions.put(f.getName(), f);
f = new Sqrt();
mFunctions.put(f.getName(), f);
f = new Stringascent();
mFunctions.put(f.getName(), f);
f = new Stringdescent();
mFunctions.put(f.getName(), f);
f = new Stringheight();
mFunctions.put(f.getName(), f);
f = new Stringwidth();
mFunctions.put(f.getName(), f);
f = new Substr();
mFunctions.put(f.getName(), f);
f = new Sum();
mFunctions.put(f.getName(), f);
f = new Tan();
mFunctions.put(f.getName(), f);
f = new Tempname();
mFunctions.put(f.getName(), f);
f = new Timestamp();
mFunctions.put(f.getName(), f);
f = new Topage();
mFunctions.put(f.getName(), f);
f = new Toworlds();
mFunctions.put(f.getName(), f);
f = new Trim();
mFunctions.put(f.getName(), f);
f = new Upper();
mFunctions.put(f.getName(), f);
f = new Wordwrap();
mFunctions.put(f.getName(), f);
try
{
/*
* Java Topology Suite functions are only available if the
* JTS JAR file is available in the classpath.
*/
f = new Buffer();
mFunctions.put(f.getName(), f);
f = new Contains();
mFunctions.put(f.getName(), f);
f = new ConvexHull();
mFunctions.put(f.getName(), f);
f = new Crosses();
mFunctions.put(f.getName(), f);
f = new Difference();
mFunctions.put(f.getName(), f);
f = new Intersection();
mFunctions.put(f.getName(), f);
f = new Overlaps();
mFunctions.put(f.getName(), f);
f = new Union();
mFunctions.put(f.getName(), f);
}
catch (NoClassDefFoundError e)
{
/*
* Add dummy placeholder functions instead.
* They'll fail if they are ever called though.
*/
mFunctions.put("buffer", new DummyFunction("buffer"));
mFunctions.put("contains", new DummyFunction("contains"));
mFunctions.put("convexhull", new DummyFunction("convexhull"));
mFunctions.put("difference", new DummyFunction("difference"));
mFunctions.put("intersection", new DummyFunction("intersection"));
mFunctions.put("overlaps", new DummyFunction("overlaps"));
mFunctions.put("union", new DummyFunction("union"));
}
try
{
/*
* Reprojection only available if jhlabs.com PROJ.4 JAR file is in classpath.
*/
f = new Reproject();
mFunctions.put(f.getName(), f);
}
catch (NoClassDefFoundError e)
{
mFunctions.put("reproject", new DummyFunction("reproject"));
}
}
/**
* Lookup Java method using reflection.
* @param funcName name of class and method to lookup.
* @return function for calling this method, or null if no method found.
*/
private static Function getJavaFunction(String funcName, int dotIndex)
{
String methodName = funcName.substring(dotIndex + 1);
String className = funcName.substring(0, dotIndex);
Function retval = null;
try
{
/*
* Try to find Java class.
*/
Class clazz = Class.forName(className);
/*
* Now try to find method in the Java class.
*/
Method[] methods = clazz.getDeclaredMethods();
ArrayList<Method> possibleMethods = new ArrayList<Method>();
for (int i = 0; i < methods.length; i++)
{
int modifiers = methods[i].getModifiers();
if ((modifiers & Modifier.STATIC) != 0 &&
(modifiers & Modifier.PUBLIC) != 0 &&
methodName.equals(methods[i].getName()))
{
possibleMethods.add(methods[i]);
}
}
if (!possibleMethods.isEmpty())
{
retval = new JavaFunction(className, methodName, possibleMethods);
/*
* Add function to standard function table to avoid having to search
* for it again next time it is used.
*/
mFunctions.put(funcName, retval);
}
}
catch (ClassNotFoundException e)
{
}
return(retval);
}
/**
* Lookup function from name and return object
* @param name name of function to lookup.
* @return object for evaluating this function, or null if not found.
*/
public static Function getFunction(String funcName)
{
Function retval = mFunctions.get(funcName);
if (retval == null)
{
/*
* Try and find a Java method with this name instead.
*/
int index = funcName.lastIndexOf('.');
if (index >= 0)
retval = getJavaFunction(funcName, index);
}
return(retval);
}
}
| Add Chr function.
| src/org/mapyrus/function/FunctionTable.java | Add Chr function. | <ide><path>rc/org/mapyrus/function/FunctionTable.java
<ide> f = new Ceil();
<ide> mFunctions.put(f.getName(), f);
<ide>
<add> f = new Chr();
<add> mFunctions.put(f.getName(), f);
<add>
<ide> f = new Cos();
<ide> mFunctions.put(f.getName(), f);
<ide> |
|
Java | apache-2.0 | ca334097faed6f27a77dc7a53fd7ec8aea26bffc | 0 | mjl68/FallAssistant,mjl68/FallAssistant,vaibhav-jani/FallAssistant,vaibhav-jani/FallAssistant | package com.falldetect2015.android.fallassistant;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class PrefsActivity extends Activity implements View.OnClickListener {
private EditText phone, hMsg;
private Button oSave, oReset;
private SeekBar sensorMax;
private TextView titleTV;
private SharedPreferences sp;
private SharedPreferences.Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prefs);
phone = (EditText) findViewById(R.id.phoneNum);
hMsg = (EditText) findViewById(R.id.helpMsg);
sensorMax = (SeekBar) findViewById(R.id.snsrMaxAcc);
titleTV = (TextView) findViewById(R.id.settingsTV);
titleTV.setText(getString(R.string.options_message));
titleTV.invalidate();
sensorMax.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
Log.d(MainActivity.LOG_TAG, "sensorMax Current Progress:" + progress
+ System.getProperty("line.separator")
+ "Progress changed by User:" + fromUser);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
//Log.d(MainActivity.LOG_TAG, "sensorMax Tracking Started...");
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
//Log.d(MainActivity.LOG_TAG, "sensorMax... Tracking Stopped");
}
});
sp = getSharedPreferences(MainActivity.PREF_FILE, MODE_PRIVATE);
edit = sp.edit();
loadPrefs();
oSave = (Button) findViewById(R.id.btnOpSave);
oSave.setOnClickListener(this);
oReset = (Button) findViewById(R.id.btnOptReset);
oReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.phoneNum = "5126469115";
MainActivity.helpMsg = getString(R.string.fall_message);
loadPrefs();
}
});
}
private void loadPrefs() {
String strVal = null;
int intVal;
float floatVal = 0;
try {
sp.getString(MainActivity.PREF_CONTACT_NUMBER, strVal);
if (strVal == null) strVal = MainActivity.phoneNum;
phone.setText(strVal);
strVal = null;
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + strVal);
if (strVal == null) strVal = MainActivity.helpMsg;
sp.getString(MainActivity.PREF_HELP_MSG, strVal);
hMsg.setText(strVal);
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + strVal);
sp.getFloat(MainActivity.PREF_SENSOR_MAX, floatVal);
sensorMax.setProgress(40 - Math.round((floatVal - 15) * 4));
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + floatVal + " set " + sensorMax.getProgress());
phone.invalidate();
hMsg.invalidate();
sensorMax.invalidate();
} catch (Exception ex) {
if (MainActivity.DEBUG)
Log.d(MainActivity.LOG_TAG, "LoadPrefs Error: " + ex.getMessage());
}
}
@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_prefs, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void savePrefs(String key, float value) {
edit.putFloat(key, value);
edit.commit();
}
private void savePrefs(String key, String value) {
Log.d(MainActivity.LOG_TAG, "SavePrefs loaded: " + key + ": " + value);
edit.putString(key, value.trim());
edit.commit();
String val = "";
sp.getString(MainActivity.PREF_CONTACT_NUMBER, val);
Toast.makeText(this, val, Toast.LENGTH_SHORT);
}
@Override
public void onClick(View v) {
MainActivity.phoneNum = phone.getText().toString();
MainActivity.helpMsg = hMsg.getText().toString();
faSensorService.normalThreshold = new Float(Math.abs(15 + 0.4 * (sensorMax.getProgress() - 40)));
savePrefs(MainActivity.PREF_CONTACT_NUMBER, phone.getText().toString());
savePrefs(MainActivity.PREF_HELP_MSG, hMsg.getText().toString());
savePrefs(MainActivity.PREF_SENSOR_MAX, faSensorService.normalThreshold);
}
}
| Application/src/main/java/com/falldetect2015/android/fallassistant/PrefsActivity.java | package com.falldetect2015.android.fallassistant;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class PrefsActivity extends Activity implements View.OnClickListener {
private EditText phone, hMsg;
private Button oSave, oReset;
private SeekBar sensorMax;
private TextView titleTV;
private SharedPreferences sp;
private SharedPreferences.Editor edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prefs);
phone = (EditText) findViewById(R.id.phoneNum);
hMsg = (EditText) findViewById(R.id.helpMsg);
sensorMax = (SeekBar) findViewById(R.id.snsrMaxAcc);
titleTV = (TextView) findViewById(R.id.settingsTV);
titleTV.setText(getString(R.string.options_message));
titleTV.invalidate();
//sensorMax.setMax(40);
sensorMax.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
Log.d(MainActivity.LOG_TAG, "sensorMax Current Progress:" + progress
+ System.getProperty("line.separator")
+ "Progress changed by User:" + fromUser);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
//Log.d(MainActivity.LOG_TAG, "sensorMax Tracking Started...");
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
//Log.d(MainActivity.LOG_TAG, "sensorMax... Tracking Stopped");
}
});
sp = getSharedPreferences(MainActivity.PREF_FILE, MODE_PRIVATE);
edit = sp.edit();
loadPrefs();
oSave = (Button) findViewById(R.id.btnOpSave);
oSave.setOnClickListener(this);
oReset = (Button) findViewById(R.id.btnOptReset);
oReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.phoneNum = "5126469115";
MainActivity.helpMsg = getString(R.string.fall_message);
loadPrefs();
}
});
}
private void loadPrefs() {
String strVal = null;
int intVal;
float floatVal = 0;
try {
sp.getString(MainActivity.PREF_CONTACT_NUMBER, strVal);
if (strVal == null) strVal = MainActivity.phoneNum;
phone.setText(strVal);
strVal = null;
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + strVal);
if (strVal == null) strVal = MainActivity.helpMsg;
sp.getString(MainActivity.PREF_HELP_MSG, strVal);
hMsg.setText(strVal);
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + strVal);
sp.getFloat(MainActivity.PREF_SENSOR_MAX, floatVal);
sensorMax.setProgress(40 - Math.round((floatVal - 15) * 4));
Log.d(MainActivity.LOG_TAG, "LoadPrefs loaded: " + floatVal + " set " + sensorMax.getProgress());
phone.invalidate();
hMsg.invalidate();
sensorMax.invalidate();
} catch (Exception ex) {
if (MainActivity.DEBUG)
Log.d(MainActivity.LOG_TAG, "LoadPrefs Error: " + ex.getMessage());
}
}
@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_prefs, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void savePrefs(String key, float value) {
edit.putFloat(key, value);
edit.commit();
}
private void savePrefs(String key, String value) {
Log.d(MainActivity.LOG_TAG, "SavePrefs loaded: " + key + ": " + value);
edit.putString(key, value.trim());
edit.commit();
String val = "";
sp.getString(MainActivity.PREF_CONTACT_NUMBER, val);
Toast.makeText(this, val, Toast.LENGTH_SHORT);
}
@Override
public void onClick(View v) {
MainActivity.phoneNum = phone.getText().toString();
MainActivity.helpMsg = hMsg.getText().toString();
faSensorService.normalThreshold = new Float(Math.abs(15 + 0.4 * (sensorMax.getProgress() - 40)));
savePrefs(MainActivity.PREF_CONTACT_NUMBER, phone.getText().toString());
savePrefs(MainActivity.PREF_HELP_MSG, hMsg.getText().toString());
savePrefs(MainActivity.PREF_SENSOR_MAX, faSensorService.normalThreshold);
}
}
| updated prefsActivity
| Application/src/main/java/com/falldetect2015/android/fallassistant/PrefsActivity.java | updated prefsActivity | <ide><path>pplication/src/main/java/com/falldetect2015/android/fallassistant/PrefsActivity.java
<ide> titleTV = (TextView) findViewById(R.id.settingsTV);
<ide> titleTV.setText(getString(R.string.options_message));
<ide> titleTV.invalidate();
<del> //sensorMax.setMax(40);
<ide> sensorMax.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
<ide>
<ide> @Override |
|
Java | mit | 9545b4bba897f352977c1ba72bfc9dd8349bd2cf | 0 | oxguy3/AwesomeProxy | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;
public class ProxyServer extends Thread {
// should the server respond to HTTP requests at all?
volatile static boolean isAlive;
// should the server respond to proxy HTTP requests?
volatile static boolean isProxyActive;
Socket clientSocket; // connection to client
BufferedReader clientIn; // client -> proxy
DataOutputStream clientOut; // proxy -> client
Socket remoteSocket; // connection to remote
DataInputStream remoteIn; // remote -> proxy
DataOutputStream remoteOut; // proxy -> remote
Hashtable<String,String> remoteHeaders; // headers received from remote
public ProxyServer(Socket srv) {
clientSocket = srv;
}
public static void main(String[] args) {
int port = 8080;
if (args.length > 0) {
String portStr = args[0];
port = Integer.parseInt(portStr);
}
// start listening for connections
ServerSocket srvSock;
try {
srvSock = new ServerSocket(port);
System.out.println("Listening for connections on port " + Integer.toString(port) + "...");
} catch (IOException e) {
System.err.println("Failed to bind socket");
e.printStackTrace();
return;
}
isAlive = true;
isProxyActive = true;
while (isAlive) {
try {
Socket server = srvSock.accept();
if (!isAlive) break;
//System.out.println("Received new connection...");
ProxyServer worker = new ProxyServer(server);
worker.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
srvSock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
// reader for client->proxy data
clientIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), Charset.forName("UTF-8")));
// writer for proxy->client data
clientOut = new DataOutputStream(clientSocket.getOutputStream());
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = clientIn.readLine()) != null) {
// break after two lines
if (line.equals("")) break;
//System.out.println("C->P | "+line);
lines.add(line);
}
// ignore empty requests
if (lines.size() < 1) {
System.out.println("Closing empty request...");
clientSocket.close();
return;
}
// the first line of the request
String request = lines.get(0);
System.out.println("> " + request);
String[] requestArgs = request.split(" ");
if (requestArgs.length != 3) {
respondWithHtmlStatus(HttpStatus.BAD_REQUEST);
return;
}
// we only support GET
if (!requestArgs[0].equalsIgnoreCase("GET")) {
respondWithHtmlStatus(HttpStatus.METHOD_NOT_ALLOWED);
return;
}
// force http/1.1
if (!requestArgs[2].equalsIgnoreCase(Utils.HTTP_VERSION)) {
respondWithHtmlStatus(HttpStatus.HTTP_VER_NOT_SUPPORTED);
return;
}
String requestUrl = requestArgs[1]; // the URI that our client wants to access
// handle internal local addresses
if (requestUrl.startsWith("/")) {
String[] requestParams = requestUrl.split("/");
if (requestParams.length <= 1) {
// a simple homepage
respondWithHtml(HttpStatus.ACCEPTED, Utils.getSimpleHtml(
"Welcome to " + Utils.SERVER_NAME + "!",
"<p>Made by Hayden Schiff and Shir Maimon.</p>"
+ "<p>Actions available:</p>"
+ "<ul>"
+ "<li><a href=\"/proxy/on\">Enable proxy service</a></li>"
+ "<li><a href=\"/proxy/off\">Disable proxy service</a></li>"
+ "<li><a href=\"/exit\">Shutdown the server</a></li>"
+ "</ul>"
));
return;
} else if (requestParams[1].equals("exit")) {
// command to shutdown the server
ProxyServer.isAlive = false;
respondWithMessage(
HttpStatus.ACCEPTED,
"Exit command received",
"The server is no longer accepting new connections, and "
+ "will shutdown after all active connections are closed."
);
return;
} else if (requestParams[1].equals("proxy") && requestParams.length > 2) {
// commands to turn proxy service on/off
if (requestParams[2].equals("on")) {
ProxyServer.isProxyActive = true;
respondWithMessage(
HttpStatus.ACCEPTED,
"Proxy enabled",
"The server will now accept proxy requests."
);
return;
} else if (requestParams[2].equals("off")) {
ProxyServer.isProxyActive = false;
respondWithMessage(
HttpStatus.ACCEPTED,
"Proxy disabled",
"The server will stop accepting proxy requests."
);
return;
}
} else if (requestParams[1].equals("teapot")) {
// i couldn't resist
respondWithHtmlStatus(HttpStatus.IM_A_TEAPOT);
return;
}
respondWithHtmlStatus(HttpStatus.NOT_FOUND);
return;
}
// forbid unfamiliar protocols and local files
if (!requestUrl.startsWith("http://")) {
respondWithHtmlStatus(HttpStatus.FORBIDDEN);
return;
}
if (!ProxyServer.isProxyActive) {
respondWithHtmlStatus(HttpStatus.SERVICE_UNAVAILABLE);
}
String urlMinusProtocol = requestUrl.substring("http://".length());
String hostname = urlMinusProtocol.split("/")[0];
String requestPath = urlMinusProtocol.substring(hostname.length());
// pull the port out of the url, if necessary
int remotePort = 80;
String[] hostnameExplode = hostname.split(":");
if (hostnameExplode.length > 1) {
hostname = hostnameExplode[0];
remotePort = Integer.parseInt(hostnameExplode[1]);
}
remoteSocket = new Socket(hostname, remotePort);
System.out.println("Connecting to remote server...");
remoteOut = new DataOutputStream(remoteSocket.getOutputStream());
remoteIn = new DataInputStream(remoteSocket.getInputStream());
String remoteReq = "";
remoteReq += "GET " + requestPath + " " + Utils.HTTP_VERSION;
remoteReq += Utils.httpHeader("Host", hostname);
remoteReq += Utils.httpHeader("User-Agent", Utils.SERVER_NAME);
remoteReq += Utils.HTTP_HEADER_END;
remoteOut.writeBytes(remoteReq);
System.out.println("Sent request to remote server...");
remoteHeaders = new Hashtable<String,String>();
String remoteResponseLine = remoteIn.readLine();
System.out.println("< " + remoteResponseLine);
//System.out.println("R->P | " + remoteResponseLine);
// read all the headers
if (!readRemoteHeaders()) return;
byte[] remoteBody = null;
if (remoteHeaders.containsKey("content-length")) {
// remote server told us from the get-go how much data to
// expect, so just read exactly that many bytes
String contentLengthStr = remoteHeaders.get("content-length");
int contentLength = 0;
try {
contentLength = Integer.parseInt(contentLengthStr);
} catch (NumberFormatException nfe) {
System.err.println("Couldn't parse content length from remote server");
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
remoteBody = new byte[contentLength];
for (int i = 0; i < contentLength; i++) {
remoteBody[i] = (byte) remoteIn.read();
}
} else if (remoteHeaders.containsKey("transfer-encoding")) {
// remote server is sending data in chunks, so read all the chunks
// we do not support any transfer-encoding methods besides chunked
if (!remoteHeaders.get("transfer-encoding").equalsIgnoreCase("chunked")) {
System.err.println("Unknown transfer-encoding method: " + remoteHeaders.get("transfer-encoding"));
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
remoteBody = new byte[0];
String chunkHead;
while ((chunkHead = remoteIn.readLine()) != null) {
if (chunkHead.equals("0") || chunkHead.equals("")) break;
int chunkSize = 0;
try {
// get the size of this chunk
chunkSize = Integer.parseInt(chunkHead.split(";")[0], 16);
} catch (NumberFormatException e) {
System.err.println("Couldn't parse chunk size from remote server");
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
int oldLength = remoteBody.length;
int newLength = oldLength + chunkSize;
remoteBody = Arrays.copyOf(remoteBody, newLength);
for (int i = oldLength; i < newLength; i++) {
remoteBody[i] = (byte) remoteIn.read();
}
remoteIn.skipBytes(2); // skip the CRLF
}
remoteHeaders.remove("transfer-encoding");
remoteHeaders.put("content-length", String.valueOf(remoteBody.length));
// we've reached the end of the chunks, so add footers to our headers array if any exist
if (!readRemoteHeaders()) return;
} else {
// remote server is sending data using some voodoo magic we don't understand
System.err.println("Unknown data tranfer method");
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
//System.out.println("Closing remote connection...");
remoteOut.close();
remoteIn.close();
remoteSocket.close();
clientOut.writeBytes(remoteResponseLine);
Enumeration<String> keys = remoteHeaders.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
clientOut.writeBytes(Utils.httpHeader(key, remoteHeaders.get(key)));
}
clientOut.writeBytes(Utils.HTTP_HEADER_END);
clientOut.write(remoteBody);
//System.out.println("Closing client connection...");
clientOut.close();
clientIn.close();
clientSocket.close();
// dos.writeUTF(HTTP_VERSION + " 200 S'all good");
// sendObligatoryHeaders(dos);
// server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Reads headers from remote server until end of header block is reached
*
* @return success
*/
public boolean readRemoteHeaders() throws IOException {
String remoteLine;
while ((remoteLine = remoteIn.readLine()) != null) {
if (remoteLine.equals("")) break;
//System.out.println("R->P | "+remoteLine);
String[] splitLine = remoteLine.split(":");
if (splitLine.length < 2) {
System.err.println("Invalid header from remote server: " + remoteLine);
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return false;
}
String headerKey = splitLine[0].toLowerCase();
remoteHeaders.put(headerKey, remoteLine.substring(headerKey.length()+1).trim());
}
return true;
}
/**
* Begins to send the header block to the client
*/
public void beginResponse(HttpStatus status) throws IOException {
System.err.println(status.getFullName());
clientOut.writeBytes(Utils.HTTP_VERSION + " " + status.getFullName());
sendHeader("Server", Utils.SERVER_NAME);
sendHeader("Date", Utils.getRFC1123Date());
}
/**
* Finishes the header block being sent to the client
*/
public void endHeader() throws IOException {
clientOut.writeBytes(Utils.HTTP_HEADER_END);
}
/**
* Closes up all open connections for this request
*/
public void endResponse() throws IOException {
clientOut.close();
if (clientSocket != null && !clientSocket.isClosed()) clientSocket.close();
if (remoteSocket != null && !remoteSocket.isClosed()) remoteSocket.close();
}
/**
* Responds to client with some html text
*/
public void respondWithHtml(HttpStatus status, String body) throws IOException {
beginResponse(status);
sendHeader("Content-Length", String.valueOf(body.length()));
sendHeader("Content-Type", "text/html");
endHeader();
clientOut.writeBytes(body);
endResponse();
}
/**
* Responds to client with simple HTML page with a title and a message
*/
public void respondWithMessage(HttpStatus status, String title, String message) throws IOException {
respondWithHtml(status, Utils.getSimpleHtmlMessage(title, message));
}
/**
* Responds to client with generic message for given HTTP status
*/
public void respondWithHtmlStatus(HttpStatus status) throws IOException {
String body = Utils.getSimpleHtmlMessage(status.getFullName(), status.description);
respondWithHtml(status, body);
}
/**
* Convenience method for sending an HTTP header to the client
*/
public void sendHeader(String key, String value) throws IOException {
clientOut.writeBytes(Utils.httpHeader(key, value));
}
}
| src/ProxyServer.java | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;
public class ProxyServer extends Thread {
// should the server respond to HTTP requests at all?
volatile static boolean isAlive;
// should the server respond to proxy HTTP requests?
volatile static boolean isProxyActive;
Socket server; // connection to client
BufferedReader buff; // client -> proxy
DataOutputStream dos; // proxy -> client
Socket client; // connection to remote
DataInputStream remoteDis; // remote -> proxy
DataOutputStream remoteDos; // proxy -> remote
Hashtable<String,String> remoteHeaders; // headers received from remote
public ProxyServer(Socket srv) {
server = srv;
}
public static void main(String[] args) {
int port = 8080;
if (args.length > 0) {
String portStr = args[0];
port = Integer.parseInt(portStr);
}
ServerSocket srvSock;
try {
srvSock = new ServerSocket(port);
System.out.println("Listening for connections on port " + Integer.toString(port) + "...");
} catch (IOException e) {
e.printStackTrace();
return;
}
isAlive = true;
isProxyActive = true;
while (isAlive) {
try {
Socket server = srvSock.accept();
if (!isAlive) break;
System.out.println("Received new connection...");
ProxyServer worker = new ProxyServer(server);
worker.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void run() {
try {
// reader for client->proxy data
buff = new BufferedReader(new InputStreamReader(server.getInputStream(), Charset.forName("UTF-8")));
// writer for proxy->client data
dos = new DataOutputStream(server.getOutputStream());
ArrayList<String> lines = new ArrayList<String>();
String line;
while ((line = buff.readLine()) != null) {
// break after two lines
if (line.equals("")) break;
System.out.println("C->P | "+line);
lines.add(line);
}
// ignore empty requests
if (lines.size() < 1) {
System.out.println("Closing empty request...");
server.close();
return;
}
// the first line of the request
String request = lines.get(0);
String[] requestArgs = request.split(" ");
if (requestArgs.length != 3) {
respondWithHtmlStatus(HttpStatus.BAD_REQUEST);
return;
}
// we only support GET
if (!requestArgs[0].equalsIgnoreCase("GET")) {
respondWithHtmlStatus(HttpStatus.METHOD_NOT_ALLOWED);
return;
}
// force http/1.1
if (!requestArgs[2].equalsIgnoreCase(Utils.HTTP_VERSION)) {
respondWithHtmlStatus(HttpStatus.HTTP_VER_NOT_SUPPORTED);
return;
}
String requestUrl = requestArgs[1]; // the URI that our client wants to access
// handle local (i.e. non-remote) addresses
if (requestUrl.startsWith("/")) {
String[] requestParams = requestUrl.split("/");
if (requestParams.length <= 1) {
// a simple homepage
respondWithHtml(HttpStatus.ACCEPTED, Utils.getSimpleHtml(
"Welcome to " + Utils.SERVER_NAME + "!",
"<p>Made by Hayden Schiff and Shir Maimon.</p>"
+ "<p>Actions available:</p>"
+ "<ul>"
+ "<li><a href=\"/proxy/on\">Enable proxy service</a></li>"
+ "<li><a href=\"/proxy/off\">Disable proxy service</a></li>"
+ "<li><a href=\"/exit\">Shutdown the server</a></li>"
+ "</ul>"
));
return;
} else if (requestParams[1].equals("exit")) {
// command to shutdown the server
ProxyServer.isAlive = false;
respondWithMessage(
HttpStatus.ACCEPTED,
"Exit command received",
"The server is no longer accepting new connections, and "
+ "will shutdown after all active connections are closed."
);
return;
} else if (requestParams[1].equals("proxy") && requestParams.length > 2) {
// commands to turn proxy service on/off
if (requestParams[2].equals("on")) {
ProxyServer.isProxyActive = true;
respondWithMessage(
HttpStatus.ACCEPTED,
"Proxy enabled",
"The server will now accept proxy requests."
);
return;
} else if (requestParams[2].equals("off")) {
ProxyServer.isProxyActive = false;
respondWithMessage(
HttpStatus.ACCEPTED,
"Proxy disabled",
"The server will stop accepting proxy requests."
);
return;
}
} else if (requestParams[1].equals("teapot")) {
// i couldn't resist
respondWithHtmlStatus(HttpStatus.IM_A_TEAPOT);
return;
}
respondWithHtmlStatus(HttpStatus.NOT_FOUND);
return;
}
// forbid unfamiliar protocols and local files
if (!requestUrl.startsWith("http://")) {
respondWithHtmlStatus(HttpStatus.FORBIDDEN);
return;
}
if (!ProxyServer.isProxyActive) {
respondWithHtmlStatus(HttpStatus.SERVICE_UNAVAILABLE);
}
String urlMinusProtocol = requestUrl.substring("http://".length());
String hostname = urlMinusProtocol.split("/")[0];
String requestPath = urlMinusProtocol.substring(hostname.length());
// pull the port out of the url, if necessary
int remotePort = 80;
String[] hostnameExplode = hostname.split(":");
if (hostnameExplode.length > 1) {
hostname = hostnameExplode[0];
remotePort = Integer.parseInt(hostnameExplode[1]);
}
client = new Socket(hostname, remotePort);
System.out.println("Connecting to remote server...");
remoteDos = new DataOutputStream(client.getOutputStream());
remoteDis = new DataInputStream(client.getInputStream());
String remoteReq = "";
remoteReq += "GET " + requestPath + " " + Utils.HTTP_VERSION;
remoteReq += Utils.httpHeader("Host", hostname);
remoteReq += Utils.httpHeader("User-Agent", Utils.SERVER_NAME);
remoteReq += Utils.HTTP_HEADER_END;
remoteDos.writeBytes(remoteReq);
System.out.println("Sent request to remote server...");
remoteHeaders = new Hashtable<String,String>();
String remoteResponseLine = remoteDis.readLine();
System.out.println("R->P | " + remoteResponseLine);
// read all the headers
if (!readRemoteHeaders()) return;
byte[] remoteBody = null;
if (remoteHeaders.containsKey("content-length")) {
// remote server told us from the get-go how much data to
// expect, so just read exactly that many bytes
String contentLengthStr = remoteHeaders.get("content-length");
int contentLength = 0;
try {
contentLength = Integer.parseInt(contentLengthStr);
} catch (NumberFormatException nfe) {
System.err.println("Couldn't parse content length from remote server");
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
remoteBody = new byte[contentLength];
for (int i = 0; i < contentLength; i++) {
remoteBody[i] = (byte) remoteDis.read();
}
} else if (remoteHeaders.containsKey("transfer-encoding")) {
// remote server is sending data in chunks, so read all the chunks
// we do not support any transfer-encoding methods besides chunked
if (!remoteHeaders.get("transfer-encoding").equalsIgnoreCase("chunked")) {
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
remoteBody = new byte[0];
String chunkHead;
while ((chunkHead = remoteDis.readLine()) != null) {
if (chunkHead.equals("0") || chunkHead.equals("")) break;
System.out.println("CHNK | " + chunkHead);
int chunkSize = 0;
try {
// get the size of this chunk
chunkSize = Integer.parseInt(chunkHead.split(";")[0], 16);
} catch (NumberFormatException e) {
System.err.println("Couldn't parse chunk size from remote server");
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return;
}
int oldLength = remoteBody.length;
int newLength = oldLength + chunkSize;
remoteBody = Arrays.copyOf(remoteBody, newLength);
for (int i = oldLength; i < newLength; i++) {
remoteBody[i] = (byte) remoteDis.read();
}
remoteDis.skipBytes(2); // skip the CRLF
}
System.out.println("SIZE | " + remoteBody.length);
System.out.println("BODY | " + Arrays.toString(remoteBody));
remoteHeaders.remove("transfer-encoding");
remoteHeaders.put("content-length", String.valueOf(remoteBody.length));
// we've reached the end of the chunks, so add footers to our headers array if any exist
if (!readRemoteHeaders()) return;
}
System.out.println("Closing remote connection...");
client.close();
dos.writeBytes(remoteResponseLine);
Enumeration<String> keys = remoteHeaders.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
dos.writeBytes(Utils.httpHeader(key, remoteHeaders.get(key)));
}
dos.writeBytes(Utils.HTTP_HEADER_END);
dos.write(remoteBody);
dos.flush();
dos.close();
System.out.println("Closing client connection...");
server.close();
// dos.writeUTF(HTTP_VERSION + " 200 S'all good");
// sendObligatoryHeaders(dos);
// server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Reads headers from remote server until end of header block is reached
*
* @return success
*/
public boolean readRemoteHeaders() throws IOException {
String remoteLine;
while ((remoteLine = remoteDis.readLine()) != null) {
if (remoteLine.equals("")) break;
System.out.println("R->P | "+remoteLine);
String[] splitLine = remoteLine.split(":");
if (splitLine.length < 2) {
System.err.println("Invalid header from remote server: " + remoteLine);
respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
return false;
}
String headerKey = splitLine[0].toLowerCase();
remoteHeaders.put(headerKey, remoteLine.substring(headerKey.length()+1).trim());
}
return true;
}
/**
* Begins to send the header block to the client
*/
public void beginResponse(HttpStatus status) throws IOException {
System.err.println(status.getFullName());
dos.writeBytes(Utils.HTTP_VERSION + " " + status.getFullName());
sendHeader("Server", Utils.SERVER_NAME);
sendHeader("Date", Utils.getRFC1123Date());
}
/**
* Finishes the header block being sent to the client
*/
public void endHeader() throws IOException {
dos.writeBytes(Utils.HTTP_HEADER_END);
}
/**
* Closes up all open connections for this request
*/
public void endResponse() throws IOException {
dos.close();
if (server != null && !server.isClosed()) server.close();
if (client != null && !client.isClosed()) client.close();
}
/**
* Responds to client with some html text
*/
public void respondWithHtml(HttpStatus status, String body) throws IOException {
beginResponse(status);
sendHeader("Content-Length", String.valueOf(body.length()));
sendHeader("Content-Type", "text/html");
endHeader();
dos.writeBytes(body);
endResponse();
}
/**
* Responds to client with simple HTML page with a title and a message
*/
public void respondWithMessage(HttpStatus status, String title, String message) throws IOException {
respondWithHtml(status, Utils.getSimpleHtmlMessage(title, message));
}
/**
* Responds to client with generic message for given HTTP status
*/
public void respondWithHtmlStatus(HttpStatus status) throws IOException {
String body = Utils.getSimpleHtmlMessage(status.getFullName(), status.description);
respondWithHtml(status, body);
}
/**
* Convenience method for sending an HTTP header to the client
*/
public void sendHeader(String key, String value) throws IOException {
dos.writeBytes(Utils.httpHeader(key, value));
}
}
| refactoring
| src/ProxyServer.java | refactoring | <ide><path>rc/ProxyServer.java
<ide> volatile static boolean isProxyActive;
<ide>
<ide>
<del> Socket server; // connection to client
<del> BufferedReader buff; // client -> proxy
<del> DataOutputStream dos; // proxy -> client
<del>
<del> Socket client; // connection to remote
<del> DataInputStream remoteDis; // remote -> proxy
<del> DataOutputStream remoteDos; // proxy -> remote
<add> Socket clientSocket; // connection to client
<add> BufferedReader clientIn; // client -> proxy
<add> DataOutputStream clientOut; // proxy -> client
<add>
<add> Socket remoteSocket; // connection to remote
<add> DataInputStream remoteIn; // remote -> proxy
<add> DataOutputStream remoteOut; // proxy -> remote
<ide> Hashtable<String,String> remoteHeaders; // headers received from remote
<ide>
<ide> public ProxyServer(Socket srv) {
<del> server = srv;
<add> clientSocket = srv;
<ide> }
<ide>
<ide> public static void main(String[] args) {
<ide> port = Integer.parseInt(portStr);
<ide> }
<ide>
<add> // start listening for connections
<ide> ServerSocket srvSock;
<del>
<ide> try {
<ide> srvSock = new ServerSocket(port);
<ide> System.out.println("Listening for connections on port " + Integer.toString(port) + "...");
<ide>
<ide> } catch (IOException e) {
<add> System.err.println("Failed to bind socket");
<ide> e.printStackTrace();
<ide> return;
<ide> }
<ide> Socket server = srvSock.accept();
<ide> if (!isAlive) break;
<ide>
<del> System.out.println("Received new connection...");
<add> //System.out.println("Received new connection...");
<ide> ProxyServer worker = new ProxyServer(server);
<ide> worker.start();
<ide> } catch (IOException e) {
<ide> e.printStackTrace();
<ide> }
<ide> }
<add>
<add> try {
<add> srvSock.close();
<add> } catch (IOException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<ide>
<ide> public void run() {
<ide> try {
<ide>
<ide> // reader for client->proxy data
<del> buff = new BufferedReader(new InputStreamReader(server.getInputStream(), Charset.forName("UTF-8")));
<add> clientIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), Charset.forName("UTF-8")));
<ide>
<ide> // writer for proxy->client data
<del> dos = new DataOutputStream(server.getOutputStream());
<add> clientOut = new DataOutputStream(clientSocket.getOutputStream());
<ide>
<ide>
<ide> ArrayList<String> lines = new ArrayList<String>();
<ide>
<ide> String line;
<del> while ((line = buff.readLine()) != null) {
<add> while ((line = clientIn.readLine()) != null) {
<ide>
<ide> // break after two lines
<ide> if (line.equals("")) break;
<ide>
<del> System.out.println("C->P | "+line);
<add> //System.out.println("C->P | "+line);
<ide> lines.add(line);
<ide> }
<ide>
<ide> // ignore empty requests
<ide> if (lines.size() < 1) {
<ide> System.out.println("Closing empty request...");
<del> server.close();
<add> clientSocket.close();
<ide> return;
<ide> }
<ide>
<ide> // the first line of the request
<ide> String request = lines.get(0);
<add>
<add> System.out.println("> " + request);
<ide>
<ide> String[] requestArgs = request.split(" ");
<ide> if (requestArgs.length != 3) {
<ide> String requestUrl = requestArgs[1]; // the URI that our client wants to access
<ide>
<ide>
<del> // handle local (i.e. non-remote) addresses
<add> // handle internal local addresses
<ide> if (requestUrl.startsWith("/")) {
<ide> String[] requestParams = requestUrl.split("/");
<ide>
<ide>
<ide>
<ide>
<del> client = new Socket(hostname, remotePort);
<add> remoteSocket = new Socket(hostname, remotePort);
<ide> System.out.println("Connecting to remote server...");
<del> remoteDos = new DataOutputStream(client.getOutputStream());
<del> remoteDis = new DataInputStream(client.getInputStream());
<add> remoteOut = new DataOutputStream(remoteSocket.getOutputStream());
<add> remoteIn = new DataInputStream(remoteSocket.getInputStream());
<ide>
<ide> String remoteReq = "";
<ide>
<ide> remoteReq += Utils.httpHeader("User-Agent", Utils.SERVER_NAME);
<ide> remoteReq += Utils.HTTP_HEADER_END;
<ide>
<del> remoteDos.writeBytes(remoteReq);
<add> remoteOut.writeBytes(remoteReq);
<ide> System.out.println("Sent request to remote server...");
<ide>
<ide> remoteHeaders = new Hashtable<String,String>();
<ide>
<del> String remoteResponseLine = remoteDis.readLine();
<del> System.out.println("R->P | " + remoteResponseLine);
<add> String remoteResponseLine = remoteIn.readLine();
<add> System.out.println("< " + remoteResponseLine);
<add> //System.out.println("R->P | " + remoteResponseLine);
<ide>
<ide> // read all the headers
<ide> if (!readRemoteHeaders()) return;
<ide>
<ide> byte[] remoteBody = null;
<add>
<ide>
<ide> if (remoteHeaders.containsKey("content-length")) {
<ide> // remote server told us from the get-go how much data to
<ide>
<ide> remoteBody = new byte[contentLength];
<ide> for (int i = 0; i < contentLength; i++) {
<del> remoteBody[i] = (byte) remoteDis.read();
<add> remoteBody[i] = (byte) remoteIn.read();
<ide> }
<add>
<ide>
<ide> } else if (remoteHeaders.containsKey("transfer-encoding")) {
<ide> // remote server is sending data in chunks, so read all the chunks
<ide>
<ide> // we do not support any transfer-encoding methods besides chunked
<ide> if (!remoteHeaders.get("transfer-encoding").equalsIgnoreCase("chunked")) {
<add> System.err.println("Unknown transfer-encoding method: " + remoteHeaders.get("transfer-encoding"));
<ide> respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
<ide> return;
<ide> }
<ide> remoteBody = new byte[0];
<ide>
<ide> String chunkHead;
<del> while ((chunkHead = remoteDis.readLine()) != null) {
<add> while ((chunkHead = remoteIn.readLine()) != null) {
<ide>
<ide> if (chunkHead.equals("0") || chunkHead.equals("")) break;
<del>
<del> System.out.println("CHNK | " + chunkHead);
<ide>
<ide> int chunkSize = 0;
<ide> try {
<ide>
<ide> remoteBody = Arrays.copyOf(remoteBody, newLength);
<ide> for (int i = oldLength; i < newLength; i++) {
<del> remoteBody[i] = (byte) remoteDis.read();
<add> remoteBody[i] = (byte) remoteIn.read();
<ide> }
<del> remoteDis.skipBytes(2); // skip the CRLF
<add> remoteIn.skipBytes(2); // skip the CRLF
<ide> }
<del>
<del> System.out.println("SIZE | " + remoteBody.length);
<del> System.out.println("BODY | " + Arrays.toString(remoteBody));
<ide>
<ide> remoteHeaders.remove("transfer-encoding");
<ide> remoteHeaders.put("content-length", String.valueOf(remoteBody.length));
<ide>
<ide> // we've reached the end of the chunks, so add footers to our headers array if any exist
<ide> if (!readRemoteHeaders()) return;
<del> }
<del>
<del>
<del> System.out.println("Closing remote connection...");
<del> client.close();
<del>
<del>
<del>
<del>
<del> dos.writeBytes(remoteResponseLine);
<add>
<add>
<add> } else {
<add> // remote server is sending data using some voodoo magic we don't understand
<add> System.err.println("Unknown data tranfer method");
<add> respondWithHtmlStatus(HttpStatus.BAD_GATEWAY);
<add> return;
<add> }
<add>
<add>
<add> //System.out.println("Closing remote connection...");
<add> remoteOut.close();
<add> remoteIn.close();
<add> remoteSocket.close();
<add>
<add>
<add>
<add>
<add> clientOut.writeBytes(remoteResponseLine);
<ide> Enumeration<String> keys = remoteHeaders.keys();
<ide> while (keys.hasMoreElements()) {
<ide> String key = keys.nextElement();
<del> dos.writeBytes(Utils.httpHeader(key, remoteHeaders.get(key)));
<del> }
<del> dos.writeBytes(Utils.HTTP_HEADER_END);
<del>
<del> dos.write(remoteBody);
<del>
<del> dos.flush();
<del> dos.close();
<del>
<del> System.out.println("Closing client connection...");
<del> server.close();
<add> clientOut.writeBytes(Utils.httpHeader(key, remoteHeaders.get(key)));
<add> }
<add> clientOut.writeBytes(Utils.HTTP_HEADER_END);
<add>
<add> clientOut.write(remoteBody);
<add>
<add> //System.out.println("Closing client connection...");
<add> clientOut.close();
<add> clientIn.close();
<add> clientSocket.close();
<ide>
<ide>
<ide>
<ide> */
<ide> public boolean readRemoteHeaders() throws IOException {
<ide> String remoteLine;
<del> while ((remoteLine = remoteDis.readLine()) != null) {
<add> while ((remoteLine = remoteIn.readLine()) != null) {
<ide>
<ide> if (remoteLine.equals("")) break;
<ide>
<del> System.out.println("R->P | "+remoteLine);
<add> //System.out.println("R->P | "+remoteLine);
<ide>
<ide> String[] splitLine = remoteLine.split(":");
<ide> if (splitLine.length < 2) {
<ide> */
<ide> public void beginResponse(HttpStatus status) throws IOException {
<ide> System.err.println(status.getFullName());
<del> dos.writeBytes(Utils.HTTP_VERSION + " " + status.getFullName());
<add> clientOut.writeBytes(Utils.HTTP_VERSION + " " + status.getFullName());
<ide> sendHeader("Server", Utils.SERVER_NAME);
<ide> sendHeader("Date", Utils.getRFC1123Date());
<ide> }
<ide> * Finishes the header block being sent to the client
<ide> */
<ide> public void endHeader() throws IOException {
<del> dos.writeBytes(Utils.HTTP_HEADER_END);
<add> clientOut.writeBytes(Utils.HTTP_HEADER_END);
<ide> }
<ide>
<ide> /**
<ide> * Closes up all open connections for this request
<ide> */
<ide> public void endResponse() throws IOException {
<del> dos.close();
<del> if (server != null && !server.isClosed()) server.close();
<del> if (client != null && !client.isClosed()) client.close();
<add> clientOut.close();
<add> if (clientSocket != null && !clientSocket.isClosed()) clientSocket.close();
<add> if (remoteSocket != null && !remoteSocket.isClosed()) remoteSocket.close();
<ide> }
<ide>
<ide> /**
<ide> sendHeader("Content-Length", String.valueOf(body.length()));
<ide> sendHeader("Content-Type", "text/html");
<ide> endHeader();
<del> dos.writeBytes(body);
<add> clientOut.writeBytes(body);
<ide> endResponse();
<ide> }
<ide>
<ide> * Convenience method for sending an HTTP header to the client
<ide> */
<ide> public void sendHeader(String key, String value) throws IOException {
<del> dos.writeBytes(Utils.httpHeader(key, value));
<add> clientOut.writeBytes(Utils.httpHeader(key, value));
<ide> }
<ide>
<ide> } |
|
JavaScript | mit | eb57b35089d0d361df6a1f9488c2461258a1507e | 0 | sinsinpub/KC3Kai,KC3Kai/KC3Kai,sinsinpub/KC3Kai,KC3Kai/KC3Kai,KC3Kai/KC3Kai,dragonjet/KC3Kai,DynamicSTOP/KC3Kai,sinsinpub/KC3Kai,dragonjet/KC3Kai,DynamicSTOP/KC3Kai,DynamicSTOP/KC3Kai | /* SortieManager.js
KC3改 Sortie Manager
Stores and manages states and functions during sortie of fleets (including PvP battle).
*/
(function(){
"use strict";
window.KC3SortieManager = {
onSortie: false,
onPvP: false,
onCat: false,
fleetSent: 1,
map_world: 0,
map_num: 0,
map_difficulty: 0,
hqExpGained: 0,
nodes: [],
boss: {},
focusedFleet: [],
supportFleet: [],
fcfCheck: [],
escapedList: [],
materialBefore: false,
materialGain: Array.apply(null, {length:8}).map(v => 0),
sinkList: {main:[], escr:[]},
slotitemConsumed: false,
sortieTime: 0,
startSortie :function(world, mapnum, fleetNum, stime, eventData){
const self = this;
// If still on sortie, end previous one
if(this.isOnSortie()){
this.endSortie();
}
this.fleetSent = parseInt(fleetNum);
this.map_world = world;
this.map_num = mapnum;
const thisMap = this.getCurrentMapData();
this.map_difficulty = world < 10 ? 0 : thisMap.difficulty || 0;
this.hqExpGained = 0;
this.materialBefore = PlayerManager.hq.lastMaterial.concat(
PlayerManager.consumables.torch,
PlayerManager.consumables.buckets,
PlayerManager.consumables.devmats,
PlayerManager.consumables.screws
);
this.slotitemConsumed = false;
this.boss = {
info: false,
bosscell: -1,
comp: -1,
letters: []
};
this.clearNodes();
this.snapshotFleetState();
const fleet = PlayerManager.fleets[this.fleetSent-1];
fleet.resetAfterHp();
// Prepare sortie database record
const sortie = {
diff: this.map_difficulty,
world: world,
mapnum: mapnum,
fleetnum: parseInt(fleetNum, 10),
combined: PlayerManager.combinedFleet,
fleet1: PlayerManager.fleets[0].sortieJson(),
fleet2: PlayerManager.fleets[1].sortieJson(),
fleet3: PlayerManager.fleets[2].sortieJson(),
fleet4: PlayerManager.fleets[3].sortieJson(),
support1: this.getSupportingFleet(false),
support2: this.getSupportingFleet(true),
lbas: this.getWorldLandBases(world, mapnum),
time: stime
};
// Add optional properties
// Record states of unclear normal (or EO) maps
if(world < 10 && (mapnum > 4 || thisMap.kind === "multiple")){
sortie.mapinfo = { "api_cleared": thisMap.clear };
if(thisMap.kills !== false || thisMap.killsRequired){
sortie.mapinfo.api_defeat_count = thisMap.kills || 0;
if(thisMap.killsRequired > 0)
sortie.mapinfo.api_required_defeat_count = thisMap.killsRequired;
}
if(thisMap.gaugeNum > 1){
sortie.mapinfo.api_gauge_num = thisMap.gaugeNum;
}
}
// Record boss HP gauge states of event maps
if(eventData){
const mergedEventInfo = {};
$.extend(mergedEventInfo, eventData, {
// api_state not stored, use this instead
"api_cleared": thisMap.clear,
"api_gauge_type": thisMap.gaugeType,
"api_gauge_num": thisMap.gaugeNum || 1
});
// api_dmg seems always 0 on sortie start
delete mergedEventInfo.api_dmg;
sortie.eventmap = mergedEventInfo;
// Update event map now/max hp at once for panel display,
// because first run after rank selected, they were set to 9999
if((thisMap.curhp || 9999) === 9999 && eventData.api_now_maphp){
thisMap.curhp = parseInt(eventData.api_now_maphp, 10);
thisMap.maxhp = parseInt(eventData.api_max_maphp, 10);
this.setCurrentMapData(thisMap);
}
}
if(ConfigManager.isNotToSaveSortie(this.map_world, this.map_num)){
// Ignore database saving if user demands, set a pseudo sortie id (keep > 0)
this.onSortie = Number.MAX_SAFE_INTEGER;
this.sortieTime = stime;
this.save();
} else {
this.onSortie = 0;
this.sortieTime = stime;
// Save on database and remember current sortie id
KC3Database.Sortie(sortie, function(id){
self.onSortie = id;
self.save();
// Lazy save event map hp to stat.onBoss.hpdat after sortie id confirmed
if(eventData){
if(thisMap.stat && thisMap.stat.onBoss){
const hpData = thisMap.stat.onBoss.hpdat || [];
hpData[id] = [eventData.api_now_maphp, eventData.api_max_maphp];
thisMap.stat.onBoss.hpdat = hpData;
self.setCurrentMapData(thisMap);
console.log("Event map HP on sortie " + id + " recorded as", hpData[id]);
}
}
});
}
// Remember morale values of sortied ships on sortieing started for GunFit tests
if(ConfigManager.TsunDBSubmissionExtra_enabled){
this.initialMorale = fleet.ships.map((rid, idx) => {
const ship = fleet.ship(idx);
return !ship.isDummy() ? ship.morale : 0;
});
} else {
this.initialMorale = [];
}
},
snapshotFleetState :function(){
PlayerManager.hq.lastSortie = PlayerManager.cloneFleets();
// remember index(es) of sent fleet(s) to battle
this.focusedFleet = this.isCombinedSortie() ? [0,1] : [this.fleetSent-1];
// remember index(es) of sent fleet(s) to exped support
this.supportFleet = [];
if(!this.isPvP()){
var support1 = this.getSupportingFleet(false),
support2 = this.getSupportingFleet(true);
if(support1 > 0){
this.supportFleet.push(support1 - 1);
console.assert(this.focusedFleet.indexOf(support1 - 1) < 0, "focused fleet should not include pre-boss support");
}
if(support2 > 0){
this.supportFleet.push(support2 - 1);
console.assert(this.focusedFleet.indexOf(support2 - 1) < 0, "focused fleet should not include boss support");
}
}
PlayerManager.hq.save();
},
getBattleFleetStates :function(addEquip = this.slotitemConsumed, addMorale = false){
const fleetStates = this.focusedFleet.map(id => PlayerManager.fleets[id]).map(fleet => {
const fleetState = {
fuel: fleet.ships.map(ship => KC3ShipManager.get(ship).fuel),
ammo: fleet.ships.map(ship => KC3ShipManager.get(ship).ammo),
slots: fleet.ships.map(ship => KC3ShipManager.get(ship).slots),
};
// Could add more if necessary to track these properties of ships
if(addEquip) fleetState.equip = fleet.ships.map(ship => KC3ShipManager.get(ship).equipment(true).map(g => g.masterId));
if(addMorale) fleetState.morale = fleet.ships.map(ship => KC3ShipManager.get(ship).morale);
return fleetState;
});
return fleetStates;
},
getSupportingFleet :function(bossSupport){
const isSupportExpedition = (expedId, isBoss) => {
const m = KC3Master.mission(expedId);
// check sortied world matches with exped world
return m && m.api_maparea_id === this.map_world &&
// check is the right support exped display number
(isBoss ? ["34", "S2"] : ["33", "S1"]).includes(m.api_disp_no);
};
for(let i = 2; i <= 4; i++)
if(PlayerManager.fleets[i-1].active){
const fleetExpedition = PlayerManager.fleets[i-1].mission[1];
if(isSupportExpedition(fleetExpedition, bossSupport)){
return i;
}
}
return 0;
},
getWorldLandBases :function(world, map){
// Now mapinfo declares max land base amount can be sortied via `api_air_base_decks`
const mapInfo = this.getCurrentMapData(world, map),
maxLbasAllowed = mapInfo.airBase,
// Ignore regular maps that not allow to use land base, such as 6-1, 6-2, 6-3
// For event maps, not sure if devs make 0 sortie but air raid defense needed map?
isIgnoreThisMap = world < 10 && map !== undefined && !!mapInfo.id && !maxLbasAllowed;
const lbas = [];
$.each(PlayerManager.bases, function(i, base){
if(base.rid > -1 && base.map === world && !isIgnoreThisMap
// Not only sortie and defend, all actions saved for future loading
//&& [1,2].indexOf(base.action) > -1
){
lbas.push(base.sortieJson());
}
});
return lbas;
},
getSortieFleet: function() {
return this.focusedFleet.slice(0);
},
isFullySupplied: function() {
return this.focusedFleet.map(function(x){
return PlayerManager.hq.lastSortie[x];
}).every(function(ships){
return ships.every(function(ship){
return ship.isSupplied();
});
});
},
getSortieId: function() {
return this.isOnUnsavedSortie() ? 0 : this.onSortie || 0;
},
getSortieMap: function() {
return [this.map_world, this.map_num];
},
isOnSortie: function() {
return Number.isInteger(this.onSortie) || this.isOnUnsavedSortie();
},
isOnUnsavedSortie: function() {
return this.onSortie === Number.MAX_SAFE_INTEGER;
},
isOnSavedSortie: function() {
return !this.isOnUnsavedSortie() && this.isOnSortie();
},
isSortieAt: function(world, map) {
// Always return false on event maps
// (speculated map_world for events >= 10 as expedition format follows)
return (this.map_world == world && !KC3Meta.isEventWorld(this.map_world)) &&
(this.map_num == (map || this.map_num));
},
isPvP: function(){
return this.isSortieAt(-1) || this.onPvP;
},
isCombinedSortie: function() {
return !!PlayerManager.combinedFleet && this.fleetSent === 1;
},
setBoss :function( cellno, comp ){
// These are set on sortie start API call
this.boss.bosscell = cellno;
this.boss.comp = comp;
this.boss.letters = [KC3Meta.nodeLetter(this.map_world, this.map_num, cellno)];
console.debug("Boss node info on start", this.boss);
},
setSlotitemConsumed :function(cond, requestParams){
if(cond === undefined && !!requestParams){
const dameconUsedType = parseInt(requestParams.api_recovery_type, 10) || 0,
resupplyUsedFlag = requestParams.api_supply_flag == 1,
rationUsedFlag = requestParams.api_ration_flag == 1;
// 1: repair team used, 2: repair goddess used
cond = dameconUsedType > 0 || resupplyUsedFlag || rationUsedFlag;
}
if(typeof cond === "function"){
this.slotitemConsumed = this.slotitemConsumed || !!cond.call(this);
} else if(!!cond){
this.slotitemConsumed = true;
}
},
onBossAvailable :function(nodeObj){
if(this.boss && nodeObj){
this.boss.edge = nodeObj.id;
this.boss.formation = nodeObj.eformation;
this.boss.ships = nodeObj.eships;
this.boss.lvls = nodeObj.elevels;
this.boss.maxhps = nodeObj.maxHPs.enemy;
this.boss.stats = nodeObj.eParam;
this.boss.equip = nodeObj.eSlot;
this.boss.info = true;
console.log("Boss node reached", this.boss);
}
},
currentNode :function(){
return this.nodes[ this.nodes.length - 1 ] || new KC3Node();
},
/**
* @see Next node event selection in-game client references since Phase 2:
* `main.js#TaskNextSpot.prototype._cellEvent`, `MapScene.prototype._preNext` and `NextModel`
*/
advanceNode :function( nodeData, UTCTime ){
//console.debug("Raw next node data", nodeData);
let nodeKind = "Dud";
// Map Start Point (not exists anyway)
// api_event_id = 0
if (nodeData.api_event_id === 0) {
nodeKind = "Dud";
}
// Route Selection Node (TaskBranchRoute)
// api_event_id = 6
// api_event_kind = 2
// unrelated to api_event_id, map pre-next judged it by
// `api_select_route` existed and `.api_select_cells` length > 1,
// in fact, only 2-cells junction has been implemented in-game for now
else if (typeof nodeData.api_select_route !== "undefined") {
nodeKind = "Selector";
}
// Battle avoided node (CellTaskFancy), message might be: Enemy not found / Peace sea / etc
// api_event_id = 1/6
// api_event_kind = 0/1/3~25
// in fact, api_event_id = 1 not exists any more; api_event_kind = 2 taken by route branching
// since Phase 2, message might be seen in `nodeData.api_cell_flavor.api_message`
else if (nodeData.api_event_id === 6 || nodeData.api_event_id === 1) {
nodeKind = "Dud";
}
// Resource Node (CellTaskItem)
// since event fall 2020 (E49-1 U), the anchor icon (api_color_no = 8) is also used instead of green dot (api_color_no = 2)
// api_event_id = 2
else if (typeof nodeData.api_itemget !== "undefined") {
nodeKind = "Resource";
}
// Maelstrom Node (CellTaskHappening)
// api_event_id = 3
else if (typeof nodeData.api_happening !== "undefined") {
nodeKind = "Maelstrom";
}
// Aerial Reconnaissance Node (CellTaskAirReconnaissance)
// api_event_id = 7
// api_event_kind = 0
else if (nodeData.api_event_id === 7 && nodeData.api_event_kind === 0) {
// similar with both Resource and Transport, found at 6-3 G & H
nodeKind = "Dud";
}
// Bounty Node (CellTaskAnchor), typical example: 1-6-N
// api_event_id = 8
else if (typeof nodeData.api_itemget_eo_comment !== "undefined") {
nodeKind = "Bounty";
}
// Transport Node (CellTaskLanding), event only for now
// since event fall 2020 (E49-3 M/U), the anchor icon (api_color_no = 8, used by previous type) is used instead of green dot (api_color_no = 6)
// api_event_id = 9
else if (nodeData.api_event_id === 9) {
nodeKind = "Transport";
}
// Emergency Anchorage Repair Node (CellTaskAnchorageRepair), event only for now
// api_event_id = 10
else if (nodeData.api_event_id === 10) {
nodeKind = "Dud";
}
// Battle Node
// api_event_kind = 1 (start from day battle)
// api_event_kind = 2 (start at night battle), eg: 2-5 D; 5-3 BCDF; 6-5 J
// api_event_kind = 3 (night battle first, then day battle), event in the past only
// api_event_kind = 4 (aerial exchange battle), eg: 1-6 DFL
// api_event_kind = 5 (enemy combined), eg: 6-5 Boss M
// api_event_kind = 6 (defensive aerial battle), eg: 6-4 DFG; 6-5 GH
// api_event_kind = 7 (night to day battle), since event fall 2017, all stages in 1 call
// api_event_kind = 8 (long range radar ambush battle), since event winter 2019
// api_event_id = 4 (normal battle)
// api_event_id = 5 (boss battle)
// api_event_id = 7 (aerial battle / reconnaissance (api_event_kind = 0)) (battle removed?)
else if ([4, 5, 7].includes(nodeData.api_event_id) && nodeData.api_event_kind > 0) {
// Log unknown value of api_event_kind
if (nodeData.api_event_kind > 8) {
console.log(`Unknown node kind, api_event_id = ${nodeData.api_event_id} and api_event_kind = ${nodeData.api_event_kind}, defining as battle`);
}
nodeKind = "Battle";
} else {
// Otherwise, we supposed to be non-battle node,
// however in-game client uses CellTaskItem (item gains) as default event
console.log(`Unknown node kind, api_event_id = ${nodeData.api_event_id} and api_event_kind = ${nodeData.api_event_kind}, defining as dud`);
nodeKind = "Dud";
}
// According testing, boss node not able to be indicated since api_bosscell_no return random values even edge is still hidden,
// now we use manually configures to indicate known boss nodes (and their corresponding map gauges), see `fud_quarterly.json`
const bossLetter = KC3Meta.nodeLetter(this.map_world, this.map_num, nodeData.api_bosscell_no);
if(Array.isArray(this.boss.letters) && this.boss.letters.indexOf(bossLetter) < 0)
this.boss.letters.push(bossLetter);
console.debug("Next edge points to boss node", nodeData.api_bosscell_no, bossLetter);
const definedKind = "defineAs" + nodeKind;
const thisNode = (new KC3Node( this.getSortieId(), nodeData.api_no, UTCTime,
this.map_world, this.map_num, nodeData ))[definedKind](nodeData);
this.nodes.push(thisNode);
this.updateNodeCompassResults();
console.log("Next node", nodeData.api_no, definedKind, thisNode);
this.save();
return thisNode;
},
appendNode :function( nodeObj ){
if(nodeObj instanceof KC3Node){
this.nodes.push(nodeObj);
return this.countNodes();
}
return false;
},
countNodes :function(){
return this.nodes.length;
},
clearNodes :function(){
// remove all array elements but no new array instance created,
// alternative method (will pop up a new array): this.nodes.splice(0);
this.nodes.length = 0;
},
engageLandBaseAirRaid :function( battleData ){
// can not check node type because air raid may occur at any node
this.currentNode().airBaseRaid( battleData );
},
engageBattle :function( battleData, stime ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().engage( battleData, this.fleetSent );
},
engageBattleNight :function( nightData, stime ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().engageNight( nightData, this.fleetSent );
},
engageNight :function( nightData ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().night( nightData );
},
resultScreen :function( resultData ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.hqExpGained += resultData.api_get_exp;
if(this.isPvP()){
this.currentNode().resultsPvP( resultData );
} else {
this.currentNode().results( resultData );
this.addSunk(this.currentNode().lostShips);
this.checkFCF( resultData.api_escape );
}
this.updateMvps( this.currentNode().mvps );
if(!ConfigManager.info_delta){
PlayerManager.hq.checkRankPoints();
PlayerManager.hq.updateLevel( resultData.api_member_lv, resultData.api_member_exp);
}
if(resultData.api_m1){
console.info("Map gimmick flag detected", resultData.api_m1);
}
},
/**
* @param node - current battle node instance by default.
* @param position - 0-based index of ship position, ranged in [0, 6].
* @param isOnEscortFleet - if ship is on escort fleet of combined fleet.
* @return true if ship at specified position is not taken any damage in any wave of opening airstrike,
* will return undefined if bombing phase not occur or no data for specified ship.
* @see Node.js#takenAirBombingDamages - contains all waves of opening airstrike damages dealt to player fleets,
* for now excluding LBAS battle (no damage can be taken), jet assaults (PvP ignored).
* @see main.js#TaskAircraftFlightBase.prototype._antiAircraft
* @see main.js#TaskAirWarAntiAircraft.prototype._start
* in-game `12cm 30tube Rocket Launcher Kai Ni` animation will show the banner if damage <= 0.
*/
isPlayerNotTakenAirBombingDamage :function(node, position, isOnEscortFleet){
const thisNode = node || this.currentNode();
if(Array.isArray(thisNode.takenAirBombingDamages)) {
let isUndefined = false;
const found = thisNode.takenAirBombingDamages.find(wave => {
const fleetIdx = isOnEscortFleet ? 1 : 0;
if(!Array.isArray(wave[fleetIdx]) || wave[fleetIdx][position] === undefined) {
isUndefined = true;
return true;
} else if(wave[fleetIdx][position] <= 0) {
return true;
}
}) !== undefined;
return isUndefined ? undefined : found;
}
return undefined;
},
updateMvps :function(mvps){
if(Array.isArray(mvps) && mvps.length){
if(this.isCombinedSortie()){
const mainMvp = mvps[0] || 1,
escortMvp = mvps[1] || 1,
mainFleet = PlayerManager.fleets[0],
escortFleet = PlayerManager.fleets[1];
if(mainMvp > 0){
this.cleanMvpShips(mainFleet);
mainFleet.ship(mainMvp - 1).mvp = true;
}
if(escortMvp > 0){
this.cleanMvpShips(escortFleet);
escortFleet.ship(escortMvp - 1).mvp = true;
}
} else {
const mvp = mvps[0] || mvps[1] || -1,
fleet = PlayerManager.fleets[this.fleetSent - 1];
if(mvp > 0){
this.cleanMvpShips(fleet);
fleet.ship(mvp - 1).mvp = true;
}
}
}
},
cleanMvpShips :function(fleet){
fleet.ship((rid, idx, ship) => {
ship.mvp = false;
});
},
applyShipsAfterHp :function(){
PlayerManager.fleets.forEach(fleet => {
fleet.ship((rosterId, slotId, shipData) => {
shipData.hp[0] = shipData.afterHp[0];
});
});
},
checkTaihaShips :function(){
// To check Taiha correctly on battle result screen, have to apply predicted afterHp first (invoke `#applyShipsAfterHp`)
let hasTaihaShip = false;
let isForcedToRetreat = false;
let isSafeToAdvance = false;
// No Taiha blocker needed if current battle node is an end point of the map, such as boss
const nextEdgesAmount = this.currentNode().nodeData.api_next;
if(nextEdgesAmount !== undefined && !nextEdgesAmount) isSafeToAdvance = true;
// To check FCF correctly on battle result screen, have to first invoke `#checkFCF` (in another word `#resultScreen`)
//const fcfInfo = this.getCurrentFCF();
// TODO get FCF info and find a method to delay blocker after denying FCF decision screen
KC3SortieManager.getSortieFleet().forEach((fleetId, fleetIdx) => {
const fleet = PlayerManager.fleets[fleetId];
fleet.ship().forEach((ship, slotIdx) => {
// skip ships: not taiha, already escaped/sunk, damecon still equipped
if (isForcedToRetreat || ship.isAbsent() || !ship.isTaiha() || ship.findDameCon().pos >= 0) {
return;
}
// flagship of first fleet in taiha with no damecon
if (fleetIdx === 0 && slotIdx === 0) {
isForcedToRetreat = true;
}
// ignore taiha state of combined escort fleet flagship if setting demands
if (fleetIdx === 1 && slotIdx === 0 && !ConfigManager.next_blocker_2_fs) {
return;
}
hasTaihaShip = true;
});
});
return hasTaihaShip && !isForcedToRetreat && !isSafeToAdvance;
},
checkFCF :function(escapeData){
if (escapeData) {
const getRetreatableShipId = (escapeIdx) => {
if (!escapeIdx || !escapeIdx[0]) { return 0; }
// Although there may be more elements in escape array, but only 1st element used
// since only 1 ship (topmost one) can be retreated per battle
const shipIndex = escapeIdx[0];
// If combined fleets sent, index > 6 belongs to escort fleet
if (this.isCombinedSortie() && shipIndex > 6) {
return PlayerManager.fleets[1].ship(shipIndex - 7).rosterId;
}
return PlayerManager.fleets[this.fleetSent - 1].ship(shipIndex - 1).rosterId;
};
const taihadShip = getRetreatableShipId(escapeData.api_escape_idx);
const escortShip = getRetreatableShipId(escapeData.api_tow_idx);
this.fcfCheck = [taihadShip, escortShip].filter(rosterId => rosterId > 0);
console.log("FCF escape-able ships have set to", this.fcfCheck);
}
},
getCurrentFCF :function(){
// For now only to event map, can sortie with CF and SF
const isSortieAtEvent = KC3Meta.isEventWorld(this.map_world);
const sortiedFleets = this.focusedFleet.map(id => PlayerManager.fleets[id]);
if(!isSortieAtEvent || !sortiedFleets.length || !this.fcfCheck.length)
return { isAvailable: false };
const isCombinedSortie = sortiedFleets.length >= 2;
const flagship = sortiedFleets[0].ship(0);
const taihaShip = KC3ShipManager.get(this.fcfCheck[0]);
const escortShip = isCombinedSortie && KC3ShipManager.get(this.fcfCheck[1]);
const isNextNodeFound = !!this.currentNode().nodeData.api_next;
const canUseFCF = !isCombinedSortie ?
// is Striking Force (fleet #3) sortied (both check)
this.fleetSent === 3 && sortiedFleets[0].ships[6] > 0
// And flagship has SF-FCF (FCF incapable) (client check)
&& flagship.hasEquipment(272)
// And not flagship Taiha (supposed server-side checked already)
//&& taihaShip.fleetPosition()[0] > 0
// And current battle is not the final node (client check)
&& isNextNodeFound
:
// Main fleet flagship has FCF (client check)
flagship.hasEquipment(107)
// And Taiha ship not flagship of main and escort (server check)
//&& taihaShip.fleetPosition()[0] > 0
// And escort-able DD available (flagship DD incapable) (server check)
//&& !!escortShip && !escortShip.isDummy() && !escortShip.isAbsent()
//&& escortShip.fleetPosition()[0] > 0
//&& !escortShip.isTaiha()
// And current battle is not the final node (client check)
&& isNextNodeFound
;
return {
isAvailable: canUseFCF,
isCombined: isCombinedSortie,
shipToRetreat: taihaShip,
shipToEscort: escortShip,
sortiedFleets: sortiedFleets,
shipIdsToBeAbsent: this.fcfCheck.slice(0)
};
},
sendFCFHome :function(){
console.debug("FCF escape-able ships", this.fcfCheck);
this.fcfCheck.forEach(function(fcfShip) {
KC3ShipManager.get(fcfShip).didFlee = true;
});
[].push.apply(this.escapedList, this.fcfCheck.splice(0));
console.log("Have escaped ships", this.escapedList);
},
addSunk :function(shizuList){
console.debug("Adding sink list", shizuList);
this.sinkList.main = this.sinkList.main.concat(shizuList[0]);
this.sinkList.escr = this.sinkList.escr.concat(shizuList[1]);
},
discardSunk :function(){
var fleetDesg = [this.fleetSent-1,1],
self = this;
Object.keys(this.sinkList).forEach(function(fleetType, fleetId){
console.debug("Checking " + fleetType + " fleet #", fleetDesg[fleetId] + 1,
"consisting of", PlayerManager.fleets[fleetDesg[fleetId]].ships);
var sinkList = self.sinkList[fleetType];
if(Array.isArray(sinkList) && sinkList.length > 0){
console.log("Found sink losses", sinkList);
sinkList.map(function(x){
KC3ShipManager.remove(x);
return x;
}).filter(function(x){return false;});
}
});
},
updateNodeCompassResults: function(){
if(this.isOnSavedSortie()) {
KC3Database.updateSortie(this.onSortie, {"nodes": this.nodes.map(node => {
// Basic edge ID and parsed type (dud === "")
const toSave = { id: node.id, type: node.type };
// Raw API result data
const mapNext = node.nodeData;
if(mapNext) {
if(mapNext.api_event_id !== undefined) // Node raw event ID, 0 should be saved
toSave.eventId = mapNext.api_event_id;
if(mapNext.api_event_kind !== undefined) // Node raw event kind, 0 should be saved
toSave.eventKind = mapNext.api_event_kind;
if(mapNext.api_destruction_battle) // Land Base Enemy Raid
toSave.airRaid = mapNext.api_destruction_battle;
if(mapNext.api_offshore_supply) // Resupplier used event
toSave.offshoreSupply = mapNext.api_offshore_supply;
}
// FIXME saving nodeDesc directly will save translated text,
// which causes i18n switching not affect old records.
// To resolve this, parsed 'type, item & count' info should be saved,
// which could be recognized via all these attributes:
// api_itemget, api_happening, api_itemget_eo_result, api_itemget_eo_comment
if(node.nodeDesc)
toSave.desc = node.nodeDesc;
return toSave;
})});
}
},
updateSortiedLandBases: function(){
PlayerManager.saveBases();
if(this.isOnSavedSortie()) {
KC3Database.updateSortie(this.onSortie, {
"lbas": this.getWorldLandBases(this.map_world, this.map_num)
});
}
},
// return empty object if not found
getAllMapData: function(){
return localStorage.getObject("maps") || {};
},
setAllMapData: function(allMapData){
localStorage.setObject("maps", allMapData || {});
},
// return empty object if not found
getCurrentMapData: function(world, map){
return (this.getAllMapData()[
['m', world || this.map_world, map || this.map_num].join('')
]) || {};
},
setCurrentMapData: function(mapData, world, map){
const allMapData = this.getAllMapData();
allMapData[
['m', world || this.map_world, map || this.map_num].join('')
] = (mapData || {});
this.setAllMapData(allMapData);
},
load :function(){
if(localStorage.sortie) {
$.extend(this, localStorage.getObject("sortie"));
}
},
save :function(){
localStorage.setObject("sortie", this);
},
sortieName :function(diff){
const pvpData = JSON.parse(localStorage.statistics || '{"pvp":{"win":0,"lose":0}}').pvp;
return this.isPvP() ? (
"pvp" + (this.onSortie = (Number(pvpData.win) + Number(pvpData.lose) + (diff||1)))
) : ("sortie" + (this.isOnUnsavedSortie() ? 0 : this.onSortie || 0));
},
endSortie :function(portApiData){
var sentFleet = this.fleetSent,
self = this,
cons = {};
this.fleetSent = 1;
cons.name = self.sortieName();
cons.resc = Array.apply(null,{length:8}).map(function(){return 0;});
// Calculate sortie difference with buffer
var sentBattleSupportFleets = Array.isArray(PlayerManager.hq.lastSortie)
? this.focusedFleet.concat(this.supportFleet) : [];
sentBattleSupportFleets.map(id => PlayerManager.hq.lastSortie[id]).forEach(function(fleet, fleetIdx){
if(!fleet){
console.error("Last sortie fleets snapshot lost", sentBattleSupportFleets, PlayerManager.hq.lastSortie);
}
fleet.forEach(function(after, ship_pos){
var fleet_id = sentBattleSupportFleets[fleetIdx] + 1,
rosterId = after.rosterId,
before = KC3ShipManager.get(rosterId),
supply = [
/*
[Fuel Difference] [Ammo Difference] [All Slots Difference]
*/
function(ship1,ship2){return ship1.fuel - ship2.fuel;},
function(ship1,ship2){return ship1.ammo - ship2.ammo;},
function(ship1,ship2){
return Array.apply(null,{length:ship1.slots.length}).map(function(x,i){return (ship1.slots[i] - ship2.slots[i])*1;})
.reduce(function(x,y){return x+y;});
}
].map(function(supplyFunc){return supplyFunc(before, after);}),
/*
RepairLength = 3, third entry always zero.
if PvP => RepairLength = 0, all zero entry.
*/
repLen = before.repair.length * !self.isPvP(),
repair = [1,2,9].map(function(x){
return (x<repLen) ? Math.min(0, after.repair[x] - before.repair[x]) : 0;
}),
pendingCon = before.pendingConsumption[cons.name];
if(!self.isPvP()) {
before.lastSortie.unshift(cons.name);
}
if(pendingCon) {
console.log("Battle pending consumption #", fleet_id, ship_pos, rosterId, pendingCon);
}
// Count steel consumed by jet
if(Array.isArray(pendingCon) && pendingCon.length > 2) {
cons.resc[2] += pendingCon[2][0] || 0;
pendingCon.splice(2,1);
}
if(!(supply.every(function(matr){return !matr;}) && repair.every(function(matr){return !matr;}))){
console.log("Supply & repair pending consumption #", fleet_id, ship_pos, rosterId, supply, repair);
before.pendingConsumption[cons.name] = [supply, repair];
}
});
});
// Count torches consumed by powerful friend fleet,
// assuming materialGain and consumables already updated before this invoked
if(this.materialBefore && !!PlayerManager.friendlySettings.api_request_type) {
const usedTorch = this.materialBefore[4] + this.materialGain[4] - PlayerManager.consumables.torch;
if(usedTorch > 0) {
cons.resc[4] -= usedTorch;
console.log("Powerful friend fleet consumption detected", usedTorch);
}
}
if(cons.name !== "sortie0") {
console.log("Before " + cons.name +" sent fleets", sentBattleSupportFleets, PlayerManager.hq.lastSortie);
console.log("After " + cons.name +" battle consumption and fleets", cons.resc, PlayerManager.cloneFleets());
}
// Ignore every resource gain if disconnected during sortie
if(this.onCat)
this.materialGain.fill(0);
// Fill the resource gain to the current material checkout
// Not need to increase lastMaterial because they've already updated at API 'api_port/port'
// Otherwise lastMaterial will become 'doubled' issue.
/*
this.materialGain.forEach(function(x,i){
if(i<(PlayerManager.hq.lastMaterial || []).length)
PlayerManager.hq.lastMaterial[i] += x;
});
*/
// Control Consumption of the Current Sortie
cons.resc.forEach(function(matr,indx){
self.materialGain[indx] += matr;
});
// Still save as a record with sortie id unknown 'sortie0',
// for saving resupply / repair costs later
if(this.isOnSortie()){
KC3Database.Naverall({
hour: Math.hrdInt('floor', this.sortieTime / 3.6, 3, 1),
type: cons.name,
data: this.materialGain.slice(0)
}, null, true);
// Save node data to sortie table even end at 1st node
this.updateNodeCompassResults();
}
// Remove sortie comparison buffer
PlayerManager.hq.lastSortie = null;
// Record event debuff flags
if(portApiData && portApiData.api_event_object
&& KC3Meta.isEventWorld(this.map_world) && this.map_num > 0){
const eventObject = portApiData.api_event_object;
const thisMap = this.getCurrentMapData(this.map_world, this.map_num);
let updated = false;
if(eventObject.api_m_flag){
if(thisMap.debuffFlag != eventObject.api_m_flag){
console.info("Map gimmick flag updated", thisMap.debuffFlag, eventObject);
}
thisMap.debuffFlag = eventObject.api_m_flag;
updated = true;
}
if(eventObject.api_m_flag2){
thisMap.debuffSound = (thisMap.debuffSound || 0) + 1;
updated = true;
console.info("Map gimmick flag sound", thisMap.debuffSound, eventObject);
}
// first found at event Winter 2018
/*
if(eventObject.api_m_flag3){
thisMap.selectedOperation = eventObject.api_m_flag3;
updated = true;
}
*/
if(updated){
this.setCurrentMapData(thisMap, this.map_world, this.map_num);
}
}
// Reset sortie statistics
this.map_world = 0;
this.map_num = 0;
this.map_difficulty = 0;
this.hqExpGained = 0;
this.boss = { info: false };
this.clearNodes();
if(PlayerManager.combinedFleet && sentFleet === 1){
this.cleanMvpShips(PlayerManager.fleets[0]);
this.cleanMvpShips(PlayerManager.fleets[1]);
PlayerManager.fleets[0].setEscapeShip();
PlayerManager.fleets[1].setEscapeShip();
} else {
this.cleanMvpShips(PlayerManager.fleets[sentFleet - 1]);
PlayerManager.fleets[sentFleet - 1].setEscapeShip();
}
for(var ectr in this.escapedList){
KC3ShipManager.get( this.escapedList[ectr] ).didFlee = false;
}
KC3ShipManager.save();
this.focusedFleet = [];
this.supportFleet = [];
this.fcfCheck = [];
this.escapedList = [];
this.initialMorale = [];
this.materialBefore = false;
this.materialGain.fill(0);
this.sinkList.main.splice(0);
this.sinkList.escr.splice(0);
KC3ShipManager.pendingShipNum = 0;
KC3GearManager.pendingGearNum = 0;
this.onSortie = false;
this.onPvP = false;
this.onCat = false;
this.slotitemConsumed = false;
this.sortieTime = 0;
this.save();
},
/**
* Prepares encounter/real battle data for simulator export while on sortie.
* @param enemyData - an instance include enemy formation and ship master IDs of fleets.
* @param resultFleets - predicated fleets data from BP module output.
* @param realBattle - indicates real battle data not from encounter.
* @return the constructed data object for exporting to simulator.
* @see https://kc3kai.github.io/kancolle-replay/simulator-import-help.html
*/
prepareSimData :function(enemyData, resultFleets = {}, realBattle = false) {
const thisNode = this.currentNode();
const combined = this.isCombinedSortie();
const fleet = PlayerManager.fleets[this.fleetSent - 1];
const fleetF = {
ships: this.prepareSimPlayerFleetShips(fleet, realBattle),
formation: (ConfigManager.aaFormation < 7 && !combined) || (ConfigManager.aaFormation > 10 && combined) ? ConfigManager.aaFormation
: !combined ? 1 : 14
};
if (combined) {
fleetF.shipsC = this.prepareSimPlayerFleetShips(PlayerManager.fleets[1], realBattle);
fleetF.combineType = PlayerManager.combinedFleet;
}
const fleetE = {
ships: this.prepareSimEnemyFleetShips(enemyData.main, resultFleets.enemyMain)
};
if (enemyData.escort && enemyData.escort.length > 0) {
fleetE.shipsC = this.prepareSimEnemyFleetShips(enemyData.escort, resultFleets.enemyEscort);
}
const nodes = [{
fleetE: fleetE
}];
const result = {
numSims: 10000,
fleetF: fleetF,
nodes: nodes,
};
// If real battle, we can ignore stuff like lbas/support fleets since we are only interested in yasen prediction
if (realBattle) {
result.nodes[0].NBOnly = 1;
const battleData = thisNode.battleDay || thisNode.battleNight;
fleetF.formation = battleData.api_formation[0];
fleetE.formation = battleData.api_formation[1];
return result;
}
// For simulating from encounters, we need to prepare LBAS, Support Fleets and Enemy Formation
fleetE.formation = enemyData.formation;
const isBoss = thisNode.isBoss();
const supportFleetNum = this.getSupportingFleet(isBoss);
if (supportFleetNum > 0) {
const supportFleet = PlayerManager.fleets[supportFleetNum - 1];
result.fleetSupportB = {
ships: this.prepareSimPlayerFleetShips(supportFleet),
formation: fleetF.formation,
};
}
// Simulator options
const eventKind = thisNode.eventKind;
if (eventKind === 2) {
result.nodes[0].NBOnly = 1;
}
else if (eventKind === 4) {
result.nodes[0].airOnly = 1;
}
else if (eventKind === 6) {
result.nodes[0].airRaid = 1;
}
else if (isBoss) {
result.nodes[0].doNB = 1;
}
// Export LBAS (if any)
const bases = PlayerManager.bases.filter(base => base.action === 1 && base.map === this.map_world);
// Convert to node letter in case airstrike selected node id different from route node id (multiple path to same node)
const thisNodeName = KC3Meta.nodeLetter(this.map_world, this.map_num, thisNode.id);
let sortiedBaseNo = 0;
if (bases.length > 0) {
const lbas = [], waves = [], simPlayerEqIdMax = 308;
bases.forEach(base => {
const strikeNodes = (base.strikePoints || []).map(edge => (
KC3Meta.nodeLetter(this.map_world, this.map_num, edge)
));
if (!strikeNodes.length || !strikeNodes.includes(thisNodeName)) { return; }
sortiedBaseNo += 1;
const equips = [], slotdata = [];
base.planes.forEach(plane => {
const gear = KC3GearManager.get(plane.api_slotid);
if (gear.isDummy()) { return; }
const eqData = {
masterId: gear.masterId,
improve: gear.stars,
proficiency: gear.ace
};
slotdata.push(plane.api_count);
if (gear.masterId > simPlayerEqIdMax) {
eqData.stats = this.buildEquipMasterStats(gear.masterId);
}
equips.push(eqData);
});
lbas.push({
equips: equips,
slots: slotdata
});
strikeNodes.forEach(nodeName => {
if (nodeName === thisNodeName) waves.push(sortiedBaseNo);
});
});
result.lbas = lbas;
result.nodes[0].lbas = waves;
}
return result;
},
prepareSimEnemyFleetShips :function(masterIdList, predicatedShips){
// Enemies here are abyssal ships, PvP not supported
const simAbyssMasterIdMax = 1845;
const buildEnemyStats = (masterId, idx) => {
const ship = { masterId: masterId };
if (predicatedShips) {
ship.HPInit = predicatedShips[idx].hp;
}
// If new enemy and not in sim yet, fill stats
if (masterId > simAbyssMasterIdMax) {
const master = KC3Master.ship(masterId) || {};
ship.stats = {
type: master.api_stype,
};
if (KC3Master.abyssalShip(masterId)) {
const stats = KC3Master.abyssalShip(masterId);
ship.stats.HP = stats.api_taik;
ship.stats.FP = stats.api_houg;
ship.stats.TP = stats.api_raig;
ship.stats.AA = stats.api_tyku;
ship.stats.AR = stats.api_souk;
const equips = stats.kc3_slots || [];
ship.stats.SLOTS = stats.api_maxeq || equips.map(() => 0);
ship.equips = equips.map(id => ({
masterId: id,
stats: this.buildEquipMasterStats(id)
}));
}
}
return ship;
};
// Assumed ID-0 ships are in the last part, to ensure index matches with predicatedShips array
return masterIdList.filter(id => id > 0).map(buildEnemyStats);
},
prepareSimPlayerFleetShips :function(fleet, realBattle = false) {
const simPlayerEqIdMax = 308;
const buildShipStats = ship => {
if (ship.isDummy() || ship.isAbsent()) return;
const shipMst = ship.master();
const stats = {
HP: ship.hp[1],
FP: ship.fp[0],
TP: ship.tp[0],
AA: ship.aa[0],
AR: ship.ar[0],
LUK: ship.lk[0],
EV: ship.ev[0],
ASW: ship.as[0],
LOS: ship.ls[0],
RNG: ship.range,
SPD: ship.speed,
SLOTS: ship.slots,
type: shipMst.api_stype
};
const equips = ship.equipment(true).filter(g => !g.isDummy()).map(gear => {
const equip = {
masterId: gear.masterId,
improve: gear.stars,
proficiency: gear.ace
};
// If equip data not in sim yet, fill with stats
if (equip.masterId > simPlayerEqIdMax) {
equip.stats = this.buildEquipMasterStats(gear.masterId);
}
return equip;
});
let morale = ship.morale;
// Undo KC3 morale decrement in Node.js, ignore case for -9 and align morale to sim cutoffs
if (realBattle) {
morale += 3;
} else if (morale > 49 && morale < 53) {
morale += 3;
}
return {
masterId: ship.masterId,
LVL: ship.level,
stats: stats,
HPInit: !realBattle ? ship.hp[0] : ship.afterHp[0],
fuelInit: ship.fuel / shipMst.api_fuel_max,
ammoInit: ship.ammo / shipMst.api_bull_max,
morale: morale,
equips: equips,
includesEquipStats: 1
};
};
return fleet.shipsUnescaped().map(buildShipStats);
},
buildEquipMasterStats :function(masterId) {
const gearMaster = KC3Master.slotitem(masterId),
stats = {},
simulatorKeys = {
FP: "api_houg",
TP: "api_raig",
AA: "api_tyku",
AR: "api_souk",
EV: "api_houk",
ASW: "api_tais",
LOS: "api_saku",
ACC: "api_houm",
DIVEBOMB: "api_baku",
RNG: "api_leng"
};
for (const key in simulatorKeys) {
const apiName = simulatorKeys[key];
stats[key] = gearMaster[apiName];
}
stats.type = gearMaster.api_type[3];
return stats;
}
};
})();
| src/library/managers/SortieManager.js | /* SortieManager.js
KC3改 Sortie Manager
Stores and manages states and functions during sortie of fleets (including PvP battle).
*/
(function(){
"use strict";
window.KC3SortieManager = {
onSortie: false,
onPvP: false,
onCat: false,
fleetSent: 1,
map_world: 0,
map_num: 0,
map_difficulty: 0,
hqExpGained: 0,
nodes: [],
boss: {},
focusedFleet: [],
supportFleet: [],
fcfCheck: [],
escapedList: [],
materialBefore: false,
materialGain: Array.apply(null, {length:8}).map(v => 0),
sinkList: {main:[], escr:[]},
slotitemConsumed: false,
sortieTime: 0,
startSortie :function(world, mapnum, fleetNum, stime, eventData){
const self = this;
// If still on sortie, end previous one
if(this.isOnSortie()){
this.endSortie();
}
this.fleetSent = parseInt(fleetNum);
this.map_world = world;
this.map_num = mapnum;
const thisMap = this.getCurrentMapData();
this.map_difficulty = world < 10 ? 0 : thisMap.difficulty || 0;
this.hqExpGained = 0;
this.materialBefore = PlayerManager.hq.lastMaterial.concat(
PlayerManager.consumables.torch,
PlayerManager.consumables.buckets,
PlayerManager.consumables.devmats,
PlayerManager.consumables.screws
);
this.slotitemConsumed = false;
this.boss = {
info: false,
bosscell: -1,
comp: -1,
letters: []
};
this.clearNodes();
this.snapshotFleetState();
const fleet = PlayerManager.fleets[this.fleetSent-1];
fleet.resetAfterHp();
// Prepare sortie database record
const sortie = {
diff: this.map_difficulty,
world: world,
mapnum: mapnum,
fleetnum: parseInt(fleetNum, 10),
combined: PlayerManager.combinedFleet,
fleet1: PlayerManager.fleets[0].sortieJson(),
fleet2: PlayerManager.fleets[1].sortieJson(),
fleet3: PlayerManager.fleets[2].sortieJson(),
fleet4: PlayerManager.fleets[3].sortieJson(),
support1: this.getSupportingFleet(false),
support2: this.getSupportingFleet(true),
lbas: this.getWorldLandBases(world, mapnum),
time: stime
};
// Add optional properties
// Record states of unclear normal (or EO) maps
if(world < 10 && (mapnum > 4 || thisMap.kind === "multiple")){
sortie.mapinfo = { "api_cleared": thisMap.clear };
if(thisMap.kills !== false || thisMap.killsRequired){
sortie.mapinfo.api_defeat_count = thisMap.kills || 0;
if(thisMap.killsRequired > 0)
sortie.mapinfo.api_required_defeat_count = thisMap.killsRequired;
}
if(thisMap.gaugeNum > 1){
sortie.mapinfo.api_gauge_num = thisMap.gaugeNum;
}
}
// Record boss HP gauge states of event maps
if(eventData){
const mergedEventInfo = {};
$.extend(mergedEventInfo, eventData, {
// api_state not stored, use this instead
"api_cleared": thisMap.clear,
"api_gauge_type": thisMap.gaugeType,
"api_gauge_num": thisMap.gaugeNum || 1
});
// api_dmg seems always 0 on sortie start
delete mergedEventInfo.api_dmg;
sortie.eventmap = mergedEventInfo;
// Update event map now/max hp at once for panel display,
// because first run after rank selected, they were set to 9999
if((thisMap.curhp || 9999) === 9999 && eventData.api_now_maphp){
thisMap.curhp = parseInt(eventData.api_now_maphp, 10);
thisMap.maxhp = parseInt(eventData.api_max_maphp, 10);
this.setCurrentMapData(thisMap);
}
}
if(ConfigManager.isNotToSaveSortie(this.map_world, this.map_num)){
// Ignore database saving if user demands, set a pseudo sortie id (keep > 0)
this.onSortie = Number.MAX_SAFE_INTEGER;
this.sortieTime = stime;
this.save();
} else {
this.onSortie = 0;
this.sortieTime = stime;
// Save on database and remember current sortie id
KC3Database.Sortie(sortie, function(id){
self.onSortie = id;
self.save();
// Lazy save event map hp to stat.onBoss.hpdat after sortie id confirmed
if(eventData){
if(thisMap.stat && thisMap.stat.onBoss){
const hpData = thisMap.stat.onBoss.hpdat || [];
hpData[id] = [eventData.api_now_maphp, eventData.api_max_maphp];
thisMap.stat.onBoss.hpdat = hpData;
self.setCurrentMapData(thisMap);
console.log("Event map HP on sortie " + id + " recorded as", hpData[id]);
}
}
});
}
// Remember morale values of sortied ships on sortieing started for GunFit tests
if(ConfigManager.TsunDBSubmissionExtra_enabled){
this.initialMorale = fleet.ships.map((rid, idx) => {
const ship = fleet.ship(idx);
return !ship.isDummy() ? ship.morale : 0;
});
} else {
this.initialMorale = [];
}
},
snapshotFleetState :function(){
PlayerManager.hq.lastSortie = PlayerManager.cloneFleets();
// remember index(es) of sent fleet(s) to battle
this.focusedFleet = this.isCombinedSortie() ? [0,1] : [this.fleetSent-1];
// remember index(es) of sent fleet(s) to exped support
this.supportFleet = [];
if(!this.isPvP()){
var support1 = this.getSupportingFleet(false),
support2 = this.getSupportingFleet(true);
if(support1 > 0){
this.supportFleet.push(support1 - 1);
console.assert(this.focusedFleet.indexOf(support1 - 1) < 0, "focused fleet should not include pre-boss support");
}
if(support2 > 0){
this.supportFleet.push(support2 - 1);
console.assert(this.focusedFleet.indexOf(support2 - 1) < 0, "focused fleet should not include boss support");
}
}
PlayerManager.hq.save();
},
getBattleFleetStates :function(addEquip = this.slotitemConsumed, addMorale = false){
const fleetStates = this.focusedFleet.map(id => PlayerManager.fleets[id]).map(fleet => {
const fleetState = {
fuel: fleet.ships.map(ship => KC3ShipManager.get(ship).fuel),
ammo: fleet.ships.map(ship => KC3ShipManager.get(ship).ammo),
slots: fleet.ships.map(ship => KC3ShipManager.get(ship).slots),
};
// Could add more if necessary to track these properties of ships
if(addEquip) fleetState.equip = fleet.ships.map(ship => KC3ShipManager.get(ship).equipment(true).map(g => g.masterId));
if(addMorale) fleetState.morale = fleet.ships.map(ship => KC3ShipManager.get(ship).morale);
return fleetState;
});
return fleetStates;
},
getSupportingFleet :function(bossSupport){
const isSupportExpedition = (expedId, isBoss) => {
const m = KC3Master.mission(expedId);
// check sortied world matches with exped world
return m && m.api_maparea_id === this.map_world &&
// check is the right support exped display number
(isBoss ? ["34", "S2"] : ["33", "S1"]).includes(m.api_disp_no);
};
for(let i = 2; i <= 4; i++)
if(PlayerManager.fleets[i-1].active){
const fleetExpedition = PlayerManager.fleets[i-1].mission[1];
if(isSupportExpedition(fleetExpedition, bossSupport)){
return i;
}
}
return 0;
},
getWorldLandBases :function(world, map){
// Now mapinfo declares max land base amount can be sortied via `api_air_base_decks`
const mapInfo = this.getCurrentMapData(world, map),
maxLbasAllowed = mapInfo.airBase,
// Ignore regular maps that not allow to use land base, such as 6-1, 6-2, 6-3
// For event maps, not sure if devs make 0 sortie but air raid defense needed map?
isIgnoreThisMap = world < 10 && map !== undefined && !!mapInfo.id && !maxLbasAllowed;
const lbas = [];
$.each(PlayerManager.bases, function(i, base){
if(base.rid > -1 && base.map === world && !isIgnoreThisMap
// Not only sortie and defend, all actions saved for future loading
//&& [1,2].indexOf(base.action) > -1
){
lbas.push(base.sortieJson());
}
});
return lbas;
},
getSortieFleet: function() {
return this.focusedFleet.slice(0);
},
isFullySupplied: function() {
return this.focusedFleet.map(function(x){
return PlayerManager.hq.lastSortie[x];
}).every(function(ships){
return ships.every(function(ship){
return ship.isSupplied();
});
});
},
getSortieId: function() {
return this.isOnUnsavedSortie() ? 0 : this.onSortie || 0;
},
getSortieMap: function() {
return [this.map_world, this.map_num];
},
isOnSortie: function() {
return Number.isInteger(this.onSortie) || this.isOnUnsavedSortie();
},
isOnUnsavedSortie: function() {
return this.onSortie === Number.MAX_SAFE_INTEGER;
},
isOnSavedSortie: function() {
return !this.isOnUnsavedSortie() && this.isOnSortie();
},
isSortieAt: function(world, map) {
// Always return false on event maps
// (speculated map_world for events >= 10 as expedition format follows)
return (this.map_world == world && !KC3Meta.isEventWorld(this.map_world)) &&
(this.map_num == (map || this.map_num));
},
isPvP: function(){
return this.isSortieAt(-1) || this.onPvP;
},
isCombinedSortie: function() {
return !!PlayerManager.combinedFleet && this.fleetSent === 1;
},
setBoss :function( cellno, comp ){
// These are set on sortie start API call
this.boss.bosscell = cellno;
this.boss.comp = comp;
this.boss.letters = [KC3Meta.nodeLetter(this.map_world, this.map_num, cellno)];
console.debug("Boss node info on start", this.boss);
},
setSlotitemConsumed :function(cond, requestParams){
if(cond === undefined && !!requestParams){
const dameconUsedType = parseInt(requestParams.api_recovery_type, 10) || 0,
resupplyUsedFlag = requestParams.api_supply_flag == 1,
rationUsedFlag = requestParams.api_ration_flag == 1;
// 1: repair team used, 2: repair goddess used
cond = dameconUsedType > 0 || resupplyUsedFlag || rationUsedFlag;
}
if(typeof cond === "function"){
this.slotitemConsumed = this.slotitemConsumed || !!cond.call(this);
} else if(!!cond){
this.slotitemConsumed = true;
}
},
onBossAvailable :function(nodeObj){
if(this.boss && nodeObj){
this.boss.edge = nodeObj.id;
this.boss.formation = nodeObj.eformation;
this.boss.ships = nodeObj.eships;
this.boss.lvls = nodeObj.elevels;
this.boss.maxhps = nodeObj.maxHPs.enemy;
this.boss.stats = nodeObj.eParam;
this.boss.equip = nodeObj.eSlot;
this.boss.info = true;
console.log("Boss node reached", this.boss);
}
},
currentNode :function(){
return this.nodes[ this.nodes.length - 1 ] || new KC3Node();
},
/**
* @see Next node event selection in-game client references since Phase 2:
* `main.js#TaskNextSpot.prototype._cellEvent`, `MapScene.prototype._preNext` and `NextModel`
*/
advanceNode :function( nodeData, UTCTime ){
//console.debug("Raw next node data", nodeData);
let nodeKind = "Dud";
// Map Start Point (not exists anyway)
// api_event_id = 0
if (nodeData.api_event_id === 0) {
nodeKind = "Dud";
}
// Route Selection Node (TaskBranchRoute)
// api_event_id = 6
// api_event_kind = 2
// unrelated to api_event_id, map pre-next judged it by
// `api_select_route` existed and `.api_select_cells` length > 1,
// in fact, only 2-cells junction has been implemented in-game for now
else if (typeof nodeData.api_select_route !== "undefined") {
nodeKind = "Selector";
}
// Battle avoided node (CellTaskFancy), message might be: Enemy not found / Peace sea / etc
// api_event_id = 1/6
// api_event_kind = 0/1/3~25
// in fact, api_event_id = 1 not exists any more; api_event_kind = 2 taken by route branching
// since Phase 2, message might be seen in `nodeData.api_cell_flavor.api_message`
else if (nodeData.api_event_id === 6 || nodeData.api_event_id === 1) {
nodeKind = "Dud";
}
// Resource Node (CellTaskItem)
// since event fall 2020 (E49-1 U), the anchor icon (api_color_no = 8) is also used instead of green dot (api_color_no = 2)
// api_event_id = 2
else if (typeof nodeData.api_itemget !== "undefined") {
nodeKind = "Resource";
}
// Maelstrom Node (CellTaskHappening)
// api_event_id = 3
else if (typeof nodeData.api_happening !== "undefined") {
nodeKind = "Maelstrom";
}
// Aerial Reconnaissance Node (CellTaskAirReconnaissance)
// api_event_id = 7
// api_event_kind = 0
else if (nodeData.api_event_id === 7 && nodeData.api_event_kind === 0) {
// similar with both Resource and Transport, found at 6-3 G & H
nodeKind = "Dud";
}
// Bounty Node (CellTaskAnchor), typical example: 1-6-N
// api_event_id = 8
else if (typeof nodeData.api_itemget_eo_comment !== "undefined") {
nodeKind = "Bounty";
}
// Transport Node (CellTaskLanding), event only for now
// since event fall 2020 (E49-3 M/U), the anchor icon (api_color_no = 8, used by previous type) is used instead of green dot (api_color_no = 6)
// api_event_id = 9
else if (nodeData.api_event_id === 9) {
nodeKind = "Transport";
}
// Emergency Anchorage Repair Node (CellTaskAnchorageRepair), event only for now
// api_event_id = 10
else if (nodeData.api_event_id === 10) {
nodeKind = "Dud";
}
// Battle Node
// api_event_kind = 1 (start from day battle)
// api_event_kind = 2 (start at night battle), eg: 2-5 D; 5-3 BCDF; 6-5 J
// api_event_kind = 3 (night battle first, then day battle), event in the past only
// api_event_kind = 4 (aerial exchange battle), eg: 1-6 DFL
// api_event_kind = 5 (enemy combined), eg: 6-5 Boss M
// api_event_kind = 6 (defensive aerial battle), eg: 6-4 DFG; 6-5 GH
// api_event_kind = 7 (night to day battle), since event fall 2017, all stages in 1 call
// api_event_kind = 8 (long range radar ambush battle), since event winter 2019
// api_event_id = 4 (normal battle)
// api_event_id = 5 (boss battle)
// api_event_id = 7 (aerial battle / reconnaissance (api_event_kind = 0)) (battle removed?)
else if ([4, 5, 7].includes(nodeData.api_event_id) && nodeData.api_event_kind > 0) {
// Log unknown value of api_event_kind
if (nodeData.api_event_kind > 8) {
console.log(`Unknown node kind, api_event_id = ${nodeData.api_event_id} and api_event_kind = ${nodeData.api_event_kind}, defining as battle`);
}
nodeKind = "Battle";
} else {
// Otherwise, we supposed to be non-battle node,
// however in-game client uses CellTaskItem (item gains) as default event
console.log(`Unknown node kind, api_event_id = ${nodeData.api_event_id} and api_event_kind = ${nodeData.api_event_kind}, defining as dud`);
nodeKind = "Dud";
}
// According testing, boss node not able to be indicated since api_bosscell_no return random values even edge is still hidden,
// now we use manually configures to indicate known boss nodes (and their corresponding map gauges), see `fud_quarterly.json`
const bossLetter = KC3Meta.nodeLetter(this.map_world, this.map_num, nodeData.api_bosscell_no);
if(Array.isArray(this.boss.letters) && this.boss.letters.indexOf(bossLetter) < 0)
this.boss.letters.push(bossLetter);
console.debug("Next edge points to boss node", nodeData.api_bosscell_no, bossLetter);
const definedKind = "defineAs" + nodeKind;
const thisNode = (new KC3Node( this.getSortieId(), nodeData.api_no, UTCTime,
this.map_world, this.map_num, nodeData ))[definedKind](nodeData);
this.nodes.push(thisNode);
this.updateNodeCompassResults();
console.log("Next node", nodeData.api_no, definedKind, thisNode);
this.save();
return thisNode;
},
appendNode :function( nodeObj ){
if(nodeObj instanceof KC3Node){
this.nodes.push(nodeObj);
return this.countNodes();
}
return false;
},
countNodes :function(){
return this.nodes.length;
},
clearNodes :function(){
// remove all array elements but no new array instance created,
// alternative method (will pop up a new array): this.nodes.splice(0);
this.nodes.length = 0;
},
engageLandBaseAirRaid :function( battleData ){
// can not check node type because air raid may occur at any node
this.currentNode().airBaseRaid( battleData );
},
engageBattle :function( battleData, stime ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().engage( battleData, this.fleetSent );
},
engageBattleNight :function( nightData, stime ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().engageNight( nightData, this.fleetSent );
},
engageNight :function( nightData ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.currentNode().night( nightData );
},
resultScreen :function( resultData ){
if(this.currentNode().type != "battle"){ console.warn("Wrong node handling"); return false; }
this.hqExpGained += resultData.api_get_exp;
if(this.isPvP()){
this.currentNode().resultsPvP( resultData );
} else {
this.currentNode().results( resultData );
this.addSunk(this.currentNode().lostShips);
this.checkFCF( resultData.api_escape );
}
this.updateMvps( this.currentNode().mvps );
if(!ConfigManager.info_delta){
PlayerManager.hq.checkRankPoints();
PlayerManager.hq.updateLevel( resultData.api_member_lv, resultData.api_member_exp);
}
if(resultData.api_m1){
console.info("Map gimmick flag detected", resultData.api_m1);
}
},
/**
* @param node - current battle node instance by default.
* @param position - 0-based index of ship position, ranged in [0, 6].
* @param isOnEscortFleet - if ship is on escort fleet of combined fleet.
* @return true if ship at specified position is not taken any damage in any wave of opening airstrike,
* will return undefined if bombing phase not occur or no data for specified ship.
* @see Node.js#takenAirBombingDamages - contains all waves of opening airstrike damages dealt to player fleets,
* for now excluding LBAS battle (no damage can be taken), jet assaults (PvP ignored).
* @see main.js#TaskAircraftFlightBase.prototype._antiAircraft
* @see main.js#TaskAirWarAntiAircraft.prototype._start
* in-game `12cm 30tube Rocket Launcher Kai Ni` animation will show the banner if damage <= 0.
*/
isPlayerNotTakenAirBombingDamage :function(node, position, isOnEscortFleet){
const thisNode = node || this.currentNode();
if(Array.isArray(thisNode.takenAirBombingDamages)) {
let isUndefined = false;
const found = thisNode.takenAirBombingDamages.find(wave => {
const fleetIdx = isOnEscortFleet ? 1 : 0;
if(!Array.isArray(wave[fleetIdx]) || wave[fleetIdx][position] === undefined) {
isUndefined = true;
return true;
} else if(wave[fleetIdx][position] <= 0) {
return true;
}
}) !== undefined;
return isUndefined ? undefined : found;
}
return undefined;
},
updateMvps :function(mvps){
if(Array.isArray(mvps) && mvps.length){
if(this.isCombinedSortie()){
const mainMvp = mvps[0] || 1,
escortMvp = mvps[1] || 1,
mainFleet = PlayerManager.fleets[0],
escortFleet = PlayerManager.fleets[1];
if(mainMvp > 0){
this.cleanMvpShips(mainFleet);
mainFleet.ship(mainMvp - 1).mvp = true;
}
if(escortMvp > 0){
this.cleanMvpShips(escortFleet);
escortFleet.ship(escortMvp - 1).mvp = true;
}
} else {
const mvp = mvps[0] || mvps[1] || -1,
fleet = PlayerManager.fleets[this.fleetSent - 1];
if(mvp > 0){
this.cleanMvpShips(fleet);
fleet.ship(mvp - 1).mvp = true;
}
}
}
},
cleanMvpShips :function(fleet){
fleet.ship((rid, idx, ship) => {
ship.mvp = false;
});
},
applyShipsAfterHp :function(){
PlayerManager.fleets.forEach(fleet => {
fleet.ship((rosterId, slotId, shipData) => {
shipData.hp[0] = shipData.afterHp[0];
});
});
},
checkTaihaShips :function(){
// To check Taiha correctly on battle result screen, have to apply predicted afterHp first (invoke `#applyShipsAfterHp`)
let hasTaihaShip = false;
let isForcedToRetreat = false;
KC3SortieManager.getSortieFleet().forEach((fleetId, fleetIdx) => {
const fleet = PlayerManager.fleets[fleetId];
fleet.ship().forEach((ship, slotIdx) => {
// skip ships: not taiha, already escaped/sunk, damecon still equipped
if (isForcedToRetreat || ship.isAbsent() || !ship.isTaiha() || ship.findDameCon().pos >= 0) {
return;
}
// flagship of first fleet in taiha with no damecon
if (fleetIdx === 0 && slotIdx === 0) {
isForcedToRetreat = true;
}
// ignore taiha state of combined escort fleet flagship if setting demands
if (fleetIdx === 1 && slotIdx === 0 && !ConfigManager.next_blocker_2_fs) {
return;
}
hasTaihaShip = true;
});
});
return hasTaihaShip && !isForcedToRetreat;
},
checkFCF :function(escapeData){
if (escapeData) {
const getRetreatableShipId = (escapeIdx) => {
if (!escapeIdx || !escapeIdx[0]) { return 0; }
// Although there may be more elements in escape array, but only 1st element used
// since only 1 ship (topmost one) can be retreated per battle
const shipIndex = escapeIdx[0];
// If combined fleets sent, index > 6 belongs to escort fleet
if (this.isCombinedSortie() && shipIndex > 6) {
return PlayerManager.fleets[1].ship(shipIndex - 7).rosterId;
}
return PlayerManager.fleets[this.fleetSent - 1].ship(shipIndex - 1).rosterId;
};
const taihadShip = getRetreatableShipId(escapeData.api_escape_idx);
const escortShip = getRetreatableShipId(escapeData.api_tow_idx);
this.fcfCheck = [taihadShip, escortShip].filter(rosterId => rosterId > 0);
console.log("FCF escape-able ships have set to", this.fcfCheck);
}
},
getCurrentFCF :function(){
// For now only to event map, can sortie with CF and SF
const isSortieAtEvent = KC3Meta.isEventWorld(this.map_world);
const sortiedFleets = this.focusedFleet.map(id => PlayerManager.fleets[id]);
if(!isSortieAtEvent || !sortiedFleets.length || !this.fcfCheck.length)
return { isAvailable: false };
const isCombinedSortie = sortiedFleets.length >= 2;
const flagship = sortiedFleets[0].ship(0);
const taihaShip = KC3ShipManager.get(this.fcfCheck[0]);
const escortShip = isCombinedSortie && KC3ShipManager.get(this.fcfCheck[1]);
const isNextNodeFound = !!this.currentNode().nodeData.api_next;
const canUseFCF = !isCombinedSortie ?
// is Striking Force (fleet #3) sortied (both check)
this.fleetSent === 3 && sortiedFleets[0].ships[6] > 0
// And flagship has SF-FCF (FCF incapable) (client check)
&& flagship.hasEquipment(272)
// And not flagship Taiha (supposed server-side checked already)
//&& taihaShip.fleetPosition()[0] > 0
// And current battle is not the final node (client check)
&& isNextNodeFound
:
// Main fleet flagship has FCF (client check)
flagship.hasEquipment(107)
// And Taiha ship not flagship of main and escort (server check)
//&& taihaShip.fleetPosition()[0] > 0
// And escort-able DD available (flagship DD incapable) (server check)
//&& !!escortShip && !escortShip.isDummy() && !escortShip.isAbsent()
//&& escortShip.fleetPosition()[0] > 0
//&& !escortShip.isTaiha()
// And current battle is not the final node (client check)
&& isNextNodeFound
;
return {
isAvailable: canUseFCF,
isCombined: isCombinedSortie,
shipToRetreat: taihaShip,
shipToEscort: escortShip,
sortiedFleets: sortiedFleets,
shipIdsToBeAbsent: this.fcfCheck.slice(0)
};
},
sendFCFHome :function(){
console.debug("FCF escape-able ships", this.fcfCheck);
this.fcfCheck.forEach(function(fcfShip) {
KC3ShipManager.get(fcfShip).didFlee = true;
});
[].push.apply(this.escapedList, this.fcfCheck.splice(0));
console.log("Have escaped ships", this.escapedList);
},
addSunk :function(shizuList){
console.debug("Adding sink list", shizuList);
this.sinkList.main = this.sinkList.main.concat(shizuList[0]);
this.sinkList.escr = this.sinkList.escr.concat(shizuList[1]);
},
discardSunk :function(){
var fleetDesg = [this.fleetSent-1,1],
self = this;
Object.keys(this.sinkList).forEach(function(fleetType, fleetId){
console.debug("Checking " + fleetType + " fleet #", fleetDesg[fleetId] + 1,
"consisting of", PlayerManager.fleets[fleetDesg[fleetId]].ships);
var sinkList = self.sinkList[fleetType];
if(Array.isArray(sinkList) && sinkList.length > 0){
console.log("Found sink losses", sinkList);
sinkList.map(function(x){
KC3ShipManager.remove(x);
return x;
}).filter(function(x){return false;});
}
});
},
updateNodeCompassResults: function(){
if(this.isOnSavedSortie()) {
KC3Database.updateSortie(this.onSortie, {"nodes": this.nodes.map(node => {
// Basic edge ID and parsed type (dud === "")
const toSave = { id: node.id, type: node.type };
// Raw API result data
const mapNext = node.nodeData;
if(mapNext) {
if(mapNext.api_event_id !== undefined) // Node raw event ID, 0 should be saved
toSave.eventId = mapNext.api_event_id;
if(mapNext.api_event_kind !== undefined) // Node raw event kind, 0 should be saved
toSave.eventKind = mapNext.api_event_kind;
if(mapNext.api_destruction_battle) // Land Base Enemy Raid
toSave.airRaid = mapNext.api_destruction_battle;
if(mapNext.api_offshore_supply) // Resupplier used event
toSave.offshoreSupply = mapNext.api_offshore_supply;
}
// FIXME saving nodeDesc directly will save translated text,
// which causes i18n switching not affect old records.
// To resolve this, parsed 'type, item & count' info should be saved,
// which could be recognized via all these attributes:
// api_itemget, api_happening, api_itemget_eo_result, api_itemget_eo_comment
if(node.nodeDesc)
toSave.desc = node.nodeDesc;
return toSave;
})});
}
},
updateSortiedLandBases: function(){
PlayerManager.saveBases();
if(this.isOnSavedSortie()) {
KC3Database.updateSortie(this.onSortie, {
"lbas": this.getWorldLandBases(this.map_world, this.map_num)
});
}
},
// return empty object if not found
getAllMapData: function(){
return localStorage.getObject("maps") || {};
},
setAllMapData: function(allMapData){
localStorage.setObject("maps", allMapData || {});
},
// return empty object if not found
getCurrentMapData: function(world, map){
return (this.getAllMapData()[
['m', world || this.map_world, map || this.map_num].join('')
]) || {};
},
setCurrentMapData: function(mapData, world, map){
const allMapData = this.getAllMapData();
allMapData[
['m', world || this.map_world, map || this.map_num].join('')
] = (mapData || {});
this.setAllMapData(allMapData);
},
load :function(){
if(localStorage.sortie) {
$.extend(this, localStorage.getObject("sortie"));
}
},
save :function(){
localStorage.setObject("sortie", this);
},
sortieName :function(diff){
const pvpData = JSON.parse(localStorage.statistics || '{"pvp":{"win":0,"lose":0}}').pvp;
return this.isPvP() ? (
"pvp" + (this.onSortie = (Number(pvpData.win) + Number(pvpData.lose) + (diff||1)))
) : ("sortie" + (this.isOnUnsavedSortie() ? 0 : this.onSortie || 0));
},
endSortie :function(portApiData){
var sentFleet = this.fleetSent,
self = this,
cons = {};
this.fleetSent = 1;
cons.name = self.sortieName();
cons.resc = Array.apply(null,{length:8}).map(function(){return 0;});
// Calculate sortie difference with buffer
var sentBattleSupportFleets = Array.isArray(PlayerManager.hq.lastSortie)
? this.focusedFleet.concat(this.supportFleet) : [];
sentBattleSupportFleets.map(id => PlayerManager.hq.lastSortie[id]).forEach(function(fleet, fleetIdx){
if(!fleet){
console.error("Last sortie fleets snapshot lost", sentBattleSupportFleets, PlayerManager.hq.lastSortie);
}
fleet.forEach(function(after, ship_pos){
var fleet_id = sentBattleSupportFleets[fleetIdx] + 1,
rosterId = after.rosterId,
before = KC3ShipManager.get(rosterId),
supply = [
/*
[Fuel Difference] [Ammo Difference] [All Slots Difference]
*/
function(ship1,ship2){return ship1.fuel - ship2.fuel;},
function(ship1,ship2){return ship1.ammo - ship2.ammo;},
function(ship1,ship2){
return Array.apply(null,{length:ship1.slots.length}).map(function(x,i){return (ship1.slots[i] - ship2.slots[i])*1;})
.reduce(function(x,y){return x+y;});
}
].map(function(supplyFunc){return supplyFunc(before, after);}),
/*
RepairLength = 3, third entry always zero.
if PvP => RepairLength = 0, all zero entry.
*/
repLen = before.repair.length * !self.isPvP(),
repair = [1,2,9].map(function(x){
return (x<repLen) ? Math.min(0, after.repair[x] - before.repair[x]) : 0;
}),
pendingCon = before.pendingConsumption[cons.name];
if(!self.isPvP()) {
before.lastSortie.unshift(cons.name);
}
if(pendingCon) {
console.log("Battle pending consumption #", fleet_id, ship_pos, rosterId, pendingCon);
}
// Count steel consumed by jet
if(Array.isArray(pendingCon) && pendingCon.length > 2) {
cons.resc[2] += pendingCon[2][0] || 0;
pendingCon.splice(2,1);
}
if(!(supply.every(function(matr){return !matr;}) && repair.every(function(matr){return !matr;}))){
console.log("Supply & repair pending consumption #", fleet_id, ship_pos, rosterId, supply, repair);
before.pendingConsumption[cons.name] = [supply, repair];
}
});
});
// Count torches consumed by powerful friend fleet,
// assuming materialGain and consumables already updated before this invoked
if(this.materialBefore && !!PlayerManager.friendlySettings.api_request_type) {
const usedTorch = this.materialBefore[4] + this.materialGain[4] - PlayerManager.consumables.torch;
if(usedTorch > 0) {
cons.resc[4] -= usedTorch;
console.log("Powerful friend fleet consumption detected", usedTorch);
}
}
if(cons.name !== "sortie0") {
console.log("Before " + cons.name +" sent fleets", sentBattleSupportFleets, PlayerManager.hq.lastSortie);
console.log("After " + cons.name +" battle consumption and fleets", cons.resc, PlayerManager.cloneFleets());
}
// Ignore every resource gain if disconnected during sortie
if(this.onCat)
this.materialGain.fill(0);
// Fill the resource gain to the current material checkout
// Not need to increase lastMaterial because they've already updated at API 'api_port/port'
// Otherwise lastMaterial will become 'doubled' issue.
/*
this.materialGain.forEach(function(x,i){
if(i<(PlayerManager.hq.lastMaterial || []).length)
PlayerManager.hq.lastMaterial[i] += x;
});
*/
// Control Consumption of the Current Sortie
cons.resc.forEach(function(matr,indx){
self.materialGain[indx] += matr;
});
// Still save as a record with sortie id unknown 'sortie0',
// for saving resupply / repair costs later
if(this.isOnSortie()){
KC3Database.Naverall({
hour: Math.hrdInt('floor', this.sortieTime / 3.6, 3, 1),
type: cons.name,
data: this.materialGain.slice(0)
}, null, true);
// Save node data to sortie table even end at 1st node
this.updateNodeCompassResults();
}
// Remove sortie comparison buffer
PlayerManager.hq.lastSortie = null;
// Record event debuff flags
if(portApiData && portApiData.api_event_object
&& KC3Meta.isEventWorld(this.map_world) && this.map_num > 0){
const eventObject = portApiData.api_event_object;
const thisMap = this.getCurrentMapData(this.map_world, this.map_num);
let updated = false;
if(eventObject.api_m_flag){
if(thisMap.debuffFlag != eventObject.api_m_flag){
console.info("Map gimmick flag updated", thisMap.debuffFlag, eventObject);
}
thisMap.debuffFlag = eventObject.api_m_flag;
updated = true;
}
if(eventObject.api_m_flag2){
thisMap.debuffSound = (thisMap.debuffSound || 0) + 1;
updated = true;
console.info("Map gimmick flag sound", thisMap.debuffSound, eventObject);
}
// first found at event Winter 2018
/*
if(eventObject.api_m_flag3){
thisMap.selectedOperation = eventObject.api_m_flag3;
updated = true;
}
*/
if(updated){
this.setCurrentMapData(thisMap, this.map_world, this.map_num);
}
}
// Reset sortie statistics
this.map_world = 0;
this.map_num = 0;
this.map_difficulty = 0;
this.hqExpGained = 0;
this.boss = { info: false };
this.clearNodes();
if(PlayerManager.combinedFleet && sentFleet === 1){
this.cleanMvpShips(PlayerManager.fleets[0]);
this.cleanMvpShips(PlayerManager.fleets[1]);
PlayerManager.fleets[0].setEscapeShip();
PlayerManager.fleets[1].setEscapeShip();
} else {
this.cleanMvpShips(PlayerManager.fleets[sentFleet - 1]);
PlayerManager.fleets[sentFleet - 1].setEscapeShip();
}
for(var ectr in this.escapedList){
KC3ShipManager.get( this.escapedList[ectr] ).didFlee = false;
}
KC3ShipManager.save();
this.focusedFleet = [];
this.supportFleet = [];
this.fcfCheck = [];
this.escapedList = [];
this.initialMorale = [];
this.materialBefore = false;
this.materialGain.fill(0);
this.sinkList.main.splice(0);
this.sinkList.escr.splice(0);
KC3ShipManager.pendingShipNum = 0;
KC3GearManager.pendingGearNum = 0;
this.onSortie = false;
this.onPvP = false;
this.onCat = false;
this.slotitemConsumed = false;
this.sortieTime = 0;
this.save();
},
/**
* Prepares encounter/real battle data for simulator export while on sortie.
* @param enemyData - an instance include enemy formation and ship master IDs of fleets.
* @param resultFleets - predicated fleets data from BP module output.
* @param realBattle - indicates real battle data not from encounter.
* @return the constructed data object for exporting to simulator.
* @see https://kc3kai.github.io/kancolle-replay/simulator-import-help.html
*/
prepareSimData :function(enemyData, resultFleets = {}, realBattle = false) {
const thisNode = this.currentNode();
const combined = this.isCombinedSortie();
const fleet = PlayerManager.fleets[this.fleetSent - 1];
const fleetF = {
ships: this.prepareSimPlayerFleetShips(fleet, realBattle),
formation: (ConfigManager.aaFormation < 7 && !combined) || (ConfigManager.aaFormation > 10 && combined) ? ConfigManager.aaFormation
: !combined ? 1 : 14
};
if (combined) {
fleetF.shipsC = this.prepareSimPlayerFleetShips(PlayerManager.fleets[1], realBattle);
fleetF.combineType = PlayerManager.combinedFleet;
}
const fleetE = {
ships: this.prepareSimEnemyFleetShips(enemyData.main, resultFleets.enemyMain)
};
if (enemyData.escort && enemyData.escort.length > 0) {
fleetE.shipsC = this.prepareSimEnemyFleetShips(enemyData.escort, resultFleets.enemyEscort);
}
const nodes = [{
fleetE: fleetE
}];
const result = {
numSims: 10000,
fleetF: fleetF,
nodes: nodes,
};
// If real battle, we can ignore stuff like lbas/support fleets since we are only interested in yasen prediction
if (realBattle) {
result.nodes[0].NBOnly = 1;
const battleData = thisNode.battleDay || thisNode.battleNight;
fleetF.formation = battleData.api_formation[0];
fleetE.formation = battleData.api_formation[1];
return result;
}
// For simulating from encounters, we need to prepare LBAS, Support Fleets and Enemy Formation
fleetE.formation = enemyData.formation;
const isBoss = thisNode.isBoss();
const supportFleetNum = this.getSupportingFleet(isBoss);
if (supportFleetNum > 0) {
const supportFleet = PlayerManager.fleets[supportFleetNum - 1];
result.fleetSupportB = {
ships: this.prepareSimPlayerFleetShips(supportFleet),
formation: fleetF.formation,
};
}
// Simulator options
const eventKind = thisNode.eventKind;
if (eventKind === 2) {
result.nodes[0].NBOnly = 1;
}
else if (eventKind === 4) {
result.nodes[0].airOnly = 1;
}
else if (eventKind === 6) {
result.nodes[0].airRaid = 1;
}
else if (isBoss) {
result.nodes[0].doNB = 1;
}
// Export LBAS (if any)
const bases = PlayerManager.bases.filter(base => base.action === 1 && base.map === this.map_world);
// Convert to node letter in case airstrike selected node id different from route node id (multiple path to same node)
const thisNodeName = KC3Meta.nodeLetter(this.map_world, this.map_num, thisNode.id);
let sortiedBaseNo = 0;
if (bases.length > 0) {
const lbas = [], waves = [], simPlayerEqIdMax = 308;
bases.forEach(base => {
const strikeNodes = (base.strikePoints || []).map(edge => (
KC3Meta.nodeLetter(this.map_world, this.map_num, edge)
));
if (!strikeNodes.length || !strikeNodes.includes(thisNodeName)) { return; }
sortiedBaseNo += 1;
const equips = [], slotdata = [];
base.planes.forEach(plane => {
const gear = KC3GearManager.get(plane.api_slotid);
if (gear.isDummy()) { return; }
const eqData = {
masterId: gear.masterId,
improve: gear.stars,
proficiency: gear.ace
};
slotdata.push(plane.api_count);
if (gear.masterId > simPlayerEqIdMax) {
eqData.stats = this.buildEquipMasterStats(gear.masterId);
}
equips.push(eqData);
});
lbas.push({
equips: equips,
slots: slotdata
});
strikeNodes.forEach(nodeName => {
if (nodeName === thisNodeName) waves.push(sortiedBaseNo);
});
});
result.lbas = lbas;
result.nodes[0].lbas = waves;
}
return result;
},
prepareSimEnemyFleetShips :function(masterIdList, predicatedShips){
// Enemies here are abyssal ships, PvP not supported
const simAbyssMasterIdMax = 1845;
const buildEnemyStats = (masterId, idx) => {
const ship = { masterId: masterId };
if (predicatedShips) {
ship.HPInit = predicatedShips[idx].hp;
}
// If new enemy and not in sim yet, fill stats
if (masterId > simAbyssMasterIdMax) {
const master = KC3Master.ship(masterId) || {};
ship.stats = {
type: master.api_stype,
};
if (KC3Master.abyssalShip(masterId)) {
const stats = KC3Master.abyssalShip(masterId);
ship.stats.HP = stats.api_taik;
ship.stats.FP = stats.api_houg;
ship.stats.TP = stats.api_raig;
ship.stats.AA = stats.api_tyku;
ship.stats.AR = stats.api_souk;
const equips = stats.kc3_slots || [];
ship.stats.SLOTS = stats.api_maxeq || equips.map(() => 0);
ship.equips = equips.map(id => ({
masterId: id,
stats: this.buildEquipMasterStats(id)
}));
}
}
return ship;
};
// Assumed ID-0 ships are in the last part, to ensure index matches with predicatedShips array
return masterIdList.filter(id => id > 0).map(buildEnemyStats);
},
prepareSimPlayerFleetShips :function(fleet, realBattle = false) {
const simPlayerEqIdMax = 308;
const buildShipStats = ship => {
if (ship.isDummy() || ship.isAbsent()) return;
const shipMst = ship.master();
const stats = {
HP: ship.hp[1],
FP: ship.fp[0],
TP: ship.tp[0],
AA: ship.aa[0],
AR: ship.ar[0],
LUK: ship.lk[0],
EV: ship.ev[0],
ASW: ship.as[0],
LOS: ship.ls[0],
RNG: ship.range,
SPD: ship.speed,
SLOTS: ship.slots,
type: shipMst.api_stype
};
const equips = ship.equipment(true).filter(g => !g.isDummy()).map(gear => {
const equip = {
masterId: gear.masterId,
improve: gear.stars,
proficiency: gear.ace
};
// If equip data not in sim yet, fill with stats
if (equip.masterId > simPlayerEqIdMax) {
equip.stats = this.buildEquipMasterStats(gear.masterId);
}
return equip;
});
let morale = ship.morale;
// Undo KC3 morale decrement in Node.js, ignore case for -9 and align morale to sim cutoffs
if (realBattle) {
morale += 3;
} else if (morale > 49 && morale < 53) {
morale += 3;
}
return {
masterId: ship.masterId,
LVL: ship.level,
stats: stats,
HPInit: !realBattle ? ship.hp[0] : ship.afterHp[0],
fuelInit: ship.fuel / shipMst.api_fuel_max,
ammoInit: ship.ammo / shipMst.api_bull_max,
morale: morale,
equips: equips,
includesEquipStats: 1
};
};
return fleet.shipsUnescaped().map(buildShipStats);
},
buildEquipMasterStats :function(masterId) {
const gearMaster = KC3Master.slotitem(masterId),
stats = {},
simulatorKeys = {
FP: "api_houg",
TP: "api_raig",
AA: "api_tyku",
AR: "api_souk",
EV: "api_houk",
ASW: "api_tais",
LOS: "api_saku",
ACC: "api_houm",
DIVEBOMB: "api_baku",
RNG: "api_leng"
};
for (const key in simulatorKeys) {
const apiName = simulatorKeys[key];
stats[key] = gearMaster[apiName];
}
stats.type = gearMaster.api_type[3];
return stats;
}
};
})();
| Safe to advance for map end nodes
| src/library/managers/SortieManager.js | Safe to advance for map end nodes | <ide><path>rc/library/managers/SortieManager.js
<ide> // To check Taiha correctly on battle result screen, have to apply predicted afterHp first (invoke `#applyShipsAfterHp`)
<ide> let hasTaihaShip = false;
<ide> let isForcedToRetreat = false;
<add> let isSafeToAdvance = false;
<add> // No Taiha blocker needed if current battle node is an end point of the map, such as boss
<add> const nextEdgesAmount = this.currentNode().nodeData.api_next;
<add> if(nextEdgesAmount !== undefined && !nextEdgesAmount) isSafeToAdvance = true;
<add> // To check FCF correctly on battle result screen, have to first invoke `#checkFCF` (in another word `#resultScreen`)
<add> //const fcfInfo = this.getCurrentFCF();
<add> // TODO get FCF info and find a method to delay blocker after denying FCF decision screen
<ide> KC3SortieManager.getSortieFleet().forEach((fleetId, fleetIdx) => {
<ide> const fleet = PlayerManager.fleets[fleetId];
<ide> fleet.ship().forEach((ship, slotIdx) => {
<ide> hasTaihaShip = true;
<ide> });
<ide> });
<del> return hasTaihaShip && !isForcedToRetreat;
<add> return hasTaihaShip && !isForcedToRetreat && !isSafeToAdvance;
<ide> },
<ide>
<ide> checkFCF :function(escapeData){ |
|
Java | apache-2.0 | 4be74fb68fc95ec60b10394e17ab637cbc994974 | 0 | atcult/mod-cataloging,atcult/mod-cataloging,atcult/mod-cataloging | package org.folio.cataloging.resources;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.folio.cataloging.Global;
import org.folio.cataloging.ModCataloging;
import org.folio.cataloging.business.codetable.Avp;
import org.folio.cataloging.log.MessageCatalog;
import org.folio.cataloging.resources.domain.CatalogingEntityType;
import org.folio.cataloging.resources.domain.RecordTemplate;
import org.folio.cataloging.resources.domain.RecordTemplateCollection;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.function.Function;
import static java.util.stream.Collectors.toList;
import static org.folio.cataloging.F.isNotNullOrEmpty;
import static org.folio.cataloging.integration.CatalogingHelper.*;
import static org.folio.cataloging.resources.domain.CatalogingEntityType.A;
/**
* BIB / AUT Record templates API.
*
* @since 1.0
* @author agazzarini
* @author carment
*/
@RestController
@CrossOrigin("http://localhost:3000")
@Api(value = "modcat-api", description = "Record template resource API")
@RequestMapping(value = ModCataloging.BASE_URI, produces = "application/json")
public class RecordTemplateAPI extends BaseResource {
private Function<Avp<Integer>, RecordTemplate> toRecordTemplate = avp -> {
final RecordTemplate template = new RecordTemplate();
template.setId(avp.getValue());
template.setName(avp.getLabel());
return template;
};
@ApiOperation(value = "Returns all templates associated with a given type")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Method successfully returned the requested templates."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@GetMapping("/record-templates")
public RecordTemplateCollection getRecordTemplates(
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doGet((storageService, configuration) -> {
final List<Avp<Integer>> templates =
type == A
? storageService.getAuthorityRecordTemplates()
: storageService.getBibliographicRecordTemplates();
final RecordTemplateCollection collection = new RecordTemplateCollection();
collection.setRecordTemplates(templates.stream().map(toRecordTemplate).collect(toList()));
return collection;
}, tenant, configurator);
}
@ApiOperation(value = "Returns the template associated with a given type and identifier")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Method successfully returned the requested template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@GetMapping("/record-template/{id}")
public RecordTemplate getCatalogingRecordTemplatesById(
@PathVariable final String id,
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doGet((storageService, configuration) ->
type == A
? storageService.getAuthorityRecordRecordTemplatesById(id)
: storageService.getBibliographicRecordRecordTemplatesById(id)
,tenant, configurator);
}
@ApiOperation(value = "Creates a new template.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Method successfully created the new template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@PostMapping("/record-template/{id}")
public ResponseEntity<RecordTemplate> createNew(
@RequestBody final RecordTemplate template,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doPost((storageService, configuration) -> {
if("A".equals(template.getType())) {
storageService.saveAuthorityRecordTemplate(template);
} else {
storageService.saveBibliographicRecordTemplate(template);
}
return template;
}, tenant, configurator, () -> isNotNullOrEmpty(template.getName()), () -> String.valueOf(template.getId()));
}
@ApiOperation(value = "Updates an existing template.")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Method successfully updated the template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@ResponseStatus(HttpStatus.NO_CONTENT)
@PutMapping("/record-template/{id}")
public void update(
@PathVariable final String id,
@RequestBody final RecordTemplate template,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
doPut((storageService, configuration) -> {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonInString = mapper.writeValueAsString(template);
if("A".equals(template.getType())) {
storageService.updateAuthorityRecordTemplate(template);
} else {
storageService.updateBibliographicRecordTemplate(template);
}
return template;
} catch (final Exception exception) {
logger.error(MessageCatalog._00010_DATA_ACCESS_FAILURE, exception);
return null;
}
}, tenant, configurator, () -> isNotNullOrEmpty(id) && isNotNullOrEmpty(template.getName()));
}
@ApiOperation(value = "Deletes a template.")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Method successfully deleted the target template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/record-template/{id}")
public void deleteCatalogingRecordTemplatesById(
@PathVariable final String id,
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
doDelete((storageService, configuration) -> {
switch(type) {
case A:
storageService.deleteAuthorityRecordTemplate(id);
break;
case B:
storageService.deleteBibliographicRecordTemplate(id);
}
return id;
}, tenant, configurator);
}
}
| src/main/java/org/folio/cataloging/resources/RecordTemplateAPI.java | package org.folio.cataloging.resources;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.folio.cataloging.Global;
import org.folio.cataloging.ModCataloging;
import org.folio.cataloging.business.codetable.Avp;
import org.folio.cataloging.log.MessageCatalog;
import org.folio.cataloging.resources.domain.CatalogingEntityType;
import org.folio.cataloging.resources.domain.RecordTemplate;
import org.folio.cataloging.resources.domain.RecordTemplateCollection;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.function.Function;
import static java.util.stream.Collectors.toList;
import static org.folio.cataloging.F.isNotNullOrEmpty;
import static org.folio.cataloging.integration.CatalogingHelper.*;
import static org.folio.cataloging.resources.domain.CatalogingEntityType.A;
/**
* BIB / AUT Record templates API.
*
* @since 1.0
* @author agazzarini
* @author carment
*/
@RestController
@Api(value = "modcat-api", description = "Record template resource API")
@RequestMapping(value = ModCataloging.BASE_URI, produces = "application/json")
public class RecordTemplateAPI extends BaseResource {
private Function<Avp<Integer>, RecordTemplate> toRecordTemplate = avp -> {
final RecordTemplate template = new RecordTemplate();
template.setId(avp.getValue());
template.setName(avp.getLabel());
return template;
};
@ApiOperation(value = "Returns all templates associated with a given type")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Method successfully returned the requested templates."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@GetMapping("/record-templates")
public RecordTemplateCollection getRecordTemplates(
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doGet((storageService, configuration) -> {
final List<Avp<Integer>> templates =
type == A
? storageService.getAuthorityRecordTemplates()
: storageService.getBibliographicRecordTemplates();
final RecordTemplateCollection collection = new RecordTemplateCollection();
collection.setRecordTemplates(templates.stream().map(toRecordTemplate).collect(toList()));
return collection;
}, tenant, configurator);
}
@ApiOperation(value = "Returns the template associated with a given type and identifier")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Method successfully returned the requested template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@GetMapping("/record-template/{id}")
public RecordTemplate getCatalogingRecordTemplatesById(
@PathVariable final String id,
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doGet((storageService, configuration) ->
type == A
? storageService.getAuthorityRecordRecordTemplatesById(id)
: storageService.getBibliographicRecordRecordTemplatesById(id)
,tenant, configurator);
}
@ApiOperation(value = "Creates a new template.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Method successfully created the new template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@PostMapping("/record-template/{id}")
public ResponseEntity<RecordTemplate> createNew(
@RequestBody final RecordTemplate template,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
return doPost((storageService, configuration) -> {
if("A".equals(template.getType())) {
storageService.saveAuthorityRecordTemplate(template);
} else {
storageService.saveBibliographicRecordTemplate(template);
}
return template;
}, tenant, configurator, () -> isNotNullOrEmpty(template.getName()), () -> String.valueOf(template.getId()));
}
@ApiOperation(value = "Updates an existing template.")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Method successfully updated the template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@ResponseStatus(HttpStatus.NO_CONTENT)
@PutMapping("/record-template/{id}")
public void update(
@PathVariable final String id,
@RequestBody final RecordTemplate template,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
doPut((storageService, configuration) -> {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonInString = mapper.writeValueAsString(template);
if("A".equals(template.getType())) {
storageService.updateAuthorityRecordTemplate(template);
} else {
storageService.updateBibliographicRecordTemplate(template);
}
return template;
} catch (final Exception exception) {
logger.error(MessageCatalog._00010_DATA_ACCESS_FAILURE, exception);
return null;
}
}, tenant, configurator, () -> isNotNullOrEmpty(id) && isNotNullOrEmpty(template.getName()));
}
@ApiOperation(value = "Deletes a template.")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Method successfully deleted the target template."),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 414, message = "Request-URI Too Long"),
@ApiResponse(code = 500, message = "System internal failure occurred.")
})
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/record-template/{id}")
public void deleteCatalogingRecordTemplatesById(
@PathVariable final String id,
@RequestParam final CatalogingEntityType type,
@RequestParam final String lang,
@RequestHeader(Global.OKAPI_TENANT_HEADER_NAME) final String tenant) {
doDelete((storageService, configuration) -> {
switch(type) {
case A:
storageService.deleteAuthorityRecordTemplate(id);
break;
case B:
storageService.deleteBibliographicRecordTemplate(id);
}
return id;
}, tenant, configurator);
}
} | Update RecordTemplateAPI.java | src/main/java/org/folio/cataloging/resources/RecordTemplateAPI.java | Update RecordTemplateAPI.java | <ide><path>rc/main/java/org/folio/cataloging/resources/RecordTemplateAPI.java
<ide> * @author carment
<ide> */
<ide> @RestController
<add>@CrossOrigin("http://localhost:3000")
<ide> @Api(value = "modcat-api", description = "Record template resource API")
<ide> @RequestMapping(value = ModCataloging.BASE_URI, produces = "application/json")
<ide> public class RecordTemplateAPI extends BaseResource { |
|
JavaScript | mit | d1c093ee3e638fdbcf7cdf8855d2094c00ab0d01 | 0 | neusdq/www,neusdq/www,neusdq/www,neusdq/www,neusdq/www | $(document).ready(function () {
$(".chzn_a").chosen({
allow_single_deselect: true
});
//成功提示框设置
$('#alert-success').modal({
backdrop: false,
show: false
});
//监听radio事件
$('input[name="g_type"]:radio').change(function () {
var value = $(this).val();
if (value == 1) {
$("div.goods-multiple-own").hide();
$("div.goods-single-own").show();
$("label.g-unit").removeClass('col-sm-2');
$("label.g-unit").addClass('col-sm-1');
} else {
$("div.goods-single-own").hide();
$("div.goods-multiple-own").show();
$("label.g-unit").removeClass('col-sm-1');
$("label.g-unit").addClass('col-sm-2');
}
});
$("span.delete").die().live('click',function(){
$(this).parent().remove();
})
$("#add-goods-ok").die().live('click', function () {
var flag = true;
var g_name = $("#g_name").val();
var g_type = $('input[name="g_type"]:checked ').val();
var g_classify = $("#g_classify").val();
var g_brand = $("#g_brand").val();
var g_supplier = $("#g_supplier").val();
var g_ids = $("#g_ids").val();
var g_price = $("#g_price").val();
var g_cost = $("#g_cost").val();
var g_inventory = $("#g_inventory").val();
var g_unit = $("#g_unit").val();
var g_deliver = $("#g_deliver").val();
var g_description = $("#g_description").val();
var g_remark = $("#g_rk").val();
var pic_ids = getUploadImg();
var price_preg = /^([0-9]+[\.]?[0-9]+|\d+)$/;
if (g_name == '' || g_name == undefined) {
flag = flag & false;
alertError("#alert-error", '商品名称不能为空!');
return;
}
if (g_type == 2) {
if (g_ids == '') {
flag = flag & false;
alertError("#alert-error", '商品ID不能为空!');
return;
}
}
if (g_price == '' || !price_preg.test(g_price)) {
flag = flag & false;
alertError("#alert-error", '请填写正确的销售价格!');
return;
}
if (g_cost == '' || !price_preg.test(g_cost)) {
flag = flag & false;
alertError("#alert-error", '请填写正确的采购价格!');
return;
}
if (g_type == 1 && (g_inventory == '' || !/^[0-9]+$/.test(g_inventory))) {
flag = flag & false;
alertError("#alert-error", '请填写商品库存!');
return;
}
if (g_type == 2){
g_inventory = 0;
}
if (g_unit == '') {
flag = flag & false;
alertError("#alert-error", '请填写商品单位!');
return;
}
if (pic_ids == '') {
flag = flag & false;
alertError("#alert-error", '请上传宣传图片!');
return;
}
if (flag) {
$.post('/goods_manage/add_goods',
{
name: g_name, groupid: g_ids, type: g_type, classify_id: g_classify,
brand_id: g_brand, supply_id: g_supplier, sale_price: g_price,
buy_price: g_cost, store_num: g_inventory, deliver_id: g_deliver,
munit: g_unit, desciption: g_description, remark: g_remark,
pic_ids: pic_ids
}, function (ret) {
var d = $.parseJSON(ret);
if (d.errCode == 0) {
alertSuccess("#alert-success", '/goods_manage/goods_list');
} else {
alertError("#alert-error", d.msg);
}
});
}
});
});
| res/goods_manage/add_goods.js | $(document).ready(function () {
$(".chzn_a").chosen({
allow_single_deselect: true
});
//成功提示框设置
$('#alert-success').modal({
backdrop: false,
show: false
});
//监听radio事件
$('input[name="g_type"]:radio').change(function () {
var value = $(this).val();
if (value == 1) {
$("div.goods-multiple-own").hide();
$("div.goods-single-own").show();
$("label.g-unit").removeClass('col-sm-2');
$("label.g-unit").addClass('col-sm-1');
} else {
$("div.goods-single-own").hide();
$("div.goods-multiple-own").show();
$("label.g-unit").removeClass('col-sm-1');
$("label.g-unit").addClass('col-sm-2');
}
});
$("span.delete").die().live('click',function(){
$(this).parent().remove();
})
$("#add-goods-ok").die().live('click', function () {
var flag = true;
var g_name = $("#g_name").val();
var g_type = $('input[name="g_type"]:checked ').val();
var g_classify = $("#g_classify").val();
var g_brand = $("#g_brand").val();
var g_supplier = $("#g_supplier").val();
var g_ids = $("#g_ids").val();
var g_price = $("#g_price").val();
var g_cost = $("#g_cost").val();
var g_inventory = $("#g_inventory").val();
var g_unit = $("#g_unit").val();
var g_deliver = $("#g_deliver").val();
var g_description = $("#g_description").val();
var g_remark = $("#g_rk").val();
var pic_ids = getUploadImg();
var price_preg = /^([0-9]+[\.]?[0-9]+|\d+)$/;
if (g_name == '' || g_name == undefined) {
flag = flag & false;
alertError("#alert-error", '商品名称不能为空!');
return;
}
if (g_type == 2) {
if (g_ids == '') {
flag = flag & false;
alertError("#alert-error", '商品ID不能为空!');
return;
}
}
if (g_price == '' || !price_preg.test(g_price)) {
flag = flag & false;
alertError("#alert-error", '请填写正确的销售价格!');
return;
}
if (g_cost == '' || !price_preg.test(g_cost)) {
flag = flag & false;
alertError("#alert-error", '请填写正确的采购价格!');
return;
}
if (g_type == 1 && (g_inventory == '' || !/^[0-9]+$/.test(g_inventory))) {
flag = flag & false;
alertError("#alert-error", '请填写商品库存!');
return;
}
if (g_type == 2){
g_inventory = 0;
}
if (g_unit == '') {
flag = flag & false;
alertError("#alert-error", '请填写商品单位!');
return;
}
if (pic_ids == '') {
flag = flag & false;
alertError("#alert-error", '请上传宣传图片!');
return;
}
if (flag) {
$.post('/goods_manage/add_goods',
{
name: g_name, groupid: g_ids, type: g_type, classify_id: g_classify,
brand_id: g_brand, supply_id: g_supplier, sale_price: g_price,
buy_price: g_cost, store_num: g_inventory, deliver_id: g_deliver,
munit: g_unit, desciption: g_description, remark: g_remark,
pic_ids: pic_ids
}, function (ret) {
var d = $.parseJSON(ret);
if (d.errCode == 0) {
alertSuccess("#alert-success", '/goods_manage/add_goods');
} else {
alertError("#alert-error", d.msg);
}
});
}
});
});
| fix bug
| res/goods_manage/add_goods.js | fix bug | <ide><path>es/goods_manage/add_goods.js
<ide> }, function (ret) {
<ide> var d = $.parseJSON(ret);
<ide> if (d.errCode == 0) {
<del> alertSuccess("#alert-success", '/goods_manage/add_goods');
<add> alertSuccess("#alert-success", '/goods_manage/goods_list');
<ide> } else {
<ide> alertError("#alert-error", d.msg);
<ide> } |
|
JavaScript | mit | 376972d41790637b6ef35eb04ee5d6cb4a14c29c | 0 | ewoudj/game,ewoudj/game,ewoudj/game | /*
* Engine
*/
if(typeof(require) !== 'undefined'){
var helpers = require("./helpers").helpers;
}
var engine = function(config){
helpers.apply({
debug : false,
width : 800,
height : 600,
pageColor : '#555',
canvasColor : '#000',
crosshair : true
}, this);
helpers.apply(config, this);
if(this.mode == 'standalone' || this.mode == 'client'){
// Disable selection of text/elements in the browser
document.onselectstart = function() {return false;};
document.body.style.background = this.pageColor;
// Initialize the settings UI
engine.settings.initialize();
}
this.buttonDown = false;
this.mousePosition = {x: 0, y: 0};
this.buttonDown2 = false;
this.mousePosition2 = {x: 0, y: 0};
this.entities = [];
this.remoteData = [];
this.previousControllerMessageTime = 0;
this.remoteDataString = [];
if(this.rulesType){
this.rules = new this.rulesType({engine: this});
this.add(this.rules);
}
if(this.mode === 'server'){
this.serverUpdateLoop();
}
else{
var self = this;
this.socket.on('game state', function(msg){
self.remoteDataString.push(msg);
});
}
if(this.mode == 'standalone' || this.mode === 'client'){
this.animate();
}
};
engine.prototype.serverUpdateLoop = function(){
setTimeout( this.serverUpdateLoop.bind(this), 1000 / 60 );
this.update();
};
engine.prototype.animate = function(){
requestAnimationFrame(this.animate.bind(this));
this.update();
// Check to see if the renderer changed,
// if so, suspend the previous renderer (if it exists at all)
if(engine.previousRenderer && engine.previousRenderer !== engine.renderer){
engine.rendering[engine.previousRenderer].call(this, true);
}
engine.rendering[engine.renderer].call(this);
engine.previousRenderer = engine.renderer;
};
engine.prototype.add = function(entity){
if(this.entities.length === 0){
this.entityIdCounter = 0;
}
if(!entity.engineId && this.mode === 'server'){
entity.engineId = this.entityIdCounter;
this.entityIdCounter++;
}
this.entities.push(entity);
entity.engine = this;
};
engine.prototype.calculateCollisions = function(){
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
e1.collisions = [];
for(var j = 0; j < l; j++){
var e2 = this.entities[j];
var e2 = this.entities[j];
if(e1 != e2 && e1.collidesWith(e2)){
e1.collisions.push(e2);
if(!e2.collisions){
e2.collisions = [];
}
e2.collisions.push(e1);
}
}
}
};
engine.prototype.processRemoteData = function(){
var s = this.remoteDataString.shift();
while(s){
var dataFromServer = s.split(",");
var offset = 0;
var l = dataFromServer.length;
var i = 0;
while(offset < l){
var e = null;
var engineId = parseInt(dataFromServer[offset]);
offset++;
for(var j = 0, m = this.entities.length; j < m; j++){
if(engineId === this.entities[j].engineId){
e = this.entities[j];
break;
}
}
if(e === null){
// Add new entities
var entityType = engine.remoteRenderer[dataFromServer[offset]];
e = new entityType({
engine: this,
engineId: engineId
});
this.add(e);
}
offset = e.renderRemoteData(dataFromServer,offset);
i++;
}
s = this.remoteDataString.shift();
}
};
engine.prototype.update = function(time){
time = time || new Date().getTime();
var remoteData = "";
if(this.mode !== "client"){
this.calculateCollisions();
}
else if(this.mode === "client"){
this.processRemoteData();
}
// Update
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
if(e1 && e1.update){
// Run the entity update logic
if(this.mode !== "client" && e1.update){
e1.update(time);
}
// If we are on the server we want to serialize the objects now
// before finished entities get removed from the list.
if(this.mode === "server"){
if(e1.getRemoteData){
if(remoteData != ""){
remoteData = remoteData + ",";
}
remoteData = remoteData + e1.engineId + "," + e1.getRemoteData();
}
}
}
}
// Filter out the objects that indicate they are finished
var newList = [];
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
if(e1 && !e1.finished){
newList.push(e1);
}
}
this.entities = newList;
if(this.mode === "client"){
if(this.socket){
// Send controller state to the server
// Send the message at most 20 times per second
if((time - this.previousControllerMessageTime) >= 50) {
this.previousControllerMessageTime = time;
this.controllerMessage = this.mousePosition.x + ',' + this.mousePosition.y + ',' + (this.buttonDown ? 1 : 0);
// If the controls have not changed, do not send a message
if(this.controllerMessage !== this.previousControllerMessage){
this.previousControllerMessage = this.controllerMessage;
this.socket.emit('controller state',this.controllerMessage);
}
}
}
}
if(this.mode == 'server'){
// Send game state to the clients
if(this.player1){
this.player1.emit('game state', remoteData);
}
if(this.player2){
this.player2.emit('game state', remoteData);
}
}
};
//Stores a value in local storage. Will handle objects, will probably fail when called on the server.
engine.setItem = function(key, value) {
if (typeof value == "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
};
// Gets an object from local storage, if no value for key was found defaultValue is returned;
engine.getItem = function(key, defaultValue) {
var result = null;
if(typeof localStorage != 'undefined'){
result = localStorage.getItem(key);
// assume it is an object that has been stringified
if (result && result[0] == "{") {
result = JSON.parse(result);
}
}
return result || defaultValue;
};
/*
* Everything below this line needs to move into
* either server or client settings files.
*/
// Configuration options, still need to make this nice
engine.ai = {};
engine.player1ai = engine.getItem("player1ai", 'heuristic');
engine.player2ai = engine.getItem("player2ai", 'heuristic');
engine.rendering = {};
engine.renderer = engine.getItem("renderer",'classic');
engine.effectsVolume = parseInt(engine.getItem("effectsVolume", 25));
engine.musicVolume = parseInt(engine.getItem("musicVolume", 40));
if(typeof(exports) !== 'undefined'){
exports.engine = engine;
}
else {
// The order of this list is important, the index
// maps to what the ship emits as the first number
// in it's remoting data
engine.remoteRenderer = [];
engine.remoteRenderer.push(ship);
engine.remoteRenderer.push(laserbeam);
engine.remoteRenderer.push(star);
engine.remoteRenderer.push(ufo);
engine.remoteRenderer.push(explosion);
engine.remoteRenderer.push(rules);
}
| static/laserwar/engine.js | /*
* Engine
*/
if(typeof(require) !== 'undefined'){
var helpers = require("./helpers").helpers;
}
var engine = function(config){
helpers.apply({
debug : false,
width : 800,
height : 600,
pageColor : '#555',
canvasColor : '#000',
crosshair : true
}, this);
helpers.apply(config, this);
if(this.mode == 'standalone' || this.mode == 'client'){
// Disable selection of text/elements in the browser
document.onselectstart = function() {return false;};
document.body.style.background = this.pageColor;
// Initialize the settings UI
engine.settings.initialize();
}
this.buttonDown = false;
this.mousePosition = {x: 0, y: 0};
this.buttonDown2 = false;
this.mousePosition2 = {x: 0, y: 0};
this.entities = [];
this.remoteData = [];
this.previousControllerMessageTime = 0;
this.remoteDataString = [];
if(this.rulesType){
this.add(new this.rulesType({engine: this}));
}
if(this.mode === 'server'){
this.serverUpdateLoop();
}
else{
var self = this;
this.socket.on('game state', function(msg){
self.remoteDataString.push(msg);
});
}
if(this.mode == 'standalone' || this.mode === 'client'){
this.animate();
}
};
engine.prototype.serverUpdateLoop = function(){
setTimeout( this.serverUpdateLoop.bind(this), 1000 / 60 );
this.update();
};
engine.prototype.animate = function(){
requestAnimationFrame(this.animate.bind(this));
this.update();
// Check to see if the renderer changed,
// if so, suspend the previous renderer (if it exists at all)
if(engine.previousRenderer && engine.previousRenderer !== engine.renderer){
engine.rendering[engine.previousRenderer].call(this, true);
}
engine.rendering[engine.renderer].call(this);
engine.previousRenderer = engine.renderer;
};
engine.prototype.add = function(entity){
if(this.entities.length === 0){
this.entityIdCounter = 0;
}
if(!entity.engineId && this.mode === 'server'){
entity.engineId = this.entityIdCounter;
this.entityIdCounter++;
}
this.entities.push(entity);
entity.engine = this;
};
engine.prototype.calculateCollisions = function(){
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
e1.collisions = [];
for(var j = 0; j < l; j++){
var e2 = this.entities[j];
var e2 = this.entities[j];
if(e1 != e2 && e1.collidesWith(e2)){
e1.collisions.push(e2);
if(!e2.collisions){
e2.collisions = [];
}
e2.collisions.push(e1);
}
}
}
};
engine.prototype.processRemoteData = function(){
var s = this.remoteDataString.shift();
while(s){
var dataFromServer = s.split(",");
var offset = 0;
var l = dataFromServer.length;
var i = 0;
while(offset < l){
var e = null;
var engineId = parseInt(dataFromServer[offset]);
offset++;
for(var j = 0, m = this.entities.length; j < m; j++){
if(engineId === this.entities[j].engineId){
e = this.entities[j];
break;
}
}
if(e === null){
// Add new entities
var entityType = engine.remoteRenderer[dataFromServer[offset]];
e = new entityType({
engine: this,
engineId: engineId
});
this.add(e);
}
offset = e.renderRemoteData(dataFromServer,offset);
i++;
}
s = this.remoteDataString.shift();
}
};
engine.prototype.update = function(time){
time = time || new Date().getTime();
var remoteData = "";
if(this.mode !== "client"){
this.calculateCollisions();
}
else if(this.mode === "client"){
this.processRemoteData();
}
// Update
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
if(e1 && e1.update){
// Run the entity update logic
if(this.mode !== "client" && e1.update){
e1.update(time);
}
// If we are on the server we want to serialize the objects now
// before finished entities get removed from the list.
if(this.mode === "server"){
if(e1.getRemoteData){
if(remoteData != ""){
remoteData = remoteData + ",";
}
remoteData = remoteData + e1.engineId + "," + e1.getRemoteData();
}
}
}
}
// Filter out the objects that indicate they are finished
var newList = [];
for(var i = 0, l = this.entities.length; i < l; i++){
var e1 = this.entities[i];
if(e1 && !e1.finished){
newList.push(e1);
}
}
this.entities = newList;
if(this.mode === "client"){
if(this.socket){
// Send controller state to the server
// Send the message at most 20 times per second
if((time - this.previousControllerMessageTime) >= 50) {
this.previousControllerMessageTime = time;
this.controllerMessage = this.mousePosition.x + ',' + this.mousePosition.y + ',' + (this.buttonDown ? 1 : 0);
// If the controls have not changed, do not send a message
if(this.controllerMessage !== this.previousControllerMessage){
this.previousControllerMessage = this.controllerMessage;
this.socket.emit('controller state',this.controllerMessage);
}
}
}
}
if(this.mode == 'server'){
// Send game state to the clients
if(this.player1){
this.player1.emit('game state', remoteData);
}
if(this.player2){
this.player2.emit('game state', remoteData);
}
}
};
//Stores a value in local storage. Will handle objects, will probably fail when called on the server.
engine.setItem = function(key, value) {
if (typeof value == "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
};
// Gets an object from local storage, if no value for key was found defaultValue is returned;
engine.getItem = function(key, defaultValue) {
var result = null;
if(typeof localStorage != 'undefined'){
result = localStorage.getItem(key);
// assume it is an object that has been stringified
if (result && result[0] == "{") {
result = JSON.parse(result);
}
}
return result || defaultValue;
};
/*
* Everything below this line needs to move into
* either server or client settings files.
*/
// Configuration options, still need to make this nice
engine.ai = {};
engine.player1ai = engine.getItem("player1ai", 'heuristic');
engine.player2ai = engine.getItem("player2ai", 'heuristic');
engine.rendering = {};
engine.renderer = engine.getItem("renderer",'classic');
engine.effectsVolume = parseInt(engine.getItem("effectsVolume", 25));
engine.musicVolume = parseInt(engine.getItem("musicVolume", 40));
if(typeof(exports) !== 'undefined'){
exports.engine = engine;
}
else {
// The order of this list is important, the index
// maps to what the ship emits as the first number
// in it's remoting data
engine.remoteRenderer = [];
engine.remoteRenderer.push(ship);
engine.remoteRenderer.push(laserbeam);
engine.remoteRenderer.push(star);
engine.remoteRenderer.push(ufo);
engine.remoteRenderer.push(explosion);
engine.remoteRenderer.push(rules);
}
| Rules object is now referenced by the engine
| static/laserwar/engine.js | Rules object is now referenced by the engine | <ide><path>tatic/laserwar/engine.js
<ide> this.previousControllerMessageTime = 0;
<ide> this.remoteDataString = [];
<ide> if(this.rulesType){
<del> this.add(new this.rulesType({engine: this}));
<add> this.rules = new this.rulesType({engine: this});
<add> this.add(this.rules);
<ide> }
<ide>
<ide> if(this.mode === 'server'){ |
|
Java | apache-2.0 | b992a08822a1d5536ef91120d577d64bf6683e75 | 0 | signed/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,semonte/intellij-community,da1z/intellij-community,hurricup/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,da1z/intellij-community,FHannes/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,allotria/intellij-community,fitermay/intellij-community,fitermay/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,semonte/intellij-community,hurricup/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,apixandru/intellij-community,da1z/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,xfournet/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,xfournet/intellij-community,hurricup/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,xfournet/intellij-community,semonte/intellij-community,da1z/intellij-community,allotria/intellij-community,fitermay/intellij-community,allotria/intellij-community,semonte/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,signed/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,da1z/intellij-community,fitermay/intellij-community,semonte/intellij-community,signed/intellij-community,semonte/intellij-community,ibinti/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,apixandru/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,signed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,hurricup/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,fitermay/intellij-community,asedunov/intellij-community,apixandru/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,signed/intellij-community,da1z/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,apixandru/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,da1z/intellij-community,da1z/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,apixandru/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,FHannes/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,semonte/intellij-community | /*
* Copyright 2000-2016 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.codeInsight.hint;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.ide.IdeTooltip;
import com.intellij.lang.parameterInfo.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon.Position;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
public class ParameterInfoController implements Disposable {
private final Project myProject;
@NotNull private final Editor myEditor;
private final RangeMarker myLbraceMarker;
private final LightweightHint myHint;
private final ParameterInfoComponent myComponent;
private final CaretListener myEditorCaretListener;
@NotNull private final ParameterInfoHandler<Object, Object> myHandler;
private final ShowParameterInfoHandler.BestLocationPointProvider myProvider;
private final Alarm myAlarm = new Alarm();
private static final int DELAY = 200;
private boolean myDisposed = false;
/**
* Keeps Vector of ParameterInfoController's in Editor
*/
private static final Key<List<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY");
public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) {
List<ParameterInfoController> allControllers = getAllControllers(editor);
for (int i = 0; i < allControllers.size(); ++i) {
ParameterInfoController controller = allControllers.get(i);
if (controller.myLbraceMarker.getStartOffset() == offset) {
if (controller.myHint.isVisible()) return controller;
Disposer.dispose(controller);
--i;
}
}
return null;
}
public Object[] getSelectedElements() {
ParameterInfoContext context = new ParameterInfoContext() {
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myComponent.getParameterOwner().getContainingFile();
}
@Override
public int getOffset() {
return myEditor.getCaretModel().getOffset();
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
};
if (!myHandler.tracksParameterIndex()) {
return myHandler.getParametersForDocumentation(myComponent.getObjects()[0],context);
}
final Object[] objects = myComponent.getObjects();
int selectedParameterIndex = myComponent.getCurrentParameterIndex();
List<Object> params = new ArrayList<Object>(objects.length);
final Object highlighted = myComponent.getHighlighted();
for(Object o:objects) {
if (highlighted != null && !o.equals(highlighted)) continue;
collectParams(context, selectedParameterIndex, params, o);
}
//choose anything when highlighted is not applicable
if (highlighted != null && params.isEmpty()) {
for (Object o : objects) {
collectParams(context, selectedParameterIndex, params, o);
}
}
return ArrayUtil.toObjectArray(params);
}
private void collectParams(ParameterInfoContext context, int selectedParameterIndex, List<Object> params, Object o) {
final Object[] availableParams = myHandler.getParametersForDocumentation(o, context);
if (availableParams != null &&
selectedParameterIndex < availableParams.length &&
selectedParameterIndex >= 0
) {
params.add(availableParams[selectedParameterIndex]);
}
}
private static List<ParameterInfoController> getAllControllers(@NotNull Editor editor) {
List<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY);
if (array == null){
array = new ArrayList<ParameterInfoController>();
editor.putUserData(ALL_CONTROLLERS_KEY, array);
}
return array;
}
public static boolean isShownForEditor(@NotNull Editor editor) {
return !getAllControllers(editor).isEmpty();
}
public static boolean isAlreadyShown(Editor editor, int lbraceOffset) {
return findControllerAtOffset(editor, lbraceOffset) != null;
}
public ParameterInfoController(@NotNull Project project,
@NotNull Editor editor,
int lbraceOffset,
@NotNull LightweightHint hint,
@NotNull ParameterInfoHandler handler,
@NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) {
myProject = project;
myEditor = editor;
myHandler = handler;
myProvider = provider;
myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset);
myHint = hint;
myComponent = (ParameterInfoComponent)myHint.getComponent();
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.add(this);
myEditorCaretListener = new CaretAdapter(){
@Override
public void caretPositionChanged(CaretEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
};
myEditor.getCaretModel().addCaretListener(myEditorCaretListener);
myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
}, this);
PropertyChangeListener lookupListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) {
Lookup lookup = (Lookup)evt.getNewValue();
if (lookup != null) {
adjustPositionForLookup(lookup);
}
}
}
};
LookupManager.getInstance(project).addPropertyChangeListener(lookupListener, this);
updateComponent();
if (myEditor instanceof EditorImpl) {
Disposer.register(((EditorImpl)myEditor).getDisposable(), this);
}
}
@Override
public void dispose(){
if (myDisposed) return;
myDisposed = true;
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.remove(this);
myEditor.getCaretModel().removeCaretListener(myEditorCaretListener);
}
private void adjustPositionForLookup(@NotNull Lookup lookup) {
if (!myHint.isVisible() || myEditor.isDisposed()) {
Disposer.dispose(this);
return;
}
IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
if (tooltip != null) {
JRootPane root = myEditor.getComponent().getRootPane();
if (root != null) {
Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane());
if (lookup.isPositionedAboveCaret()) {
if (Position.above == tooltip.getPreferredPosition()) {
myHint.pack();
myHint.updatePosition(Position.below);
myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY());
}
}
else {
if (Position.below == tooltip.getPreferredPosition()) {
myHint.pack();
myHint.updatePosition(Position.above);
myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY());
}
}
}
}
}
private void addAlarmRequest(){
Runnable request = () -> {
if (!myDisposed && !myProject.isDisposed()) {
PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() ->
DumbService.getInstance(myProject).withAlternativeResolveEnabled(this::updateComponent)
);
}
};
myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
}
private void updateComponent(){
if (!myHint.isVisible()){
Disposer.dispose(this);
return;
}
final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
CharSequence chars = myEditor.getDocument().getCharsSequence();
final int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file);
final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context);
if (elementForUpdating != null) {
myHandler.updateParameterInfo(elementForUpdating, context);
if (!myDisposed && myHint.isVisible() && myEditor.getComponent().getRootPane() != null) {
myComponent.update();
IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
short position = tooltip != null
? toShort(tooltip.getPreferredPosition())
: HintManager.UNDER;
Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating,
myEditor.getCaretModel().getOffset(), true, position);
HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
}
}
else {
context.removeHint();
}
}
@HintManager.PositionFlags
private static short toShort(Position position) {
switch (position) {
case above:
return HintManager.ABOVE;
case atLeft:
return HintManager.LEFT;
case atRight:
return HintManager.RIGHT;
default:
return HintManager.UNDER;
}
}
public static boolean hasPrevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
return controller != null && controller.getPrevOrNextParameterOffset(isNext) != -1;
}
public static void prevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
int newOffset = controller != null ? controller.getPrevOrNextParameterOffset(isNext) : -1;
if (newOffset != -1) {
controller.moveToParameterAtOffset(newOffset);
}
}
private void moveToParameterAtOffset(int offset) {
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argsList = findArgumentList(file, offset, -1);
if (argsList == null) return;
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
}
private int getPrevOrNextParameterOffset(boolean isNext) {
if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1;
int offset = CharArrayUtil.shiftBackward(myEditor.getDocument().getCharsSequence(), myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
int lbraceOffset = myLbraceMarker.getStartOffset();
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null;
if (argList == null) return -1;
ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler;
int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType());
if (currentParameterIndex == -1) return -1;
@SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList);
int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 :
!isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1;
return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1;
}
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){
if (file == null) return null;
ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());
if (handlers != null) {
for(ParameterInfoHandler handler:handlers) {
if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;
// please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
final E e = (E) ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
if (e != null) return e;
}
}
}
return null;
}
private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext {
private final int myOffset;
private final PsiFile myFile;
public MyUpdateParameterInfoContext(final int offset, final PsiFile file) {
myOffset = offset;
myFile = file;
}
@Override
public int getParameterListStart() {
return myLbraceMarker.getStartOffset();
}
@Override
public int getOffset() {
return myOffset;
}
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myFile;
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
@Override
public void removeHint() {
myHint.hide();
Disposer.dispose(ParameterInfoController.this);
}
@Override
public void setParameterOwner(final PsiElement o) {
myComponent.setParameterOwner(o);
}
@Override
public PsiElement getParameterOwner() {
return myComponent.getParameterOwner();
}
@Override
public void setHighlightedParameter(final Object method) {
myComponent.setHighlightedParameter(method);
}
@Override
public void setCurrentParameter(final int index) {
myComponent.setCurrentParameterIndex(index);
}
@Override
public boolean isUIComponentEnabled(int index) {
return myComponent.isEnabled(index);
}
@Override
public void setUIComponentEnabled(int index, boolean enabled) {
myComponent.setEnabled(index, enabled);
}
@Override
public Object[] getObjectsToView() {
return myComponent.getObjects();
}
}
}
| platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java | /*
* Copyright 2000-2016 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.codeInsight.hint;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.ide.IdeTooltip;
import com.intellij.lang.parameterInfo.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon.Position;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
public class ParameterInfoController implements Disposable {
private final Project myProject;
@NotNull private final Editor myEditor;
private final RangeMarker myLbraceMarker;
private final LightweightHint myHint;
private final ParameterInfoComponent myComponent;
private final CaretListener myEditorCaretListener;
@NotNull private final ParameterInfoHandler<Object, Object> myHandler;
private final ShowParameterInfoHandler.BestLocationPointProvider myProvider;
private final Alarm myAlarm = new Alarm();
private static final int DELAY = 200;
private boolean myDisposed = false;
/**
* Keeps Vector of ParameterInfoController's in Editor
*/
private static final Key<List<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY");
public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) {
List<ParameterInfoController> allControllers = getAllControllers(editor);
for (int i = 0; i < allControllers.size(); ++i) {
ParameterInfoController controller = allControllers.get(i);
if (controller.myLbraceMarker.getStartOffset() == offset) {
if (controller.myHint.isVisible()) return controller;
Disposer.dispose(controller);
--i;
}
}
return null;
}
public Object[] getSelectedElements() {
ParameterInfoContext context = new ParameterInfoContext() {
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myComponent.getParameterOwner().getContainingFile();
}
@Override
public int getOffset() {
return myEditor.getCaretModel().getOffset();
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
};
if (!myHandler.tracksParameterIndex()) {
return myHandler.getParametersForDocumentation(myComponent.getObjects()[0],context);
}
final Object[] objects = myComponent.getObjects();
int selectedParameterIndex = myComponent.getCurrentParameterIndex();
List<Object> params = new ArrayList<Object>(objects.length);
final Object highlighted = myComponent.getHighlighted();
for(Object o:objects) {
if (highlighted != null && !o.equals(highlighted)) continue;
collectParams(context, selectedParameterIndex, params, o);
}
//choose anything when highlighted is not applicable
if (highlighted != null && params.isEmpty()) {
for (Object o : objects) {
collectParams(context, selectedParameterIndex, params, o);
}
}
return ArrayUtil.toObjectArray(params);
}
private void collectParams(ParameterInfoContext context, int selectedParameterIndex, List<Object> params, Object o) {
final Object[] availableParams = myHandler.getParametersForDocumentation(o, context);
if (availableParams != null &&
selectedParameterIndex < availableParams.length &&
selectedParameterIndex >= 0
) {
params.add(availableParams[selectedParameterIndex]);
}
}
private static List<ParameterInfoController> getAllControllers(@NotNull Editor editor) {
List<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY);
if (array == null){
array = new ArrayList<ParameterInfoController>();
editor.putUserData(ALL_CONTROLLERS_KEY, array);
}
return array;
}
public static boolean isShownForEditor(@NotNull Editor editor) {
return !getAllControllers(editor).isEmpty();
}
public static boolean isAlreadyShown(Editor editor, int lbraceOffset) {
return findControllerAtOffset(editor, lbraceOffset) != null;
}
public ParameterInfoController(@NotNull Project project,
@NotNull Editor editor,
int lbraceOffset,
@NotNull LightweightHint hint,
@NotNull ParameterInfoHandler handler,
@NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) {
myProject = project;
myEditor = editor;
myHandler = handler;
myProvider = provider;
myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset);
myHint = hint;
myComponent = (ParameterInfoComponent)myHint.getComponent();
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.add(this);
myEditorCaretListener = new CaretAdapter(){
@Override
public void caretPositionChanged(CaretEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
};
myEditor.getCaretModel().addCaretListener(myEditorCaretListener);
myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
}, this);
PropertyChangeListener lookupListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) {
Lookup lookup = (Lookup)evt.getNewValue();
if (lookup != null) {
adjustPositionForLookup(lookup);
}
}
}
};
LookupManager.getInstance(project).addPropertyChangeListener(lookupListener, this);
updateComponent();
if (myEditor instanceof EditorImpl) {
Disposer.register(((EditorImpl)myEditor).getDisposable(), this);
}
}
@Override
public void dispose(){
if (myDisposed) return;
myDisposed = true;
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.remove(this);
myEditor.getCaretModel().removeCaretListener(myEditorCaretListener);
}
private void adjustPositionForLookup(@NotNull Lookup lookup) {
if (!myHint.isVisible() || myEditor.isDisposed()) {
Disposer.dispose(this);
return;
}
IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
if (tooltip != null) {
JRootPane root = myEditor.getComponent().getRootPane();
if (root != null) {
Point p = tooltip.getShowingPoint().getPoint(root.getLayeredPane());
if (lookup.isPositionedAboveCaret()) {
if (Position.above == tooltip.getPreferredPosition()) {
myHint.pack();
myHint.updatePosition(Position.below);
myHint.updateLocation(p.x, p.y + tooltip.getPositionChangeY());
}
}
else {
if (Position.below == tooltip.getPreferredPosition()) {
myHint.pack();
myHint.updatePosition(Position.above);
myHint.updateLocation(p.x, p.y - tooltip.getPositionChangeY());
}
}
}
}
}
private void addAlarmRequest(){
Runnable request = () -> {
if (!myDisposed && !myProject.isDisposed()) {
PsiDocumentManager.getInstance(myProject).performLaterWhenAllCommitted(() ->
DumbService.getInstance(myProject).withAlternativeResolveEnabled(this::updateComponent)
);
}
};
myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
}
private void updateComponent(){
if (!myHint.isVisible()){
Disposer.dispose(this);
return;
}
final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
CharSequence chars = myEditor.getDocument().getCharsSequence();
final int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file);
final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context);
if (elementForUpdating != null) {
myHandler.updateParameterInfo(elementForUpdating, context);
if (!myDisposed && myHint.isVisible() && myEditor.getComponent().getRootPane() != null) {
myComponent.update();
IdeTooltip tooltip = myHint.getCurrentIdeTooltip();
short position = tooltip != null
? toShort(tooltip.getPreferredPosition())
: HintManager.UNDER;
Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating, offset, true, position);
HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
}
}
else {
context.removeHint();
}
}
@HintManager.PositionFlags
private static short toShort(Position position) {
switch (position) {
case above:
return HintManager.ABOVE;
case atLeft:
return HintManager.LEFT;
case atRight:
return HintManager.RIGHT;
default:
return HintManager.UNDER;
}
}
public static boolean hasPrevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
return controller != null && controller.getPrevOrNextParameterOffset(isNext) != -1;
}
public static void prevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
int newOffset = controller != null ? controller.getPrevOrNextParameterOffset(isNext) : -1;
if (newOffset != -1) {
controller.moveToParameterAtOffset(newOffset);
}
}
private void moveToParameterAtOffset(int offset) {
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argsList = findArgumentList(file, offset, -1);
if (argsList == null) return;
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
}
private int getPrevOrNextParameterOffset(boolean isNext) {
if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1;
int offset = CharArrayUtil.shiftBackward(myEditor.getDocument().getCharsSequence(), myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
int lbraceOffset = myLbraceMarker.getStartOffset();
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null;
if (argList == null) return -1;
ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler;
int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType());
if (currentParameterIndex == -1) return -1;
@SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList);
int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 :
!isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1;
return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1;
}
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){
if (file == null) return null;
ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());
if (handlers != null) {
for(ParameterInfoHandler handler:handlers) {
if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;
// please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
final E e = (E) ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
if (e != null) return e;
}
}
}
return null;
}
private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext {
private final int myOffset;
private final PsiFile myFile;
public MyUpdateParameterInfoContext(final int offset, final PsiFile file) {
myOffset = offset;
myFile = file;
}
@Override
public int getParameterListStart() {
return myLbraceMarker.getStartOffset();
}
@Override
public int getOffset() {
return myOffset;
}
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myFile;
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
@Override
public void removeHint() {
myHint.hide();
Disposer.dispose(ParameterInfoController.this);
}
@Override
public void setParameterOwner(final PsiElement o) {
myComponent.setParameterOwner(o);
}
@Override
public PsiElement getParameterOwner() {
return myComponent.getParameterOwner();
}
@Override
public void setHighlightedParameter(final Object method) {
myComponent.setHighlightedParameter(method);
}
@Override
public void setCurrentParameter(final int index) {
myComponent.setCurrentParameterIndex(index);
}
@Override
public boolean isUIComponentEnabled(int index) {
return myComponent.isEnabled(index);
}
@Override
public void setUIComponentEnabled(int index, boolean enabled) {
myComponent.setEnabled(index, enabled);
}
@Override
public Object[] getObjectsToView() {
return myComponent.getObjects();
}
}
}
| PY-9516 Wrong current parameter info popup position with caret on indented line
| platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java | PY-9516 Wrong current parameter info popup position with caret on indented line | <ide><path>latform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java
<ide> short position = tooltip != null
<ide> ? toShort(tooltip.getPreferredPosition())
<ide> : HintManager.UNDER;
<del> Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating, offset, true, position);
<add> Pair<Point, Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating,
<add> myEditor.getCaretModel().getOffset(), true, position);
<ide> HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
<ide> }
<ide> } |
|
JavaScript | mit | 836cee3094a9f1c803a258b68d771c0e846b31cf | 0 | ColorfulCakeChen/query-submit-canvas,ColorfulCakeChen/query-submit-canvas | export { Params, Base };
import * as ValueMax from "../ValueMax.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as ParamDesc from "../Unpacker/ParamDesc.js";
import * as Weights from "../Unpacker/Weights.js";
import * as ReturnOrClone from "./ReturnOrClone.js";
import * as Pointwise from "./Pointwise.js";
import * as Depthwise from "./Depthwise.js";
import * as AddTwoTensors from "./AddTwoTensors.js";
import * as ConcatAlongAxisId2 from "./ConcatAlongAxisId2.js";
import * as ConcatShuffleSplit from "./ConcatShuffleSplit.js";
import * as TensorOpCounter from "./TensorOpCounter.js";
//!!! ...unfinished... (2021/08/18)
// tf.batchNorm() is faster than tf.add() when with broadcasting by CPU.
// Whether batchNorm could be used as bias? even activation function?
//
/**
* Pointwise-depthwise-pointwise convolution layer parameters.
*/
class Params extends Weights.Params {
/**
* If a parameter's value is null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {Float32Array} inputFloat32Array
* A Float32Array whose values will be interpreted as weights.
*
* @param {number} byteOffsetBegin
* The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
* (not to the inputFloat32Array.byteOffset).
*
* @param {number} channelCount0_pointwise1Before
* The channel count of apply_and_destroy_or_keep()'s first input image (i.e. inputTensors[ 0 ]). If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* @param {number} channelCount1_pointwise1Before
* The channel count of apply_and_destroy_or_keep()'s second input image (i.e. inputTensors[ 1 ]). If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_TWO_DEPTHWISE (-2): The inputTensors[ 1 ] will not be used at
* all (will be ignored completel). The inputTensors[ 0 ] will be processed by two pathes: one is by pointwise1 and one
* depthwise operation, the other is by another depthwise operation (without pointwise1). These two depthwise operations will
* have the same configurations (i.e. same depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad,
* bDepthwiseBias, depthwiseActivationId) but have different (filter and bias) weights. The two depthwise results will be
* concatenated. The concatenated result will be processed by pointwise2 convolution. This is the only one case which there
* will be second depthwise.
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_ADD_TO_OUTPUT (-1): The inputTensors[ 1 ] will not be used at
* all (will be ignored completely). The inputTensors[ 0 ] will be processed by pointwise1, one depthwise operation, and
* pointwise2 convolution. Finally, the inputTensors[ 0 ] will be added to the result of pointwise2. This is the only one case
* which will do add-input-to-output.
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT (0): The inputTensors[ 1 ] will not be used at all (will be
* ignored completely). The inputTensors[ 0 ] will be processed by pointwise1, one depthwise operation, and pointwise2 convolution.
*
* - ( channelCount1_pointwise1Before > 0 ): TWO_INPUTS: It should be the channel count of inputTensors[ 1 ]. The inputTensors[ 1 ]
* will not be processed by any pointwise1 and depthwise operation.
*
//!!! ...unfinished... (2021/08/19) Perhaps, combine channelCount1_pointwise1Before and pointwise21ChannelCount,
// since they should be the same in many cases.
* - If ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT ),
* (-2), input1 will be concatenated with the result of pointwise21 operation of input0. The concatenated
* result will be channel-shuffled and splitted into [ output0, output1 ].
* - The input1's channel count (i.e. channelCount1_pointwise1Before) must be the same as pointwise21 (i.e. pointwise21ChannelCount).
* - The output0 and output1 will have the same channel count as pointwise21 (i.e. pointwise21ChannelCount).
*
* - If ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__CONCAT_POINTWISE21_INPUT1 ),
* (-1), input1 will be concatenated with the result of pointwise21 operation of input0. The concatenated
* result will become output0.
* - The input1's channel count (i.e. channelCount1_pointwise1Before) could be any value (i.e. needs not be pointwise21ChannelCount).
* - The output0 will have channel count as ( pointwise21ChannelCount + channelCount1_pointwise1Before ).
*
* - If ( pointwise22ChannelCount >= 0 ), input1 will be concatenated with the result of depthwise operation
* of input0. The concatenated result will be processed by pointwise2 convolution.
* - The input1's channel count (i.e. channelCount1_pointwise1Before) could be any value (i.e. needs not be pointwise21ChannelCount).
* - The output0 will be the result of pointwise21.
* - The output1 will be the result of pointwise22.
*
*
//!!! ...unfinished... (2021/07/27)
// Perhaps, ( channelCount1_pointwise1Before == -3 ): ONE_INPUT_TWO_DEPTHWISE_ONE_MAX_POOLING
//
// A max pooling will be used as a branch of input0. The max pooling result of input0 should be concatenated with the
// two depthwise convolutions' result of input0. The reason is that max pooling could provide information which is difficult achieved
// by a depthwise convolution. (Thinks that for a while: how to calculate maximum value by linear combination (i.e. add-multiply).)
* @param {number} pointwise1ChannelCount
* The output channel count of the pointwise1 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If 0, there will be no pointwise convolution before depthwise convolution.
*
* @param {boolean} bPointwise1Bias
* If true, there will be a bias after pointwise1 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( pointwise1ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise1ActivationId
* The activation function id (Params.pointwise1ActivationId.valueDesc.Ids.Xxx) after the pointwise1 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise1ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {number} depthwise_AvgMax_Or_ChannelMultiplier
* Depthwise operation. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If non-null, it should be
* integer between [ -2, 32 ]:
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.AVG (-2): average pooling.
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.MAX (-1): max pooling.
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.NONE (0): there will be no depthwise operation.
* - positive integer between [ 1, 32 ]: depthwise convolution and the number indicates channel multiplier.
*
* @param {number} depthwiseFilterHeight
* The height (and width) of depthwise convolution's filter. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this will also be ignored.
*
* @param {number} depthwiseStridesPad
* The strides and padding of depthwise convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this depthwiseStridesPad will also be ignored. It has three possible value:
* - 0: means ( depthwiseStrides == 1 ) and ( depthwisePad == "valid" )
* - 1: means ( depthwiseStrides == 1 ) and ( depthwisePad == "same" )
* - 2: means ( depthwiseStrides == 2 ) and ( depthwisePad == "same" )
* Default is 1 because ( depthwiseStrides == 1 ) and ( depthwisePad == "same" ) is a pre-condition for ( bAddInputToOutputRequested == true ).
*
* @param {boolean} bDepthwiseBias
* If null, it will be extracted from inputFloat32Array (i.e. by evolution). If true, there will be a bias after depthwise convolution.
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this bias will also be ignored.
*
* @param {number} depthwiseActivationId
* The activation function id (Params.depthwiseActivationId.valueDesc.Ids.Xxx) after depthwise convolution. If null, it will be
* extracted from inputFloat32Array (i.e. by evolution). If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this activation function
* will also be ignored.
*
* @param {number} pointwise21ChannelCount
* The output channel count of the first pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), there will be no pointwise convolution after depthwise convolution.
*
* @param {boolean} bPointwise21Bias
* If true, there will be a bias after the first pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise21ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise21ActivationId
* The activation function id (Params.pointwise21ActivationId.valueDesc.Ids.Xxx) after the first pointwise1 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise21ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {number} pointwise22ChannelCount
* The output channel count of the second pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), there will be no pointwise convolution
* after depthwise convolution. The pointwise22 convolution could achieve some kinds of channel shuffling of ShuffleNetV2. Please
* see channelCount1_pointwise1Before explanation.
*
* @param {boolean} bPointwise22Bias
* If true, there will be a bias after the second pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise22ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise21ActivationId
* The activation function id (Params.pointwise22ActivationId.valueDesc.Ids.Xxx) after the second pointwise2 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise22ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {boolean} bKeepInputTensor
* If true, apply_and_destroy_or_keep() will not dispose inputTensor (i.e. keep). For example, for the branch of step 0 of ShuffleNetV2.
* For another example, the input image should be shared across many neural networks. If it is null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
*
*/
constructor( inputFloat32Array, byteOffsetBegin,
channelCount0_pointwise1Before,
channelCount1_pointwise1Before,
pointwise1ChannelCount, bPointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, bDepthwiseBias, depthwiseActivationId,
pointwise21ChannelCount, bPointwise21Bias, pointwise21ActivationId,
pointwise22ChannelCount, bPointwise22Bias, pointwise22ActivationId,
bKeepInputTensor
) {
//!!! ...unfinished...
// squeeze-and-excitation ?
let parameterMap = new Map( [
[ Params.channelCount0_pointwise1Before, channelCount0_pointwise1Before ],
[ Params.channelCount1_pointwise1Before, channelCount1_pointwise1Before ],
[ Params.pointwise1ChannelCount, pointwise1ChannelCount ],
[ Params.bPointwise1Bias, bPointwise1Bias ],
[ Params.pointwise1ActivationId, pointwise1ActivationId ],
[ Params.depthwise_AvgMax_Or_ChannelMultiplier, depthwise_AvgMax_Or_ChannelMultiplier ],
[ Params.depthwiseFilterHeight, depthwiseFilterHeight ],
[ Params.depthwiseStridesPad, depthwiseStridesPad ],
[ Params.bDepthwiseBias, bDepthwiseBias ],
[ Params.depthwiseActivationId, depthwiseActivationId ],
[ Params.pointwise21ChannelCount, pointwise21ChannelCount ],
[ Params.bPointwise21Bias, bPointwise21Bias ],
[ Params.pointwise21ActivationId, pointwise21ActivationId ],
[ Params.pointwise22ChannelCount, pointwise22ChannelCount ],
[ Params.bPointwise22Bias, bPointwise22Bias ],
[ Params.pointwise22ActivationId, pointwise22ActivationId ],
[ Params.bKeepInputTensor, bKeepInputTensor ],
] );
return super( inputFloat32Array, byteOffsetBegin, parameterMap );
}
/**
* Extract parameters from inputFloat32Array.
*
* @return {boolean} Return false, if extraction failed.
*
* @override
*/
extract() {
let bExtractOk = super.extract();
if ( !bExtractOk )
return false;
// Determine input tensor count and whether request add-input-to-output.
Params.setFlags_by__channelCount1_pointwise1Before__pointwise22ChannelCount.call(
this, this.channelCount1_pointwise1Before, this.pointwise22ChannelCount );
return bExtractOk;
}
/**
* Determine the following properties:
* - this.inputTensorCount
* - this.bDepthwise2Requested
* - this.bConcat1Requested
* - this.bAddInputToOutputRequested
* - this.bConcat2ShuffleSplitRequested
* - this.outputTensorCount
*
* @param {number} channelCount1_pointwise1Before
* @param {number} pointwise22ChannelCount
*/
static setFlags_by__channelCount1_pointwise1Before__pointwise22ChannelCount(
channelCount1_pointwise1Before, pointwise22ChannelCount ) {
// 1.
if ( channelCount1_pointwise1Before <= 0 ) {
this.inputTensorCount = 1; // One input.
this.bConcat2ShuffleSplitRequested = false; // One input never uses concat2-shuffle-split.
if ( pointwise22ChannelCount > 0 ) // One input's output count is determined by pointwise22ChannelCount totally.
this.outputTensorCount = 2;
else
this.outputTensorCount = 1;
switch ( channelCount1_pointwise1Before ) {
// 1.1
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT: // ( 0)
this.bDepthwise2Requested = this.bConcat1Requested = false; this.bAddInputToOutputRequested = false; break;
// 1.2 The only case uses add-input-to-output. (MobileNetV2)
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT_ADD_TO_OUTPUT: // (-1)
this.bDepthwise2Requested = this.bConcat1Requested = false; this.bAddInputToOutputRequested = true; break;
// 1.3 The only case uses depthwise2. (ShuffleNetV2's head)
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT_TWO_DEPTHWISE: // (-2)
this.bDepthwise2Requested = this.bConcat1Requested = true; this.bAddInputToOutputRequested = false; break;
}
} else { // 2. ( channelCount1_pointwise1Before > 0 ) (i.e. ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.TWO_INPUTS_XXX)
this.inputTensorCount = 2; // Two inputs.
this.bDepthwise2Requested = false; // Two inputs never use depthwise2.
this.bAddInputToOutputRequested = false; // Two inputs never do add-input-to-output. (It always use concatenation.)
if ( pointwise22ChannelCount > 0 ) { // 2.1 Two-inputs-two-outputs: by concat1. (slower ShuffleNetV2's body)
this.bConcat1Requested = true; this.bConcat2ShuffleSplitRequested = false; this.outputTensorCount = 2;
} else {
switch ( pointwise22ChannelCount ) {
// 2.2 Two-inputs-one-output: by concat1. (slower ShuffleNetV2's tail)
case ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__POINTWISE21: // ( 0)
this.bConcat1Requested = true; this.bConcat2ShuffleSplitRequested = false; this.outputTensorCount = 1; break;
// 2.3 Two-inputs-one-output: by concat2(-shuffle-split). (ShuffleNetV2's tail)
case ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__CONCAT_POINTWISE21_INPUT1: // (-1)
this.bConcat1Requested = false; this.bConcat2ShuffleSplitRequested = true; this.outputTensorCount = 1; break;
// 2.4 Two-inputs-two-outputs: by concat2-shuffle-split. (ShuffleNetV2's body)
case ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT: // (-2)
this.bConcat1Requested = false; this.bConcat2ShuffleSplitRequested = true; this.outputTensorCount = 2; break;
}
}
}
}
get channelCount0_pointwise1Before() { return this.parameterMapModified.get( Params.channelCount0_pointwise1Before ); }
/** @return {number} The number version of channelCount1_pointwise1Before. */
get channelCount1_pointwise1Before() { return this.parameterMapModified.get( Params.channelCount1_pointwise1Before ); }
/** @return {string} The string version of channelCount1_pointwise1Before. */
get channelCount1_pointwise1Before_Name() {
return Params.channelCount1_pointwise1Before.getStringOfValue( this.channelCount1_pointwise1Before );
}
get pointwise1ChannelCount() { return this.parameterMapModified.get( Params.pointwise1ChannelCount ); }
get bPointwise1Bias() { return this.parameterMapModified.get( Params.bPointwise1Bias ); }
get pointwise1ActivationId() { return this.parameterMapModified.get( Params.pointwise1ActivationId ); }
get pointwise1ActivationName() { return Params.pointwise1ActivationId.getStringOfValue( this.pointwise1ActivationId ); }
/** @return {number} The number version of the depthwise opertion. */
get depthwise_AvgMax_Or_ChannelMultiplier() { return this.parameterMapModified.get( Params.depthwise_AvgMax_Or_ChannelMultiplier ); }
/** @return {string} The string version of the depthwise opertion. */
get depthwise_AvgMax_Or_ChannelMultiplier_Name() {
return Params.depthwise_AvgMax_Or_ChannelMultiplier.getStringOfValue( this.depthwise_AvgMax_Or_ChannelMultiplier );
}
get depthwiseFilterHeight() { return this.parameterMapModified.get( Params.depthwiseFilterHeight ); }
get depthwiseStridesPad() { return this.parameterMapModified.get( Params.depthwiseStridesPad ); }
get bDepthwiseBias() { return this.parameterMapModified.get( Params.bDepthwiseBias ); }
get depthwiseActivationId() { return this.parameterMapModified.get( Params.depthwiseActivationId ); }
get depthwiseActivationName() { return Params.depthwiseActivationId.getStringOfValue( this.depthwiseActivationId ); }
get pointwise21ChannelCount() { return this.parameterMapModified.get( Params.pointwise21ChannelCount ); }
get bPointwise21Bias() { return this.parameterMapModified.get( Params.bPointwise21Bias ); }
get pointwise21ActivationId() { return this.parameterMapModified.get( Params.pointwise21ActivationId ); }
get pointwise21ActivationName() { return Params.pointwise21ActivationId.getStringOfValue( this.pointwise21ActivationId ); }
get pointwise22ChannelCount() { return this.parameterMapModified.get( Params.pointwise22ChannelCount ); }
/** @return {string} The string version of pointwise22ChannelCount. */
get pointwise22ChannelCountName() {
return Params.pointwise21ChannelCount.getStringOfValue( this.pointwise21ChannelCount );
}
get bPointwise22Bias() { return this.parameterMapModified.get( Params.bPointwise22Bias ); }
get pointwise22ActivationId() { return this.parameterMapModified.get( Params.pointwise22ActivationId ); }
get pointwise22ActivationName() { return Params.pointwise22ActivationId.getStringOfValue( this.pointwise22ActivationId ); }
get bKeepInputTensor() { return this.parameterMapModified.get( Params.bKeepInputTensor ); }
}
// Define parameter descriptions.
/** At least, there should be 1 input channel. */
Params.channelCount0_pointwise1Before = new ParamDesc.Int( "channelCount0_pointwise1Before", 1, ( 10 * 1024 ) );
Params.channelCount1_pointwise1Before = new ParamDesc.channelCount1_pointwise1Before( "channelCount1_pointwise1Before" );
Params.pointwise1ChannelCount = new ParamDesc.Int( "pointwise1ChannelCount", 0, ( 10 * 1024 ) );
Params.bPointwise1Bias = new ParamDesc.Bool( "bPointwise1Bias" );
Params.pointwise1ActivationId = new ParamDesc.ActivationFunction( "pointwise1ActivationId" );
/** Define depthwise operation's id, range, name.
*
* Convert number value into integer between [ -2, 32 ] representing depthwise operation:
* - -1: average pooling. (AVG)
* - -2: maximum pooling. (MAX)
* - 0: no depthwise operation. (NONE)
* - [ 1, 32 ]: depthwise convolution with channel multiplier between 1 and 32 (inclusive).
*/
Params.depthwise_AvgMax_Or_ChannelMultiplier = new ParamDesc.AvgMax_Or_ChannelMultiplier( "depthwise_AvgMax_Or_ChannelMultiplier" );
/** Define suitable value for depthwise convolution filter size.
*
* At least 1, because depthwise filter size ( 0 * 0 ) is meaningless.
*
* For avg pooling or max pooling, it is less meaningful if filter size is ( 1 * 1 ) because the result will be the same as input.
* For depthwise convolution, it is meaningful if filter size is ( 1 * 1 ) because they could be used as simple channel multiplier.
*
* Avoid too large filter size. Otherwise, performance may be poor.
*/
Params.depthwiseFilterHeight = new ParamDesc.Int( "depthwiseFilterHeight", 1, 9 );
/** Define suitable value for depthwise convolution strides and pad. Integer between [ 0, 2 ]. */
Params.depthwiseStridesPad = new ParamDesc.Int( "depthwiseStridesPad", 0, 2 );
Params.bDepthwiseBias = new ParamDesc.Bool( "bDepthwiseBias" );
Params.depthwiseActivationId = new ParamDesc.ActivationFunction( "depthwiseActivationId" );
Params.pointwise21ChannelCount = new ParamDesc.Int( "pointwise21ChannelCount", 0, ( 10 * 1024 ) );
Params.bPointwise21Bias = new ParamDesc.Bool( "bPointwise21Bias" );
Params.pointwise21ActivationId = new ParamDesc.ActivationFunction( "pointwise21ActivationId" );
Params.pointwise22ChannelCount = new ParamDesc.pointwise22ChannelCount( "pointwise22ChannelCount" );
Params.bPointwise22Bias = new ParamDesc.Bool( "bPointwise22Bias" );
Params.pointwise22ActivationId = new ParamDesc.ActivationFunction( "pointwise22ActivationId" );
Params.bKeepInputTensor = new ParamDesc.Bool( "bKeepInputTensor" );
/**
* One step of one block of convolution neural network. There are at most three convolutions inside this object.
* - 1x1 pointwise convolution: change channel count. (exapnd)
* - NxN depthwise convolution: change channel count. (channel multiplier)
* - 1x1 pointwise convolution: change channel count. (shrink)
*
* Every convolution (no matter pointwise or depthwise) could exist or not exist. If exists, it could have or have no bias and
* activation function.
*
*
* There six main combinations:
*
* - When ( channelCount1_pointwise1Before == -2 ): ONE_INPUT_TWO_DEPTHWISE: (our adjusted ShuffleNetV2's head)
* <pre>
* input0 - pointwise1 - depthwise1 - concat1 - pointwise21
* \------------- depthwise2 / \ pointwise22
* </pre>
*
*
* - When ( channelCount1_pointwise1Before == -1 ): ONE_INPUT_ADD_TO_OUTPUT: (MobileNetV2)
* <pre>
* /------------------------------------------------------\
* input0 - pointwise1 - depthwise1 ---------------- pointwise21 - addInput0ToPointwise21
* \ \ pointwise22 - addInput0ToPointwise22
* \-----------------------------------------------------/
* </pre>
*
*
* - When ( channelCount1_pointwise1Before == 0 ): ONE_INPUT: (MobileNetV1)
* <pre>
* input0 - pointwise1 - depthwise1 ---------------- pointwise21
* \ pointwise22
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount == -2 ): TWO_INPUTS: TWO_OUTPUT: (ShuffleNetV2's body)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2ShuffleSplit - output0
* input1 ----------------------------------------/ \ output1
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount == -1 ): TWO_INPUTS: ONE_OUTPUT: (ShuffleNetV2's tail)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2(ShuffleSplit) - output0
* input1 ----------------------------------------/
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount >= 0 ): TWO_INPUTS: (slower ShuffleNetV2's body and tail)
* <pre>
* input0 - pointwise1 - depthwise1 - concat1 - pointwise21
* input1 --------------------------/ \ pointwise22
* </pre>
*
*
*
* Strictly speaking, the real (original) ShuffleNetV2 is more like the following:
*
* (original ShuffleNetV2's head)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2 - channelShuffler
* \------------- depthwise2 - pointwise22 /
* </pre>
*
* (original ShuffleNetV2's tail)
* <pre>
* input0 - channelSplitter - pointwise1 - depthwise1 - pointwise21 - concat2 - channelShuffler
* \---------------------------------------/
* </pre>
*
* The channelShuffler of original ShuffleNetV2 is achieved by tf.reshape() operation. According to experiments, however, the
* channelShuffler could be acheived by pointwise convolution more efficiently (than reshape). This results in our simplified
* ShuffleNetV2 structure: replacing pointwise-concat-shuffle-split with concat-pointwise. It should be more efficient because
* less operations are used than original structure.
*
*
*
*
* @member {boolean} bInitOk
* If true, this object initialized (i.e. initer()) successfully.
*
* @member {number} byteOffsetBegin
* The position which is started (inclusive) to extract from inputFloat32Array.buffer by initer().
*
* @member {number} byteOffsetEnd
* The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by initer(). Where to extract next weights.
* Only meaningful when ( this.bInitOk == true ).
*
* @member {number} inputTensorCount
* How many input tensors will be past into apply_and_destroy_or_keep() as parameter inputTensors[].
*
* @member {boolean} bDepthwise2Requested
* It will be true only when ( channelCount1_pointwise1Before == -2 ). If true, it means a second depthwise might be needed.
*
* @member {boolean} bConcat1Requested
* If true, the concat1 (after depthwise and before pointwise2) is needed.
*
* @member {boolean} bConcat2ShuffleSplitRequested
* If true, the concat2 (after pointwise2) is needed. It may or may not follow channel shuffling and splitting.
*
* @member {boolean} bAddInputToOutputRequested
* It will be true when ( this.channelCount1_pointwise1Before == -1 ). The input (in this case, the main input (i.e. inputTensorArray[ 0 ])
* will be added to the output for achieving skip connection.
*
* @member {number} outputTensorCount
* How many output tensors will be returned by the parameter outputTensors of apply_and_destroy_or_keep(). At least 1. At most 2. It is
* determined by channelCount1_pointwise1Before and pointwise22ChannelCount.
*
* @member {string} pointwise22ChannelCountName
* The string version of pointwise22ChannelCount. Useful for negative value.
*
* @member {boolean} bPointwise1
* If true, the pointwise1 convolution exists.
*
* @member {string} pointwise1ActivationName
* The activation function id (Params.pointwise1ActivationId.valueDesc.Ids.Xxx) after the first pointwise convolution.
*
* @member {boolean} bDepthwise1
* If true, the first depthwise convolution (or average pooling, or maximum pooling) exists.
*
* @member {boolean} bDepthwise2
* If true, the second depthwise convolution (or average pooling, or maximum pooling) exists.
*
* @member {string} depthwise_AvgMax_Or_ChannelMultiplier_Name
* Depthwise operation name.
*
* @member {string} depthwiseActivationName
* The activation function name (Params.depthwiseActivationId.valueDesc.Ids.Xxx) after depthwise convolution.
*
* @member {boolean} bPointwise2
* If true, the pointwise2 (i.e. pointwise21 or/and pointwise22) convolution exists.
*
* @member {boolean} bPointwise21
* If true, the first pointwise2 convolution exists.
*
* @member {boolean} bPointwise22
* If true, the second pointwise2 convolution exists.
*
* @member {string} pointwise21ActivationName
* The activation function id (Params.pointwise21ActivationId.valueDesc.Ids.Xxx) after the first pointwise2 convolution.
*
* @member {string} pointwise22ActivationName
* The activation function id (Params.pointwise22ActivationId.valueDesc.Ids.Xxx) after the second pointwise2 convolution.
*
* @member {number} inChannels0
* The channel count of the first input tensor (i.e. inputTensors[ 0 ]). This is the same as this.channelCount0_pointwise1Before (from initer()).
*
* @member {number} inChannels1
* The channel count of the second input tensor (i.e. inputTensors[ 1 ]). This is the same as this.channelCount1_pointwise1Before (from initer()).
*
* @member {number} outChannels0
* The channel count of the outputTensor[ 0 ]. Even if ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ),
* this will still be non-zero.
*
* @member {number} outChannels1
* The channel count of the outputTensor[ 1 ]. If ( pointwise22ChannelCount == 0 ), this will be zero.
*
* @member {number} outChannels
* The channel count of all output tensors (i.e. both outputTensor[ 0 ] and outputTensor[ 1 ]).
*
* @member {number} channelCount_pointwise1After_depthwise1Before
* The channel count after the first 1x1 pointwise convolution. If ( pointwise1ChannelCount > 0 ), it equals pointwise1ChannelCount.
* If ( pointwise1ChannelCount == 0 ), it equals inChannels0.
*
* @member {number} channelCount_depthwise1After_concat1Before
* The channel count after the first depthwise convolution which applies to the result of pointwise1.
* - If depthwise1 exists, it will be the channel count of depthwise1's output.
* - When ( depthwise_AvgMax_Or_ChannelMultiplier >= 1 ), it equals
* ( channelCount_pointwise1After_depthwise1Before * depthwise_AvgMax_Or_ChannelMultiplier ).
* - When ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.AVG ) (i.e. -2)
* or ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.MAX ) (i.e. -1)
* or ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.NONE ) (i.e. 0),
* it equals channelCount_pointwise1After_depthwise1Before.
* - If depthwise1 does not exist, it will be the channel count of previous operation (i.e. pointwise1)
* which is channelCount_pointwise1After_depthwise1Before.
*
* @member {number} channelCount_depthwise2After_concat1Before
* The channel count after the second depthwise convolution which applies to input0 or input1. If depthwise2 does not exist,
* this will be the same as Math.max( 0, channelCount1_pointwise1Before ) (i.e. the depthwise2 will be viewed as short circuit
* to input1).
*
* @member {number} channelCount_concat1After_pointwise2Before
* The channel count before pointwise2. It is may be the concatenated result of input0 (with depthwise1, with/without depthwise2)
* with/without input1 (without depthwise2).
*
* @member {number} channelCount_pointwise21After_concat2Before
* The channel count after the pointwise21 convolution. If ( pointwise21ChannelCount > 0 ), it equals pointwise21ChannelCount.
* If ( pointwise21ChannelCount == 0 ), it will be 0.
*
* @member {number} channelCount_pointwise22After_concat2Before
* The channel count after the pointwise22 convolution. If ( pointwise22ChannelCount > 0 ), it equals pointwise22ChannelCount.
* If ( pointwise22ChannelCount == 0 ), it will be 0.
*
* @member {number} channelCount_pointwise2After_concat2Before
* The channel count after all pointwise2 convolution.
*
* - Basically, it will be ( channelCount_pointwise21After_concat2Before + channelCount_pointwise22After_concat2Before )
* if at least one pointwise2 convolution existed.
*
* - If both ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), it will be channelCount_concat1After_pointwise2Before.
*
* @member {ChannelShuffler.ConcatPointwiseConv} channelShuffler_ConcatPointwiseConv
* The channelShuffler. It must be implemented by ChannelShuffler.ConcatPointwiseConv with ( outputGroupCount == 2 ).
*
* - It will not be disposed by this object (i.e. it is supposed to be shared with outter callers).
*
* - The channelShuffler's outputGroupCount must be 2 (i.e. split into two groups after channel-shuffling).
*
* - It is only used when ( channelCount1_pointwise1Before > 1 ) (i.e. TWO_INPUTS) and
* ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT )
* (-2) (i.e. channel shuffle the concatenated pointwise21 and input1).
*
* - The channelShuffler.shuffleInfo.totalChannelCount should be the same as the channel count of the concatenation
* of pointwise21 and input1.
*
* @member {function} apply_and_destroy_or_keep
* This is a method. It has two parameters inputTensors and outputTensors. The inputTensors (tf.tensor3d[]) represents the images
* ( height x width x channel ) which will be processed. The outputTensors (tf.tensor3d[]) will be placed one or two tf.tensor3d as
* the result. All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls
* one of apply_X_Y_and_destroy_or_keep_ConcatInput0Depthwise2(), apply_X_Y_and_destroy_AddInputToOutput(),
* apply_X_Y_and_destroy_or_keep_NoSkipConnection(), apply_X_Y_and_destroy_or_keep_ConcatInput1(),
* return_input_directly_array(), keep_input_return_copy_array() according to the initer()'s parameters.
*/
class Base extends ReturnOrClone.Base {
/**
* Generator for initializing this object.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The created progressToAdvance will be
* increased when every time advanced. The progressParent.getRoot() will be returned when every time yield.
*
* @param {Params} params
* A Params object. The params.extract() will be called to extract parameters.
*
* @yield {ValueMax.Percentage.Aggregate}
* Yield ( value = progressParent.getRoot() ) when ( done = false ).
*
* @yield {boolean}
* Yield ( value = true ) when ( done = true ) successfully.
* Yield ( value = false ) when ( done = true ) failed.
*/
* initer( progressParent, params, channelShuffler_ConcatPointwiseConv ) {
// 0. Prepare
// Estimate the maximum value of progress.
let progressMax =
1 // for extracting parameters from inputFloat32Array.
+ 1 // for extracting pointwise1 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting depthwise filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for concat1.
+ 1 // for extracting pointwise2 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for add-input-to-output.
+ 1 // for concat2-shuffle-split.
+ 1 // for all pointwise1-depthwise-pointwise2 filters (and biases) ready.
;
let progressRoot = progressParent.getRoot();
let progressToAdvance = progressParent.addChild( new ValueMax.Percentage.Concrete( progressMax ) );
this.disposeTensors(); // Also initialize some member function pointers to no_operation().
this.channelShuffler_ConcatPointwiseConv = channelShuffler_ConcatPointwiseConv;
// 1. Extract parameters.
if ( !params )
return false;
this.byteOffsetEnd = this.byteOffsetBegin = params.defaultByteOffsetBegin;
if ( !params.extract() )
return false; // e.g. input array does not have enough data.
// Record where to extract next weights. Only meaningful when ( this.bInitOk == true ).
this.byteOffsetEnd = params.defaultByteOffsetEnd;
// Get parameters' real (adjusted) values.
//
// Do not keep params in this.params so that the inputFloat32Array could be released.
this.channelCount0_pointwise1Before = params.channelCount0_pointwise1Before;
this.channelCount1_pointwise1Before = params.channelCount1_pointwise1Before;
this.channelCount1_pointwise1Before_Name = params.channelCount1_pointwise1Before_Name;
this.pointwise1ChannelCount = params.pointwise1ChannelCount;
this.bPointwise1Bias = params.bPointwise1Bias;
this.pointwise1ActivationId = params.pointwise1ActivationId;
this.pointwise1ActivationName = params.pointwise1ActivationName;
this.depthwise_AvgMax_Or_ChannelMultiplier = params.depthwise_AvgMax_Or_ChannelMultiplier;
this.depthwise_AvgMax_Or_ChannelMultiplier_Name = params.depthwise_AvgMax_Or_ChannelMultiplier_Name;
this.depthwiseFilterHeight = params.depthwiseFilterHeight;
this.depthwiseStridesPad = params.depthwiseStridesPad;
this.bDepthwiseBias = params.bDepthwiseBias;
this.depthwiseActivationId = params.depthwiseActivationId;
this.depthwiseActivationName = params.depthwiseActivationName;
this.pointwise21ChannelCount = params.pointwise21ChannelCount;
this.bPointwise21Bias = params.bPointwise21Bias;
this.pointwise21ActivationId = params.pointwise21ActivationId;
this.pointwise21ActivationName = params.pointwise21ActivationName;
this.pointwise22ChannelCount = params.pointwise22ChannelCount;
this.pointwise22ChannelCountName = params.pointwise22ChannelCountName;
this.bPointwise22Bias = params.bPointwise22Bias;
this.pointwise22ActivationId = params.pointwise22ActivationId;
this.pointwise22ActivationName = params.pointwise22ActivationName;
this.bKeepInputTensor = params.bKeepInputTensor;
// The parameters which are determined (inferenced) from the above parameters.
this.inputTensorCount = params.inputTensorCount;
this.bDepthwise2Requested = params.bDepthwise2Requested;
this.bConcat1Requested = params.bConcat1Requested;
this.bAddInputToOutputRequested = params.bAddInputToOutputRequested;
this.bConcat2ShuffleSplitRequested = params.bConcat2ShuffleSplitRequested;
this.outputTensorCount = params.outputTensorCount;
this.intermediateTensorsArray = new Array( 2 ); // Pre-allocate array to place intermediate 2 tensors. This could reduce memory re-allocation.
++progressToAdvance.value;
yield progressRoot; // Parameters extracted. Report progress.
// For analyzing every tensor processed by how many operations. These will be used to determine whether
// the operation should dispose its input tensor.
let TensorOpCounterId = -1;
let TensorOpCounters = {
input0: new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_input0", null, null ),
input1: new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_input1", null, null ),
};
// 2. The first 1x1 pointwise convolution.
this.pointwise1 = new Pointwise.Base(
this.channelCount0_pointwise1Before,
this.pointwise1ChannelCount, this.bPointwise1Bias, this.pointwise1ActivationId );
if ( !this.pointwise1.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise1.byteOffsetEnd;
this.bPointwise1 = this.pointwise1.bExisted;
if ( this.bPointwise1 ) {
this.channelCount_pointwise1After_depthwise1Before = this.pointwise1.outputChannelCount;
TensorOpCounters.pointwise1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise1", this.pointwise1, TensorOpCounters.input0 );
} else {
this.channelCount_pointwise1After_depthwise1Before = this.channelCount0_pointwise1Before; // No pointwise1 convolution.
TensorOpCounters.pointwise1 = TensorOpCounters.input0; // Its output is just its input tensor.
}
++progressToAdvance.value;
yield progressRoot; // pointwise1 filters was ready. Report progress.
// 3. The depthwise operation.
//
// Note: When ( pad == valid ), it seems that depthwise (avg/max pooling) filter size can not greater than input image size.
// 3.1 The first depthwise operation.
this.depthwise1 = new Depthwise.Base(
this.channelCount_pointwise1After_depthwise1Before,
this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight,
this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId );
if ( !this.depthwise1.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.depthwise1.byteOffsetEnd;
this.bDepthwise1 = this.depthwise1.bExisted;
if ( this.bDepthwise1 ) {
this.channelCount_depthwise1After_concat1Before = this.depthwise1.outputChannelCount;
TensorOpCounters.depthwise1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_depthwise1", this.depthwise1, TensorOpCounters.pointwise1 );
} else {
this.channelCount_depthwise1After_concat1Before = this.channelCount_pointwise1After_depthwise1Before; // No depthwise1 operation.
TensorOpCounters.depthwise1 = TensorOpCounters.pointwise1; // Its output is just its input tensor.
}
// 3.2 The second depthwise operation.
this.bDepthwise2 = false;
if ( this.bDepthwise2Requested ) {
// Q: Why does depthwise2 use the same configuration as depthwise1?
// A: To ensure both result have the same ( height, width ) so that could be inputted to concatenator). This is especially
// true for StridesPad.
this.depthwise2 = new Depthwise.Base(
// The depthwise2 processes the inputTensors[ 0 ] directly (i.e. not the pointwise1 result of inputTensors[ 0 ], and
// not inputTensors[ 1 ]).
this.channelCount0_pointwise1Before,
this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight,
this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId );
if ( !this.depthwise2.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.depthwise2.byteOffsetEnd;
this.bDepthwise2 = this.depthwise2.bExisted;
if ( this.bDepthwise2 ) {
// The depthwise2 is requested and created. It means ONE_INPUT_TWO_DEPTHWISE.
this.channelCount_depthwise2After_concat1Before = this.depthwise2.outputChannelCount;
TensorOpCounters.depthwise2 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_depthwise2", this.depthwise2, TensorOpCounters.input0 );
} else {
// The depthwise2 is requested but not created. It means no depthwise operation (i.e. ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ).
// In this case, the depthwise2 should be short circuit to inputTensor[ 0 ] (i.e. not inputTensor[ 1 ]).
this.channelCount_depthwise2After_concat1Before = this.channelCount0_pointwise1Before;
TensorOpCounters.depthwise2 = TensorOpCounters.input0;
}
} else {
// Since the depthwise2 is not requested, it is always short circuit to input1 (i.e. not input0).
this.channelCount_depthwise2After_concat1Before = Math.max( 0, this.channelCount1_pointwise1Before ); // At least 0. Avoid negative.
TensorOpCounters.depthwise2 = TensorOpCounters.input1;
}
++progressToAdvance.value;
yield progressRoot; // depthwise filters was ready. Report progress.
// 4. Concat1
if ( this.bConcat1Requested ) {
this.channelCount_concat1After_pointwise2Before
= this.channelCount_depthwise1After_concat1Before + this.channelCount_depthwise2After_concat1Before;
this.concat1 = new ConcatAlongAxisId2.Base( false, false );
TensorOpCounters.concat1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_concat1",
this.concat1, TensorOpCounters.depthwise1, TensorOpCounters.depthwise2 );
} else {
this.channelCount_concat1After_pointwise2Before = this.channelCount_depthwise1After_concat1Before;
TensorOpCounters.concat1 = TensorOpCounters.depthwise1;
}
++progressToAdvance.value;
yield progressRoot; // concat1 was ready. Report progress.
// 5. The pointwise2 convolution.
// 5.1 Pointwise21
this.pointwise21 = new Pointwise.Base(
this.channelCount_concat1After_pointwise2Before,
this.pointwise21ChannelCount, this.bPointwise21Bias, this.pointwise21ActivationId );
if ( !this.pointwise21.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise21.byteOffsetEnd;
this.bPointwise21 = this.pointwise21.bExisted;
if ( this.bPointwise21 ) {
this.channelCount_pointwise21After_concat2Before = this.pointwise21ChannelCount;
} else {
this.channelCount_pointwise21After_concat2Before = 0; // No first pointwise2 convolution.
}
// 5.2 Pointwise22
this.pointwise22 = new Pointwise.Base(
this.channelCount_concat1After_pointwise2Before,
this.pointwise22ChannelCount, this.bPointwise22Bias, this.pointwise22ActivationId );
if ( !this.pointwise22.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise22.byteOffsetEnd;
this.bPointwise22 = this.pointwise22.bExisted;
if ( this.bPointwise22 ) {
this.channelCount_pointwise22After_concat2Before = this.pointwise22ChannelCount;
} else {
this.channelCount_pointwise22After_concat2Before = 0; // No second pointwise2 convolution.
}
// 5.3 Pointwise2 (= Pointwise21 + Pointwise22 )
this.bPointwise2 = ( this.bPointwise21 || this.bPointwise22 );
this.channelCount_pointwise2After_concat2Before = this.pointwise21ChannelCount + this.pointwise22ChannelCount;
if ( !this.bPointwise2 ) {
// If there is not any pointwise2 convolution, the result channel count will not be zero. It should be the channel count after
// depthwise1 operation together with the input1 channel count (if existed). And it should be at the first output tensor
// (i.e. outputTensors[ 0 ]).
this.channelCount_pointwise2After_concat2Before = this.channelCount_pointwise21After_concat2Before
= this.channelCount_concat1After_pointwise2Before;
}
//!!! ...unfinished... (2021/08/21 Remarked) outputChannelCount should already determined in the above.
// // If both pointwise21 and pointwise22 existed, the pointwise21 should keep-input-tensor.
// // Otherwise, the pointwise22 will fail to process it.
// if ( this.bPointwise21 && this.bPointwise22 ) {
// this.outputTensorCount = 2; // This is the only case which will output two tensors.
// } else {
// this.outputTensorCount = 1; // All other cases, there will be only one output tensor.
// }
// 5.4
++progressToAdvance.value;
yield progressRoot; // pointwise2 filters was ready. Report progress.
// 6. Add-input-to-output
// 6.1
//
// Although caller could request add-input-to-output, it may or may not doable.
// Only if the dimension of output is the same as the dimension of input, it is possible to add-input-to-output.
//
// Only if depthwise stride is "1" and pad is "same" (or pad is "valid" but filter size 1x1), the dimension 0 (height)
// and 1 (width) of the output will be the same as input.
//
// Only if output channel is equals to input channel, the dimension 2 (channel) of the output will be the same as input.
//
// For example:
// - if MobileNetV2 and not step 0, should not destroy input tensor so that can add input to output.
// - However, even if MobileNetV2, only if not setp 0 (whose strides == 2) of a block can add input to output.
if ( ( this.bAddInputToOutputRequested ) && ( this.depthwise1.is_Output_Same_HeightWidth_As_Input() ) ) {
// Note:
//
// Usually, if no pointwise21, then no addInput0ToPointwise21.
// Usually, if no pointwise22, then no addInput0ToPointwise22.
//
// However, there is one exception: When both no pointwise21 and no pointwise22, there might be addInput0ToPointwise21
// if channelCount_concat1After_pointwise2Before (which is already assigned to channelCount_pointwise21After_concat2Before in this case)
// has the same dimension as inputTensors[ 0 ].
if ( this.channelCount0_pointwise1Before == this.channelCount_pointwise21After_concat2Before ) {
this.bShould_addInput0ToPointwise21 = true;
this.addInput0ToPointwise21 = new AddTwoTensors.Base();
}
// Only inputTensors[ 0 ] will be used to add to output. So still check against channelCount0_pointwise1Before
// (not channelCount1_pointwise1Before).
if ( this.channelCount0_pointwise1Before == this.channelCount_pointwise22After_concat2Before ) {
this.bShould_addInput0ToPointwise22 = true;
this.addInput0ToPointwise22 = new AddTwoTensors.Base();
}
}
this.bShouldAddInputToOutput = this.bShould_addInput0ToPointwise21 || this.bShould_addInput0ToPointwise22;
// 6.2
//
// Q: Why not create TensorOpCounter in the above codes?
// A: The reason is that let addInput0ToPointwise21 in front of pointwise22.
// This is because apply_X_X_and_destroy_or_keep_AddInputToOutput_X() does them in this order.
{
if ( this.bPointwise21 )
TensorOpCounters.pointwise21 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise21",
this.pointwise21, TensorOpCounters.concat1 );
else
TensorOpCounters.pointwise21 = TensorOpCounters.concat1; // Its output is just its input tensor.
// Note: This should be before pointwise22.
if ( this.bShould_addInput0ToPointwise21 )
TensorOpCounters.addInput0ToPointwise21 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_addInput0ToPointwise21",
this.addInput0ToPointwise21, TensorOpCounters.input0, TensorOpCounters.pointwise21 );
else
TensorOpCounters.addInput0ToPointwise21 = TensorOpCounters.pointwise21;
if ( this.bPointwise22 )
TensorOpCounters.pointwise22 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise22",
this.pointwise22, TensorOpCounters.concat1 );
else
TensorOpCounters.pointwise22 = TensorOpCounters.concat1; // Its output is just its input tensor.
// Only inputTensors[ 0 ] will be used to add to output. So still use TensorOpCounters.input0 (not TensorOpCounters.input1) as input.
if ( this.bShould_addInput0ToPointwise22 )
TensorOpCounters.addInput0ToPointwise22 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_addInput0ToPointwise22",
this.addInput0ToPointwise22, TensorOpCounters.input0, TensorOpCounters.pointwise22 );
else
TensorOpCounters.addInput0ToPointwise22 = TensorOpCounters.pointwise22;
}
// 6.3
++progressToAdvance.value;
yield progressRoot; // add-input-to-output was ready. Report progress.
// 7. Concat2-Shuffle-Split
if ( this.bConcat2ShuffleSplitRequested ) {
//!!! ...unfinished... (2021/08/23)
let bShuffleSplit, TensorOpCounters_NamePostfix;
if ( this.outputTensorCount == 1 ) {
bShuffleSplit = false;
TensorOpCounters_NamePostfix = "_concat2"; // only concat2, no shuffle, no split.
this.outChannels0 = this.channelCount_pointwise21After_concat2Before + this.channelCount1_pointwise1Before;
this.outChannels1 = 0;
} else { // ( this.outputTensorCount == 2 )
bShuffleSplit = true;
TensorOpCounters_NamePostfix = "_concat2ShuffleSplit";
this.outChannels0 =
this.outChannels1 = this.channelCount_pointwise21After_concat2Before; // Both output0 and output1 will have the same channel count.
// If ( pointwise21ChannelCount != channelCount1_pointwise1Before ), the shuffle-split algorithm can not work.
tf.util.assert( ( this.channelCount_pointwise21After_concat2Before == this.channelCount1_pointwise1Before ),
`PointDepthPoint.initer(): When concat2-shuffle-split, `
+ `input1's channel count ( ${this.channelCount1_pointwise1Before} ) `
+ `should be the same as output0's channel count ( ${this.channelCount_pointwise21After_concat2Before} ).`
);
}
this.concat2ShuffleSplit = new Concat2ShuffleSplit.Base( channelShuffler_ConcatPointwiseConv, bShuffleSplit, false, false );
// In theory, concat2 use the result of add-input0-to-pointwise21 as first parameter. In reality, it usually uses the result
// of pointwise21 (without add-input0-to-output) as first parameter.
TensorOpCounters.concat2ShuffleSplit = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + TensorOpCounters_NamePostfix,
this.concat2ShuffleSplit, TensorOpCounters.addInput0ToPointwise21, TensorOpCounters.input1 );
} else {
// Since no concat2(-shuffle-split), the final output come from pointwise2 (and add-input-to-output) directly.
this.outChannels0 = this.channelCount_pointwise21After_concat2Before;
this.outChannels1 = this.channelCount_pointwise22After_concat2Before;
//!!! ...unfinished... (2021/08/23) How about the second input (i.e. TensorOpCounters.addInput0ToPointwise22)?
TensorOpCounters.concat2ShuffleSplit = TensorOpCounters.addInput0ToPointwise21;
}
this.outChannelsAll = this.outChannels0 + this.outChannels1;
++progressToAdvance.value;
yield progressRoot; // concat2-Shuffle-Split was ready. Report progress.
//!!! ...unfinished... (2021/08/23) channelShuffler_ConcatPointwiseConv, ConcatShuffleSplit, outputChannelCount
// 8. Configure correct function pointers according to whether keeping or destroying input tensor.
// 8.1 Determine which apply_Xxx() function should be used.
//
// This should be done before adjusting the first operation from "Xxx_destroy" to "Xxx_keep",
// because the adjustment might also need to select different apply_Xxx() function.
this.apply_and_destroy_or_keep = Base.Determine_apply_and_destroy_or_keep.call( this );
// 8.2 Adjust the destroy-or-keep behavior of every tensor according to whether the operation is the first operation or last operation.
{
let alwaysKeepSet;
if ( this.bKeepInputTensor ) { // User requests to keep input tensors.
alwaysKeepSet = new Set( [ TensorOpCounters.input0, TensorOpCounters.input1 ] );
}
// Using Set (instead of Array) so that duplicated TensorOpCounter will only be analyzed once.
// Note: When an operation does not exist, its output TensorOpCounter will be just its input TensorOpCounter (so duplicated).
let TensorOpCounterSet = new Set( [
TensorOpCounters.pointwise1, TensorOpCounters.depthwise1, TensorOpCounters.depthwise2, TensorOpCounters.concat1,
TensorOpCounters.pointwise21, TensorOpCounters.addInput0ToPointwise21,
TensorOpCounters.pointwise22, TensorOpCounters.addInput0ToPointwise22
] );
for ( let TensorOpCounter of TensorOpCounterSet ) {
TensorOpCounter.setKeepInputTensor_IfNotLastOperation_Or_In( alwaysKeepSet );
}
}
// 8.3
++progressToAdvance.value;
yield progressRoot; // All pointwise1-depthwise-pointwise2 filters was ready. Report progress.
this.bInitOk = true;
return true;
}
/**
* Initialize this object by calling initer() and advance the generator by loop until done.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* If null, a temporary progress object will be created.
*
* @return {boolean}
* Return true if successfully (and progressParent.valuePercentage will be equal to 100).
* Return false if failed (and progressParent.valuePercentage will be less than 100).
*/
init( progressParent, params, channelShuffler_ConcatPointwiseConv ) {
progressParent = progressParent || ( new ValueMax.Percentage.Aggregate() );
let initer = this.initer( progressParent, params, channelShuffler_ConcatPointwiseConv );
let initerNext;
do {
initerNext = initer.next();
} while ( ! initerNext.done ); // When ( false == initerNext.done ), the ( initerNext.value ) will be progressParent.getRoot().
let bInitOk = initerNext.value; // When ( true == initerNext.done ), the ( initerNext.value ) will be initialization successfully or failed.
return bInitOk;
}
/** Release all tensors. */
disposeTensors() {
if ( this.pointwise1 ) {
this.pointwise1.disposeTensors();
this.pointwise1 = null;
}
if ( this.depthwise1 ) {
this.depthwise1.disposeTensors();
this.depthwise1 = null;
}
if ( this.depthwise2 ) {
this.depthwise2.disposeTensors();
this.depthwise2 = null;
}
if ( this.concat1 ) {
this.concat1 = null;
}
if ( this.pointwise21 ) {
this.pointwise21.disposeTensors();
this.pointwise21 = null;
}
if ( this.pointwise22 ) {
this.pointwise22.disposeTensors();
this.pointwise22 = null;
}
if ( this.addInput0ToPointwise21 ) {
this.addInputToPointwise21Output = null;
}
if ( this.addInput0ToPointwise22 ) {
this.addInputToPointwise22Output = null;
}
if ( this.concat2ShuffleSplit ) {
this.concat2ShuffleSplit = null;
}
this.intermediateTensorsArray = null;
this.inputTensorCount
= this.bPointwise1
= this.bDepthwise1 = this.bDepthwise2 = this.bDepthwise2Requested
= this.bConcat1Requested
= this.bPointwise21 = this.bPointwise22 = this.bAddInputToOutputRequested
= this.bShouldAddInputToOutput = this.bShould_addInput0ToPointwise21 = this.bShould_addInput0ToPointwise22
= this.bConcat2ShuffleSplitRequested
= this.outputTensorCount
= undefined;
this.byteOffsetBegin = this.byteOffsetEnd = -1;
this.bInitOk = false;
}
/** Determine which apply_Xxx() function should be used.
* @return {function} Return one of the apply_Xxx function.
*/
static Determine_apply_and_destroy_or_keep() {
switch ( this.channelCount1_pointwise1Before ) {
// 1.
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_TWO_DEPTHWISE: // (-2) (simplified ShuffleNetV2's head)
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_1_2_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.3 Only pointwise22 existed (and no pointwise21).
} else {
return Base.apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.4 Both pointwise21 and pointwise22 not existed. (Use pointwise21.)
}
}
break;
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_ADD_TO_OUTPUT: // (-1) (MobileNetV2)
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT: // ( 0) (MobileNetV1)
if ( this.bShouldAddInputToOutput ) { // ( this.bAddInputToOutputRequested == true ) and possible to add-input-to-output.
// 2. add-input-to-output and (keep-input or destroy-input).
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
// 2.1 Both pointwise21 and pointwise22 exist.
//
// Although both pointwise21 and pointwise22 exist, but it may be only pointwise21 or pointwise22 could (or need) add-input-to-output.
if ( this.bShould_addInput0ToPointwise21 ) {
if ( this.bShould_addInput0ToPointwise22 ) {
// 2.1.1 Both pointwise21 and pointwise22 exist, and both addInput0ToPointwise21 and addInput0ToPointwise22 exist.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_2;
} else {
// 2.1.2 Both pointwise21 and pointwise22 exist, but only addInput0ToPointwise21 exists.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_21;
}
} else {
if ( this.bShould_addInput0ToPointwise22 ) {
// 2.1.3 Both pointwise21 and pointwise22 exist, but only addInput0ToPointwise22 exists.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_22;
} else {
// 2.1.4 Both pointwise21 and pointwise22 exist, but both addInput0ToPointwise21 and addInput0ToPointwise22 do not exist.
// It should not execute to here.
tf.util.assert( false,
`PointDepthPoint.Determine_apply_and_destroy_or_keep(), this.bShouldAddInputToOutput (${this.bShouldAddInputToOutput}) `
+ `should equal this.bShould_addInput0ToPointwise21 (${this.bShould_addInput0ToPointwise21}) `
+ ` or this.bShould_addInput0ToPointwise22 (${this.bShould_addInput0ToPointwise22}). ${this.parametersDescription}`);
return undefined;
}
}
} else {
return Base.apply_1_21_and_destroy_or_keep_AddInputToOutput; // 2.2 Only pointwise21 exists (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_AddInputToOutput; // 2.3 Only pointwise22 exists (and no pointwise21).
} else {
// 2.4 Both pointwise21 and pointwise22 do not exist. (Use pointwise21, but channel count is the same as channel count before pointwise2.)
return Base.apply_1_21_and_destroy_or_keep_AddInputToOutput;
}
}
} else {
// 3. no-add-input-to-output, no-concat, and destroy-input (or keep-input).
//
// ( this.inputTensorCount == 1 ) or ( ( this.bAddInputToOutputRequested == true ) but not-possible to add-input-to-output ).
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_1_2_and_destroy_or_keep_NoSkipConnection; // 3.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_1_21_and_destroy_or_keep_NoSkipConnection; // 3.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_NoSkipConnection; // 3.3 Only pointwise22 existed (and no pointwise21).
} else {
// 3.4 Both pointwise21 and pointwise22 not existed.
// no pointwise1, no depthwise1, no concat1, no pointwise21, no addInput0ToPointwise21, no pointwise22, no addInput0ToPointwise22
if ( !this.bPointwise1 && !this.bDepthwise1 ) {
// Note: This may be wrong, however, if there are wrongly two input tensors (there should be only one input
// (i.e. inputTensors[ 0 ]) for should-add-input-to-output).
if ( this.bKeepInputTensor )
return Base.keep_input_return_copy_array; // 3.4.1
else
return Base.return_input_directly_array; // 3.4.2
} else {
return Base.apply_1_21_and_destroy_or_keep_NoSkipConnection; // 3.4.3 At least, there are pointwise1 or depthwise. (Use pointwise21.)
}
}
}
}
break;
// 4. (no-add-input-to-output but has) concat and destroy-input (or keep-input).
//
// ( this.inputTensorCount > 1 ).
default: // Params.channelCount1_pointwise1Before.valueDesc.Ids.TWO_INPUTS_XXX (> 0) (simplified ShuffleNetV2's tail)
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_2_2_and_destroy_or_keep_ConcatInput1; // 4.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_2_21_and_destroy_or_keep_ConcatInput1; // 4.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_2_22_and_destroy_or_keep_ConcatInput1; // 4.3 Only pointwise22 existed (and no pointwise21).
} else {
return Base.apply_2_21_and_destroy_or_keep_ConcatInput1; // 4.4 Both pointwise21 and pointwise22 not existed. (Use pointwise21.)
}
}
break;
}
}
/** The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 0 ]. */
static apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = null;
}
/** The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 1 ]. */
static apply_1_22_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/**
* The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 0 ] and outputTensors[ 1 ].
* The input tensors may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/** The only one input will be added to the only one output (pointwise21). The inputTensor may or may not be disposed.*/
static apply_1_21_and_destroy_or_keep_AddInputToOutput( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
outputTensors[ 1 ] = null;
}
/** The only one input will be added to the only one output (pointwise22). The inputTensor may or may not be disposed.*/
static apply_1_22_and_destroy_or_keep_AddInputToOutput( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to both of them.
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to only outputTensors[ 0 ].
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_21( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to only outputTensors[ 1 ].
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_22( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** One input to one output (pointwise21) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_21_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 ); // may destroy t1.
outputTensors[ 1 ] = null;
}
/** One input to one output (pointwise22) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_22_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 ); // may destroy t1.
}
/** One input to two output (pointwise21 and pointwise22) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_2_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 ); // may destroy t1.
}
/** The inputTensors[ 1 ] will be concatenated before outputTensors[ 0 ]. */
static apply_2_21_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = null;
}
/** The inputTensors[ 1 ] will be concatenated before outputTensors[ 1 ]. */
static apply_2_22_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/**
* The inputTensors[ 1 ] will be concatenated before outputTensors[ 0 ] and outputTensors[ 1 ].
* The input tensors may or may not be disposed.
*
* @param {tf.tensor[]} inputTensors
* An array of tensors. If ( this.inputTensorCount == 1 ), the inputTensors[ 0 ] will be used.
* If ( this.inputTensorCount == 2 ), the inputTensors[ 0 ] and inputTensors[ 1 ] will be used.
*
* @param {tf.tensor[]} outputTensors
* An array for returning the result (output) tensors. If ( this.outputTensorCount == 0 ) or ( this.outputTensorCount == 1 ),
* the outputTensors[ 0 ] will be the result. If ( this.outputTensorCount == 2 ), the outputTensors[ 0 ] and outputTensors[ 1 ] will
* be the result.
*/
static apply_2_2_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
//!!! ...unfinished... (2021/08/20) channelShuffler_ConcatPointwiseConv, ConcatShuffleSplit
/** @return {number} The channel count of the first input tensor (i.e. inputTensors[ 0 ]). */
get inChannels0() { return this.channelCount0_pointwise1Before; }
/** @return {number} The channel count of the second input tensor (i.e. inputTensors[ 1 ]). */
get inChannels1() { return this.channelCount1_pointwise1Before; }
//!!! ...unfinished... (2021/08/23 Remarked) Replaced by read/write property.
//
// /** @return {number} The channel count of the first output tensor (i.e. outputTensors[ 0 ]). */
// get outChannels0() { return this.channelCount_pointwise21After_concat2Before; }
//
// /** @return {number} The channel count of the second output tensor (i.e. outputTensors[ 1 ]). */
// get outChannels1() { return this.channelCount_pointwise22After_concat2Before; }
/
// /** @return {number} The channel count of both the first and second output tensors. */
// get outChannelsAll() { return this.channelCount_pointwise2After_concat2Before; }
/** @return {string} The description string of all (adjusted) parameters of initer(). */
get parametersDescription() {
let str =
`inputTensorCount=${this.inputTensorCount}, `
+ `inChannels0=${this.inChannels0}, inChannels1=${this.inChannels1}, `
+ `outChannels0=${this.outChannels0}, outChannels1=${this.outChannels1}, outChannelsAll=${this.outChannelsAll}, `
+ `channelCount1_pointwise1Before_Name=${this.channelCount1_pointwise1Before_Name}, `
+ `pointwise1ChannelCount=${this.pointwise1ChannelCount}, `
+ `bPointwise1Bias=${this.bPointwise1Bias}, `
+ `pointwise1ActivationName=${this.pointwise1ActivationName}, `
+ `bDepthwise2Requested=${this.bDepthwise2Requested}, `
+ `depthwise_AvgMax_Or_ChannelMultiplier=${this.depthwise_AvgMax_Or_ChannelMultiplier_Name}, `
+ `depthwiseFilterHeight=${this.depthwiseFilterHeight}, `
+ `depthwiseStridesPad=${this.depthwiseStridesPad}, `
+ `bDepthwiseBias=${this.bDepthwiseBias}, `
+ `depthwiseActivationName=${this.depthwiseActivationName}, `
+ `bConcat1Requested=${this.bConcat1Requested}, `
+ `pointwise21ChannelCount=${this.pointwise21ChannelCount}, `
+ `bPointwise21Bias=${this.bPointwise21Bias}, `
+ `pointwise21ActivationName=${this.pointwise21ActivationName}, `
+ `pointwise22ChannelCount=${this.pointwise22ChannelCount}, `
+ `pointwise22ChannelCountName=${this.pointwise22ChannelCountName}, `
+ `bPointwise22Bias=${this.bPointwise22Bias}, `
+ `pointwise22ActivationName=${this.pointwise22ActivationName}, `
+ `bAddInputToOutputRequested=${this.bAddInputToOutputRequested}, `
+ `bConcat2ShuffleSplitRequested=${this.bConcat2ShuffleSplitRequested}, `
+ `outputTensorCount=${this.outputTensorCount}, `
+ `bKeepInputTensor=${this.bKeepInputTensor}`
;
return str;
}
}
| CNN/Conv/PointDepthPoint.js | export { Params, Base };
import * as ValueMax from "../ValueMax.js";
import * as ValueDesc from "../Unpacker/ValueDesc.js";
import * as ParamDesc from "../Unpacker/ParamDesc.js";
import * as Weights from "../Unpacker/Weights.js";
import * as ReturnOrClone from "./ReturnOrClone.js";
import * as Pointwise from "./Pointwise.js";
import * as Depthwise from "./Depthwise.js";
import * as AddTwoTensors from "./AddTwoTensors.js";
import * as ConcatAlongAxisId2 from "./ConcatAlongAxisId2.js";
import * as ConcatShuffleSplit from "./ConcatShuffleSplit.js";
import * as TensorOpCounter from "./TensorOpCounter.js";
//!!! ...unfinished... (2021/08/18)
// tf.batchNorm() is faster than tf.add() when with broadcasting by CPU.
// Whether batchNorm could be used as bias? even activation function?
//
/**
* Pointwise-depthwise-pointwise convolution layer parameters.
*/
class Params extends Weights.Params {
/**
* If a parameter's value is null, it will be extracted from inputFloat32Array (i.e. by evolution).
*
* @param {Float32Array} inputFloat32Array
* A Float32Array whose values will be interpreted as weights.
*
* @param {number} byteOffsetBegin
* The position to start to decode from the inputFloat32Array. This is relative to the inputFloat32Array.buffer
* (not to the inputFloat32Array.byteOffset).
*
* @param {number} channelCount0_pointwise1Before
* The channel count of apply_and_destroy_or_keep()'s first input image (i.e. inputTensors[ 0 ]). If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* @param {number} channelCount1_pointwise1Before
* The channel count of apply_and_destroy_or_keep()'s second input image (i.e. inputTensors[ 1 ]). If null, it will be extracted
* from inputFloat32Array (i.e. by evolution).
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_TWO_DEPTHWISE (-2): The inputTensors[ 1 ] will not be used at
* all (will be ignored completel). The inputTensors[ 0 ] will be processed by two pathes: one is by pointwise1 and one
* depthwise operation, the other is by another depthwise operation (without pointwise1). These two depthwise operations will
* have the same configurations (i.e. same depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad,
* bDepthwiseBias, depthwiseActivationId) but have different (filter and bias) weights. The two depthwise results will be
* concatenated. The concatenated result will be processed by pointwise2 convolution. This is the only one case which there
* will be second depthwise.
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_ADD_TO_OUTPUT (-1): The inputTensors[ 1 ] will not be used at
* all (will be ignored completely). The inputTensors[ 0 ] will be processed by pointwise1, one depthwise operation, and
* pointwise2 convolution. Finally, the inputTensors[ 0 ] will be added to the result of pointwise2. This is the only one case
* which will do add-input-to-output.
*
* - Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT (0): The inputTensors[ 1 ] will not be used at all (will be
* ignored completely). The inputTensors[ 0 ] will be processed by pointwise1, one depthwise operation, and pointwise2 convolution.
*
* - ( channelCount1_pointwise1Before > 0 ): TWO_INPUTS: It should be the channel count of inputTensors[ 1 ]. The inputTensors[ 1 ]
* will not be processed by any pointwise1 and depthwise operation.
*
//!!! ...unfinished... (2021/08/19) Perhaps, combine channelCount1_pointwise1Before and pointwise21ChannelCount,
// since they should be the same in many cases.
* - If ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT ),
* (-2), input1 will be concatenated with the result of pointwise21 operation of input0. The concatenated
* result will be channel-shuffled and splitted into [ output0, output1 ].
* - The input1's channel count (i.e. channelCount1_pointwise1Before) must be the same as pointwise21 (i.e. pointwise21ChannelCount).
* - The output0 and output1 will have the same channel count as pointwise21 (i.e. pointwise21ChannelCount).
*
* - If ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__CONCAT_POINTWISE21_INPUT1 ),
* (-1), input1 will be concatenated with the result of pointwise21 operation of input0. The concatenated
* result will become output0.
* - The input1's channel count (i.e. channelCount1_pointwise1Before) could be any value (i.e. needs not be pointwise21ChannelCount).
* - The output0 will have channel count as ( pointwise21ChannelCount + channelCount1_pointwise1Before ).
*
* - If ( pointwise22ChannelCount >= 0 ), input1 will be concatenated with the result of depthwise operation
* of input0. The concatenated result will be processed by pointwise2 convolution.
* - The input1's channel count (i.e. channelCount1_pointwise1Before) could be any value (i.e. needs not be pointwise21ChannelCount).
* - The output0 will be the result of pointwise21.
* - The output1 will be the result of pointwise22.
*
*
//!!! ...unfinished... (2021/07/27)
// Perhaps, ( channelCount1_pointwise1Before == -3 ): ONE_INPUT_TWO_DEPTHWISE_ONE_MAX_POOLING
//
// A max pooling will be used as a branch of input0. The max pooling result of input0 should be concatenated with the
// two depthwise convolutions' result of input0. The reason is that max pooling could provide information which is difficult achieved
// by a depthwise convolution. (Thinks that for a while: how to calculate maximum value by linear combination (i.e. add-multiply).)
* @param {number} pointwise1ChannelCount
* The output channel count of the pointwise1 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If 0, there will be no pointwise convolution before depthwise convolution.
*
* @param {boolean} bPointwise1Bias
* If true, there will be a bias after pointwise1 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( pointwise1ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise1ActivationId
* The activation function id (Params.pointwise1ActivationId.valueDesc.Ids.Xxx) after the pointwise1 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise1ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {number} depthwise_AvgMax_Or_ChannelMultiplier
* Depthwise operation. If null, it will be extracted from inputFloat32Array (i.e. by evolution). If non-null, it should be
* integer between [ -2, 32 ]:
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.AVG (-2): average pooling.
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.MAX (-1): max pooling.
* - Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.NONE (0): there will be no depthwise operation.
* - positive integer between [ 1, 32 ]: depthwise convolution and the number indicates channel multiplier.
*
* @param {number} depthwiseFilterHeight
* The height (and width) of depthwise convolution's filter. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this will also be ignored.
*
* @param {number} depthwiseStridesPad
* The strides and padding of depthwise convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this depthwiseStridesPad will also be ignored. It has three possible value:
* - 0: means ( depthwiseStrides == 1 ) and ( depthwisePad == "valid" )
* - 1: means ( depthwiseStrides == 1 ) and ( depthwisePad == "same" )
* - 2: means ( depthwiseStrides == 2 ) and ( depthwisePad == "same" )
* Default is 1 because ( depthwiseStrides == 1 ) and ( depthwisePad == "same" ) is a pre-condition for ( bAddInputToOutputRequested == true ).
*
* @param {boolean} bDepthwiseBias
* If null, it will be extracted from inputFloat32Array (i.e. by evolution). If true, there will be a bias after depthwise convolution.
* If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this bias will also be ignored.
*
* @param {number} depthwiseActivationId
* The activation function id (Params.depthwiseActivationId.valueDesc.Ids.Xxx) after depthwise convolution. If null, it will be
* extracted from inputFloat32Array (i.e. by evolution). If ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ), this activation function
* will also be ignored.
*
* @param {number} pointwise21ChannelCount
* The output channel count of the first pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by evolution).
* If ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), there will be no pointwise convolution after depthwise convolution.
*
* @param {boolean} bPointwise21Bias
* If true, there will be a bias after the first pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise21ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise21ActivationId
* The activation function id (Params.pointwise21ActivationId.valueDesc.Ids.Xxx) after the first pointwise1 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise21ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {number} pointwise22ChannelCount
* The output channel count of the second pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), there will be no pointwise convolution
* after depthwise convolution. The pointwise22 convolution could achieve some kinds of channel shuffling of ShuffleNetV2. Please
* see channelCount1_pointwise1Before explanation.
*
* @param {boolean} bPointwise22Bias
* If true, there will be a bias after the second pointwise2 convolution. If null, it will be extracted from inputFloat32Array (i.e. by
* evolution). If ( pointwise22ChannelCount == 0 ), this bias will also be ignored.
*
* @param {number} pointwise21ActivationId
* The activation function id (Params.pointwise22ActivationId.valueDesc.Ids.Xxx) after the second pointwise2 convolution. If null,
* it will be extracted from inputFloat32Array (i.e. by evolution). If ( pointwise22ChannelCount == 0 ), this activation function
* will also be ignored.
*
* @param {boolean} bKeepInputTensor
* If true, apply_and_destroy_or_keep() will not dispose inputTensor (i.e. keep). For example, for the branch of step 0 of ShuffleNetV2.
* For another example, the input image should be shared across many neural networks. If it is null, it will be extracted from
* inputFloat32Array (i.e. by evolution).
*
*/
constructor( inputFloat32Array, byteOffsetBegin,
channelCount0_pointwise1Before,
channelCount1_pointwise1Before,
pointwise1ChannelCount, bPointwise1Bias, pointwise1ActivationId,
depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseStridesPad, bDepthwiseBias, depthwiseActivationId,
pointwise21ChannelCount, bPointwise21Bias, pointwise21ActivationId,
pointwise22ChannelCount, bPointwise22Bias, pointwise22ActivationId,
bKeepInputTensor
) {
//!!! ...unfinished...
// squeeze-and-excitation ?
let parameterMap = new Map( [
[ Params.channelCount0_pointwise1Before, channelCount0_pointwise1Before ],
[ Params.channelCount1_pointwise1Before, channelCount1_pointwise1Before ],
[ Params.pointwise1ChannelCount, pointwise1ChannelCount ],
[ Params.bPointwise1Bias, bPointwise1Bias ],
[ Params.pointwise1ActivationId, pointwise1ActivationId ],
[ Params.depthwise_AvgMax_Or_ChannelMultiplier, depthwise_AvgMax_Or_ChannelMultiplier ],
[ Params.depthwiseFilterHeight, depthwiseFilterHeight ],
[ Params.depthwiseStridesPad, depthwiseStridesPad ],
[ Params.bDepthwiseBias, bDepthwiseBias ],
[ Params.depthwiseActivationId, depthwiseActivationId ],
[ Params.pointwise21ChannelCount, pointwise21ChannelCount ],
[ Params.bPointwise21Bias, bPointwise21Bias ],
[ Params.pointwise21ActivationId, pointwise21ActivationId ],
[ Params.pointwise22ChannelCount, pointwise22ChannelCount ],
[ Params.bPointwise22Bias, bPointwise22Bias ],
[ Params.pointwise22ActivationId, pointwise22ActivationId ],
[ Params.bKeepInputTensor, bKeepInputTensor ],
] );
return super( inputFloat32Array, byteOffsetBegin, parameterMap );
}
/**
* Extract parameters from inputFloat32Array.
*
* @return {boolean} Return false, if extraction failed.
*
* @override
*/
extract() {
let bExtractOk = super.extract();
if ( !bExtractOk )
return false;
// Determine input tensor count and whether request add-input-to-output.
Params.setFlags_by__channelCount1_pointwise1Before__pointwise22ChannelCount.call(
this, this.channelCount1_pointwise1Before, this.pointwise22ChannelCount );
return bExtractOk;
}
/**
* Determine the following properties:
* - this.inputTensorCount
* - this.bDepthwise2Requested
* - this.bConcat1Requested
* - this.bAddInputToOutputRequested
* - this.bConcat2ShuffleSplitRequested
* - this.outputTensorCount
*
* @param {number} channelCount1_pointwise1Before
* @param {number} pointwise22ChannelCount
*/
static setFlags_by__channelCount1_pointwise1Before__pointwise22ChannelCount(
channelCount1_pointwise1Before, pointwise22ChannelCount ) {
// 1.
if ( channelCount1_pointwise1Before <= 0 ) {
this.inputTensorCount = 1; // One input.
this.bConcat2ShuffleSplitRequested = false; // One input never uses concat2-shuffle-split.
if ( pointwise22ChannelCount > 0 ) // One input's output count is determined by pointwise22ChannelCount totally.
this.outputTensorCount = 2;
else
this.outputTensorCount = 1;
switch ( channelCount1_pointwise1Before ) {
// 1.1
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT: // ( 0)
this.bDepthwise2Requested = this.bConcat1Requested = false; this.bAddInputToOutputRequested = false; break;
// 1.2 The only case uses add-input-to-output. (MobileNetV2)
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT_ADD_TO_OUTPUT: // (-1)
this.bDepthwise2Requested = this.bConcat1Requested = false; this.bAddInputToOutputRequested = true; break;
// 1.3 The only case uses depthwise2. (ShuffleNetV2's head)
case ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.ONE_INPUT_TWO_DEPTHWISE: // (-2)
this.bDepthwise2Requested = this.bConcat1Requested = true; this.bAddInputToOutputRequested = false; break;
}
} else { // 2. ( channelCount1_pointwise1Before > 0 ) (i.e. ValueDesc.channelCount1_pointwise1Before.Singleton.Ids.TWO_INPUTS_XXX)
this.inputTensorCount = 2; // Two inputs.
this.bDepthwise2Requested = false; // Two inputs never use depthwise2.
this.bAddInputToOutputRequested = false; // Two inputs never do add-input-to-output. (It always use concatenation.)
if ( pointwise22ChannelCount > 0 ) { // 2.1 Two-inputs-two-outputs: by concat1. (slower ShuffleNetV2's body)
this.bConcat1Requested = true; this.bConcat2ShuffleSplitRequested = false; this.outputTensorCount = 2;
} else {
switch ( pointwise22ChannelCount ) {
// 2.2 Two-inputs-one-output: by concat1. (slower ShuffleNetV2's tail)
case ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__POINTWISE21: // ( 0)
this.bConcat1Requested = true; this.bConcat2ShuffleSplitRequested = false; this.outputTensorCount = 1; break;
// 2.3 Two-inputs-one-output: by concat2(-shuffle-split). (ShuffleNetV2's tail)
case ValueDesc.pointwise22ChannelCount.Singleton.ONE_OUTPUT__CONCAT_POINTWISE21_INPUT1: // (-1)
this.bConcat1Requested = false; this.bConcat2ShuffleSplitRequested = true; this.outputTensorCount = 1; break;
// 2.4 Two-inputs-two-outputs: by concat2-shuffle-split. (ShuffleNetV2's body)
case ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT: // (-2)
this.bConcat1Requested = false; this.bConcat2ShuffleSplitRequested = true; this.outputTensorCount = 2; break;
}
}
}
}
get channelCount0_pointwise1Before() { return this.parameterMapModified.get( Params.channelCount0_pointwise1Before ); }
/** @return {number} The number version of channelCount1_pointwise1Before. */
get channelCount1_pointwise1Before() { return this.parameterMapModified.get( Params.channelCount1_pointwise1Before ); }
/** @return {string} The string version of channelCount1_pointwise1Before. */
get channelCount1_pointwise1Before_Name() {
return Params.channelCount1_pointwise1Before.getStringOfValue( this.channelCount1_pointwise1Before );
}
get pointwise1ChannelCount() { return this.parameterMapModified.get( Params.pointwise1ChannelCount ); }
get bPointwise1Bias() { return this.parameterMapModified.get( Params.bPointwise1Bias ); }
get pointwise1ActivationId() { return this.parameterMapModified.get( Params.pointwise1ActivationId ); }
get pointwise1ActivationName() { return Params.pointwise1ActivationId.getStringOfValue( this.pointwise1ActivationId ); }
/** @return {number} The number version of the depthwise opertion. */
get depthwise_AvgMax_Or_ChannelMultiplier() { return this.parameterMapModified.get( Params.depthwise_AvgMax_Or_ChannelMultiplier ); }
/** @return {string} The string version of the depthwise opertion. */
get depthwise_AvgMax_Or_ChannelMultiplier_Name() {
return Params.depthwise_AvgMax_Or_ChannelMultiplier.getStringOfValue( this.depthwise_AvgMax_Or_ChannelMultiplier );
}
get depthwiseFilterHeight() { return this.parameterMapModified.get( Params.depthwiseFilterHeight ); }
get depthwiseStridesPad() { return this.parameterMapModified.get( Params.depthwiseStridesPad ); }
get bDepthwiseBias() { return this.parameterMapModified.get( Params.bDepthwiseBias ); }
get depthwiseActivationId() { return this.parameterMapModified.get( Params.depthwiseActivationId ); }
get depthwiseActivationName() { return Params.depthwiseActivationId.getStringOfValue( this.depthwiseActivationId ); }
get pointwise21ChannelCount() { return this.parameterMapModified.get( Params.pointwise21ChannelCount ); }
get bPointwise21Bias() { return this.parameterMapModified.get( Params.bPointwise21Bias ); }
get pointwise21ActivationId() { return this.parameterMapModified.get( Params.pointwise21ActivationId ); }
get pointwise21ActivationName() { return Params.pointwise21ActivationId.getStringOfValue( this.pointwise21ActivationId ); }
get pointwise22ChannelCount() { return this.parameterMapModified.get( Params.pointwise22ChannelCount ); }
/** @return {string} The string version of pointwise22ChannelCount. */
get pointwise22ChannelCountName() {
return Params.pointwise21ChannelCount.getStringOfValue( this.pointwise21ChannelCount );
}
get bPointwise22Bias() { return this.parameterMapModified.get( Params.bPointwise22Bias ); }
get pointwise22ActivationId() { return this.parameterMapModified.get( Params.pointwise22ActivationId ); }
get pointwise22ActivationName() { return Params.pointwise22ActivationId.getStringOfValue( this.pointwise22ActivationId ); }
get bKeepInputTensor() { return this.parameterMapModified.get( Params.bKeepInputTensor ); }
}
// Define parameter descriptions.
/** At least, there should be 1 input channel. */
Params.channelCount0_pointwise1Before = new ParamDesc.Int( "channelCount0_pointwise1Before", 1, ( 10 * 1024 ) );
Params.channelCount1_pointwise1Before = new ParamDesc.channelCount1_pointwise1Before( "channelCount1_pointwise1Before" );
Params.pointwise1ChannelCount = new ParamDesc.Int( "pointwise1ChannelCount", 0, ( 10 * 1024 ) );
Params.bPointwise1Bias = new ParamDesc.Bool( "bPointwise1Bias" );
Params.pointwise1ActivationId = new ParamDesc.ActivationFunction( "pointwise1ActivationId" );
/** Define depthwise operation's id, range, name.
*
* Convert number value into integer between [ -2, 32 ] representing depthwise operation:
* - -1: average pooling. (AVG)
* - -2: maximum pooling. (MAX)
* - 0: no depthwise operation. (NONE)
* - [ 1, 32 ]: depthwise convolution with channel multiplier between 1 and 32 (inclusive).
*/
Params.depthwise_AvgMax_Or_ChannelMultiplier = new ParamDesc.AvgMax_Or_ChannelMultiplier( "depthwise_AvgMax_Or_ChannelMultiplier" );
/** Define suitable value for depthwise convolution filter size.
*
* At least 1, because depthwise filter size ( 0 * 0 ) is meaningless.
*
* For avg pooling or max pooling, it is less meaningful if filter size is ( 1 * 1 ) because the result will be the same as input.
* For depthwise convolution, it is meaningful if filter size is ( 1 * 1 ) because they could be used as simple channel multiplier.
*
* Avoid too large filter size. Otherwise, performance may be poor.
*/
Params.depthwiseFilterHeight = new ParamDesc.Int( "depthwiseFilterHeight", 1, 9 );
/** Define suitable value for depthwise convolution strides and pad. Integer between [ 0, 2 ]. */
Params.depthwiseStridesPad = new ParamDesc.Int( "depthwiseStridesPad", 0, 2 );
Params.bDepthwiseBias = new ParamDesc.Bool( "bDepthwiseBias" );
Params.depthwiseActivationId = new ParamDesc.ActivationFunction( "depthwiseActivationId" );
Params.pointwise21ChannelCount = new ParamDesc.Int( "pointwise21ChannelCount", 0, ( 10 * 1024 ) );
Params.bPointwise21Bias = new ParamDesc.Bool( "bPointwise21Bias" );
Params.pointwise21ActivationId = new ParamDesc.ActivationFunction( "pointwise21ActivationId" );
Params.pointwise22ChannelCount = new ParamDesc.pointwise22ChannelCount( "pointwise22ChannelCount" );
Params.bPointwise22Bias = new ParamDesc.Bool( "bPointwise22Bias" );
Params.pointwise22ActivationId = new ParamDesc.ActivationFunction( "pointwise22ActivationId" );
Params.bKeepInputTensor = new ParamDesc.Bool( "bKeepInputTensor" );
/**
* One step of one block of convolution neural network. There are at most three convolutions inside this object.
* - 1x1 pointwise convolution: change channel count. (exapnd)
* - NxN depthwise convolution: change channel count. (channel multiplier)
* - 1x1 pointwise convolution: change channel count. (shrink)
*
* Every convolution (no matter pointwise or depthwise) could exist or not exist. If exists, it could have or have no bias and
* activation function.
*
*
* There six main combinations:
*
* - When ( channelCount1_pointwise1Before == -2 ): ONE_INPUT_TWO_DEPTHWISE: (our adjusted ShuffleNetV2's head)
* <pre>
* input0 - pointwise1 - depthwise1 - concat1 - pointwise21
* \------------- depthwise2 / \ pointwise22
* </pre>
*
*
* - When ( channelCount1_pointwise1Before == -1 ): ONE_INPUT_ADD_TO_OUTPUT: (MobileNetV2)
* <pre>
* /------------------------------------------------------\
* input0 - pointwise1 - depthwise1 ---------------- pointwise21 - addInput0ToPointwise21
* \ \ pointwise22 - addInput0ToPointwise22
* \-----------------------------------------------------/
* </pre>
*
*
* - When ( channelCount1_pointwise1Before == 0 ): ONE_INPUT: (MobileNetV1)
* <pre>
* input0 - pointwise1 - depthwise1 ---------------- pointwise21
* \ pointwise22
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount == -2 ): TWO_INPUTS: TWO_OUTPUT: (ShuffleNetV2's body)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2ShuffleSplit - output0
* input1 ----------------------------------------/ \ output1
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount == -1 ): TWO_INPUTS: ONE_OUTPUT: (ShuffleNetV2's tail)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2(ShuffleSplit) - output0
* input1 ----------------------------------------/
* </pre>
*
*
* - When ( channelCount1_pointwise1Before > 0 ) and ( pointwise22ChannelCount >= 0 ): TWO_INPUTS: (slower ShuffleNetV2's body and tail)
* <pre>
* input0 - pointwise1 - depthwise1 - concat1 - pointwise21
* input1 --------------------------/ \ pointwise22
* </pre>
*
*
*
* Strictly speaking, the real (original) ShuffleNetV2 is more like the following:
*
* (original ShuffleNetV2's head)
* <pre>
* input0 - pointwise1 - depthwise1 - pointwise21 - concat2 - channelShuffler
* \------------- depthwise2 - pointwise22 /
* </pre>
*
* (original ShuffleNetV2's tail)
* <pre>
* input0 - channelSplitter - pointwise1 - depthwise1 - pointwise21 - concat2 - channelShuffler
* \---------------------------------------/
* </pre>
*
* The channelShuffler of original ShuffleNetV2 is achieved by tf.reshape() operation. According to experiments, however, the
* channelShuffler could be acheived by pointwise convolution more efficiently (than reshape). This results in our simplified
* ShuffleNetV2 structure: replacing pointwise-concat-shuffle-split with concat-pointwise. It should be more efficient because
* less operations are used than original structure.
*
*
*
*
* @member {boolean} bInitOk
* If true, this object initialized (i.e. initer()) successfully.
*
* @member {number} byteOffsetBegin
* The position which is started (inclusive) to extract from inputFloat32Array.buffer by initer().
*
* @member {number} byteOffsetEnd
* The position which is ended to (non-inclusive) extract from inputFloat32Array.buffer by initer(). Where to extract next weights.
* Only meaningful when ( this.bInitOk == true ).
*
* @member {number} inputTensorCount
* How many input tensors will be past into apply_and_destroy_or_keep() as parameter inputTensors[].
*
* @member {boolean} bDepthwise2Requested
* It will be true only when ( channelCount1_pointwise1Before == -2 ). If true, it means a second depthwise might be needed.
*
* @member {boolean} bConcat1Requested
* If true, the concat1 (after depthwise and before pointwise2) is needed.
*
* @member {boolean} bConcat2ShuffleSplitRequested
* If true, the concat2 (after pointwise2) is needed. It may or may not follow channel shuffling and splitting.
*
* @member {boolean} bAddInputToOutputRequested
* It will be true when ( this.channelCount1_pointwise1Before == -1 ). The input (in this case, the main input (i.e. inputTensorArray[ 0 ])
* will be added to the output for achieving skip connection.
*
* @member {number} outputTensorCount
* How many output tensors will be returned by the parameter outputTensors of apply_and_destroy_or_keep(). At least 1. At most 2. It is
* determined by channelCount1_pointwise1Before and pointwise22ChannelCount.
*
* @member {string} pointwise22ChannelCountName
* The string version of pointwise22ChannelCount. Useful for negative value.
*
* @member {boolean} bPointwise1
* If true, the pointwise1 convolution exists.
*
* @member {string} pointwise1ActivationName
* The activation function id (Params.pointwise1ActivationId.valueDesc.Ids.Xxx) after the first pointwise convolution.
*
* @member {boolean} bDepthwise1
* If true, the first depthwise convolution (or average pooling, or maximum pooling) exists.
*
* @member {boolean} bDepthwise2
* If true, the second depthwise convolution (or average pooling, or maximum pooling) exists.
*
* @member {string} depthwise_AvgMax_Or_ChannelMultiplier_Name
* Depthwise operation name.
*
* @member {string} depthwiseActivationName
* The activation function name (Params.depthwiseActivationId.valueDesc.Ids.Xxx) after depthwise convolution.
*
* @member {boolean} bPointwise2
* If true, the pointwise2 (i.e. pointwise21 or/and pointwise22) convolution exists.
*
* @member {boolean} bPointwise21
* If true, the first pointwise2 convolution exists.
*
* @member {boolean} bPointwise22
* If true, the second pointwise2 convolution exists.
*
* @member {string} pointwise21ActivationName
* The activation function id (Params.pointwise21ActivationId.valueDesc.Ids.Xxx) after the first pointwise2 convolution.
*
* @member {string} pointwise22ActivationName
* The activation function id (Params.pointwise22ActivationId.valueDesc.Ids.Xxx) after the second pointwise2 convolution.
*
* @member {number} inChannels0
* The channel count of the first input tensor (i.e. inputTensors[ 0 ]). This is the same as this.channelCount0_pointwise1Before (from initer()).
*
* @member {number} inChannels1
* The channel count of the second input tensor (i.e. inputTensors[ 1 ]). This is the same as this.channelCount1_pointwise1Before (from initer()).
*
//!!! ...unfinished... (2021/08/22) What outChannels0, outChannels1, outChannels if shuffleSplit?
* @member {number} outChannels0
* The channel count of the first output tensor. It is the same as this.channelCount_pointwise21After_concat2Before (from initer()).
*
* @member {number} outChannels1
* The channel count of the second output tensor. It is the same as this.channelCount_pointwise22After_concat2Before (from initer()).
*
* @member {number} outChannels
* The channel count of all output tensor. It is the same as this.channelCount_pointwise2After_concat2Before (from initer()).
*
* @member {number} channelCount_pointwise1After_depthwise1Before
* The channel count after the first 1x1 pointwise convolution. If ( pointwise1ChannelCount > 0 ), it equals pointwise1ChannelCount.
* If ( pointwise1ChannelCount == 0 ), it equals inChannels0.
*
* @member {number} channelCount_depthwise1After_concat1Before
* The channel count after the first depthwise convolution which applies to the result of pointwise1.
* - If depthwise1 exists, it will be the channel count of depthwise1's output.
* - When ( depthwise_AvgMax_Or_ChannelMultiplier >= 1 ), it equals
* ( channelCount_pointwise1After_depthwise1Before * depthwise_AvgMax_Or_ChannelMultiplier ).
* - When ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.AVG ) (i.e. -2)
* or ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.MAX ) (i.e. -1)
* or ( depthwise_AvgMax_Or_ChannelMultiplier == Params.depthwise_AvgMax_Or_ChannelMultiplier.valueDesc.Ids.NONE ) (i.e. 0),
* it equals channelCount_pointwise1After_depthwise1Before.
* - If depthwise1 does not exist, it will be the channel count of previous operation (i.e. pointwise1)
* which is channelCount_pointwise1After_depthwise1Before.
*
* @member {number} channelCount_depthwise2After_concat1Before
* The channel count after the second depthwise convolution which applies to input0 or input1. If depthwise2 does not exist,
* this will be the same as Math.max( 0, channelCount1_pointwise1Before ) (i.e. the depthwise2 will be viewed as short circuit
* to input1).
*
* @member {number} channelCount_concat1After_pointwise2Before
* The channel count before pointwise2. It is may be the concatenated result of input0 (with depthwise1, with/without depthwise2)
* with/without input1 (without depthwise2).
*
* @member {number} channelCount_pointwise21After_concat2Before
* The channel count after the pointwise21 convolution. If ( pointwise21ChannelCount > 0 ), it equals pointwise21ChannelCount.
* If ( pointwise21ChannelCount == 0 ), it will be 0.
*
* @member {number} channelCount_pointwise22After_concat2Before
* The channel count after the pointwise22 convolution. If ( pointwise22ChannelCount > 0 ), it equals pointwise22ChannelCount.
* If ( pointwise22ChannelCount == 0 ), it will be 0.
*
* @member {number} channelCount_pointwise2After_concat2Before
* The channel count after all pointwise2 convolution.
*
* - Basically, it will be ( channelCount_pointwise21After_concat2Before + channelCount_pointwise22After_concat2Before )
* if at least one pointwise2 convolution existed.
*
* - If both ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), it will be channelCount_concat1After_pointwise2Before.
*
//!!! ...unfinished... (2021/08/22)
// channelCount_concat2After_shuffleBefore
// channelCount_shuffleSplitAfter?
*
* @member {ChannelShuffler.ConcatPointwiseConv} channelShuffler_ConcatPointwiseConv
* The channelShuffler. It must be implemented by ChannelShuffler.ConcatPointwiseConv with ( outputGroupCount == 2 ).
*
* - It will not be disposed by this object (i.e. it is supposed to be shared with outter callers).
*
* - The channelShuffler's outputGroupCount must be 2 (i.e. split into two groups after channel-shuffling).
*
* - It is only used when ( channelCount1_pointwise1Before > 1 ) (i.e. TWO_INPUTS) and
* ( pointwise22ChannelCount == ValueDesc.pointwise22ChannelCount.Singleton.TWO_OUTPUTS__CONCAT_POINTWISE21_INPUT1__SHUFFLE__SPLIT )
* (-2) (i.e. channel shuffle the concatenated pointwise21 and input1).
*
* - The channelShuffler.shuffleInfo.totalChannelCount should be the same as the channel count of the concatenation
* of pointwise21 and input1.
*
* @member {function} apply_and_destroy_or_keep
* This is a method. It has two parameters inputTensors and outputTensors. The inputTensors (tf.tensor3d[]) represents the images
* ( height x width x channel ) which will be processed. The outputTensors (tf.tensor3d[]) will be placed one or two tf.tensor3d as
* the result. All intermediate tensors will be disposed. The inputTensors may or may not be disposed. In fact, this method calls
* one of apply_X_Y_and_destroy_or_keep_ConcatInput0Depthwise2(), apply_X_Y_and_destroy_AddInputToOutput(),
* apply_X_Y_and_destroy_or_keep_NoSkipConnection(), apply_X_Y_and_destroy_or_keep_ConcatInput1(),
* return_input_directly_array(), keep_input_return_copy_array() according to the initer()'s parameters.
*/
class Base extends ReturnOrClone.Base {
/**
* Generator for initializing this object.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* Some new progressToAdvance will be created and added to progressParent. The created progressToAdvance will be
* increased when every time advanced. The progressParent.getRoot() will be returned when every time yield.
*
* @param {Params} params
* A Params object. The params.extract() will be called to extract parameters.
*
* @yield {ValueMax.Percentage.Aggregate}
* Yield ( value = progressParent.getRoot() ) when ( done = false ).
*
* @yield {boolean}
* Yield ( value = true ) when ( done = true ) successfully.
* Yield ( value = false ) when ( done = true ) failed.
*/
* initer( progressParent, params, channelShuffler_ConcatPointwiseConv ) {
// 0. Prepare
// Estimate the maximum value of progress.
let progressMax =
1 // for extracting parameters from inputFloat32Array.
+ 1 // for extracting pointwise1 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for extracting depthwise filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for concat1.
+ 1 // for extracting pointwise2 filters (and biases) from inputFloat32Array and building tensors.
+ 1 // for add-input-to-output.
+ 1 // for concat2-shuffle-split.
+ 1 // for all pointwise1-depthwise-pointwise2 filters (and biases) ready.
;
let progressRoot = progressParent.getRoot();
let progressToAdvance = progressParent.addChild( new ValueMax.Percentage.Concrete( progressMax ) );
this.disposeTensors(); // Also initialize some member function pointers to no_operation().
this.channelShuffler_ConcatPointwiseConv = channelShuffler_ConcatPointwiseConv;
// 1. Extract parameters.
if ( !params )
return false;
this.byteOffsetEnd = this.byteOffsetBegin = params.defaultByteOffsetBegin;
if ( !params.extract() )
return false; // e.g. input array does not have enough data.
// Record where to extract next weights. Only meaningful when ( this.bInitOk == true ).
this.byteOffsetEnd = params.defaultByteOffsetEnd;
// Get parameters' real (adjusted) values.
//
// Do not keep params in this.params so that the inputFloat32Array could be released.
this.channelCount0_pointwise1Before = params.channelCount0_pointwise1Before;
this.channelCount1_pointwise1Before = params.channelCount1_pointwise1Before;
this.channelCount1_pointwise1Before_Name = params.channelCount1_pointwise1Before_Name;
this.pointwise1ChannelCount = params.pointwise1ChannelCount;
this.bPointwise1Bias = params.bPointwise1Bias;
this.pointwise1ActivationId = params.pointwise1ActivationId;
this.pointwise1ActivationName = params.pointwise1ActivationName;
this.depthwise_AvgMax_Or_ChannelMultiplier = params.depthwise_AvgMax_Or_ChannelMultiplier;
this.depthwise_AvgMax_Or_ChannelMultiplier_Name = params.depthwise_AvgMax_Or_ChannelMultiplier_Name;
this.depthwiseFilterHeight = params.depthwiseFilterHeight;
this.depthwiseStridesPad = params.depthwiseStridesPad;
this.bDepthwiseBias = params.bDepthwiseBias;
this.depthwiseActivationId = params.depthwiseActivationId;
this.depthwiseActivationName = params.depthwiseActivationName;
this.pointwise21ChannelCount = params.pointwise21ChannelCount;
this.bPointwise21Bias = params.bPointwise21Bias;
this.pointwise21ActivationId = params.pointwise21ActivationId;
this.pointwise21ActivationName = params.pointwise21ActivationName;
this.pointwise22ChannelCount = params.pointwise22ChannelCount;
this.pointwise22ChannelCountName = params.pointwise22ChannelCountName;
this.bPointwise22Bias = params.bPointwise22Bias;
this.pointwise22ActivationId = params.pointwise22ActivationId;
this.pointwise22ActivationName = params.pointwise22ActivationName;
this.bKeepInputTensor = params.bKeepInputTensor;
// The parameters which are determined (inferenced) from the above parameters.
this.inputTensorCount = params.inputTensorCount;
this.bDepthwise2Requested = params.bDepthwise2Requested;
this.bConcat1Requested = params.bConcat1Requested;
this.bAddInputToOutputRequested = params.bAddInputToOutputRequested;
this.bConcat2ShuffleSplitRequested = params.bConcat2ShuffleSplitRequested;
this.outputTensorCount = params.outputTensorCount;
this.intermediateTensorsArray = new Array( 2 ); // Pre-allocate array to place intermediate 2 tensors. This could reduce memory re-allocation.
++progressToAdvance.value;
yield progressRoot; // Parameters extracted. Report progress.
// For analyzing every tensor processed by how many operations. These will be used to determine whether
// the operation should dispose its input tensor.
let TensorOpCounterId = -1;
let TensorOpCounters = {
input0: new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_input0", null, null ),
input1: new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_input1", null, null ),
};
// 2. The first 1x1 pointwise convolution.
this.pointwise1 = new Pointwise.Base(
this.channelCount0_pointwise1Before,
this.pointwise1ChannelCount, this.bPointwise1Bias, this.pointwise1ActivationId );
if ( !this.pointwise1.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise1.byteOffsetEnd;
this.bPointwise1 = this.pointwise1.bExisted;
if ( this.bPointwise1 ) {
this.channelCount_pointwise1After_depthwise1Before = this.pointwise1.outputChannelCount;
TensorOpCounters.pointwise1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise1", this.pointwise1, TensorOpCounters.input0 );
} else {
this.channelCount_pointwise1After_depthwise1Before = this.channelCount0_pointwise1Before; // No pointwise1 convolution.
TensorOpCounters.pointwise1 = TensorOpCounters.input0; // Its output is just its input tensor.
}
++progressToAdvance.value;
yield progressRoot; // pointwise1 filters was ready. Report progress.
// 3. The depthwise operation.
//
// Note: When ( pad == valid ), it seems that depthwise (avg/max pooling) filter size can not greater than input image size.
// 3.1 The first depthwise operation.
this.depthwise1 = new Depthwise.Base(
this.channelCount_pointwise1After_depthwise1Before,
this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight,
this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId );
if ( !this.depthwise1.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.depthwise1.byteOffsetEnd;
this.bDepthwise1 = this.depthwise1.bExisted;
if ( this.bDepthwise1 ) {
this.channelCount_depthwise1After_concat1Before = this.depthwise1.outputChannelCount;
TensorOpCounters.depthwise1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_depthwise1", this.depthwise1, TensorOpCounters.pointwise1 );
} else {
this.channelCount_depthwise1After_concat1Before = this.channelCount_pointwise1After_depthwise1Before; // No depthwise1 operation.
TensorOpCounters.depthwise1 = TensorOpCounters.pointwise1; // Its output is just its input tensor.
}
// 3.2 The second depthwise operation.
this.bDepthwise2 = false;
if ( this.bDepthwise2Requested ) {
// Q: Why does depthwise2 use the same configuration as depthwise1?
// A: To ensure both result have the same ( height, width ) so that could be inputted to concatenator). This is especially
// true for StridesPad.
this.depthwise2 = new Depthwise.Base(
// The depthwise2 processes the inputTensors[ 0 ] directly (i.e. not the pointwise1 result of inputTensors[ 0 ], and
// not inputTensors[ 1 ]).
this.channelCount0_pointwise1Before,
this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight,
this.depthwiseStridesPad, this.bDepthwiseBias, this.depthwiseActivationId );
if ( !this.depthwise2.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.depthwise2.byteOffsetEnd;
this.bDepthwise2 = this.depthwise2.bExisted;
if ( this.bDepthwise2 ) {
// The depthwise2 is requested and created. It means ONE_INPUT_TWO_DEPTHWISE.
this.channelCount_depthwise2After_concat1Before = this.depthwise2.outputChannelCount;
TensorOpCounters.depthwise2 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_depthwise2", this.depthwise2, TensorOpCounters.input0 );
} else {
// The depthwise2 is requested but not created. It means no depthwise operation (i.e. ( depthwise_AvgMax_Or_ChannelMultiplier == 0 ).
// In this case, the depthwise2 should be short circuit to inputTensor[ 0 ] (i.e. not inputTensor[ 1 ]).
this.channelCount_depthwise2After_concat1Before = this.channelCount0_pointwise1Before;
TensorOpCounters.depthwise2 = TensorOpCounters.input0;
}
} else {
// Since the depthwise2 is not requested, it is always short circuit to input1 (i.e. not input0).
this.channelCount_depthwise2After_concat1Before = Math.max( 0, this.channelCount1_pointwise1Before ); // At least 0. Avoid negative.
TensorOpCounters.depthwise2 = TensorOpCounters.input1;
}
++progressToAdvance.value;
yield progressRoot; // depthwise filters was ready. Report progress.
// 4. Concat1
if ( this.bConcat1Requested ) {
this.channelCount_concat1After_pointwise2Before
= this.channelCount_depthwise1After_concat1Before + this.channelCount_depthwise2After_concat1Before;
this.concat1 = new ConcatAlongAxisId2.Base( false, false );
TensorOpCounters.concat1 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_concat1",
this.concat1, TensorOpCounters.depthwise1, TensorOpCounters.depthwise2 );
} else {
this.channelCount_concat1After_pointwise2Before = this.channelCount_depthwise1After_concat1Before;
TensorOpCounters.concat1 = TensorOpCounters.depthwise1;
}
++progressToAdvance.value;
yield progressRoot; // concat1 was ready. Report progress.
// 5. The pointwise2 convolution.
// 5.1 Pointwise21
this.pointwise21 = new Pointwise.Base(
this.channelCount_concat1After_pointwise2Before,
this.pointwise21ChannelCount, this.bPointwise21Bias, this.pointwise21ActivationId );
if ( !this.pointwise21.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise21.byteOffsetEnd;
this.bPointwise21 = this.pointwise21.bExisted;
if ( this.bPointwise21 ) {
this.channelCount_pointwise21After_concat2Before = this.pointwise21ChannelCount;
} else {
this.channelCount_pointwise21After_concat2Before = 0; // No first pointwise2 convolution.
}
// 5.2 Pointwise22
this.pointwise22 = new Pointwise.Base(
this.channelCount_concat1After_pointwise2Before,
this.pointwise22ChannelCount, this.bPointwise22Bias, this.pointwise22ActivationId );
if ( !this.pointwise22.init( params.defaultInput, this.byteOffsetEnd ) )
return false; // e.g. input array does not have enough data.
this.byteOffsetEnd = this.pointwise22.byteOffsetEnd;
this.bPointwise22 = this.pointwise22.bExisted;
if ( this.bPointwise22 ) {
this.channelCount_pointwise22After_concat2Before = this.pointwise22ChannelCount;
} else {
this.channelCount_pointwise22After_concat2Before = 0; // No second pointwise2 convolution.
}
// 5.3 Pointwise2 (= Pointwise21 + Pointwise22 )
this.bPointwise2 = ( this.bPointwise21 || this.bPointwise22 );
this.channelCount_pointwise2After_concat2Before = this.pointwise21ChannelCount + this.pointwise22ChannelCount;
if ( !this.bPointwise2 ) {
// If there is not any pointwise2 convolution, the result channel count will not be zero. It should be the channel count after
// depthwise1 operation together with the input1 channel count (if existed). And it should be at the first output tensor
// (i.e. outputTensors[ 0 ]).
this.channelCount_pointwise2After_concat2Before = this.channelCount_pointwise21After_concat2Before
= this.channelCount_concat1After_pointwise2Before;
}
//!!! ...unfinished... (2021/08/21 Remarked) outputChannelCount should already determined in the above.
// // If both pointwise21 and pointwise22 existed, the pointwise21 should keep-input-tensor.
// // Otherwise, the pointwise22 will fail to process it.
// if ( this.bPointwise21 && this.bPointwise22 ) {
// this.outputTensorCount = 2; // This is the only case which will output two tensors.
// } else {
// this.outputTensorCount = 1; // All other cases, there will be only one output tensor.
// }
// 5.4
++progressToAdvance.value;
yield progressRoot; // pointwise2 filters was ready. Report progress.
// 6. Add-input-to-output
// 6.1
//
// Although caller could request add-input-to-output, it may or may not doable.
// Only if the dimension of output is the same as the dimension of input, it is possible to add-input-to-output.
//
// Only if depthwise stride is "1" and pad is "same" (or pad is "valid" but filter size 1x1), the dimension 0 (height)
// and 1 (width) of the output will be the same as input.
//
// Only if output channel is equals to input channel, the dimension 2 (channel) of the output will be the same as input.
//
// For example:
// - if MobileNetV2 and not step 0, should not destroy input tensor so that can add input to output.
// - However, even if MobileNetV2, only if not setp 0 (whose strides == 2) of a block can add input to output.
if ( ( this.bAddInputToOutputRequested ) && ( this.depthwise1.is_Output_Same_HeightWidth_As_Input() ) ) {
// Note:
//
// Usually, if no pointwise21, then no addInput0ToPointwise21.
// Usually, if no pointwise22, then no addInput0ToPointwise22.
//
// However, there is one exception: When both no pointwise21 and no pointwise22, there might be addInput0ToPointwise21
// if channelCount_concat1After_pointwise2Before (which is already assigned to channelCount_pointwise21After_concat2Before in this case)
// has the same dimension as inputTensors[ 0 ].
if ( this.channelCount0_pointwise1Before == this.channelCount_pointwise21After_concat2Before ) {
this.bShould_addInput0ToPointwise21 = true;
this.addInput0ToPointwise21 = new AddTwoTensors.Base();
}
// Only inputTensors[ 0 ] will be used to add to output. So still check against channelCount0_pointwise1Before
// (not channelCount1_pointwise1Before).
if ( this.channelCount0_pointwise1Before == this.channelCount_pointwise22After_concat2Before ) {
this.bShould_addInput0ToPointwise22 = true;
this.addInput0ToPointwise22 = new AddTwoTensors.Base();
}
}
this.bShouldAddInputToOutput = this.bShould_addInput0ToPointwise21 || this.bShould_addInput0ToPointwise22;
// 6.2
//
// Q: Why not create TensorOpCounter in the above codes?
// A: The reason is that let addInput0ToPointwise21 in front of pointwise22.
// This is because apply_X_X_and_destroy_or_keep_AddInputToOutput_X() does them in this order.
{
if ( this.bPointwise21 )
TensorOpCounters.pointwise21 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise21",
this.pointwise21, TensorOpCounters.concat1 );
else
TensorOpCounters.pointwise21 = TensorOpCounters.concat1; // Its output is just its input tensor.
// Note: This should be before pointwise22.
if ( this.bShould_addInput0ToPointwise21 )
TensorOpCounters.addInput0ToPointwise21 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_addInput0ToPointwise21",
this.addInput0ToPointwise21, TensorOpCounters.input0, TensorOpCounters.pointwise21 );
else
TensorOpCounters.addInput0ToPointwise21 = TensorOpCounters.pointwise21;
if ( this.bPointwise22 )
TensorOpCounters.pointwise22 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_pointwise22",
this.pointwise22, TensorOpCounters.concat1 );
else
TensorOpCounters.pointwise22 = TensorOpCounters.concat1; // Its output is just its input tensor.
// Only inputTensors[ 0 ] will be used to add to output. So still use TensorOpCounters.input0 (not TensorOpCounters.input1) as input.
if ( this.bShould_addInput0ToPointwise22 )
TensorOpCounters.addInput0ToPointwise22 = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + "_addInput0ToPointwise22",
this.addInput0ToPointwise22, TensorOpCounters.input0, TensorOpCounters.pointwise22 );
else
TensorOpCounters.addInput0ToPointwise22 = TensorOpCounters.pointwise22;
}
// 6.3
++progressToAdvance.value;
yield progressRoot; // add-input-to-output was ready. Report progress.
// 7. Concat2-Shuffle-Split
if ( this.bConcat2ShuffleSplitRequested ) {
//!!! ...unfinished... (2021/08/23)
let bShuffleSplit, TensorOpCounters_NamePostfix;
if ( this.outputTensorCount == 1 ) {
bShuffleSplit = false;
TensorOpCounters_NamePostfix = "_concat2"; // only concat2, no shuffle, no split.
this.outChannels0 = this.channelCount_pointwise21After_concat2Before + this.channelCount1_pointwise1Before;
this.outChannels1 = 0;
} else { // ( this.outputTensorCount == 2 )
bShuffleSplit = true;
TensorOpCounters_NamePostfix = "_concat2ShuffleSplit";
this.outChannels0 = this.channelCount_pointwise21After_concat2Before;
this.outChannels1 = this.channelCount_pointwise21After_concat2Before;
// If ( pointwise21ChannelCount != channelCount1_pointwise1Before ), the shuffle-split algorithm can not work.
tf.util.assert( ( this.channelCount_pointwise21After_concat2Before == this.channelCount1_pointwise1Before ),
`PointDepthPoint.initer(): When concat2-shuffle-split, `
+ `input1's channel count ( ${this.channelCount1_pointwise1Before} ) `
+ `should be the same as output0's channel count ( ${this.channelCount_pointwise21After_concat2Before} ).`
);
}
this.outChannelsAll = this.outChannels0 + this.outChannels1;
this.concat2ShuffleSplit = new Concat2ShuffleSplit.Base( channelShuffler_ConcatPointwiseConv, bShuffleSplit, false, false );
// In theory, concat2 use the result of add-input0-to-pointwise21 as first parameter. In reality, it usually uses the result
// of pointwise21 (without add-input0-to-output) as first parameter.
TensorOpCounters.concat2ShuffleSplit = new TensorOpCounter.Base( ( ++TensorOpCounterId ) + TensorOpCounters_NamePostfix,
this.concat2ShuffleSplit, TensorOpCounters.addInput0ToPointwise21, TensorOpCounters.input1 );
} else {
//!!! ...unfinished... (2021/08/23)
this.channelCount_concat1After_pointwise2Before = this.channelCount_depthwise1After_concat1Before;
TensorOpCounters.concat2ShuffleSplit = TensorOpCounters.addInput0ToPointwise21;
}
++progressToAdvance.value;
yield progressRoot; // concat2-Shuffle-Split was ready. Report progress.
//!!! ...unfinished... (2021/08/23) channelShuffler_ConcatPointwiseConv, ConcatShuffleSplit, outputChannelCount
// 8. Configure correct function pointers according to whether keeping or destroying input tensor.
// 8.1 Determine which apply_Xxx() function should be used.
//
// This should be done before adjusting the first operation from "Xxx_destroy" to "Xxx_keep",
// because the adjustment might also need to select different apply_Xxx() function.
this.apply_and_destroy_or_keep = Base.Determine_apply_and_destroy_or_keep.call( this );
// 8.2 Adjust the destroy-or-keep behavior of every tensor according to whether the operation is the first operation or last operation.
{
let alwaysKeepSet;
if ( this.bKeepInputTensor ) { // User requests to keep input tensors.
alwaysKeepSet = new Set( [ TensorOpCounters.input0, TensorOpCounters.input1 ] );
}
// Using Set (instead of Array) so that duplicated TensorOpCounter will only be analyzed once.
// Note: When an operation does not exist, its output TensorOpCounter will be just its input TensorOpCounter (so duplicated).
let TensorOpCounterSet = new Set( [
TensorOpCounters.pointwise1, TensorOpCounters.depthwise1, TensorOpCounters.depthwise2, TensorOpCounters.concat1,
TensorOpCounters.pointwise21, TensorOpCounters.addInput0ToPointwise21,
TensorOpCounters.pointwise22, TensorOpCounters.addInput0ToPointwise22
] );
for ( let TensorOpCounter of TensorOpCounterSet ) {
TensorOpCounter.setKeepInputTensor_IfNotLastOperation_Or_In( alwaysKeepSet );
}
}
// 8.3
++progressToAdvance.value;
yield progressRoot; // All pointwise1-depthwise-pointwise2 filters was ready. Report progress.
this.bInitOk = true;
return true;
}
/**
* Initialize this object by calling initer() and advance the generator by loop until done.
*
* @param {ValueMax.Percentage.Aggregate} progressParent
* If null, a temporary progress object will be created.
*
* @return {boolean}
* Return true if successfully (and progressParent.valuePercentage will be equal to 100).
* Return false if failed (and progressParent.valuePercentage will be less than 100).
*/
init( progressParent, params, channelShuffler_ConcatPointwiseConv ) {
progressParent = progressParent || ( new ValueMax.Percentage.Aggregate() );
let initer = this.initer( progressParent, params, channelShuffler_ConcatPointwiseConv );
let initerNext;
do {
initerNext = initer.next();
} while ( ! initerNext.done ); // When ( false == initerNext.done ), the ( initerNext.value ) will be progressParent.getRoot().
let bInitOk = initerNext.value; // When ( true == initerNext.done ), the ( initerNext.value ) will be initialization successfully or failed.
return bInitOk;
}
/** Release all tensors. */
disposeTensors() {
if ( this.pointwise1 ) {
this.pointwise1.disposeTensors();
this.pointwise1 = null;
}
if ( this.depthwise1 ) {
this.depthwise1.disposeTensors();
this.depthwise1 = null;
}
if ( this.depthwise2 ) {
this.depthwise2.disposeTensors();
this.depthwise2 = null;
}
if ( this.concat1 ) {
this.concat1 = null;
}
if ( this.pointwise21 ) {
this.pointwise21.disposeTensors();
this.pointwise21 = null;
}
if ( this.pointwise22 ) {
this.pointwise22.disposeTensors();
this.pointwise22 = null;
}
if ( this.addInput0ToPointwise21 ) {
this.addInputToPointwise21Output = null;
}
if ( this.addInput0ToPointwise22 ) {
this.addInputToPointwise22Output = null;
}
if ( this.concat2ShuffleSplit ) {
this.concat2ShuffleSplit = null;
}
this.intermediateTensorsArray = null;
this.inputTensorCount
= this.bPointwise1
= this.bDepthwise1 = this.bDepthwise2 = this.bDepthwise2Requested
= this.bConcat1Requested
= this.bPointwise21 = this.bPointwise22 = this.bAddInputToOutputRequested
= this.bShouldAddInputToOutput = this.bShould_addInput0ToPointwise21 = this.bShould_addInput0ToPointwise22
= this.bConcat2ShuffleSplitRequested
= this.outputTensorCount
= undefined;
this.byteOffsetBegin = this.byteOffsetEnd = -1;
this.bInitOk = false;
}
/** Determine which apply_Xxx() function should be used.
* @return {function} Return one of the apply_Xxx function.
*/
static Determine_apply_and_destroy_or_keep() {
switch ( this.channelCount1_pointwise1Before ) {
// 1.
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_TWO_DEPTHWISE: // (-2) (simplified ShuffleNetV2's head)
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_1_2_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.3 Only pointwise22 existed (and no pointwise21).
} else {
return Base.apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2; // 4.4 Both pointwise21 and pointwise22 not existed. (Use pointwise21.)
}
}
break;
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT_ADD_TO_OUTPUT: // (-1) (MobileNetV2)
case Params.channelCount1_pointwise1Before.valueDesc.Ids.ONE_INPUT: // ( 0) (MobileNetV1)
if ( this.bShouldAddInputToOutput ) { // ( this.bAddInputToOutputRequested == true ) and possible to add-input-to-output.
// 2. add-input-to-output and (keep-input or destroy-input).
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
// 2.1 Both pointwise21 and pointwise22 exist.
//
// Although both pointwise21 and pointwise22 exist, but it may be only pointwise21 or pointwise22 could (or need) add-input-to-output.
if ( this.bShould_addInput0ToPointwise21 ) {
if ( this.bShould_addInput0ToPointwise22 ) {
// 2.1.1 Both pointwise21 and pointwise22 exist, and both addInput0ToPointwise21 and addInput0ToPointwise22 exist.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_2;
} else {
// 2.1.2 Both pointwise21 and pointwise22 exist, but only addInput0ToPointwise21 exists.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_21;
}
} else {
if ( this.bShould_addInput0ToPointwise22 ) {
// 2.1.3 Both pointwise21 and pointwise22 exist, but only addInput0ToPointwise22 exists.
return Base.apply_1_2_and_destroy_or_keep_AddInputToOutput_22;
} else {
// 2.1.4 Both pointwise21 and pointwise22 exist, but both addInput0ToPointwise21 and addInput0ToPointwise22 do not exist.
// It should not execute to here.
tf.util.assert( false,
`PointDepthPoint.Determine_apply_and_destroy_or_keep(), this.bShouldAddInputToOutput (${this.bShouldAddInputToOutput}) `
+ `should equal this.bShould_addInput0ToPointwise21 (${this.bShould_addInput0ToPointwise21}) `
+ ` or this.bShould_addInput0ToPointwise22 (${this.bShould_addInput0ToPointwise22}). ${this.parametersDescription}`);
return undefined;
}
}
} else {
return Base.apply_1_21_and_destroy_or_keep_AddInputToOutput; // 2.2 Only pointwise21 exists (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_AddInputToOutput; // 2.3 Only pointwise22 exists (and no pointwise21).
} else {
// 2.4 Both pointwise21 and pointwise22 do not exist. (Use pointwise21, but channel count is the same as channel count before pointwise2.)
return Base.apply_1_21_and_destroy_or_keep_AddInputToOutput;
}
}
} else {
// 3. no-add-input-to-output, no-concat, and destroy-input (or keep-input).
//
// ( this.inputTensorCount == 1 ) or ( ( this.bAddInputToOutputRequested == true ) but not-possible to add-input-to-output ).
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_1_2_and_destroy_or_keep_NoSkipConnection; // 3.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_1_21_and_destroy_or_keep_NoSkipConnection; // 3.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_1_22_and_destroy_or_keep_NoSkipConnection; // 3.3 Only pointwise22 existed (and no pointwise21).
} else {
// 3.4 Both pointwise21 and pointwise22 not existed.
// no pointwise1, no depthwise1, no concat1, no pointwise21, no addInput0ToPointwise21, no pointwise22, no addInput0ToPointwise22
if ( !this.bPointwise1 && !this.bDepthwise1 ) {
// Note: This may be wrong, however, if there are wrongly two input tensors (there should be only one input
// (i.e. inputTensors[ 0 ]) for should-add-input-to-output).
if ( this.bKeepInputTensor )
return Base.keep_input_return_copy_array; // 3.4.1
else
return Base.return_input_directly_array; // 3.4.2
} else {
return Base.apply_1_21_and_destroy_or_keep_NoSkipConnection; // 3.4.3 At least, there are pointwise1 or depthwise. (Use pointwise21.)
}
}
}
}
break;
// 4. (no-add-input-to-output but has) concat and destroy-input (or keep-input).
//
// ( this.inputTensorCount > 1 ).
default: // Params.channelCount1_pointwise1Before.valueDesc.Ids.TWO_INPUTS_XXX (> 0) (simplified ShuffleNetV2's tail)
if ( this.bPointwise21 ) {
if ( this.bPointwise22 ) {
return Base.apply_2_2_and_destroy_or_keep_ConcatInput1; // 4.1 Both pointwise21 and pointwise22 existed.
} else {
return Base.apply_2_21_and_destroy_or_keep_ConcatInput1; // 4.2 Only pointwise21 existed (and no pointwise22).
}
} else {
if ( this.bPointwise22 ) {
return Base.apply_2_22_and_destroy_or_keep_ConcatInput1; // 4.3 Only pointwise22 existed (and no pointwise21).
} else {
return Base.apply_2_21_and_destroy_or_keep_ConcatInput1; // 4.4 Both pointwise21 and pointwise22 not existed. (Use pointwise21.)
}
}
break;
}
}
/** The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 0 ]. */
static apply_1_21_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = null;
}
/** The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 1 ]. */
static apply_1_22_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/**
* The inputTensors[ 0 ] will be branched by depthwise2 and concatenated before outputTensors[ 0 ] and outputTensors[ 1 ].
* The input tensors may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_ConcatInput0Depthwise2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = this.depthwise2.pfnOperationBiasActivation( inputTensor );
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/** The only one input will be added to the only one output (pointwise21). The inputTensor may or may not be disposed.*/
static apply_1_21_and_destroy_or_keep_AddInputToOutput( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
outputTensors[ 1 ] = null;
}
/** The only one input will be added to the only one output (pointwise22). The inputTensor may or may not be disposed.*/
static apply_1_22_and_destroy_or_keep_AddInputToOutput( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to both of them.
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_2( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to only outputTensors[ 0 ].
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_21( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
t0 = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 0 ] = this.addInput0ToPointwise21.pfnAdd( inputTensor, t0 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/** Both outputTensors[ 0 ] and outputTensors[ 1 ] exist. The inputTensors[ 0 ] will be added to only outputTensors[ 1 ].
* The inputTensor may or may not be disposed.
*/
static apply_1_2_and_destroy_or_keep_AddInputToOutput_22( inputTensors, outputTensors ) {
let t0, t1;
let inputTensor = inputTensors[ 0 ];
t0 = this.pointwise1.pfnConvBiasActivation( inputTensor );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
t0 = this.pointwise22.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.addInput0ToPointwise22.pfnAdd( inputTensor, t0 );
}
/** One input to one output (pointwise21) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_21_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 ); // may destroy t1.
outputTensors[ 1 ] = null;
}
/** One input to one output (pointwise22) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_22_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 ); // may destroy t1.
}
/** One input to two output (pointwise21 and pointwise22) (i.e. no residual connection). The input tensors may or may not be disposed. */
static apply_1_2_and_destroy_or_keep_NoSkipConnection( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
t1 = this.depthwise1.pfnOperationBiasActivation( t0 );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 ); // may destroy t1.
}
/** The inputTensors[ 1 ] will be concatenated before outputTensors[ 0 ]. */
static apply_2_21_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = null;
}
/** The inputTensors[ 1 ] will be concatenated before outputTensors[ 1 ]. */
static apply_2_22_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = null;
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
/**
* The inputTensors[ 1 ] will be concatenated before outputTensors[ 0 ] and outputTensors[ 1 ].
* The input tensors may or may not be disposed.
*
* @param {tf.tensor[]} inputTensors
* An array of tensors. If ( this.inputTensorCount == 1 ), the inputTensors[ 0 ] will be used.
* If ( this.inputTensorCount == 2 ), the inputTensors[ 0 ] and inputTensors[ 1 ] will be used.
*
* @param {tf.tensor[]} outputTensors
* An array for returning the result (output) tensors. If ( this.outputTensorCount == 0 ) or ( this.outputTensorCount == 1 ),
* the outputTensors[ 0 ] will be the result. If ( this.outputTensorCount == 2 ), the outputTensors[ 0 ] and outputTensors[ 1 ] will
* be the result.
*/
static apply_2_2_and_destroy_or_keep_ConcatInput1( inputTensors, outputTensors ) {
let t0, t1;
t0 = this.pointwise1.pfnConvBiasActivation( inputTensors[ 0 ] );
this.intermediateTensorsArray[ 0 ] = this.depthwise1.pfnOperationBiasActivation( t0 );
this.intermediateTensorsArray[ 1 ] = inputTensors[ 1 ];
t1 = this.concat1.pfnConcat( this.intermediateTensorsArray );
outputTensors[ 0 ] = this.pointwise21.pfnConvBiasActivation( t1 );
outputTensors[ 1 ] = this.pointwise22.pfnConvBiasActivation( t1 );
}
//!!! ...unfinished... (2021/08/20) channelShuffler_ConcatPointwiseConv, ConcatShuffleSplit
/** @return {number} The channel count of the first input tensor (i.e. inputTensors[ 0 ]). */
get inChannels0() { return this.channelCount0_pointwise1Before; }
/** @return {number} The channel count of the second input tensor (i.e. inputTensors[ 1 ]). */
get inChannels1() { return this.channelCount1_pointwise1Before; }
//!!! ...unfinished... (2021/08/23 Remarked) Replaced by read/write property.
//
// /** @return {number} The channel count of the first output tensor (i.e. outputTensors[ 0 ]). */
// get outChannels0() { return this.channelCount_pointwise21After_concat2Before; }
//
// /** @return {number} The channel count of the second output tensor (i.e. outputTensors[ 1 ]). */
// get outChannels1() { return this.channelCount_pointwise22After_concat2Before; }
/
// /** @return {number} The channel count of both the first and second output tensors. */
// get outChannelsAll() { return this.channelCount_pointwise2After_concat2Before; }
/** @return {string} The description string of all (adjusted) parameters of initer(). */
get parametersDescription() {
let str =
`inputTensorCount=${this.inputTensorCount}, `
+ `inChannels0=${this.inChannels0}, inChannels1=${this.inChannels1}, `
+ `outChannels0=${this.outChannels0}, outChannels1=${this.outChannels1}, outChannelsAll=${this.outChannelsAll}, `
+ `channelCount1_pointwise1Before_Name=${this.channelCount1_pointwise1Before_Name}, `
+ `pointwise1ChannelCount=${this.pointwise1ChannelCount}, `
+ `bPointwise1Bias=${this.bPointwise1Bias}, `
+ `pointwise1ActivationName=${this.pointwise1ActivationName}, `
+ `bDepthwise2Requested=${this.bDepthwise2Requested}, `
+ `depthwise_AvgMax_Or_ChannelMultiplier=${this.depthwise_AvgMax_Or_ChannelMultiplier_Name}, `
+ `depthwiseFilterHeight=${this.depthwiseFilterHeight}, `
+ `depthwiseStridesPad=${this.depthwiseStridesPad}, `
+ `bDepthwiseBias=${this.bDepthwiseBias}, `
+ `depthwiseActivationName=${this.depthwiseActivationName}, `
+ `bConcat1Requested=${this.bConcat1Requested}, `
+ `pointwise21ChannelCount=${this.pointwise21ChannelCount}, `
+ `bPointwise21Bias=${this.bPointwise21Bias}, `
+ `pointwise21ActivationName=${this.pointwise21ActivationName}, `
+ `pointwise22ChannelCount=${this.pointwise22ChannelCount}, `
+ `pointwise22ChannelCountName=${this.pointwise22ChannelCountName}, `
+ `bPointwise22Bias=${this.bPointwise22Bias}, `
+ `pointwise22ActivationName=${this.pointwise22ActivationName}, `
+ `bAddInputToOutputRequested=${this.bAddInputToOutputRequested}, `
+ `bConcat2ShuffleSplitRequested=${this.bConcat2ShuffleSplitRequested}, `
+ `outputTensorCount=${this.outputTensorCount}, `
+ `bKeepInputTensor=${this.bKeepInputTensor}`
;
return str;
}
}
| Update PointDepthPoint.js | CNN/Conv/PointDepthPoint.js | Update PointDepthPoint.js | <ide><path>NN/Conv/PointDepthPoint.js
<ide> * @member {number} inChannels1
<ide> * The channel count of the second input tensor (i.e. inputTensors[ 1 ]). This is the same as this.channelCount1_pointwise1Before (from initer()).
<ide> *
<del>
<del>//!!! ...unfinished... (2021/08/22) What outChannels0, outChannels1, outChannels if shuffleSplit?
<del>
<ide> * @member {number} outChannels0
<del> * The channel count of the first output tensor. It is the same as this.channelCount_pointwise21After_concat2Before (from initer()).
<add> * The channel count of the outputTensor[ 0 ]. Even if ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ),
<add> * this will still be non-zero.
<ide> *
<ide> * @member {number} outChannels1
<del> * The channel count of the second output tensor. It is the same as this.channelCount_pointwise22After_concat2Before (from initer()).
<add> * The channel count of the outputTensor[ 1 ]. If ( pointwise22ChannelCount == 0 ), this will be zero.
<ide> *
<ide> * @member {number} outChannels
<del> * The channel count of all output tensor. It is the same as this.channelCount_pointwise2After_concat2Before (from initer()).
<add> * The channel count of all output tensors (i.e. both outputTensor[ 0 ] and outputTensor[ 1 ]).
<ide> *
<ide> * @member {number} channelCount_pointwise1After_depthwise1Before
<ide> * The channel count after the first 1x1 pointwise convolution. If ( pointwise1ChannelCount > 0 ), it equals pointwise1ChannelCount.
<ide> * if at least one pointwise2 convolution existed.
<ide> *
<ide> * - If both ( pointwise21ChannelCount == 0 ) and ( pointwise22ChannelCount == 0 ), it will be channelCount_concat1After_pointwise2Before.
<del> *
<del>
<del>//!!! ...unfinished... (2021/08/22)
<del>// channelCount_concat2After_shuffleBefore
<del>// channelCount_shuffleSplitAfter?
<del>
<ide> *
<ide> * @member {ChannelShuffler.ConcatPointwiseConv} channelShuffler_ConcatPointwiseConv
<ide> * The channelShuffler. It must be implemented by ChannelShuffler.ConcatPointwiseConv with ( outputGroupCount == 2 ).
<ide> } else { // ( this.outputTensorCount == 2 )
<ide> bShuffleSplit = true;
<ide> TensorOpCounters_NamePostfix = "_concat2ShuffleSplit";
<del> this.outChannels0 = this.channelCount_pointwise21After_concat2Before;
<del> this.outChannels1 = this.channelCount_pointwise21After_concat2Before;
<add> this.outChannels0 =
<add> this.outChannels1 = this.channelCount_pointwise21After_concat2Before; // Both output0 and output1 will have the same channel count.
<ide>
<ide> // If ( pointwise21ChannelCount != channelCount1_pointwise1Before ), the shuffle-split algorithm can not work.
<ide> tf.util.assert( ( this.channelCount_pointwise21After_concat2Before == this.channelCount1_pointwise1Before ),
<ide> );
<ide> }
<ide>
<del> this.outChannelsAll = this.outChannels0 + this.outChannels1;
<del>
<ide> this.concat2ShuffleSplit = new Concat2ShuffleSplit.Base( channelShuffler_ConcatPointwiseConv, bShuffleSplit, false, false );
<ide>
<ide> // In theory, concat2 use the result of add-input0-to-pointwise21 as first parameter. In reality, it usually uses the result
<ide> this.concat2ShuffleSplit, TensorOpCounters.addInput0ToPointwise21, TensorOpCounters.input1 );
<ide>
<ide> } else {
<del>
<del>//!!! ...unfinished... (2021/08/23)
<del> this.channelCount_concat1After_pointwise2Before = this.channelCount_depthwise1After_concat1Before;
<add> // Since no concat2(-shuffle-split), the final output come from pointwise2 (and add-input-to-output) directly.
<add> this.outChannels0 = this.channelCount_pointwise21After_concat2Before;
<add> this.outChannels1 = this.channelCount_pointwise22After_concat2Before;
<add>
<add>//!!! ...unfinished... (2021/08/23) How about the second input (i.e. TensorOpCounters.addInput0ToPointwise22)?
<ide> TensorOpCounters.concat2ShuffleSplit = TensorOpCounters.addInput0ToPointwise21;
<ide> }
<add>
<add> this.outChannelsAll = this.outChannels0 + this.outChannels1;
<ide>
<ide> ++progressToAdvance.value;
<ide> yield progressRoot; // concat2-Shuffle-Split was ready. Report progress. |
|
JavaScript | bsd-3-clause | f3660e26a19bda2ed0152b56055cd3636a7a5e84 | 0 | sakuragitevil/sakura,sakuragitevil/sakura | /**
* Created by VuThuan on 4/17/2016.
*/
(function ($) {
$.fn.yiiXhr2Upload = function (method) {
var yiiXhr2UploadView = {
id: '',
url: '',
dlg: 'dlgXhr2Upload',
init: function (options) {
yiiXhr2UploadView.id = options.id;
yiiXhr2UploadView.url = options.url;
$('#' + yiiXhr2UploadView.id).on('click', function () {
yiiXhr2UploadView.show_dialog();
});
},
show_dialog: function () {
$('#' + yiiXhr2UploadView.dlg).modal({keyboard: false});
$('#' + yiiXhr2UploadView.dlg).modal('show');
},
};
//Call functions
if (yiiXhr2UploadView[method]) {
return yiiXhr2UploadView[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return yiiXhr2UploadView.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiXhr2UploadView');
return false;
}
};
})(jQuery); | common/widgets/sakura/assets/js/jquery.xhr2.js | /**
* Created by VuThuan on 4/17/2016.
*/
(function ($) {
$.fn.yiiXhr2Upload = function (method) {
var yiiXhr2UploadView = {
id: '',
url: '',
dlg: 'dlgXhr2Upload',
init: function (options) {
yiiXhr2UploadView.id = options.id;
yiiXhr2UploadView.url = options.url;
$('#' + yiiXhr2UploadView.id).on('click', function () {
yiiXhr2UploadView.show_dialog();
});
},
show_dialog: function () {
$('#' + yiiXhr2UploadView.dlg).modal({keyboard: false});
$('#' + yiiXhr2UploadView.dlg).modal('show');
},
};
//Call functions
if (yiiXhr2UploadView[method]) {
return yiiXhr2UploadView[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return yiiXhr2UploadView.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiXhr2UploadView');
return false;
}
};
})(jQuery); | Thuan-20160421-8:07AM
| common/widgets/sakura/assets/js/jquery.xhr2.js | Thuan-20160421-8:07AM | <ide><path>ommon/widgets/sakura/assets/js/jquery.xhr2.js
<ide> return false;
<ide> }
<ide> };
<del>
<ide> })(jQuery); |
|
Java | apache-2.0 | 08fa28be1c7dc5a8c6e36e72cf7a904b36cbf477 | 0 | gk-brown/HTTP-RPC,gk-brown/HTTP-RPC,gk-brown/WebRPC,gk-brown/WebRPC,gk-brown/WebRPC,gk-brown/HTTP-RPC,gk-brown/WebRPC,gk-brown/WebRPC,gk-brown/WebRPC | /*
* 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.httprpc;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Executable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.Principal;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.httprpc.beans.BeanAdapter;
import org.httprpc.io.PagedReader;
/**
* Servlet that dispatches HTTP-RPC web service requests.
*/
public class RequestDispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 0;
/**
* Method descriptor.
*/
public static final class MethodDescriptor {
private Method method;
private ResourceBundle resourceBundle;
private MethodDescriptor(Method method, ResourceBundle resourceBundle) {
this.method = method;
this.resourceBundle = resourceBundle;
}
/**
* Returns the method's name.
*
* @return
* The name of the method.
*/
public String getName() {
return method.getName();
}
/**
* Returns the method's description.
*
* @return
* A localized description of the method.
*/
public String getDescription() {
String description = null;
if (resourceBundle != null) {
try {
description = resourceBundle.getString(method.getName());
} catch (MissingResourceException exception) {
// No-op
}
}
return description;
}
/**
* Returns the method's parameters.
*
* @return
* A list of the method's parameters.
*/
public ParameterDescriptorList getParameters() {
return new ParameterDescriptorList(method.getParameters(), resourceBundle);
}
/**
* Returns the method's return type.
*
* @return
* The type of the value returned by the method, or <tt>null</tt> if
* the method does not return a value.
*/
public String getReturns() {
return getDescriptorType(method.getReturnType());
}
}
/**
* Parameter descriptor list.
*/
public static final class ParameterDescriptorList extends AbstractList<ParameterDescriptor> {
private Parameter[] parameters;
private ResourceBundle resourceBundle;
private ParameterDescriptorList(Parameter[] parameters, ResourceBundle resourceBundle) {
this.parameters = parameters;
this.resourceBundle = resourceBundle;
}
@Override
public ParameterDescriptor get(int index) {
return new ParameterDescriptor(parameters[index], resourceBundle);
}
@Override
public int size() {
return parameters.length;
}
}
/**
* Parameter descriptor.
*/
public static final class ParameterDescriptor {
private Parameter parameter;
private ResourceBundle resourceBundle;
private ParameterDescriptor(Parameter parameter, ResourceBundle resourceBundle) {
this.parameter = parameter;
this.resourceBundle = resourceBundle;
}
/**
* Returns the parameter's name.
*
* @return
* The name of the parameter.
*/
public String getName() {
return parameter.getName();
}
/**
* Returns the parameters's description.
*
* @return
* A localized description of the parameters.
*/
public String getDescription() {
String description = null;
if (resourceBundle != null) {
Executable method = parameter.getDeclaringExecutable();
try {
description = resourceBundle.getString(method.getName() + "_" + parameter.getName());
} catch (MissingResourceException exception) {
// No-op
}
}
return description;
}
/**
* Returns the parameter's type.
*
* @return
* The type of the parameter.
*/
public String getType() {
return getDescriptorType(parameter.getType());
}
}
// User role set
private static class UserRoleSet extends AbstractSet<String> {
private HttpServletRequest request;
public UserRoleSet(HttpServletRequest request) {
this.request = request;
}
@Override
public boolean contains(Object object) {
return request.isUserInRole(object.toString());
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator() {
throw new UnsupportedOperationException();
}
}
private Class<?> serviceType = null;
private TreeMap<String, Method> methodMap = new TreeMap<>();
private static final String STRING_TYPE = "string";
private static final String NUMBER_TYPE = "number";
private static final String BOOLEAN_TYPE = "boolean";
private static final String ARRAY_TYPE = "array";
private static final String OBJECT_TYPE = "object";
private static final String UNSUPPORTED_TYPE = "?";
private static final String JSON_MIME_TYPE = "application/json; charset=UTF-8";
@Override
public void init() throws ServletException {
String serviceClassName = getServletConfig().getInitParameter("serviceClassName");
try {
serviceType = Class.forName(serviceClassName);
} catch (ClassNotFoundException exception) {
throw new ServletException(exception);
}
if (!WebService.class.isAssignableFrom(serviceType)) {
throw new ServletException("Invalid service type.");
}
Method[] methods = serviceType.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (serviceType.isAssignableFrom(method.getDeclaringClass())) {
methodMap.put(method.getName(), method);
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String pathInfo = request.getPathInfo();
if (pathInfo == null) {
// Write method descriptor list
ResourceBundle resourceBundle = null;
try {
resourceBundle = ResourceBundle.getBundle(serviceType.getName(), request.getLocale());
} catch (MissingResourceException exception) {
// No-op
}
LinkedList<MethodDescriptor> methodDescriptorList = new LinkedList<>();
for (Method method : methodMap.values()) {
methodDescriptorList.add(new MethodDescriptor(method, resourceBundle));
}
writeValue(response.getWriter(), BeanAdapter.adapt(methodDescriptorList), 0);
} else {
// Look up service method
Method method = methodMap.get(pathInfo.substring(1));
if (method == null) {
throw new ServletException("Method not found.");
}
// Construct arguments
Parameter[] parameters = method.getParameters();
Object[] arguments = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
String name = parameter.getName();
Class<?> type = parameter.getType();
Object argument;
if (type == List.class) {
String[] values = request.getParameterValues(name);
List<Object> list;
if (values != null) {
ParameterizedType parameterizedType = (ParameterizedType)parameter.getParameterizedType();
Type elementType = parameterizedType.getActualTypeArguments()[0];
int n = values.length;
list = new ArrayList<>(n);
for (int j = 0; j < n; j++) {
list.add(coerce(values[j], elementType));
}
} else {
list = Collections.EMPTY_LIST;
}
argument = list;
} else {
argument = coerce(request.getParameter(name), type);
}
arguments[i] = argument;
}
// Execute method
WebService service;
try {
service = (WebService)serviceType.newInstance();
} catch (IllegalAccessException | InstantiationException exception) {
throw new ServletException(exception);
}
service.setLocale(request.getLocale());
Principal userPrincipal = request.getUserPrincipal();
if (userPrincipal != null) {
service.setUserName(userPrincipal.getName());
service.setUserRoles(new UserRoleSet(request));
}
Object result;
try {
result = method.invoke(service, arguments);
} catch (IllegalAccessException | InvocationTargetException exception) {
throw new ServletException(exception);
}
// Write response
Class<?> returnType = method.getReturnType();
if (returnType != Void.TYPE && returnType != Void.class) {
response.setContentType(JSON_MIME_TYPE);
writeValue(response.getWriter(), result, 0);
}
}
}
private static String getDescriptorType(Class<?> type) {
String descriptorType;
if (type == String.class) {
descriptorType = STRING_TYPE;
} else if (type == Byte.TYPE
|| type == Short.TYPE
|| type == Integer.TYPE
|| type == Float.TYPE
|| type == Double.TYPE
|| Number.class.isAssignableFrom(type)) {
descriptorType = NUMBER_TYPE;
} else if (type == Boolean.TYPE || type == Boolean.class) {
descriptorType = BOOLEAN_TYPE;
} else if (List.class.isAssignableFrom(type)) {
descriptorType = ARRAY_TYPE;
} else if (Map.class.isAssignableFrom(type)) {
descriptorType = OBJECT_TYPE;
} else if (type == Void.TYPE || type == Void.class) {
descriptorType = null;
} else {
descriptorType = UNSUPPORTED_TYPE;
}
return descriptorType;
}
private static Object coerce(String value, Type type) throws ServletException {
Object argument;
if (value == null || type == String.class) {
argument = value;
} else if (type == Byte.TYPE || type == Byte.class) {
argument = Byte.parseByte(value);
} else if (type == Short.TYPE || type == Short.class) {
argument = Short.parseShort(value);
} else if (type == Integer.TYPE || type == Integer.class) {
argument = Integer.parseInt(value);
} else if (type == Long.TYPE || type == Long.class) {
argument = Long.parseLong(value);
} else if (type == Float.TYPE || type == Float.class) {
argument = Float.parseFloat(value);
} else if (type == Double.TYPE || type == Double.class) {
argument = Double.parseDouble(value);
} else if (type == BigInteger.class) {
argument = new BigInteger(value);
} else if (type == BigDecimal.class) {
argument = new BigDecimal(value);
} else if (type == Boolean.TYPE || type == Boolean.class) {
argument = Boolean.parseBoolean(value);
} else {
throw new ServletException("Invalid parameter type.");
}
return argument;
}
private static void writeValue(PrintWriter writer, Object value, int depth) throws IOException {
JSONSerializer serializer = new JSONSerializer();
serializer.writeValue(writer, value);
}
}
abstract class Serializer<V> {
abstract void writeValue(PrintWriter writer, V value) throws IOException;
}
class JSONSerializer extends Serializer<Object> {
int depth = 0;
@Override
void writeValue(PrintWriter writer, Object value) throws IOException {
if (writer.checkError()) {
throw new IOException("Error writing to output stream.");
}
if (value == null) {
writer.append(null);
} else if (value instanceof String) {
String string = (String)value;
writer.append("\"");
for (int i = 0, n = string.length(); i < n; i++) {
char c = string.charAt(i);
switch (c) {
case '"':
case '\\':
case '/': {
writer.append("\\" + c);
break;
}
case '\b': {
writer.append("\\b");
break;
}
case '\f': {
writer.append("\\f");
break;
}
case '\n': {
writer.append("\\n");
break;
}
case '\r': {
writer.append("\\r");
break;
}
case '\t': {
writer.append("\\t");
break;
}
default: {
writer.append(c);
}
}
}
writer.append("\"");
} else if (value instanceof Number || value instanceof Boolean) {
writer.append(String.valueOf(value));
} else {
try {
if (value instanceof List<?>) {
List<?> list = (List<?>)value;
writer.append("[");
depth++;
int i = 0;
for (Object element : list) {
if (i > 0) {
writer.append(",");
}
writer.append("\n");
indent(writer, depth);
writeValue(writer, element);
i++;
}
depth--;
writer.append("\n");
indent(writer, depth);
writer.append("]");
} else if (value instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>)value;
writer.append("{");
depth++;
int i = 0;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (i > 0) {
writer.append(",");
}
writer.append("\n");
Object key = entry.getKey();
if (!(key instanceof String)) {
throw new IOException("Invalid key type.");
}
indent(writer, depth);
writer.append("\"" + key + "\": ");
writeValue(writer, entry.getValue());
i++;
}
depth--;
writer.append("\n");
indent(writer, depth);
writer.append("}");
} else {
throw new IOException("Invalid value type.");
}
} finally {
if (value instanceof AutoCloseable) {
try {
((AutoCloseable)value).close();
} catch (Exception exception) {
throw new IOException(exception);
}
}
}
}
}
static void indent(Writer writer, int depth) throws IOException {
for (int i = 0; i < depth; i++) {
writer.append(" ");
}
}
}
class TemplateSerializer extends Serializer<Map<String, ?>> {
enum MarkerType {
SECTION_START,
SECTION_END,
COMMENT,
INCLUDE,
VARIABLE
}
static class Section {
Section(String marker, Iterator<Map<String, ?>> iterator, Map<String, ?> dictionary) {
this.marker = marker;
this.iterator = iterator;
this.dictionary = dictionary;
}
final String marker;
final Iterator<Map<String, ?>> iterator;
Map<String, ?> dictionary;
}
static final int EOF = -1;
LinkedList<Section> sections = new LinkedList<>();
@Override
@SuppressWarnings("unchecked")
void writeValue(PrintWriter writer, Map<String, ?> root) throws IOException {
if (root.isEmpty()) {
return;
}
sections.push(new Section(null, Collections.emptyIterator(), root));
try (PagedReader reader = new PagedReader(null)) { // TODO Open template stream
int c = reader.read();
while (c != EOF) {
if (writer.checkError()) {
throw new IOException("Error writing to output stream.");
}
if (c == '{') {
c = reader.read();
if (c == '{') {
c = reader.read();
MarkerType markerType;
if (c == '#') {
markerType = MarkerType.SECTION_START;
} else if (c == '/') {
markerType = MarkerType.SECTION_END;
} else if (c == '!') {
markerType = MarkerType.COMMENT;
} else if (c == '>') {
markerType = MarkerType.INCLUDE;
} else {
markerType = MarkerType.VARIABLE;
}
if (markerType != MarkerType.VARIABLE) {
c = reader.read();
}
StringBuilder markerBuilder = new StringBuilder();
while (c != '}' && c != EOF) {
markerBuilder.append(c);
c = reader.read();
}
if (c == EOF) {
throw new IOException("Unexpected end of character stream.");
}
c = reader.read();
if (c != '}') {
throw new IOException("Improperly terminated marker.");
}
String marker = markerBuilder.toString();
switch (markerType) {
case SECTION_START: {
Object value = sections.peek().dictionary.get(marker);
if (!(value instanceof List<?>)) {
throw new IOException("Section marker does not refer to a list.");
}
Iterator<Map<String, ?>> iterator = ((List<Map<String, ?>>)value).iterator();
Map<String, ?> dictionary;
if (iterator.hasNext()) {
dictionary = iterator.next();
reader.mark(0);
} else {
dictionary = null;
}
sections.push(new Section(marker, iterator, dictionary));
break;
}
case SECTION_END: {
Section section = sections.peek();
if (!section.marker.equals(marker)) {
throw new IOException("Section markers do not match.");
}
if (section.iterator.hasNext()) {
section.dictionary = section.iterator.next();
reader.reset();
if (section.iterator.hasNext()) {
reader.mark(0);
}
} else {
sections.pop();
}
break;
}
case COMMENT: {
// No-op
break;
}
case INCLUDE: {
throw new IOException("Includes are not currently supported.");
}
case VARIABLE: {
Object value = sections.peek().dictionary.get(marker);
if (value != null) {
writer.append(value.toString());
}
break;
}
default: {
throw new UnsupportedOperationException();
}
}
} else {
writer.append((char)c);
}
} else {
writer.append((char)c);
}
c = reader.read();
}
}
}
}
| Server/Java/httprpc-server/src/org/httprpc/RequestDispatcherServlet.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.httprpc;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.reflect.Executable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.Principal;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.httprpc.beans.BeanAdapter;
import org.httprpc.io.PagedReader;
/**
* Servlet that dispatches HTTP-RPC web service requests.
*/
public class RequestDispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 0;
/**
* Method descriptor.
*/
public static final class MethodDescriptor {
private Method method;
private ResourceBundle resourceBundle;
private MethodDescriptor(Method method, ResourceBundle resourceBundle) {
this.method = method;
this.resourceBundle = resourceBundle;
}
/**
* Returns the method's name.
*
* @return
* The name of the method.
*/
public String getName() {
return method.getName();
}
/**
* Returns the method's description.
*
* @return
* A localized description of the method.
*/
public String getDescription() {
String description = null;
if (resourceBundle != null) {
try {
description = resourceBundle.getString(method.getName());
} catch (MissingResourceException exception) {
// No-op
}
}
return description;
}
/**
* Returns the method's parameters.
*
* @return
* A list of the method's parameters.
*/
public ParameterDescriptorList getParameters() {
return new ParameterDescriptorList(method.getParameters(), resourceBundle);
}
/**
* Returns the method's return type.
*
* @return
* The type of the value returned by the method, or <tt>null</tt> if
* the method does not return a value.
*/
public String getReturns() {
return getDescriptorType(method.getReturnType());
}
}
/**
* Parameter descriptor list.
*/
public static final class ParameterDescriptorList extends AbstractList<ParameterDescriptor> {
private Parameter[] parameters;
private ResourceBundle resourceBundle;
private ParameterDescriptorList(Parameter[] parameters, ResourceBundle resourceBundle) {
this.parameters = parameters;
this.resourceBundle = resourceBundle;
}
@Override
public ParameterDescriptor get(int index) {
return new ParameterDescriptor(parameters[index], resourceBundle);
}
@Override
public int size() {
return parameters.length;
}
}
/**
* Parameter descriptor.
*/
public static final class ParameterDescriptor {
private Parameter parameter;
private ResourceBundle resourceBundle;
private ParameterDescriptor(Parameter parameter, ResourceBundle resourceBundle) {
this.parameter = parameter;
this.resourceBundle = resourceBundle;
}
/**
* Returns the parameter's name.
*
* @return
* The name of the parameter.
*/
public String getName() {
return parameter.getName();
}
/**
* Returns the parameters's description.
*
* @return
* A localized description of the parameters.
*/
public String getDescription() {
String description = null;
if (resourceBundle != null) {
Executable method = parameter.getDeclaringExecutable();
try {
description = resourceBundle.getString(method.getName() + "_" + parameter.getName());
} catch (MissingResourceException exception) {
// No-op
}
}
return description;
}
/**
* Returns the parameter's type.
*
* @return
* The type of the parameter.
*/
public String getType() {
return getDescriptorType(parameter.getType());
}
}
// User role set
private static class UserRoleSet extends AbstractSet<String> {
private HttpServletRequest request;
public UserRoleSet(HttpServletRequest request) {
this.request = request;
}
@Override
public boolean contains(Object object) {
return request.isUserInRole(object.toString());
}
@Override
public int size() {
throw new UnsupportedOperationException();
}
@Override
public Iterator<String> iterator() {
throw new UnsupportedOperationException();
}
}
private Class<?> serviceType = null;
private TreeMap<String, Method> methodMap = new TreeMap<>();
private static final String STRING_TYPE = "string";
private static final String NUMBER_TYPE = "number";
private static final String BOOLEAN_TYPE = "boolean";
private static final String ARRAY_TYPE = "array";
private static final String OBJECT_TYPE = "object";
private static final String UNSUPPORTED_TYPE = "?";
private static final String JSON_MIME_TYPE = "application/json; charset=UTF-8";
@Override
public void init() throws ServletException {
String serviceClassName = getServletConfig().getInitParameter("serviceClassName");
try {
serviceType = Class.forName(serviceClassName);
} catch (ClassNotFoundException exception) {
throw new ServletException(exception);
}
if (!WebService.class.isAssignableFrom(serviceType)) {
throw new ServletException("Invalid service type.");
}
Method[] methods = serviceType.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (serviceType.isAssignableFrom(method.getDeclaringClass())) {
methodMap.put(method.getName(), method);
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doPost(request, response);
}
@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String pathInfo = request.getPathInfo();
if (pathInfo == null) {
// Write method descriptor list
ResourceBundle resourceBundle = null;
try {
resourceBundle = ResourceBundle.getBundle(serviceType.getName(), request.getLocale());
} catch (MissingResourceException exception) {
// No-op
}
LinkedList<MethodDescriptor> methodDescriptorList = new LinkedList<>();
for (Method method : methodMap.values()) {
methodDescriptorList.add(new MethodDescriptor(method, resourceBundle));
}
writeValue(response.getWriter(), BeanAdapter.adapt(methodDescriptorList), 0);
} else {
// Look up service method
Method method = methodMap.get(pathInfo.substring(1));
if (method == null) {
throw new ServletException("Method not found.");
}
// Construct arguments
Parameter[] parameters = method.getParameters();
Object[] arguments = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
String name = parameter.getName();
Class<?> type = parameter.getType();
Object argument;
if (type == List.class) {
String[] values = request.getParameterValues(name);
List<Object> list;
if (values != null) {
ParameterizedType parameterizedType = (ParameterizedType)parameter.getParameterizedType();
Type elementType = parameterizedType.getActualTypeArguments()[0];
int n = values.length;
list = new ArrayList<>(n);
for (int j = 0; j < n; j++) {
list.add(coerce(values[j], elementType));
}
} else {
list = Collections.EMPTY_LIST;
}
argument = list;
} else {
argument = coerce(request.getParameter(name), type);
}
arguments[i] = argument;
}
// Execute method
WebService service;
try {
service = (WebService)serviceType.newInstance();
} catch (IllegalAccessException | InstantiationException exception) {
throw new ServletException(exception);
}
service.setLocale(request.getLocale());
Principal userPrincipal = request.getUserPrincipal();
if (userPrincipal != null) {
service.setUserName(userPrincipal.getName());
service.setUserRoles(new UserRoleSet(request));
}
Object result;
try {
result = method.invoke(service, arguments);
} catch (IllegalAccessException | InvocationTargetException exception) {
throw new ServletException(exception);
}
// Write response
Class<?> returnType = method.getReturnType();
if (returnType != Void.TYPE && returnType != Void.class) {
response.setContentType(JSON_MIME_TYPE);
writeValue(response.getWriter(), result, 0);
}
}
}
private static String getDescriptorType(Class<?> type) {
String descriptorType;
if (type == String.class) {
descriptorType = STRING_TYPE;
} else if (type == Byte.TYPE
|| type == Short.TYPE
|| type == Integer.TYPE
|| type == Float.TYPE
|| type == Double.TYPE
|| Number.class.isAssignableFrom(type)) {
descriptorType = NUMBER_TYPE;
} else if (type == Boolean.TYPE || type == Boolean.class) {
descriptorType = BOOLEAN_TYPE;
} else if (List.class.isAssignableFrom(type)) {
descriptorType = ARRAY_TYPE;
} else if (Map.class.isAssignableFrom(type)) {
descriptorType = OBJECT_TYPE;
} else if (type == Void.TYPE || type == Void.class) {
descriptorType = null;
} else {
descriptorType = UNSUPPORTED_TYPE;
}
return descriptorType;
}
private static Object coerce(String value, Type type) throws ServletException {
Object argument;
if (value == null || type == String.class) {
argument = value;
} else if (type == Byte.TYPE || type == Byte.class) {
argument = Byte.parseByte(value);
} else if (type == Short.TYPE || type == Short.class) {
argument = Short.parseShort(value);
} else if (type == Integer.TYPE || type == Integer.class) {
argument = Integer.parseInt(value);
} else if (type == Long.TYPE || type == Long.class) {
argument = Long.parseLong(value);
} else if (type == Float.TYPE || type == Float.class) {
argument = Float.parseFloat(value);
} else if (type == Double.TYPE || type == Double.class) {
argument = Double.parseDouble(value);
} else if (type == BigInteger.class) {
argument = new BigInteger(value);
} else if (type == BigDecimal.class) {
argument = new BigDecimal(value);
} else if (type == Boolean.TYPE || type == Boolean.class) {
argument = Boolean.parseBoolean(value);
} else {
throw new ServletException("Invalid parameter type.");
}
return argument;
}
private static void writeValue(PrintWriter writer, Object value, int depth) throws IOException {
JSONSerializer serializer = new JSONSerializer();
serializer.writeValue(writer, value);
}
}
abstract class Serializer<V> {
abstract void writeValue(PrintWriter writer, V value) throws IOException;
}
class JSONSerializer extends Serializer<Object> {
@Override
void writeValue(PrintWriter writer, Object value) throws IOException {
writeValue(writer, value, 0);
}
private static void writeValue(PrintWriter writer, Object value, int depth) throws IOException {
if (writer.checkError()) {
throw new IOException("Error writing to output stream.");
}
if (value == null) {
writer.append(null);
} else if (value instanceof String) {
String string = (String)value;
writer.append("\"");
for (int i = 0, n = string.length(); i < n; i++) {
char c = string.charAt(i);
switch (c) {
case '"':
case '\\':
case '/': {
writer.append("\\" + c);
break;
}
case '\b': {
writer.append("\\b");
break;
}
case '\f': {
writer.append("\\f");
break;
}
case '\n': {
writer.append("\\n");
break;
}
case '\r': {
writer.append("\\r");
break;
}
case '\t': {
writer.append("\\t");
break;
}
default: {
writer.append(c);
}
}
}
writer.append("\"");
} else if (value instanceof Number || value instanceof Boolean) {
writer.append(String.valueOf(value));
} else {
try {
if (value instanceof List<?>) {
List<?> list = (List<?>)value;
writer.append("[");
depth++;
int i = 0;
for (Object element : list) {
if (i > 0) {
writer.append(",");
}
writer.append("\n");
indent(writer, depth);
writeValue(writer, element, depth);
i++;
}
depth--;
writer.append("\n");
indent(writer, depth);
writer.append("]");
} else if (value instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>)value;
writer.append("{");
depth++;
int i = 0;
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (i > 0) {
writer.append(",");
}
writer.append("\n");
Object key = entry.getKey();
if (!(key instanceof String)) {
throw new IOException("Invalid key type.");
}
indent(writer, depth);
writer.append("\"" + key + "\": ");
writeValue(writer, entry.getValue(), depth);
i++;
}
depth--;
writer.append("\n");
indent(writer, depth);
writer.append("}");
} else {
throw new IOException("Invalid value type.");
}
} finally {
if (value instanceof AutoCloseable) {
try {
((AutoCloseable)value).close();
} catch (Exception exception) {
throw new IOException(exception);
}
}
}
}
}
private static void indent(Writer writer, int depth) throws IOException {
for (int i = 0; i < depth; i++) {
writer.append(" ");
}
}
}
class TemplateSerializer extends Serializer<Map<String, ?>> {
enum MarkerType {
SECTION_START,
SECTION_END,
COMMENT,
INCLUDE,
VARIABLE
}
static class Section {
public Section(String marker, Iterator<Map<String, ?>> iterator, Map<String, ?> dictionary) {
this.marker = marker;
this.iterator = iterator;
this.dictionary = dictionary;
}
private final String marker;
private final Iterator<Map<String, ?>> iterator;
private Map<String, ?> dictionary;
}
private static final int EOF = -1;
private LinkedList<Section> sections = new LinkedList<>();
@Override
@SuppressWarnings("unchecked")
void writeValue(PrintWriter writer, Map<String, ?> root) throws IOException {
if (root.isEmpty()) {
return;
}
sections.push(new Section(null, Collections.emptyIterator(), root));
try (PagedReader reader = new PagedReader(null)) { // TODO Open template stream
int c = reader.read();
while (c != EOF) {
if (writer.checkError()) {
throw new IOException("Error writing to output stream.");
}
if (c == '{') {
c = reader.read();
if (c == '{') {
c = reader.read();
MarkerType markerType;
if (c == '#') {
markerType = MarkerType.SECTION_START;
} else if (c == '/') {
markerType = MarkerType.SECTION_END;
} else if (c == '!') {
markerType = MarkerType.COMMENT;
} else if (c == '>') {
markerType = MarkerType.INCLUDE;
} else {
markerType = MarkerType.VARIABLE;
}
if (markerType != MarkerType.VARIABLE) {
c = reader.read();
}
StringBuilder markerBuilder = new StringBuilder();
while (c != '}' && c != EOF) {
markerBuilder.append(c);
c = reader.read();
}
if (c == EOF) {
throw new IOException("Unexpected end of character stream.");
}
c = reader.read();
if (c != '}') {
throw new IOException("Improperly terminated marker.");
}
String marker = markerBuilder.toString();
switch (markerType) {
case SECTION_START: {
Object value = sections.peek().dictionary.get(marker);
if (!(value instanceof List<?>)) {
throw new IOException("Section marker does not refer to a list.");
}
Iterator<Map<String, ?>> iterator = ((List<Map<String, ?>>)value).iterator();
Map<String, ?> dictionary;
if (iterator.hasNext()) {
dictionary = iterator.next();
reader.mark(0);
} else {
dictionary = null;
}
sections.push(new Section(marker, iterator, dictionary));
break;
}
case SECTION_END: {
Section section = sections.peek();
if (!section.marker.equals(marker)) {
throw new IOException("Section markers do not match.");
}
if (section.iterator.hasNext()) {
section.dictionary = section.iterator.next();
reader.reset();
if (section.iterator.hasNext()) {
reader.mark(0);
}
} else {
sections.pop();
}
break;
}
case COMMENT: {
// No-op
break;
}
case INCLUDE: {
throw new IOException("Includes are not currently supported.");
}
case VARIABLE: {
Object value = sections.peek().dictionary.get(marker);
if (value != null) {
writer.append(value.toString());
}
break;
}
default: {
throw new UnsupportedOperationException();
}
}
} else {
writer.append((char)c);
}
} else {
writer.append((char)c);
}
c = reader.read();
}
}
}
}
| Move depth to member variable in JSONSerializer.
| Server/Java/httprpc-server/src/org/httprpc/RequestDispatcherServlet.java | Move depth to member variable in JSONSerializer. | <ide><path>erver/Java/httprpc-server/src/org/httprpc/RequestDispatcherServlet.java
<ide> }
<ide>
<ide> class JSONSerializer extends Serializer<Object> {
<add> int depth = 0;
<add>
<ide> @Override
<ide> void writeValue(PrintWriter writer, Object value) throws IOException {
<del> writeValue(writer, value, 0);
<del> }
<del>
<del> private static void writeValue(PrintWriter writer, Object value, int depth) throws IOException {
<ide> if (writer.checkError()) {
<ide> throw new IOException("Error writing to output stream.");
<ide> }
<ide>
<ide> indent(writer, depth);
<ide>
<del> writeValue(writer, element, depth);
<add> writeValue(writer, element);
<ide>
<ide> i++;
<ide> }
<ide>
<ide> writer.append("\"" + key + "\": ");
<ide>
<del> writeValue(writer, entry.getValue(), depth);
<add> writeValue(writer, entry.getValue());
<ide>
<ide> i++;
<ide> }
<ide> }
<ide> }
<ide>
<del> private static void indent(Writer writer, int depth) throws IOException {
<add> static void indent(Writer writer, int depth) throws IOException {
<ide> for (int i = 0; i < depth; i++) {
<ide> writer.append(" ");
<ide> }
<ide> }
<ide>
<ide> static class Section {
<del> public Section(String marker, Iterator<Map<String, ?>> iterator, Map<String, ?> dictionary) {
<add> Section(String marker, Iterator<Map<String, ?>> iterator, Map<String, ?> dictionary) {
<ide> this.marker = marker;
<ide> this.iterator = iterator;
<ide>
<ide> this.dictionary = dictionary;
<ide> }
<ide>
<del> private final String marker;
<del> private final Iterator<Map<String, ?>> iterator;
<del>
<del> private Map<String, ?> dictionary;
<del> }
<del>
<del> private static final int EOF = -1;
<del>
<del> private LinkedList<Section> sections = new LinkedList<>();
<add> final String marker;
<add> final Iterator<Map<String, ?>> iterator;
<add>
<add> Map<String, ?> dictionary;
<add> }
<add>
<add> static final int EOF = -1;
<add>
<add> LinkedList<Section> sections = new LinkedList<>();
<ide>
<ide> @Override
<ide> @SuppressWarnings("unchecked") |
|
Java | mit | 6c97bf4d155c9bdb5d7da5f1e6e4e9cdb80ec4b6 | 0 | senilica/LostVaults,senilica/LostVaults | package lostvaults.client;
import javax.swing.*;
import javax.swing.JDialog;
import java.awt.*;
import java.awt.event.*;
public class GUI {
String name;
int screenWidth;
int screenHeight;
JTextArea dynamicInfo = new JTextArea();
JTextField commandInputField = new JTextField();
JTextArea dungeonPlayers = new JTextArea();
JTextArea roomPlayers = new JTextArea();
JTextArea others = new JTextArea();
JTextArea items = new JTextArea();
JTextArea exits = new JTextArea();
JLabel stats = new JLabel();
JFrame window = new JFrame("The Lost Vaults");
Color darkBackground = new Color(0x800000);
Color lightBackground = new Color(0xDAC8A3);
Color textColor = new Color(0x3D1515);
Color lightTextColor = new Color(0xDE9D5C);
Color mediumBackground = new Color(0xC2A366);
Color darkMediumBackground = new Color(0xB58C3C);
Font font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
Font bigFont = new Font("Serif", Font.BOLD + Font.ITALIC, 15);
public String getName() { return name; }
public GUI() {
// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = 1000; // screenSize.width;
screenHeight = 600; // screenSize.height;
window.setSize(screenWidth, screenHeight);
// window.setUndecorated(true); //true -> no exit button
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dynamicInfo.setEditable(false);
dynamicInfo.setBackground(lightBackground);
dynamicInfo.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
dynamicInfo.setFont(font);
dynamicInfo.setForeground(textColor);
JScrollPane dynamicInfoScroll = new JScrollPane(dynamicInfo);
dynamicInfo.setCaretPosition(dynamicInfo.getDocument().getLength());
dynamicInfoScroll.setBorder(BorderFactory.createEmptyBorder());
stats.setText("HP: 20/20 \t Food: 30/30");
stats.setFont(font);
stats.setForeground(lightTextColor);
JPanel dungeonPlayersPanel = createRightBox(dungeonPlayers, "Players in Dungeon: ");
JPanel roomPlayersPanel = createRightBox(roomPlayers, "Players in Room: ");
JPanel othersPanel = createRightBox(others, "Others in Room: ");
JPanel itemsPanel = createRightBox(items, "Items in Room: ");
exits.setFont(font);
exits.setForeground(textColor);
exits.setBackground(mediumBackground);
exits.setEditable(false);
JLabel exitsLabel = new JLabel("Exits in Room: ");
exitsLabel.setForeground(textColor);
exitsLabel.setFont(bigFont);
JPanel exitsPanel = new JPanel(new BorderLayout());
exitsPanel.setPreferredSize(new Dimension(0, 50));
exitsPanel.setBackground(darkMediumBackground);
exitsPanel.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
exitsPanel.add(exitsLabel, BorderLayout.NORTH);
exitsPanel.add(exits, BorderLayout.CENTER);
JPanel staticInfo = new JPanel(new GridLayout(0, 1));
staticInfo.setBackground(darkBackground);
staticInfo.add(dungeonPlayersPanel);
staticInfo.add(roomPlayersPanel);
staticInfo.add(othersPanel);
staticInfo.add(itemsPanel);
JPanel rightPanel = new JPanel(new BorderLayout());
//rightPanel.setPreferredSize(new Dimension(window.getSize().width / 3, 0));
rightPanel.setBackground(darkBackground);
rightPanel.add(stats, BorderLayout.NORTH);
rightPanel.add(staticInfo, BorderLayout.CENTER);
rightPanel.add(exitsPanel, BorderLayout.SOUTH);
JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, dynamicInfoScroll, rightPanel);
mainPanel.setResizeWeight(0.85);
mainPanel.setBackground(darkBackground);
mainPanel.setBorder(null);
// mainPanel.add(dynamicInfoScroll, BorderLayout.CENTER);
// mainPanel.add(rightPanel, BorderLayout.EAST);
JLabel commandLabel = new JLabel("Command: ");
commandLabel.setFont(new Font("Serif", Font.BOLD, 16));
commandLabel.setForeground(lightTextColor);
commandInputField.setBackground(mediumBackground);
commandInputField.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
commandInputField.setFont(font);
commandInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField source = (JTextField) (e.getSource());
playGameCommunication.sendMessage(source.getText());
source.setText("");
}
});
JPanel command = new JPanel(new BorderLayout());
command.setBackground(darkBackground);
command.add(commandLabel, BorderLayout.WEST);
command.add(commandInputField, BorderLayout.CENTER);
window.add(command, BorderLayout.SOUTH);
window.add(mainPanel, BorderLayout.CENTER);
window.setLocationRelativeTo(null);
window.setVisible(false);
new LogInPopUp(window);
}
public JPanel createRightBox(JTextArea c, String label) {
c.setFont(font);
c.setForeground(textColor);
c.setBackground(mediumBackground);
c.setEditable(false);
JScrollPane cScroll = new JScrollPane(c);
cScroll.setBorder(BorderFactory.createEmptyBorder());
JLabel cLabel = new JLabel(label);
cLabel.setForeground(textColor);
cLabel.setFont(bigFont);
JPanel cPanel = new JPanel(new BorderLayout());
cPanel.setBackground(darkMediumBackground);
cPanel.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
cPanel.add(cLabel, BorderLayout.NORTH);
cPanel.add(cScroll, BorderLayout.CENTER);
return cPanel;
}
public class LogInPopUp extends JDialog implements ActionListener {
JFrame window;
JButton button;
JTextField userNameInput = new JTextField();
JLabel userNameLabel = new JLabel("User name: ");
JPanel userName = new JPanel(new BorderLayout());
JTextField passwordInput = new JTextField();
JLabel passwordLabel = new JLabel("Password: ");
JPanel password = new JPanel(new BorderLayout());
JTextField IPInput = new JTextField();
JLabel IPLabel = new JLabel("IP: ");
JPanel IP = new JPanel(new BorderLayout());
Font font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
Color darkBackground = new Color(0x800000);
Color lightBackground = new Color(0xDAC8A3);
Color textColor = new Color(0x3D1515);
Color lightTextColor = new Color(0xDE9D5C);
Color mediumBackground = new Color(0xC2A366);
public LogInPopUp(JFrame _window) {
window = _window;
//Setting up the fields
button = new JButton("OK");
button.addActionListener(this);
button.setBackground(mediumBackground);
button.setFont(font);
button.setForeground(textColor);
userNameLabel.setPreferredSize(new Dimension(150, 0));
userNameInput.setBackground(mediumBackground);
userName.setBackground(darkBackground);
userNameLabel.setFont(font);
userNameLabel.setForeground(lightTextColor);
userName.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
userName.add(userNameInput, BorderLayout.CENTER);
userName.add(userNameLabel, BorderLayout.WEST);
passwordLabel.setPreferredSize(new Dimension(150, 0));
passwordInput.setBackground(mediumBackground);
password.setBackground(darkBackground);
passwordLabel.setFont(font);
passwordLabel.setForeground(lightTextColor);
password.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
password.add(passwordInput, BorderLayout.CENTER);
password.add(passwordLabel, BorderLayout.WEST);
IPLabel.setPreferredSize(new Dimension(150, 0));
IPInput.setBackground(mediumBackground);
IP.setBackground(darkBackground);
IPLabel.setFont(font);
IPLabel.setForeground(lightTextColor);
IP.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
IP.add(IPInput, BorderLayout.CENTER);
IP.add(IPLabel, BorderLayout.WEST);
JPanel frame = new JPanel(new GridLayout(0, 1));
frame.add(userName);
frame.add(password);
frame.add(IP);
frame.add(button);
add(frame);
setPreferredSize(new Dimension(600, 200));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String user = userNameInput.getText();
if(user.equals("")) {
userNameInput.setText("Enter username here");
} else {
System.out.println(user);
System.out.println("Hello");
//String pwd = passwordInput.getText();
//String ip = IPInput.getText();
user = user.replace(" ", "");
game = user;
playGameCommunication.sendMessage("LOGIN " + user); /// Obs, ändra till caps
window.setVisible(true);
dispose();
}
}
}
/////////Funktioner
public void updateDynamicInfo(String msg) {
dynamicInfo.append(msg);
}
public void setDungeonPlayers(String playerList) {
dungeonPlayers.setText(playerList);
}
public void addDungeonPlayer(String player) {
dungeonPlayers.append(player + "\n");
}
public void removeDungeonPlayer(String player) {
String players = dungeonPlayers.getText();
players = players.replace(player + "\n", "");
dungeonPlayers.setText(players);
}
public void setRoomPlayers(String playerList) {
roomPlayers.setText(playerList);
}
public void addRoomPlayer(String player) {
roomPlayers.append(player + "\n");
}
public void removeRoomPlayer(String player) {
String players = roomPlayers.getText();
players = players.replace(player + "\n", "");
roomPlayers.setText(players);
}
public void setOthers(String otherList) {
others.setText(otherList);
}
public void addOther(String other) {
others.append(other + "\n");
}
public void removeOther(String other) {
String npc = others.getText();
npc = npc.replace(other + "\n", "");
others.setText(npc);
}
public void setItems(String itemsList) {
items.setText(itemsList);
}
public void addItem(String item) {
items.append(item + "\n");
}
public void removeItem(String item) {
String i = items.getText();
i = i.replace(item + "\n", "");
items.setText(i);
}
public void setExits(String exitList) {
exits.setText(exitList);
}
}
| src/lostvaults/client/GUI.java | package lostvaults.client;
import javax.swing.*;
import javax.swing.JDialog;
import java.awt.*;
import java.awt.event.*;
public class GUI {
String name;
int screenWidth;
int screenHeight;
JTextArea dynamicInfo = new JTextArea();
JTextField commandInputField = new JTextField();
JTextArea dungeonPlayers = new JTextArea();
JTextArea roomPlayers = new JTextArea();
JTextArea others = new JTextArea();
JTextArea items = new JTextArea();
JTextArea exits = new JTextArea();
JLabel stats = new JLabel();
JFrame window = new JFrame("The Lost Vaults");
Color darkBackground = new Color(0x800000);
Color lightBackground = new Color(0xDAC8A3);
Color textColor = new Color(0x3D1515);
Color lightTextColor = new Color(0xDE9D5C);
Color mediumBackground = new Color(0xC2A366);
Color darkMediumBackground = new Color(0xB58C3C);
Font font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
Font bigFont = new Font("Serif", Font.BOLD + Font.ITALIC, 15);
public String getName() { return name; }
public GUI() {
// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = 1000; // screenSize.width;
screenHeight = 600; // screenSize.height;
window.setSize(screenWidth, screenHeight);
// window.setUndecorated(true); //true -> no exit button
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dynamicInfo.setEditable(false);
dynamicInfo.setBackground(lightBackground);
dynamicInfo.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
dynamicInfo.setFont(font);
dynamicInfo.setForeground(textColor);
JScrollPane dynamicInfoScroll = new JScrollPane(dynamicInfo);
dynamicInfo.setCaretPosition(dynamicInfo.getDocument().getLength());
dynamicInfoScroll.setBorder(BorderFactory.createEmptyBorder());
stats.setText("HP: 20/20 \t Food: 30/30");
stats.setFont(font);
stats.setForeground(lightTextColor);
JPanel dungeonPlayersPanel = createRightBox(dungeonPlayers, "Players in Dungeon: ");
JPanel roomPlayersPanel = createRightBox(roomPlayers, "Players in Room: ");
JPanel othersPanel = createRightBox(others, "Others in Room: ");
JPanel itemsPanel = createRightBox(items, "Items in Room: ");
exits.setFont(font);
exits.setForeground(textColor);
exits.setBackground(mediumBackground);
exits.setEditable(false);
JLabel exitsLabel = new JLabel("Exits in Room: ");
exitsLabel.setForeground(textColor);
exitsLabel.setFont(bigFont);
JPanel exitsPanel = new JPanel(new BorderLayout());
exitsPanel.setPreferredSize(new Dimension(0, 50));
exitsPanel.setBackground(darkMediumBackground);
exitsPanel.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
exitsPanel.add(exitsLabel, BorderLayout.NORTH);
exitsPanel.add(exits, BorderLayout.CENTER);
JPanel staticInfo = new JPanel(new GridLayout(0, 1));
staticInfo.setBackground(darkBackground);
staticInfo.add(dungeonPlayersPanel);
staticInfo.add(roomPlayersPanel);
staticInfo.add(othersPanel);
staticInfo.add(itemsPanel);
JPanel rightPanel = new JPanel(new BorderLayout());
//rightPanel.setPreferredSize(new Dimension(window.getSize().width / 3, 0));
rightPanel.setBackground(darkBackground);
rightPanel.add(stats, BorderLayout.NORTH);
rightPanel.add(staticInfo, BorderLayout.CENTER);
rightPanel.add(exitsPanel, BorderLayout.SOUTH);
JSplitPane mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, dynamicInfoScroll, rightPanel);
mainPanel.setResizeWeight(0.85);
mainPanel.setBackground(darkBackground);
mainPanel.setBorder(null);
// mainPanel.add(dynamicInfoScroll, BorderLayout.CENTER);
// mainPanel.add(rightPanel, BorderLayout.EAST);
JLabel commandLabel = new JLabel("Command: ");
commandLabel.setFont(new Font("Serif", Font.BOLD, 16));
commandLabel.setForeground(lightTextColor);
commandInputField.setBackground(mediumBackground);
commandInputField.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
commandInputField.setFont(font);
commandInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField source = (JTextField) (e.getSource());
playGameCommunication.sendMessage(source.getText());
source.setText("");
}
});
JPanel command = new JPanel(new BorderLayout());
command.setBackground(darkBackground);
command.add(commandLabel, BorderLayout.WEST);
command.add(commandInputField, BorderLayout.CENTER);
window.add(command, BorderLayout.SOUTH);
window.add(mainPanel, BorderLayout.CENTER);
window.setLocationRelativeTo(null);
window.setVisible(false);
new LogInPopUp(window);
}
public JPanel createRightBox(JTextArea c, String label) {
c.setFont(font);
c.setForeground(textColor);
c.setBackground(mediumBackground);
c.setEditable(false);
JScrollPane cScroll = new JScrollPane(c);
cScroll.setBorder(BorderFactory.createEmptyBorder());
JLabel cLabel = new JLabel(label);
cLabel.setForeground(textColor);
cLabel.setFont(bigFont);
JPanel cPanel = new JPanel(new BorderLayout());
cPanel.setBackground(darkMediumBackground);
cPanel.setBorder(BorderFactory.createLineBorder(darkBackground, 2));
cPanel.add(cLabel, BorderLayout.NORTH);
cPanel.add(cScroll, BorderLayout.CENTER);
return cPanel;
}
public class LogInPopUp extends JDialog implements ActionListener {
JFrame window;
JButton button;
JTextField userNameInput = new JTextField();
JLabel userNameLabel = new JLabel("User name: ");
JPanel userName = new JPanel(new BorderLayout());
JTextField passwordInput = new JTextField();
JLabel passwordLabel = new JLabel("Password: ");
JPanel password = new JPanel(new BorderLayout());
JTextField IPInput = new JTextField();
JLabel IPLabel = new JLabel("IP: ");
JPanel IP = new JPanel(new BorderLayout());
Font font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
Color darkBackground = new Color(0x800000);
Color lightBackground = new Color(0xDAC8A3);
Color textColor = new Color(0x3D1515);
Color lightTextColor = new Color(0xDE9D5C);
Color mediumBackground = new Color(0xC2A366);
public LogInPopUp(JFrame _window) {
window = _window;
//Setting up the fields
new BorderLayout();
button = new JButton("OK");
button.addActionListener(this);
button.setBackground(mediumBackground);
button.setFont(font);
button.setForeground(textColor);
userNameLabel.setPreferredSize(new Dimension(150, 0));
userNameInput.setBackground(mediumBackground);
userName.setBackground(darkBackground);
userNameLabel.setFont(font);
userNameLabel.setForeground(lightTextColor);
userName.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
userName.add(userNameInput, BorderLayout.CENTER);
userName.add(userNameLabel, BorderLayout.WEST);
passwordLabel.setPreferredSize(new Dimension(150, 0));
passwordInput.setBackground(mediumBackground);
password.setBackground(darkBackground);
passwordLabel.setFont(font);
passwordLabel.setForeground(lightTextColor);
password.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
password.add(passwordInput, BorderLayout.CENTER);
password.add(passwordLabel, BorderLayout.WEST);
IPLabel.setPreferredSize(new Dimension(150, 0));
IPInput.setBackground(mediumBackground);
IP.setBackground(darkBackground);
IPLabel.setFont(font);
IPLabel.setForeground(lightTextColor);
IP.setBorder(BorderFactory.createLineBorder(darkBackground, 1));
IP.add(IPInput, BorderLayout.CENTER);
IP.add(IPLabel, BorderLayout.WEST);
JPanel northbox = new JPanel(new BorderLayout());
JPanel southbox = new JPanel(new BorderLayout());
northbox.add(userName, BorderLayout.NORTH);
northbox.add(password, BorderLayout.CENTER);
southbox.add(IP, BorderLayout.NORTH);
southbox.add(button, BorderLayout.CENTER);
add(northbox, BorderLayout.NORTH);
add(southbox, BorderLayout.CENTER);
setSize(600, 120);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String user = userNameInput.getText();
//String pwd = passwordInput.getText();
//String ip = IPInput.getText();
user = user.replace(" ", "");
playGameCommunication.sendMessage("LOGIN " + user); /// Obs, ändra till caps
window.setVisible(true);
dispose();
}
}
/////////Funktioner
public void updateDynamicInfo(String msg) {
dynamicInfo.append(msg);
}
public void setDungeonPlayers(String playerList) {
dungeonPlayers.setText(playerList);
}
public void addDungeonPlayer(String player) {
dungeonPlayers.append(player + "\n");
}
public void removeDungeonPlayer(String player) {
String players = dungeonPlayers.getText();
players = players.replace(player + "\n", "");
dungeonPlayers.setText(players);
}
public void setRoomPlayers(String playerList) {
roomPlayers.setText(playerList);
}
public void addRoomPlayer(String player) {
roomPlayers.append(player + "\n");
}
public void removeRoomPlayer(String player) {
String players = roomPlayers.getText();
players = players.replace(player + "\n", "");
roomPlayers.setText(players);
}
public void setOthers(String otherList) {
others.setText(otherList);
}
public void addOther(String other) {
others.append(other + "\n");
}
public void removeOther(String other) {
String npc = others.getText();
npc = npc.replace(other + "\n", "");
others.setText(npc);
}
public void setItems(String itemsList) {
items.setText(itemsList);
}
public void addItem(String item) {
items.append(item + "\n");
}
public void removeItem(String item) {
String i = items.getText();
i = i.replace(item + "\n", "");
items.setText(i);
}
public void setExits(String exitList) {
exits.setText(exitList);
}
}
| Hejsan
| src/lostvaults/client/GUI.java | Hejsan | <ide><path>rc/lostvaults/client/GUI.java
<ide> window = _window;
<ide>
<ide> //Setting up the fields
<del> new BorderLayout();
<ide> button = new JButton("OK");
<ide> button.addActionListener(this);
<ide> button.setBackground(mediumBackground);
<ide> IP.add(IPInput, BorderLayout.CENTER);
<ide> IP.add(IPLabel, BorderLayout.WEST);
<ide>
<del> JPanel northbox = new JPanel(new BorderLayout());
<del> JPanel southbox = new JPanel(new BorderLayout());
<del>
<del> northbox.add(userName, BorderLayout.NORTH);
<del> northbox.add(password, BorderLayout.CENTER);
<del> southbox.add(IP, BorderLayout.NORTH);
<del> southbox.add(button, BorderLayout.CENTER);
<del> add(northbox, BorderLayout.NORTH);
<del> add(southbox, BorderLayout.CENTER);
<del>
<del> setSize(600, 120);
<add>
<add> JPanel frame = new JPanel(new GridLayout(0, 1));
<add> frame.add(userName);
<add> frame.add(password);
<add> frame.add(IP);
<add> frame.add(button);
<add> add(frame);
<add> setPreferredSize(new Dimension(600, 200));
<add> pack();
<ide>
<ide> setLocationRelativeTo(null);
<ide> setVisible(true);
<ide>
<ide> public void actionPerformed(ActionEvent e) {
<ide> String user = userNameInput.getText();
<del> //String pwd = passwordInput.getText();
<del> //String ip = IPInput.getText();
<del> user = user.replace(" ", "");
<del> playGameCommunication.sendMessage("LOGIN " + user); /// Obs, ändra till caps
<del> window.setVisible(true);
<del> dispose();
<del>
<add> if(user.equals("")) {
<add> userNameInput.setText("Enter username here");
<add> } else {
<add> System.out.println(user);
<add> System.out.println("Hello");
<add> //String pwd = passwordInput.getText();
<add> //String ip = IPInput.getText();
<add> user = user.replace(" ", "");
<add> game = user;
<add> playGameCommunication.sendMessage("LOGIN " + user); /// Obs, ändra till caps
<add> window.setVisible(true);
<add> dispose();
<add> }
<ide> }
<ide> }
<ide> |
|
Java | mit | a6cdb41d63e2d02d39b0c2b062fd535d30a33b60 | 0 | Rydog101/TurtleMod | package me.thegeekyguy101.TurtleMod.entity;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityEggInfo;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLLog;
public class customEntityList
{
/** Provides a mapping between entity classes and a string */
public static Map stringToClassMapping = new HashMap();
/** Provides a mapping between a string and an entity classes */
public static Map classToStringMapping = new HashMap();
/** provides a mapping between an entityID and an Entity Class */
public static Map IDtoClassMapping = new HashMap();
/** provides a mapping between an Entity Class and an entity ID */
private static Map classToIDMapping = new HashMap();
/** Maps entity names to their numeric identifiers */
private static Map stringToIDMapping = new HashMap();
/** This is a HashMap of the Creative Entity Eggs/Spawners. */
public static HashMap entityEggs = new LinkedHashMap();
/**
* adds a mapping between Entity classes and both a string representation and an ID
*/
public static void addMapping(Class par0Class, String par1Str, int par2)
{
stringToClassMapping.put(par1Str, par0Class);
classToStringMapping.put(par0Class, par1Str);
IDtoClassMapping.put(Integer.valueOf(par2), par0Class);
classToIDMapping.put(par0Class, Integer.valueOf(par2));
stringToIDMapping.put(par1Str, Integer.valueOf(par2));
}
/**
* Adds a entity mapping with egg info.
*/
public static void addMapping(Class par0Class, String par1Str, int par2, int par3, int par4)
{
addMapping(par0Class, par1Str, par2);
entityEggs.put(Integer.valueOf(par2), new EntityEggInfo(par2, par3, par4));
}
/**
* Create a new instance of an entity in the world by using the entity name.
*/
public static Entity createEntityByName(String par0Str, World par1World)
{
Entity entity = null;
try
{
Class oclass = (Class)stringToClassMapping.get(par0Str);
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
return entity;
}
/**
* create a new instance of an entity from NBT store
*/
public static Entity createEntityFromNBT(NBTTagCompound par0NBTTagCompound, World par1World)
{
Entity entity = null;
if ("Minecart".equals(par0NBTTagCompound.getString("id")))
{
switch (par0NBTTagCompound.getInteger("Type"))
{
case 0:
par0NBTTagCompound.setString("id", "MinecartRideable");
break;
case 1:
par0NBTTagCompound.setString("id", "MinecartChest");
break;
case 2:
par0NBTTagCompound.setString("id", "MinecartFurnace");
}
par0NBTTagCompound.removeTag("Type");
}
Class oclass = null;
try
{
oclass = (Class)stringToClassMapping.get(par0NBTTagCompound.getString("id"));
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
if (entity != null)
{
try
{
entity.readFromNBT(par0NBTTagCompound);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e,
"An Entity %s(%s) has thrown an exception during loading, its state cannot be restored. Report this to the mod author",
par0NBTTagCompound.getString("id"), oclass.getName());
entity = null;
}
}
else
{
par1World.getWorldLogAgent().logWarning("Skipping Entity with id " + par0NBTTagCompound.getString("id"));
}
return entity;
}
/**
* Create a new instance of an entity in the world by using an entity ID.
*/
public static Entity createEntityByID(int par0, World par1World)
{
Entity entity = null;
try
{
Class oclass = getClassFromID(par0);
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
if (entity == null)
{
par1World.getWorldLogAgent().logWarning("Skipping Entity with id " + par0);
}
return entity;
}
/**
* gets the entityID of a specific entity
*/
public static int getEntityID(Entity par0Entity)
{
Class oclass = par0Entity.getClass();
return classToIDMapping.containsKey(oclass) ? ((Integer)classToIDMapping.get(oclass)).intValue() : 0;
}
/**
* Return the class assigned to this entity ID.
*/
public static Class getClassFromID(int par0)
{
return (Class)IDtoClassMapping.get(Integer.valueOf(par0));
}
/**
* Gets the string representation of a specific entity.
*/
public static String getEntityString(Entity par0Entity)
{
return (String)classToStringMapping.get(par0Entity.getClass());
}
/**
* Finds the class using IDtoClassMapping and classToStringMapping
*/
public static String getStringFromID(int par0)
{
Class oclass = getClassFromID(par0);
return oclass != null ? (String)classToStringMapping.get(oclass) : null;
}
static
{
addMapping(EntityItem.class, "Item", 1);
addMapping(EntityLiving.class, "Mob", 48);
addMapping(EntityMob.class, "Monster", 49);
addMapping(EntityTurtle.class, "Turtle", 351, 0x1e8100, 0x7d3900);
addMapping(EntityZombieTurtle.class, "ZombieTurtle", 352, 0x008344, 0x823F02);
addMapping(EntityMineTurtle.class, "MineTurtle", 353, 0x1e8100, 0xef0000);
addMapping(EntityHelloGuy.class, "HelloGuy", 354, 0xffffff, 0xf90000);
addMapping(EntityLeonardo.class, "Leonardo", 355, 0x1e8100, 0x002dff);
addMapping(EntityRaphael.class, "Raphael", 356, 0x1e8100, 0xec0100);
addMapping(EntityDonatello.class, "Donatello", 357, 0x1e8100, 0x640087);
addMapping(EntityMichelangelo.class, "Michelangelo", 358, 0x1e8100, 0xff6900);
}
}
| common/me/thegeekyguy101/TurtleMod/entity/customEntityList.java | package me.thegeekyguy101.TurtleMod.entity;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityEggInfo;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLLog;
public class customEntityList
{
/** Provides a mapping between entity classes and a string */
public static Map stringToClassMapping = new HashMap();
/** Provides a mapping between a string and an entity classes */
public static Map classToStringMapping = new HashMap();
/** provides a mapping between an entityID and an Entity Class */
public static Map IDtoClassMapping = new HashMap();
/** provides a mapping between an Entity Class and an entity ID */
private static Map classToIDMapping = new HashMap();
/** Maps entity names to their numeric identifiers */
private static Map stringToIDMapping = new HashMap();
/** This is a HashMap of the Creative Entity Eggs/Spawners. */
public static HashMap entityEggs = new LinkedHashMap();
/**
* adds a mapping between Entity classes and both a string representation and an ID
*/
public static void addMapping(Class par0Class, String par1Str, int par2)
{
stringToClassMapping.put(par1Str, par0Class);
classToStringMapping.put(par0Class, par1Str);
IDtoClassMapping.put(Integer.valueOf(par2), par0Class);
classToIDMapping.put(par0Class, Integer.valueOf(par2));
stringToIDMapping.put(par1Str, Integer.valueOf(par2));
}
/**
* Adds a entity mapping with egg info.
*/
public static void addMapping(Class par0Class, String par1Str, int par2, int par3, int par4)
{
addMapping(par0Class, par1Str, par2);
entityEggs.put(Integer.valueOf(par2), new EntityEggInfo(par2, par3, par4));
}
/**
* Create a new instance of an entity in the world by using the entity name.
*/
public static Entity createEntityByName(String par0Str, World par1World)
{
Entity entity = null;
try
{
Class oclass = (Class)stringToClassMapping.get(par0Str);
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
return entity;
}
/**
* create a new instance of an entity from NBT store
*/
public static Entity createEntityFromNBT(NBTTagCompound par0NBTTagCompound, World par1World)
{
Entity entity = null;
if ("Minecart".equals(par0NBTTagCompound.getString("id")))
{
switch (par0NBTTagCompound.getInteger("Type"))
{
case 0:
par0NBTTagCompound.setString("id", "MinecartRideable");
break;
case 1:
par0NBTTagCompound.setString("id", "MinecartChest");
break;
case 2:
par0NBTTagCompound.setString("id", "MinecartFurnace");
}
par0NBTTagCompound.removeTag("Type");
}
Class oclass = null;
try
{
oclass = (Class)stringToClassMapping.get(par0NBTTagCompound.getString("id"));
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
if (entity != null)
{
try
{
entity.readFromNBT(par0NBTTagCompound);
}
catch (Exception e)
{
FMLLog.log(Level.SEVERE, e,
"An Entity %s(%s) has thrown an exception during loading, its state cannot be restored. Report this to the mod author",
par0NBTTagCompound.getString("id"), oclass.getName());
entity = null;
}
}
else
{
par1World.getWorldLogAgent().logWarning("Skipping Entity with id " + par0NBTTagCompound.getString("id"));
}
return entity;
}
/**
* Create a new instance of an entity in the world by using an entity ID.
*/
public static Entity createEntityByID(int par0, World par1World)
{
Entity entity = null;
try
{
Class oclass = getClassFromID(par0);
if (oclass != null)
{
entity = (Entity)oclass.getConstructor(new Class[] {World.class}).newInstance(new Object[] {par1World});
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
if (entity == null)
{
par1World.getWorldLogAgent().logWarning("Skipping Entity with id " + par0);
}
return entity;
}
/**
* gets the entityID of a specific entity
*/
public static int getEntityID(Entity par0Entity)
{
Class oclass = par0Entity.getClass();
return classToIDMapping.containsKey(oclass) ? ((Integer)classToIDMapping.get(oclass)).intValue() : 0;
}
/**
* Return the class assigned to this entity ID.
*/
public static Class getClassFromID(int par0)
{
return (Class)IDtoClassMapping.get(Integer.valueOf(par0));
}
/**
* Gets the string representation of a specific entity.
*/
public static String getEntityString(Entity par0Entity)
{
return (String)classToStringMapping.get(par0Entity.getClass());
}
/**
* Finds the class using IDtoClassMapping and classToStringMapping
*/
public static String getStringFromID(int par0)
{
Class oclass = getClassFromID(par0);
return oclass != null ? (String)classToStringMapping.get(oclass) : null;
}
static
{
addMapping(EntityItem.class, "Item", 1);
addMapping(EntityLiving.class, "Mob", 48);
addMapping(EntityMob.class, "Monster", 49);
addMapping(EntityTurtle.class, "Turtle", 351, 0x6F9DD1, 0x7AD16F);
addMapping(EntityZombieTurtle.class, "ZombieTurtle", 352, 0x6F9DD1, 0x7AD16F);
addMapping(EntityMineTurtle.class, "MineTurtle", 353, 0x6F9DD1, 0x7AD16F);
addMapping(EntityHelloGuy.class, "HelloGuy", 354, 0x6F9DD1, 0x7AD16F);
addMapping(EntityLeonardo.class, "Leonardo", 355, 0x6F9DD1, 0x7AD16F);
addMapping(EntityRaphael.class, "Raphael", 356, 0x6F9DD1, 0x7AD16F);
addMapping(EntityDonatello.class, "Donatello", 357, 0x6F9DD1, 0x7AD16F);
addMapping(EntityMichelangelo.class, "Michelangelo", 358, 0x6F9DD1, 0x7AD16F);
}
}
| Changed spawn egg colours
| common/me/thegeekyguy101/TurtleMod/entity/customEntityList.java | Changed spawn egg colours | <ide><path>ommon/me/thegeekyguy101/TurtleMod/entity/customEntityList.java
<ide> addMapping(EntityItem.class, "Item", 1);
<ide> addMapping(EntityLiving.class, "Mob", 48);
<ide> addMapping(EntityMob.class, "Monster", 49);
<del> addMapping(EntityTurtle.class, "Turtle", 351, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityZombieTurtle.class, "ZombieTurtle", 352, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityMineTurtle.class, "MineTurtle", 353, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityHelloGuy.class, "HelloGuy", 354, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityLeonardo.class, "Leonardo", 355, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityRaphael.class, "Raphael", 356, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityDonatello.class, "Donatello", 357, 0x6F9DD1, 0x7AD16F);
<del> addMapping(EntityMichelangelo.class, "Michelangelo", 358, 0x6F9DD1, 0x7AD16F);
<add> addMapping(EntityTurtle.class, "Turtle", 351, 0x1e8100, 0x7d3900);
<add> addMapping(EntityZombieTurtle.class, "ZombieTurtle", 352, 0x008344, 0x823F02);
<add> addMapping(EntityMineTurtle.class, "MineTurtle", 353, 0x1e8100, 0xef0000);
<add> addMapping(EntityHelloGuy.class, "HelloGuy", 354, 0xffffff, 0xf90000);
<add> addMapping(EntityLeonardo.class, "Leonardo", 355, 0x1e8100, 0x002dff);
<add> addMapping(EntityRaphael.class, "Raphael", 356, 0x1e8100, 0xec0100);
<add> addMapping(EntityDonatello.class, "Donatello", 357, 0x1e8100, 0x640087);
<add> addMapping(EntityMichelangelo.class, "Michelangelo", 358, 0x1e8100, 0xff6900);
<ide>
<ide> }
<ide> } |
|
JavaScript | mit | 17c3fef721eda310302e858b71c8340b9eea1ae2 | 0 | Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd,Flusspferd/flusspferd | require.paths.unshift('test/js/lib/modules-test');
let test = require('test'),
asserts = test.asserts;
exports.test_RequireId = function () {
// Not sure what require.id should be. it ceratinly shouldn't be 'system'
asserts.same(require.id, "modules");
}
exports.test_InstanceOf = function () {
var a1 = require('a1');
var a2 = require('a2');
asserts.instanceOf(a1.array(), Array, "Array in a1 is instanceof main Array");
asserts.instanceOf(a2.array(), Array, "Array in a2 is instanceof main Array");
asserts.instanceOf([1,2,3], Array, "sanity check");
}
var global = this;
exports.test_varPolution = function() {
require('a2');
asserts.same("a2" in global, false, "no a2 variable");
}
if (require.main == module)
test.runner(exports);
| test/js/modules.js | require.paths.unshift('test/js/lib/modules-test');
let test = require('test'),
asserts = test.asserts;
exports.test_RequireId = function () {
// Not sure what require.id should be. it ceratinly shouldn't be 'system'
asserts.same(require.id, "modules");
}
exports.test_InstanceOf = function () {
var a1 = require('a1');
var a2 = require('a2');
asserts.instanceOf(a1.array(), Array, "Array in a1 is instanceof main Array");
asserts.instanceOf(a2.array(), Array, "Array in a2 is instanceof main Array");
asserts.instanceOf([1,2,3], Array, "sanity check");
}
var global = this;
exports.test_varPolution = function() {
require('a2');
asserts.same("a2" in global, false, "no a2 variable");
}
if (require.main == module)
print(test.runner(exports));
| tests: remove unneeded print | test/js/modules.js | tests: remove unneeded print | <ide><path>est/js/modules.js
<ide> }
<ide>
<ide> if (require.main == module)
<del> print(test.runner(exports));
<add> test.runner(exports); |
|
Java | cc0-1.0 | 8a5129a5df28edbe4596b661b2fb75e16acef30c | 0 | KhorneSyrup/PolyMath | main/java/KhorneSyrup/PolyMath/Common/network/PacketSyncPolyMath.java | package KhorneSyrup.PolyMath.Common.network;
import io.netty.buffer.ByteBuf;
import java.io.IOException;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import KhorneSyrup.PolyMath.PolyMath;
import KhorneSyrup.PolyMath.Common.lib.PolyMathPlayer;
public class PacketSyncPolyMath {
}
| Delete PacketSyncPolyMath.java | main/java/KhorneSyrup/PolyMath/Common/network/PacketSyncPolyMath.java | Delete PacketSyncPolyMath.java | <ide><path>ain/java/KhorneSyrup/PolyMath/Common/network/PacketSyncPolyMath.java
<del>package KhorneSyrup.PolyMath.Common.network;
<del>
<del>import io.netty.buffer.ByteBuf;
<del>
<del>import java.io.IOException;
<del>
<del>import net.minecraft.entity.Entity;
<del>import net.minecraft.entity.player.EntityPlayer;
<del>import net.minecraft.item.ItemStack;
<del>import net.minecraft.network.PacketBuffer;
<del>import net.minecraft.world.World;
<del>import net.minecraftforge.fml.common.network.ByteBufUtils;
<del>import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
<del>import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
<del>import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
<del>import KhorneSyrup.PolyMath.PolyMath;
<del>import KhorneSyrup.PolyMath.Common.lib.PolyMathPlayer;
<del>
<del>public class PacketSyncPolyMath {
<del>
<del>} |
||
JavaScript | mit | 4b97d3a6e051e5d00eeaa04bf97faa4496a76373 | 0 | superjudge/paper.js,legendvijay/paper.js,mcanthony/paper.js,iconexperience/paper.js,li0t/paper.js,li0t/paper.js,lehni/paper.js,superjudge/paper.js,nancymark/paper.js,baiyanghese/paper.js,EskenderDev/paper.js,byte-foundry/paper.js,JunaidPaul/paper.js,baiyanghese/paper.js,proofme/paper.js,EskenderDev/paper.js,mcanthony/paper.js,proofme/paper.js,nancymark/paper.js,Olegas/paper.js,li0t/paper.js,Olegas/paper.js,ClaireRutkoske/paper.js,mcanthony/paper.js,rgordeev/paper.js,lehni/paper.js,chad-autry/paper.js,legendvijay/paper.js,legendvijay/paper.js,superjudge/paper.js,lehni/paper.js,luisbrito/paper.js,rgordeev/paper.js,fredoche/paper.js,JunaidPaul/paper.js,byte-foundry/paper.js,ClaireRutkoske/paper.js,JunaidPaul/paper.js,ClaireRutkoske/paper.js,fredoche/paper.js,luisbrito/paper.js,EskenderDev/paper.js,luisbrito/paper.js,byte-foundry/paper.js,nancymark/paper.js,proofme/paper.js,iconexperience/paper.js,iconexperience/paper.js,rgordeev/paper.js,baiyanghese/paper.js,Olegas/paper.js,fredoche/paper.js | /*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* A function scope holding all the functionality needed to convert a SVG DOM
* to a Paper.js DOM.
*/
new function() {
// Define a couple of helper functions to easily read values from SVG
// objects, dealing with baseVal, and item lists.
// index is option, and if passed, causes a lookup in a list.
function getValue(node, name, isString, allowNull) {
var namespace = SVGNamespaces[name],
value = namespace
? node.getAttributeNS(namespace, name)
: node.getAttribute(name);
if (value === 'null')
value = null;
// Interpret value as number. Never return NaN, but 0 instead.
// If the value is a sequence of numbers, parseFloat will
// return the first occuring number, which is enough for now.
return value == null
? allowNull
? null
: isString
? ''
: 0
: isString
? value
: parseFloat(value);
}
function getPoint(node, x, y, allowNull) {
x = getValue(node, x, false, allowNull);
y = getValue(node, y, false, allowNull);
return allowNull && x == null && y == null ? null
: new Point(x || 0, y || 0);
}
function getSize(node, w, h, allowNull) {
w = getValue(node, w, false, allowNull);
h = getValue(node, h, false, allowNull);
return allowNull && w == null && h == null ? null
: new Size(w || 0, h || 0);
}
// Converts a string attribute value to the specified type
function convertValue(value, type, lookup) {
return value === 'none'
? null
: type === 'number'
? parseFloat(value)
: type === 'array'
? value ? value.split(/[\s,]+/g).map(parseFloat) : []
: type === 'color'
? getDefinition(value) || value
: type === 'lookup'
? lookup[value]
: value;
}
// Importer functions for various SVG node types
function importGroup(node, type, isRoot, options) {
var nodes = node.childNodes,
clip = type === 'clippath',
item = new Group(),
project = item._project,
currentStyle = project._currentStyle,
children = [];
if (!clip) {
// Have the group not pass on all transformations to its children,
// as this is how SVG works too.
item._transformContent = false;
item = applyAttributes(item, node, isRoot);
// Style on items needs to be handled differently than all other
// items: We first apply the style to the item, then use it as the
// project's currentStyle, so it is used as a default for the
// creation of all nested items. importSVG then needs to check for
// items and avoid calling applyAttributes() again.
project._currentStyle = item._style.clone();
}
// Collect the children in an array and apply them all at once.
for (var i = 0, l = nodes.length; i < l; i++) {
var childNode = nodes[i],
child;
if (childNode.nodeType === 1
&& (child = importSVG(childNode, false, options))
&& !(child instanceof Symbol))
children.push(child);
}
item.addChildren(children);
// Clip paths are reduced (unboxed) and their attributes applied at the
// end.
if (clip)
item = applyAttributes(item.reduce(), node, isRoot);
// Restore currentStyle
project._currentStyle = currentStyle;
if (clip || type === 'defs') {
// We don't want the defs in the DOM. But we might want to use
// Symbols for them to save memory?
item.remove();
item = null;
}
return item;
}
function importPoly(node, type) {
var path = new Path(),
points = node.points;
path.moveTo(points.getItem(0));
for (var i = 1, l = points.numberOfItems; i < l; i++)
path.lineTo(points.getItem(i));
if (type === 'polygon')
path.closePath();
return path;
}
function importPath(node) {
// Get the path data, and determine whether it is a compound path or a
// normal path based on the amount of moveTo commands inside it.
var data = node.getAttribute('d'),
path = data.match(/m/gi).length > 1
? new CompoundPath()
: new Path();
path.setPathData(data);
return path;
}
function importGradient(node, type) {
var nodes = node.childNodes,
stops = [];
for (var i = 0, l = nodes.length; i < l; i++) {
var child = nodes[i];
if (child.nodeType === 1)
stops.push(applyAttributes(new GradientStop(), child));
}
var isRadial = type === 'radialgradient',
gradient = new Gradient(stops, isRadial),
origin, destination, highlight;
if (isRadial) {
origin = getPoint(node, 'cx', 'cy');
destination = origin.add(getValue(node, 'r'), 0);
highlight = getPoint(node, 'fx', 'fy', true);
} else {
origin = getPoint(node, 'x1', 'y1');
destination = getPoint(node, 'x2', 'y2');
}
applyAttributes(
new Color(gradient, origin, destination, highlight), node);
// We don't return the gradient, since we only need a reference to it in
// definitions, which is created in applyAttributes()
return null;
}
// NOTE: All importers are lowercase, since jsdom is using uppercase
// nodeNames still.
var importers = {
'#document': function(node, type, isRoot, options) {
return importSVG(node.childNodes[0], isRoot, options);
},
// http://www.w3.org/TR/SVG/struct.html#Groups
g: importGroup,
// http://www.w3.org/TR/SVG/struct.html#NewDocument
svg: importGroup,
clippath: importGroup,
// http://www.w3.org/TR/SVG/shapes.html#PolygonElement
polygon: importPoly,
// http://www.w3.org/TR/SVG/shapes.html#PolylineElement
polyline: importPoly,
// http://www.w3.org/TR/SVG/paths.html
path: importPath,
// http://www.w3.org/TR/SVG/pservers.html#LinearGradients
lineargradient: importGradient,
// http://www.w3.org/TR/SVG/pservers.html#RadialGradients
radialgradient: importGradient,
// http://www.w3.org/TR/SVG/struct.html#ImageElement
image: function (node) {
var raster = new Raster(getValue(node, 'href', true));
raster.attach('load', function() {
var size = getSize(node, 'width', 'height');
this.setSize(size);
// Since x and y start from the top left of an image, add
// half of its size:
this.translate(getPoint(node, 'x', 'y').add(size.divide(2)));
});
return raster;
},
// http://www.w3.org/TR/SVG/struct.html#SymbolElement
symbol: function(node, type, isRoot, options) {
// Pass true for dontCenter:
return new Symbol(importGroup(node, type, isRoot, options), true);
},
// http://www.w3.org/TR/SVG/struct.html#DefsElement
defs: importGroup,
// http://www.w3.org/TR/SVG/struct.html#UseElement
use: function(node) {
// Note the namespaced xlink:href attribute is just called href
// as a property on node.
// TODO: Support overflow and width, height, in combination with
// overflow: hidden. Paper.js currently does not suport PlacedSymbol
// clipping, but perhaps it should?
var id = (getValue(node, 'href', true) || '').substring(1),
definition = definitions[id],
point = getPoint(node, 'x', 'y');
// Use place if we're dealing with a symbol:
return definition
? definition instanceof Symbol
// When placing symbols, we nee to take both point and
// matrix into account. This just does the right thing:
? definition.place(point)
: definition.clone().translate(point)
: null;
},
// http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGCircleElement
circle: function(node) {
return new Shape.Circle(getPoint(node, 'cx', 'cy'),
getValue(node, 'r'));
},
// http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGEllipseElement
ellipse: function(node) {
// We only use object literal notation where the default one is not
// supported (e.g. center / radius fo Shape.Ellipse).
return new Shape.Ellipse({
center: getPoint(node, 'cx', 'cy'),
radius: getSize(node, 'rx', 'ry')
});
},
// http://www.w3.org/TR/SVG/shapes.html#RectElement
rect: function(node) {
var point = getPoint(node, 'x', 'y'),
size = getSize(node, 'width', 'height'),
radius = getSize(node, 'rx', 'ry');
return new Shape.Rectangle(new Rectangle(point, size), radius);
},
// http://www.w3.org/TR/SVG/shapes.html#LineElement
line: function(node) {
return new Path.Line(getPoint(node, 'x1', 'y1'),
getPoint(node, 'x2', 'y2'));
},
text: function(node) {
// Not supported by Paper.js
// x: multiple values for x
// y: multiple values for y
// dx: multiple values for x
// dy: multiple values for y
// TODO: Support for these is missing in Paper.js right now
// rotate: character rotation
// lengthAdjust:
var text = new PointText(getPoint(node, 'x', 'y')
.add(getPoint(node, 'dx', 'dy')));
text.setContent(node.textContent.trim() || '');
return text;
}
};
// Attributes and Styles
// NOTE: Parmeter sequence for all apply*() functions is:
// (item, value, name, node) rather than (item, node, name, value),
// so we can ommit the less likely parameters from right to left.
function applyTransform(item, value, name, node) {
// http://www.w3.org/TR/SVG/types.html#DataTypeTransformList
// Parse SVG transform string. First we split at /)\s*/, to separate
// commands
var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
matrix = new Matrix();
for (var i = 0, l = transforms.length; i < l; i++) {
var transform = transforms[i];
if (!transform)
break;
// Command come before the '(', values after
var parts = transform.split('('),
command = parts[0],
v = parts[1].split(/[\s,]+/g);
// Convert values to floats
for (var j = 0, m = v.length; j < m; j++)
v[j] = parseFloat(v[j]);
switch (command) {
case 'matrix':
matrix.concatenate(
new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
break;
case 'rotate':
matrix.rotate(v[0], v[1], v[2]);
break;
case 'translate':
matrix.translate(v[0], v[1]);
break;
case 'scale':
matrix.scale(v);
break;
case 'skewX':
case 'skewY':
var value = Math.tan(v[0] * Math.PI / 180),
isX = command == 'skewX';
matrix.shear(isX ? value : 0, isX ? 0 : value);
break;
}
}
item.transform(matrix);
}
function applyOpacity(item, value, name) {
// http://www.w3.org/TR/SVG/painting.html#FillOpacityProperty
// http://www.w3.org/TR/SVG/painting.html#StrokeOpacityProperty
var color = item[name === 'fill-opacity' ? 'getFillColor'
: 'getStrokeColor']();
if (color)
color.setAlpha(parseFloat(value));
}
// Create apply-functions for attributes, and merge in those for SVGStlyes.
// We need to define style attributes first, and merge in all others after,
// since transform needs to be applied after fill color, as transformations
// can affect gradient fills.
var attributes = Base.merge(Base.each(SVGStyles, function(entry) {
this[entry.attribute] = function(item, value) {
item[entry.set](convertValue(value, entry.type, entry.fromSVG));
// When applying gradient colors to shapes, we need to offset
// the shape's initial position to get the same results as SVG.
if (entry.type === 'color' && item instanceof Shape) {
// Do not use result of convertValue() above, since calling
// the setter will produce a new cloned color.
var color = item[entry.get]();
if (color)
color.transform(new Matrix().translate(
item.getPosition(true).negate()));
}
};
}, {}), {
id: function(item, value) {
definitions[value] = item;
if (item.setName)
item.setName(value);
},
'clip-path': function(item, value) {
// http://www.w3.org/TR/SVG/masking.html#ClipPathProperty
var clip = getDefinition(value);
if (clip) {
clip = clip.clone();
clip.setClipMask(true);
// If item is already a group, move the clip-path inside
if (item instanceof Group) {
item.insertChild(0, clip);
} else {
return new Group(clip, item);
}
}
},
gradientTransform: applyTransform,
transform: applyTransform,
'fill-opacity': applyOpacity,
'stroke-opacity': applyOpacity,
visibility: function(item, value) {
item.setVisible(value === 'visible');
},
'stop-color': function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopColorProperty
if (item.setColor)
item.setColor(value);
},
'stop-opacity': function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopOpacityProperty
// NOTE: It is important that this is applied after stop-color!
if (item._color)
item._color.setAlpha(parseFloat(value));
},
offset: function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopElementOffsetAttribute
var percentage = value.match(/(.*)%$/);
item.setRampPoint(percentage
? percentage[1] / 100
: parseFloat(value));
},
viewBox: function(item, value, name, node, styles) {
// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
// TODO: implement preserveAspectRatio attribute
// viewBox will be applied both to the group that's created for the
// content in Symbol.definition, and the Symbol itself.
var rect = new Rectangle(convertValue(value, 'array')),
size = getSize(node, 'width', 'height', true);
if (item instanceof Group) {
// This is either a top-level svg node, or the container for a
// symbol.
var scale = size ? rect.getSize().divide(size) : 1,
matrix = new Matrix().translate(rect.getPoint()).scale(scale);
item.transform(matrix.inverted());
} else if (item instanceof Symbol) {
// The symbol is wrapping a group. Note that viewBox was already
// applied to the group, and above code was executed for it.
// All that is left to handle here on the Symbol level is
// clipping. We can't do it at group level because
// applyAttributes() gets called for groups before their
// children are added, for styling reasons. See importGroup()
if (size)
rect.setSize(size);
var clip = getAttribute(node, 'overflow', styles) != 'visible',
group = item._definition;
if (clip && !rect.contains(group.getBounds())) {
// Add a clip path at the top of this symbol's group
clip = new Shape.Rectangle(rect).transform(group._matrix);
clip.setClipMask(true);
group.addChild(clip);
}
}
}
});
function getAttribute(node, name, styles) {
// First see if the given attribute is defined.
var attr = node.attributes[name],
value = attr && attr.value;
if (!value) {
// Fallback to using styles. See if there is a style, either set
// directly on the object or applied to it through CSS rules.
// We also need to filter out inheritance from their parents.
var style = Base.camelize(name);
value = node.style[style];
if (!value && styles.node[style] !== styles.parent[style])
value = styles.node[style];
}
// Return undefined if attribute is not defined, but null if it's
// defined as not set (e.g. fill / stroke).
return !value
? undefined
: value === 'none'
? null
: value;
}
/**
* Converts various SVG styles and attributes into Paper.js styles and
* attributes and applies them to the passed item.
*
* @param {SVGSVGElement} node an SVG node to read style and attributes from.
* @param {Item} item the item to apply the style and attributes to.
*/
function applyAttributes(item, node, isRoot) {
// SVG attributes can be set both as styles and direct node attributes,
// so we need to handle both.
var styles = {
node: DomElement.getStyles(node) || {},
// Do not check for inheritance if this is the root, since we want
// the default SVG settings to stick.
parent: !isRoot && DomElement.getStyles(node.parentNode) || {}
};
Base.each(attributes, function(apply, name) {
var value = getAttribute(node, name, styles);
if (value !== undefined)
item = Base.pick(apply(item, value, name, node, styles), item);
});
return item;
}
var definitions = {};
function getDefinition(value) {
// When url() comes from a style property, '#'' seems to be missing on
// WebKit, so let's make it optional here:
var match = value && value.match(/\((?:#|)([^)']+)/);
return match && definitions[match[1]];
}
function importSVG(node, isRoot, options) {
if (!options)
options = {};
if (typeof node === 'string')
node = new DOMParser().parseFromString(node, 'image/svg+xml');
// jsdom in Node.js uses uppercase values for nodeName...
var type = node.nodeName.toLowerCase(),
importer = importers[type],
item = importer && importer(node, type, isRoot, options),
data = type !== '#document' && node.getAttribute('data-paper-data');
if (item) {
// See importGroup() for an explanation of this filtering:
if (!(item instanceof Group))
item = applyAttributes(item, node, isRoot);
if (options.expandShapes && item instanceof Shape) {
item.remove();
item = item.toPath();
}
if (data)
item._data = JSON.parse(data);
}
// Clear definitions at the end of import?
if (isRoot)
definitions = {};
return item;
}
Item.inject({
importSVG: function(node, options) {
return this.addChild(importSVG(node, true, options));
}
});
Project.inject({
importSVG: function(node, options) {
this.activate();
return importSVG(node, true, options);
}
});
};
| src/svg/SVGImport.js | /*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* A function scope holding all the functionality needed to convert a SVG DOM
* to a Paper.js DOM.
*/
new function() {
// Define a couple of helper functions to easily read values from SVG
// objects, dealing with baseVal, and item lists.
// index is option, and if passed, causes a lookup in a list.
function getValue(node, name, isString, allowNull) {
var namespace = SVGNamespaces[name],
value = namespace
? node.getAttributeNS(namespace, name)
: node.getAttribute(name);
if (value === 'null')
value = null;
// Interpret value as number. Never return NaN, but 0 instead.
// If the value is a sequence of numbers, parseFloat will
// return the first occuring number, which is enough for now.
return value == null
? allowNull
? null
: isString
? ''
: 0
: isString
? value
: parseFloat(value);
}
function getPoint(node, x, y, allowNull) {
x = getValue(node, x, false, allowNull);
y = getValue(node, y, false, allowNull);
return allowNull && x == null && y == null ? null
: new Point(x || 0, y || 0);
}
function getSize(node, w, h, allowNull) {
w = getValue(node, w, false, allowNull);
h = getValue(node, h, false, allowNull);
return allowNull && w == null && h == null ? null
: new Size(w || 0, h || 0);
}
// Converts a string attribute value to the specified type
function convertValue(value, type, lookup) {
return value === 'none'
? null
: type === 'number'
? parseFloat(value)
: type === 'array'
? value ? value.split(/[\s,]+/g).map(parseFloat) : []
: type === 'color'
? getDefinition(value) || value
: type === 'lookup'
? lookup[value]
: value;
}
// Importer functions for various SVG node types
function importGroup(node, type, options) {
var nodes = node.childNodes,
clip = type === 'clippath',
item = new Group(),
project = item._project,
currentStyle = project._currentStyle,
children = [];
if (!clip) {
// Have the group not pass on all transformations to its children,
// as this is how SVG works too.
item._transformContent = false;
item = applyAttributes(item, node);
// Style on items needs to be handled differently than all other
// items: We first apply the style to the item, then use it as the
// project's currentStyle, so it is used as a default for the
// creation of all nested items. importSVG then needs to check for
// items and avoid calling applyAttributes() again.
project._currentStyle = item._style.clone();
}
// Collect the children in an array and apply them all at once.
for (var i = 0, l = nodes.length; i < l; i++) {
var childNode = nodes[i],
child;
if (childNode.nodeType === 1
&& (child = importSVG(childNode, options))
&& !(child instanceof Symbol))
children.push(child);
}
item.addChildren(children);
// Clip paths are reduced (unboxed) and their attributes applied at the
// end.
if (clip)
item = applyAttributes(item.reduce(), node);
// Restore currentStyle
project._currentStyle = currentStyle;
if (clip || type === 'defs') {
// We don't want the defs in the DOM. But we might want to use
// Symbols for them to save memory?
item.remove();
item = null;
}
return item;
}
function importPoly(node, type) {
var path = new Path(),
points = node.points;
path.moveTo(points.getItem(0));
for (var i = 1, l = points.numberOfItems; i < l; i++)
path.lineTo(points.getItem(i));
if (type === 'polygon')
path.closePath();
return path;
}
function importPath(node) {
// Get the path data, and determine whether it is a compound path or a
// normal path based on the amount of moveTo commands inside it.
var data = node.getAttribute('d'),
path = data.match(/m/gi).length > 1
? new CompoundPath()
: new Path();
path.setPathData(data);
return path;
}
function importGradient(node, type) {
var nodes = node.childNodes,
stops = [];
for (var i = 0, l = nodes.length; i < l; i++) {
var child = nodes[i];
if (child.nodeType === 1)
stops.push(applyAttributes(new GradientStop(), child));
}
var isRadial = type === 'radialgradient',
gradient = new Gradient(stops, isRadial),
origin, destination, highlight;
if (isRadial) {
origin = getPoint(node, 'cx', 'cy');
destination = origin.add(getValue(node, 'r'), 0);
highlight = getPoint(node, 'fx', 'fy', true);
} else {
origin = getPoint(node, 'x1', 'y1');
destination = getPoint(node, 'x2', 'y2');
}
applyAttributes(
new Color(gradient, origin, destination, highlight), node);
// We don't return the gradient, since we only need a reference to it in
// definitions, which is created in applyAttributes()
return null;
}
// NOTE: All importers are lowercase, since jsdom is using uppercase
// nodeNames still.
var importers = {
'#document': function(node, type, options) {
return importSVG(node.childNodes[0], options);
},
// http://www.w3.org/TR/SVG/struct.html#Groups
g: importGroup,
// http://www.w3.org/TR/SVG/struct.html#NewDocument
svg: importGroup,
clippath: importGroup,
// http://www.w3.org/TR/SVG/shapes.html#PolygonElement
polygon: importPoly,
// http://www.w3.org/TR/SVG/shapes.html#PolylineElement
polyline: importPoly,
// http://www.w3.org/TR/SVG/paths.html
path: importPath,
// http://www.w3.org/TR/SVG/pservers.html#LinearGradients
lineargradient: importGradient,
// http://www.w3.org/TR/SVG/pservers.html#RadialGradients
radialgradient: importGradient,
// http://www.w3.org/TR/SVG/struct.html#ImageElement
image: function (node) {
var raster = new Raster(getValue(node, 'href', true));
raster.attach('load', function() {
var size = getSize(node, 'width', 'height');
this.setSize(size);
// Since x and y start from the top left of an image, add
// half of its size:
this.translate(getPoint(node, 'x', 'y').add(size.divide(2)));
});
return raster;
},
// http://www.w3.org/TR/SVG/struct.html#SymbolElement
symbol: function(node, type) {
// Pass true for dontCenter:
return new Symbol(importGroup(node, type), true);
},
// http://www.w3.org/TR/SVG/struct.html#DefsElement
defs: importGroup,
// http://www.w3.org/TR/SVG/struct.html#UseElement
use: function(node) {
// Note the namespaced xlink:href attribute is just called href
// as a property on node.
// TODO: Support overflow and width, height, in combination with
// overflow: hidden. Paper.js currently does not suport PlacedSymbol
// clipping, but perhaps it should?
var id = (getValue(node, 'href', true) || '').substring(1),
definition = definitions[id],
point = getPoint(node, 'x', 'y');
// Use place if we're dealing with a symbol:
return definition
? definition instanceof Symbol
// When placing symbols, we nee to take both point and
// matrix into account. This just does the right thing:
? definition.place(point)
: definition.clone().translate(point)
: null;
},
// http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGCircleElement
circle: function(node) {
return new Shape.Circle(getPoint(node, 'cx', 'cy'),
getValue(node, 'r'));
},
// http://www.w3.org/TR/SVG/shapes.html#InterfaceSVGEllipseElement
ellipse: function(node) {
// We only use object literal notation where the default one is not
// supported (e.g. center / radius fo Shape.Ellipse).
return new Shape.Ellipse({
center: getPoint(node, 'cx', 'cy'),
radius: getSize(node, 'rx', 'ry')
});
},
// http://www.w3.org/TR/SVG/shapes.html#RectElement
rect: function(node) {
var point = getPoint(node, 'x', 'y'),
size = getSize(node, 'width', 'height'),
radius = getSize(node, 'rx', 'ry');
return new Shape.Rectangle(new Rectangle(point, size), radius);
},
// http://www.w3.org/TR/SVG/shapes.html#LineElement
line: function(node) {
return new Path.Line(getPoint(node, 'x1', 'y1'),
getPoint(node, 'x2', 'y2'));
},
text: function(node) {
// Not supported by Paper.js
// x: multiple values for x
// y: multiple values for y
// dx: multiple values for x
// dy: multiple values for y
// TODO: Support for these is missing in Paper.js right now
// rotate: character rotation
// lengthAdjust:
var text = new PointText(getPoint(node, 'x', 'y')
.add(getPoint(node, 'dx', 'dy')));
text.setContent(node.textContent.trim() || '');
return text;
}
};
// Attributes and Styles
// NOTE: Parmeter sequence for all apply*() functions is:
// (item, value, name, node) rather than (item, node, name, value),
// so we can ommit the less likely parameters from right to left.
function applyTransform(item, value, name, node) {
// http://www.w3.org/TR/SVG/types.html#DataTypeTransformList
// Parse SVG transform string. First we split at /)\s*/, to separate
// commands
var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
matrix = new Matrix();
for (var i = 0, l = transforms.length; i < l; i++) {
var transform = transforms[i];
if (!transform)
break;
// Command come before the '(', values after
var parts = transform.split('('),
command = parts[0],
v = parts[1].split(/[\s,]+/g);
// Convert values to floats
for (var j = 0, m = v.length; j < m; j++)
v[j] = parseFloat(v[j]);
switch (command) {
case 'matrix':
matrix.concatenate(
new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
break;
case 'rotate':
matrix.rotate(v[0], v[1], v[2]);
break;
case 'translate':
matrix.translate(v[0], v[1]);
break;
case 'scale':
matrix.scale(v);
break;
case 'skewX':
case 'skewY':
var value = Math.tan(v[0] * Math.PI / 180),
isX = command == 'skewX';
matrix.shear(isX ? value : 0, isX ? 0 : value);
break;
}
}
item.transform(matrix);
}
function applyOpacity(item, value, name) {
// http://www.w3.org/TR/SVG/painting.html#FillOpacityProperty
// http://www.w3.org/TR/SVG/painting.html#StrokeOpacityProperty
var color = item[name === 'fill-opacity' ? 'getFillColor'
: 'getStrokeColor']();
if (color)
color.setAlpha(parseFloat(value));
}
// Create apply-functions for attributes, and merge in those for SVGStlyes.
// We need to define style attributes first, and merge in all others after,
// since transform needs to be applied after fill color, as transformations
// can affect gradient fills.
var attributes = Base.merge(Base.each(SVGStyles, function(entry) {
this[entry.attribute] = function(item, value) {
item[entry.set](
convertValue(value, entry.type, entry.fromSVG));
// When applying gradient colors to shapes, we need to offset the
// shape's initial position to get the same results as SVG.
if (entry.type === 'color' && item instanceof Shape) {
// Do not use result of convertValue() above, since calling the
// setter will produce a new cloned color.
var color = item[entry.get]();
if (color)
color.transform(new Matrix().translate(
item.getPosition(true).negate()));
}
};
}, {}), {
id: function(item, value) {
definitions[value] = item;
if (item.setName)
item.setName(value);
},
'clip-path': function(item, value) {
// http://www.w3.org/TR/SVG/masking.html#ClipPathProperty
var clip = getDefinition(value);
if (clip) {
clip = clip.clone();
clip.setClipMask(true);
// If item is already a group, move the clip-path inside
if (item instanceof Group) {
item.insertChild(0, clip);
} else {
return new Group(clip, item);
}
}
},
gradientTransform: applyTransform,
transform: applyTransform,
'fill-opacity': applyOpacity,
'stroke-opacity': applyOpacity,
visibility: function(item, value) {
item.setVisible(value === 'visible');
},
'stop-color': function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopColorProperty
if (item.setColor)
item.setColor(value);
},
'stop-opacity': function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopOpacityProperty
// NOTE: It is important that this is applied after stop-color!
if (item._color)
item._color.setAlpha(parseFloat(value));
},
offset: function(item, value) {
// http://www.w3.org/TR/SVG/pservers.html#StopElementOffsetAttribute
var percentage = value.match(/(.*)%$/);
item.setRampPoint(percentage
? percentage[1] / 100
: parseFloat(value));
},
viewBox: function(item, value, name, node, styles) {
// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute
// TODO: implement preserveAspectRatio attribute
// viewBox will be applied both to the group that's created for the
// content in Symbol.definition, and the Symbol itself.
var rect = new Rectangle(convertValue(value, 'array')),
size = getSize(node, 'width', 'height', true);
if (item instanceof Group) {
// This is either a top-level svg node, or the container for a
// symbol.
var scale = size ? rect.getSize().divide(size) : 1,
matrix = new Matrix().translate(rect.getPoint()).scale(scale);
item.transform(matrix.inverted());
} else if (item instanceof Symbol) {
// The symbol is wrapping a group. Note that viewBox was already
// applied to the group, and above code was executed for it.
// All that is left to handle here on the Symbol level is
// clipping. We can't do it at group level because
// applyAttributes() gets called for groups before their
// children are added, for styling reasons. See importGroup()
if (size)
rect.setSize(size);
var clip = getAttribute(node, 'overflow', styles) != 'visible',
group = item._definition;
if (clip && !rect.contains(group.getBounds())) {
// Add a clip path at the top of this symbol's group
clip = new Shape.Rectangle(rect).transform(group._matrix);
clip.setClipMask(true);
group.addChild(clip);
}
}
}
});
function getAttribute(node, name, styles) {
// First see if the given attribute is defined.
var attr = node.attributes[name],
value = attr && attr.value;
if (!value) {
// Fallback to using styles. See if there is a style, either set
// directly on the object or applied to it through CSS rules.
// We also need to filter out inheritance from their parents.
var style = Base.camelize(name);
value = node.style[style];
if (!value && styles.node[style] !== styles.parent[style])
value = styles.node[style];
}
// Return undefined if attribute is not defined, but null if it's
// defined as not set (e.g. fill / stroke).
return !value
? undefined
: value === 'none'
? null
: value;
}
/**
* Converts various SVG styles and attributes into Paper.js styles and
* attributes and applies them to the passed item.
*
* @param {SVGSVGElement} node an SVG node to read style and attributes from.
* @param {Item} item the item to apply the style and attributes to.
*/
function applyAttributes(item, node) {
// SVG attributes can be set both as styles and direct node attributes,
// so we need to handle both.
var styles = {
node: DomElement.getStyles(node) || {},
parent: DomElement.getStyles(node.parentNode) || {}
};
Base.each(attributes, function(apply, name) {
var value = getAttribute(node, name, styles);
if (value !== undefined)
item = Base.pick(apply(item, value, name, node, styles), item);
});
return item;
}
var definitions = {};
function getDefinition(value) {
// When url() comes from a style property, '#'' seems to be missing on
// WebKit, so let's make it optional here:
var match = value && value.match(/\((?:#|)([^)']+)/);
return match && definitions[match[1]];
}
function importSVG(node, options, clearDefs) {
if (!options)
options = {};
if (typeof node === 'string')
node = new DOMParser().parseFromString(node, 'image/svg+xml');
// jsdom in Node.js uses uppercase values for nodeName...
var type = node.nodeName.toLowerCase(),
importer = importers[type],
item = importer && importer(node, type, options),
data = type !== '#document' && node.getAttribute('data-paper-data');
if (item) {
// See importGroup() for an explanation of this filtering:
if (!(item instanceof Group))
item = applyAttributes(item, node);
if (options.expandShapes && item instanceof Shape) {
item.remove();
item = item.toPath();
}
if (data)
item._data = JSON.parse(data);
}
// Clear definitions at the end of import?
if (clearDefs)
definitions = {};
return item;
}
Item.inject({
importSVG: function(node, options) {
return this.addChild(importSVG(node, options, true));
}
});
Project.inject({
importSVG: function(node, options) {
this.activate();
return importSVG(node, options, true);
}
});
};
| Make sure that the default SVG settings are not lost on import.
| src/svg/SVGImport.js | Make sure that the default SVG settings are not lost on import. | <ide><path>rc/svg/SVGImport.js
<ide>
<ide> // Importer functions for various SVG node types
<ide>
<del> function importGroup(node, type, options) {
<add> function importGroup(node, type, isRoot, options) {
<ide> var nodes = node.childNodes,
<ide> clip = type === 'clippath',
<ide> item = new Group(),
<ide> // Have the group not pass on all transformations to its children,
<ide> // as this is how SVG works too.
<ide> item._transformContent = false;
<del> item = applyAttributes(item, node);
<add> item = applyAttributes(item, node, isRoot);
<ide> // Style on items needs to be handled differently than all other
<ide> // items: We first apply the style to the item, then use it as the
<ide> // project's currentStyle, so it is used as a default for the
<ide> var childNode = nodes[i],
<ide> child;
<ide> if (childNode.nodeType === 1
<del> && (child = importSVG(childNode, options))
<add> && (child = importSVG(childNode, false, options))
<ide> && !(child instanceof Symbol))
<ide> children.push(child);
<ide> }
<ide> // Clip paths are reduced (unboxed) and their attributes applied at the
<ide> // end.
<ide> if (clip)
<del> item = applyAttributes(item.reduce(), node);
<add> item = applyAttributes(item.reduce(), node, isRoot);
<ide> // Restore currentStyle
<ide> project._currentStyle = currentStyle;
<ide> if (clip || type === 'defs') {
<ide> // NOTE: All importers are lowercase, since jsdom is using uppercase
<ide> // nodeNames still.
<ide> var importers = {
<del> '#document': function(node, type, options) {
<del> return importSVG(node.childNodes[0], options);
<add> '#document': function(node, type, isRoot, options) {
<add> return importSVG(node.childNodes[0], isRoot, options);
<ide> },
<ide>
<ide> // http://www.w3.org/TR/SVG/struct.html#Groups
<ide> },
<ide>
<ide> // http://www.w3.org/TR/SVG/struct.html#SymbolElement
<del> symbol: function(node, type) {
<add> symbol: function(node, type, isRoot, options) {
<ide> // Pass true for dontCenter:
<del> return new Symbol(importGroup(node, type), true);
<add> return new Symbol(importGroup(node, type, isRoot, options), true);
<ide> },
<ide>
<ide> // http://www.w3.org/TR/SVG/struct.html#DefsElement
<ide> // can affect gradient fills.
<ide> var attributes = Base.merge(Base.each(SVGStyles, function(entry) {
<ide> this[entry.attribute] = function(item, value) {
<del> item[entry.set](
<del> convertValue(value, entry.type, entry.fromSVG));
<del> // When applying gradient colors to shapes, we need to offset the
<del> // shape's initial position to get the same results as SVG.
<add> item[entry.set](convertValue(value, entry.type, entry.fromSVG));
<add> // When applying gradient colors to shapes, we need to offset
<add> // the shape's initial position to get the same results as SVG.
<ide> if (entry.type === 'color' && item instanceof Shape) {
<del> // Do not use result of convertValue() above, since calling the
<del> // setter will produce a new cloned color.
<add> // Do not use result of convertValue() above, since calling
<add> // the setter will produce a new cloned color.
<ide> var color = item[entry.get]();
<ide> if (color)
<ide> color.transform(new Matrix().translate(
<ide> * @param {SVGSVGElement} node an SVG node to read style and attributes from.
<ide> * @param {Item} item the item to apply the style and attributes to.
<ide> */
<del> function applyAttributes(item, node) {
<add> function applyAttributes(item, node, isRoot) {
<ide> // SVG attributes can be set both as styles and direct node attributes,
<ide> // so we need to handle both.
<ide> var styles = {
<ide> node: DomElement.getStyles(node) || {},
<del> parent: DomElement.getStyles(node.parentNode) || {}
<add> // Do not check for inheritance if this is the root, since we want
<add> // the default SVG settings to stick.
<add> parent: !isRoot && DomElement.getStyles(node.parentNode) || {}
<ide> };
<ide> Base.each(attributes, function(apply, name) {
<ide> var value = getAttribute(node, name, styles);
<ide> return match && definitions[match[1]];
<ide> }
<ide>
<del> function importSVG(node, options, clearDefs) {
<add> function importSVG(node, isRoot, options) {
<ide> if (!options)
<ide> options = {};
<ide> if (typeof node === 'string')
<ide> // jsdom in Node.js uses uppercase values for nodeName...
<ide> var type = node.nodeName.toLowerCase(),
<ide> importer = importers[type],
<del> item = importer && importer(node, type, options),
<add> item = importer && importer(node, type, isRoot, options),
<ide> data = type !== '#document' && node.getAttribute('data-paper-data');
<ide> if (item) {
<ide> // See importGroup() for an explanation of this filtering:
<ide> if (!(item instanceof Group))
<del> item = applyAttributes(item, node);
<add> item = applyAttributes(item, node, isRoot);
<ide> if (options.expandShapes && item instanceof Shape) {
<ide> item.remove();
<ide> item = item.toPath();
<ide> item._data = JSON.parse(data);
<ide> }
<ide> // Clear definitions at the end of import?
<del> if (clearDefs)
<add> if (isRoot)
<ide> definitions = {};
<ide> return item;
<ide> }
<ide>
<ide> Item.inject({
<ide> importSVG: function(node, options) {
<del> return this.addChild(importSVG(node, options, true));
<add> return this.addChild(importSVG(node, true, options));
<ide> }
<ide> });
<ide>
<ide> Project.inject({
<ide> importSVG: function(node, options) {
<ide> this.activate();
<del> return importSVG(node, options, true);
<add> return importSVG(node, true, options);
<ide> }
<ide> });
<ide> }; |
|
Java | apache-2.0 | 8ea8e37e24283142985e9a466cf584e2617cfe9b | 0 | Stratio/stratio-connector-cassandra,Stratio/stratio-connector-cassandra | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.cassandra;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.datastax.driver.core.CloseFuture;
import com.datastax.driver.core.Session;
import com.stratio.connector.cassandra.engine.CassandraMetadataEngine;
import com.stratio.connector.cassandra.engine.CassandraQueryEngine;
import com.stratio.connector.cassandra.engine.CassandraStorageEngine;
import com.stratio.connector.cassandra.engine.Engine;
import com.stratio.connector.cassandra.engine.EngineConfig;
import com.stratio.crossdata.common.connector.ConnectorClusterConfig;
import com.stratio.crossdata.common.connector.IConfiguration;
import com.stratio.crossdata.common.connector.IConnector;
import com.stratio.crossdata.common.connector.IMetadataEngine;
import com.stratio.crossdata.common.connector.IQueryEngine;
import com.stratio.crossdata.common.connector.IStorageEngine;
import com.stratio.crossdata.common.data.ClusterName;
import com.stratio.crossdata.common.exceptions.ConnectionException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.exceptions.InitializationException;
import com.stratio.crossdata.common.exceptions.UnsupportedException;
import com.stratio.crossdata.common.security.ICredentials;
import com.stratio.crossdata.connectors.ConnectorApp;
/**
* Cassandra Connector class. This class contain a main that starts the connector.
*/
public class CassandraConnector implements IConnector {
/**
* Class logger.
*/
private static final Logger LOG = Logger.getLogger(CassandraConnector.class);
/**
* DEFAULT_LIMIT for the select queries.
*/
private static final int DEFAULT_LIMIT = 100;
/**
* The sessions of the connector.
*/
private Map<String, Session> sessions;
/**
* Map of the clusterName with a list with the properties and values of the connector.
*/
private Map<String, List<Pair<String, String>>> connectorOptionsPerCluster;
private String connectorName;
private String[] datastoreName;
/**
* String that contains the connector manifest.
*/
private String connectorString;
/**
* String that contains the datastore manifest.
*/
private String datastoreString;
/**
* Engines
*/
private CassandraStorageEngine storageEngine;
private CassandraQueryEngine queryEngine;
private CassandraMetadataEngine metadataEngine;
/**
* Constructor.
*/
public CassandraConnector() {
sessions = new HashMap<>();
connectorOptionsPerCluster = new HashMap<>();
XPathFactory xFactory = XPathFactory.newInstance();
Document d = null;
try {
InputStream connectorStream = getClass()
.getResourceAsStream("CassandraConnector.xml");
InputStream datastoreStream = getClass()
.getResourceAsStream("CassandraDataStore.xml");
datastoreString = stream2String(datastoreStream);
if (connectorStream == null) {
File file = new File("../conf/CassandraConnector.xml");
connectorStream = new FileInputStream(file);
}
connectorString = stream2String(connectorStream);
InputStream connectorStream2 = getClass()
.getResourceAsStream("CassandraConnector.xml");
if (connectorStream == null) {
File file = new File("../conf/CassandraConnector.xml");
connectorStream2 = new FileInputStream(file);
}
d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connectorStream2);
} catch (SAXException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
} catch (IOException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
} catch (ParserConfigurationException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
}
// create an XPath object
XPath xpath = xFactory.newXPath();
Object result;
XPathExpression expr;
try {
expr = xpath.compile("//ConnectorName/text()");
result = expr.evaluate(d, XPathConstants.NODESET);
this.connectorName = ((NodeList) result).item(0).getNodeValue();
} catch (XPathExpressionException e) {
LOG.trace("Impossible to read Manifest with the connector name", e);
this.connectorName = "UNKNOWN";
}
try {
expr = xpath.compile("//DataStores/DataStoreName/text()");
result = expr.evaluate(d, XPathConstants.NODESET);
datastoreName = new String[((NodeList) result).getLength()];
for (int i = 0; i < ((NodeList) result).getLength(); i++) {
this.datastoreName[i] = ((NodeList) result).item(i).getNodeValue();
}
} catch (XPathExpressionException e) {
LOG.trace("Impossible to read Manifest with the Datastore name ", e);
datastoreName = new String[1];
this.datastoreName[0] = "UNKNOWN";
}
}
/**
* Main method that start the connector and controls the unexpected shutdowns.
*
* @param args
*/
public static void main(String[] args) {
CassandraConnector cassandraConnector = new CassandraConnector();
ConnectorApp connectorApp = new ConnectorApp();
connectorApp.startup(cassandraConnector);
cassandraConnector.attachShutDownHook();
}
private void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
uncontrolledShutdown();
}
});
}
/**
* Get the name of the connector.
*
* @return The name.
*/
@Override
public String getConnectorName() {
return connectorName;
}
/**
* Get the name of the datastores required by the connector.
*
* @return The names.
*/
@Override
public String[] getDatastoreName() {
return datastoreName.clone();
}
/**
* Init Method with the needed configuration for the connector.
*
* @param configuration
* @throws InitializationException
*/
@Override
public void init(IConfiguration configuration) throws InitializationException {
}
/**
* Connect Method: Enabled the connector with his own configuration.
*
* @param credentials The credentials.
* @param config The cluster config
* @throws ConnectionException
*/
@Override
public void connect(ICredentials credentials, ConnectorClusterConfig config)
throws ConnectionException {
ClusterName clusterName = config.getName();
//Check if the cluster is attached with other connector
if (sessions.containsKey(clusterName.getName())) {
throw new ConnectionException("The connection to " + clusterName.getName() + " already exists.");
}
Map<String, String> clusterOptions = config.getClusterOptions();
Map<String, String> connectorOptions = config.getConnectorOptions();
EngineConfig engineConfig = new EngineConfig();
//the hosts must be received as [host1:port,host2:port,host3:port...]
engineConfig.setCassandraHosts(
clusterOptions.get("Hosts").substring(1, clusterOptions.get("Hosts").length() - 1)
.split(","));
engineConfig.setCassandraPort(Integer.parseInt(clusterOptions.get("Port")));
engineConfig.setCredentials(credentials);
Pair<String, String> connectorPropertiesValues;
List<Pair<String, String>> connectorPropertiesList = new ArrayList<>();
if (connectorOptions.get("DefaultLimit") == null) {
connectorPropertiesValues = new ImmutablePair<>("DefaultLimit", Integer.toString(DEFAULT_LIMIT));
} else {
connectorPropertiesValues = new ImmutablePair<>("DefaultLimit", connectorOptions.get("DefaultLimit"));
}
connectorPropertiesList.add(connectorPropertiesValues);
connectorOptionsPerCluster.put(clusterName.getName(), connectorPropertiesList);
Engine engine = new Engine(engineConfig);
LOG.info("Cassandra session created.");
sessions.put(clusterName.getName(), engine.getSession());
}
/**
* Close the session of the cluster name specified.
*
* @param name Name of the cluster.
* @throws ConnectionException
*/
@Override
public void close(ClusterName name) throws ConnectionException {
LOG.info("Closing cassandra session");
sessions.get(name.getName()).close();
sessions.remove(name.getName());
}
/**
* Close all the sessions of the connector.
*
* @throws ExecutionException
*/
@Override
public void shutdown() throws ExecutionException {
List<CloseFuture> closeFutureList = new ArrayList<>();
for (Session s : sessions.values()) {
closeFutureList.add(s.closeAsync());
}
sessions = new HashMap<>();
}
/**
* Close at the moment all the sessions of the connector.
*/
public void uncontrolledShutdown() {
for (Session s : sessions.values()) {
s.close();
}
sessions = new HashMap<>();
}
/**
* Controls if there is a session started for a cluster name.
*
* @param name cluster name.
* @return if the connector is connected to the cluster.
*/
@Override
public boolean isConnected(ClusterName name) {
boolean connected;
if (sessions.get(name.getName()) != null) {
if (sessions.get(name.getName()).getCluster() != null) {
connected = true;
} else {
connected = false;
}
} else {
connected = false;
}
return connected;
}
/**
* Get the storage com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IStorageEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IStorageEngine getStorageEngine() throws UnsupportedException {
if (storageEngine != null) {
return storageEngine;
} else {
return new CassandraStorageEngine(sessions);
}
}
/**
* Get the query com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IQueryEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IQueryEngine getQueryEngine() throws UnsupportedException {
if (queryEngine != null) {
return queryEngine;
} else {
return new CassandraQueryEngine(sessions, connectorOptionsPerCluster);
}
}
/**
* Get the metadata com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IMetadataEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IMetadataEngine getMetadataEngine() throws UnsupportedException {
if (metadataEngine != null) {
return metadataEngine;
} else {
return new CassandraMetadataEngine(sessions);
}
}
@Override
public String getConnectorManifest(){
return connectorString;
}
@Override
public String getDatastoreManifest(){
return datastoreString;
}
private String stream2String(InputStream stream) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer);
return writer.toString();
}
}
| cassandra-connector/src/main/java/com/stratio/connector/cassandra/CassandraConnector.java | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.connector.cassandra;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.datastax.driver.core.CloseFuture;
import com.datastax.driver.core.Session;
import com.stratio.connector.cassandra.engine.CassandraMetadataEngine;
import com.stratio.connector.cassandra.engine.CassandraQueryEngine;
import com.stratio.connector.cassandra.engine.CassandraStorageEngine;
import com.stratio.connector.cassandra.engine.Engine;
import com.stratio.connector.cassandra.engine.EngineConfig;
import com.stratio.crossdata.common.connector.ConnectorClusterConfig;
import com.stratio.crossdata.common.connector.IConfiguration;
import com.stratio.crossdata.common.connector.IConnector;
import com.stratio.crossdata.common.connector.IMetadataEngine;
import com.stratio.crossdata.common.connector.IQueryEngine;
import com.stratio.crossdata.common.connector.IStorageEngine;
import com.stratio.crossdata.common.data.ClusterName;
import com.stratio.crossdata.common.exceptions.ConnectionException;
import com.stratio.crossdata.common.exceptions.ExecutionException;
import com.stratio.crossdata.common.exceptions.InitializationException;
import com.stratio.crossdata.common.exceptions.UnsupportedException;
import com.stratio.crossdata.common.security.ICredentials;
import com.stratio.crossdata.connectors.ConnectorApp;
import org.apache.commons.lang3.tuple.Pair;
/**
* Cassandra Connector class. This class contain a main that starts the connector.
*/
public class CassandraConnector implements IConnector {
/**
* Class logger.
*/
private static final Logger LOG = Logger.getLogger(CassandraConnector.class);
/**
* DEFAULT_LIMIT for the select queries.
*/
private static final int DEFAULT_LIMIT = 100;
/**
* The sessions of the connector.
*/
private Map<String, Session> sessions;
/**
* Map of the clusterName with a list with the properties and values of the connector.
*/
private Map<String,List<Pair<String,String>>> connectorOptionsPerCluster;
private String connectorName;
private String[] datastoreName;
/**
* Stream that contains the connector manifest.
*/
private InputStream connectorStream;
/**
* Stream that contains the datastore manifest.
*/
private InputStream datastoreStream;
/**
* Engines
*/
private CassandraStorageEngine storageEngine;
private CassandraQueryEngine queryEngine;
private CassandraMetadataEngine metadataEngine;
/**
* Constructor.
*/
public CassandraConnector() {
sessions = new HashMap<>();
connectorOptionsPerCluster = new HashMap<>();
XPathFactory xFactory = XPathFactory.newInstance();
Document d = null;
try {
connectorStream = getClass()
.getResourceAsStream("CassandraConnector.xml");
datastoreStream = getClass()
.getResourceAsStream("CassandraDataStore.xml");
if(connectorStream == null){
File file = new File("../conf/CassandraConnector.xml");
connectorStream = new FileInputStream(file);
}
d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connectorStream);
} catch (SAXException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
} catch (IOException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
} catch (ParserConfigurationException e) {
LOG.trace("Impossible to read Manifest with the connector configuration", e);
}
// create an XPath object
XPath xpath = xFactory.newXPath();
Object result;
XPathExpression expr;
try {
expr = xpath.compile("//ConnectorName/text()");
result = expr.evaluate(d, XPathConstants.NODESET);
this.connectorName = ((NodeList) result).item(0).getNodeValue();
} catch (XPathExpressionException e) {
LOG.trace("Impossible to read Manifest with the connector name", e);
this.connectorName = "UNKNOWN";
}
try {
expr = xpath.compile("//DataStores/DataStoreName/text()");
result = expr.evaluate(d, XPathConstants.NODESET);
datastoreName = new String[((NodeList) result).getLength()];
for (int i = 0; i < ((NodeList) result).getLength(); i++) {
this.datastoreName[i] = ((NodeList) result).item(i).getNodeValue();
}
} catch (XPathExpressionException e) {
LOG.trace("Impossible to read Manifest with the Datastore name ", e);
datastoreName = new String[1];
this.datastoreName[0] = "UNKNOWN";
}
}
/**
* Main method that start the connector and controls the unexpected shutdowns.
*
* @param args
*/
public static void main(String[] args) {
CassandraConnector cassandraConnector = new CassandraConnector();
ConnectorApp connectorApp = new ConnectorApp();
connectorApp.startup(cassandraConnector);
cassandraConnector.attachShutDownHook();
}
private void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
uncontrolledShutdown();
}
});
}
/**
* Get the name of the connector.
*
* @return The name.
*/
@Override
public String getConnectorName() {
return connectorName;
}
/**
* Get the name of the datastores required by the connector.
*
* @return The names.
*/
@Override
public String[] getDatastoreName() {
return datastoreName.clone();
}
/**
* Init Method with the needed configuration for the connector.
*
* @param configuration
* @throws InitializationException
*/
@Override
public void init(IConfiguration configuration) throws InitializationException {
}
/**
* Connect Method: Enabled the connector with his own configuration.
*
* @param credentials The credentials.
* @param config The cluster config
* @throws ConnectionException
*/
@Override
public void connect(ICredentials credentials, ConnectorClusterConfig config)
throws ConnectionException {
ClusterName clusterName = config.getName();
//Check if the cluster is attached with other connector
if (sessions.containsKey(clusterName.getName())){
throw new ConnectionException("The connection to " + clusterName.getName() + " already exists." );
}
Map<String, String> clusterOptions = config.getClusterOptions();
Map<String, String> connectorOptions = config.getConnectorOptions();
EngineConfig engineConfig = new EngineConfig();
//the hosts must be received as [host1:port,host2:port,host3:port...]
engineConfig.setCassandraHosts(
clusterOptions.get("Hosts").substring(1, clusterOptions.get("Hosts").length() - 1)
.split(","));
engineConfig.setCassandraPort(Integer.parseInt(clusterOptions.get("Port")));
engineConfig.setCredentials(credentials);
Pair<String,String> connectorPropertiesValues;
List<Pair<String,String>> connectorPropertiesList= new ArrayList<>();
if (connectorOptions.get("DefaultLimit") == null) {
connectorPropertiesValues=new ImmutablePair<>("DefaultLimit", Integer.toString(DEFAULT_LIMIT));
} else {
connectorPropertiesValues=new ImmutablePair<>("DefaultLimit",connectorOptions.get("DefaultLimit"));
}
connectorPropertiesList.add(connectorPropertiesValues);
connectorOptionsPerCluster.put(clusterName.getName(),connectorPropertiesList);
Engine engine = new Engine(engineConfig);
LOG.info("Cassandra session created.");
sessions.put(clusterName.getName(), engine.getSession());
}
/**
* Close the session of the cluster name specified.
*
* @param name Name of the cluster.
* @throws ConnectionException
*/
@Override
public void close(ClusterName name) throws ConnectionException {
LOG.info("Closing cassandra session");
sessions.get(name.getName()).close();
sessions.remove(name.getName());
}
/**
* Close all the sessions of the connector.
*
* @throws ExecutionException
*/
@Override
public void shutdown() throws ExecutionException {
List<CloseFuture> closeFutureList = new ArrayList<>();
for (Session s : sessions.values()) {
closeFutureList.add(s.closeAsync());
}
sessions = new HashMap<>();
}
/**
* Close at the moment all the sessions of the connector.
*/
public void uncontrolledShutdown() {
for (Session s : sessions.values()) {
s.close();
}
sessions = new HashMap<>();
}
/**
* Controls if there is a session started for a cluster name.
*
* @param name cluster name.
* @return if the connector is connected to the cluster.
*/
@Override
public boolean isConnected(ClusterName name) {
boolean connected;
if (sessions.get(name.getName()) != null) {
if (sessions.get(name.getName()).getCluster() != null) {
connected = true;
} else {
connected = false;
}
} else {
connected = false;
}
return connected;
}
/**
* Get the storage com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IStorageEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IStorageEngine getStorageEngine() throws UnsupportedException {
if (storageEngine != null) {
return storageEngine;
} else {
return new CassandraStorageEngine(sessions);
}
}
/**
* Get the query com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IQueryEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IQueryEngine getQueryEngine() throws UnsupportedException {
if (queryEngine != null) {
return queryEngine;
} else {
return new CassandraQueryEngine(sessions, connectorOptionsPerCluster);
}
}
/**
* Get the metadata com.stratio.connector.cassandra.
*
* @return An implementation of {@link com.stratio.crossdata.common.connector.IMetadataEngine}.
* @throws UnsupportedException If the connector does not provide this functionality.
*/
@Override
public IMetadataEngine getMetadataEngine() throws UnsupportedException {
if (metadataEngine != null) {
return metadataEngine;
} else {
return new CassandraMetadataEngine(sessions);
}
}
@Override
public InputStream getConnectorManifest() {
return connectorStream;
}
@Override
public InputStream getDatastoreManifest() {
return datastoreStream;
}
}
| Fix to send manifest to crossdata
| cassandra-connector/src/main/java/com/stratio/connector/cassandra/CassandraConnector.java | Fix to send manifest to crossdata | <ide><path>assandra-connector/src/main/java/com/stratio/connector/cassandra/CassandraConnector.java
<ide> import java.io.FileInputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.io.StringWriter;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import javax.xml.xpath.XPathExpressionException;
<ide> import javax.xml.xpath.XPathFactory;
<ide>
<add>import org.apache.commons.io.IOUtils;
<ide> import org.apache.commons.lang3.tuple.ImmutablePair;
<add>import org.apache.commons.lang3.tuple.Pair;
<ide> import org.apache.log4j.Logger;
<ide> import org.w3c.dom.Document;
<ide> import org.w3c.dom.NodeList;
<ide> import com.stratio.crossdata.common.security.ICredentials;
<ide> import com.stratio.crossdata.connectors.ConnectorApp;
<ide>
<del>import org.apache.commons.lang3.tuple.Pair;
<del>
<ide> /**
<ide> * Cassandra Connector class. This class contain a main that starts the connector.
<ide> */
<ide> /**
<ide> * Map of the clusterName with a list with the properties and values of the connector.
<ide> */
<del> private Map<String,List<Pair<String,String>>> connectorOptionsPerCluster;
<add> private Map<String, List<Pair<String, String>>> connectorOptionsPerCluster;
<ide> private String connectorName;
<ide> private String[] datastoreName;
<ide>
<ide> /**
<del> * Stream that contains the connector manifest.
<del> */
<del> private InputStream connectorStream;
<del>
<del> /**
<del> * Stream that contains the datastore manifest.
<del> */
<del> private InputStream datastoreStream;
<del>
<add> * String that contains the connector manifest.
<add> */
<add> private String connectorString;
<add>
<add> /**
<add> * String that contains the datastore manifest.
<add> */
<add> private String datastoreString;
<ide>
<ide> /**
<ide> * Engines
<ide> XPathFactory xFactory = XPathFactory.newInstance();
<ide> Document d = null;
<ide> try {
<del> connectorStream = getClass()
<add> InputStream connectorStream = getClass()
<ide> .getResourceAsStream("CassandraConnector.xml");
<del> datastoreStream = getClass()
<add>
<add> InputStream datastoreStream = getClass()
<ide> .getResourceAsStream("CassandraDataStore.xml");
<del> if(connectorStream == null){
<add> datastoreString = stream2String(datastoreStream);
<add> if (connectorStream == null) {
<ide> File file = new File("../conf/CassandraConnector.xml");
<ide> connectorStream = new FileInputStream(file);
<ide> }
<del> d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connectorStream);
<add> connectorString = stream2String(connectorStream);
<add>
<add> InputStream connectorStream2 = getClass()
<add> .getResourceAsStream("CassandraConnector.xml");
<add>
<add> if (connectorStream == null) {
<add> File file = new File("../conf/CassandraConnector.xml");
<add> connectorStream2 = new FileInputStream(file);
<add> }
<add> d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connectorStream2);
<ide>
<ide> } catch (SAXException e) {
<ide> LOG.trace("Impossible to read Manifest with the connector configuration", e);
<ide> } catch (ParserConfigurationException e) {
<ide> LOG.trace("Impossible to read Manifest with the connector configuration", e);
<ide> }
<add>
<ide> // create an XPath object
<ide> XPath xpath = xFactory.newXPath();
<ide> Object result;
<ide> ClusterName clusterName = config.getName();
<ide>
<ide> //Check if the cluster is attached with other connector
<del> if (sessions.containsKey(clusterName.getName())){
<del> throw new ConnectionException("The connection to " + clusterName.getName() + " already exists." );
<add> if (sessions.containsKey(clusterName.getName())) {
<add> throw new ConnectionException("The connection to " + clusterName.getName() + " already exists.");
<ide> }
<ide>
<ide> Map<String, String> clusterOptions = config.getClusterOptions();
<ide> engineConfig.setCassandraPort(Integer.parseInt(clusterOptions.get("Port")));
<ide> engineConfig.setCredentials(credentials);
<ide>
<del> Pair<String,String> connectorPropertiesValues;
<del> List<Pair<String,String>> connectorPropertiesList= new ArrayList<>();
<add> Pair<String, String> connectorPropertiesValues;
<add> List<Pair<String, String>> connectorPropertiesList = new ArrayList<>();
<ide> if (connectorOptions.get("DefaultLimit") == null) {
<del> connectorPropertiesValues=new ImmutablePair<>("DefaultLimit", Integer.toString(DEFAULT_LIMIT));
<add> connectorPropertiesValues = new ImmutablePair<>("DefaultLimit", Integer.toString(DEFAULT_LIMIT));
<ide> } else {
<del> connectorPropertiesValues=new ImmutablePair<>("DefaultLimit",connectorOptions.get("DefaultLimit"));
<add> connectorPropertiesValues = new ImmutablePair<>("DefaultLimit", connectorOptions.get("DefaultLimit"));
<ide> }
<ide> connectorPropertiesList.add(connectorPropertiesValues);
<del> connectorOptionsPerCluster.put(clusterName.getName(),connectorPropertiesList);
<add> connectorOptionsPerCluster.put(clusterName.getName(), connectorPropertiesList);
<ide>
<ide> Engine engine = new Engine(engineConfig);
<ide>
<ide> }
<ide>
<ide> @Override
<del> public InputStream getConnectorManifest() {
<del> return connectorStream;
<del> }
<del>
<del> @Override
<del> public InputStream getDatastoreManifest() {
<del> return datastoreStream;
<add> public String getConnectorManifest(){
<add> return connectorString;
<add>
<add> }
<add>
<add> @Override
<add> public String getDatastoreManifest(){
<add> return datastoreString;
<add> }
<add>
<add> private String stream2String(InputStream stream) throws IOException {
<add> StringWriter writer = new StringWriter();
<add>
<add> IOUtils.copy(stream, writer);
<add>
<add> return writer.toString();
<ide> }
<ide> } |
|
Java | apache-2.0 | 27ecdccae85c147908ef85b1f78584064211f8d0 | 0 | dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android | package org.commcare.views.media;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.IdRes;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.commcare.dalvik.R;
import org.commcare.preferences.CommCarePreferences;
import org.commcare.preferences.DeveloperPreferences;
import org.commcare.utils.MediaUtil;
import org.commcare.utils.QRCodeEncoder;
import org.commcare.views.ResizingImageView;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import java.io.File;
/**
* This layout is used anywhere we can have image/audio/video/text.
* TODO: Put this in a layout file!!!!
*
* @author carlhartung
*/
public class MediaLayout extends RelativeLayout {
private static final String TAG = MediaLayout.class.getSimpleName();
@IdRes
public static final int INLINE_VIDEO_PANE_ID = 99999;
@IdRes
private static final int QUESTION_TEXT_PANE_ID = 2342134;
@IdRes
private static final int AUDIO_BUTTON_ID = 3245345;
@IdRes
private static final int VIDEO_BUTTON_ID = 234982340;
@IdRes
private static final int IMAGE_VIEW_ID = 23423534;
@IdRes
private static final int MISSING_IMAGE_ID = 234873453;
private TextView mView_Text;
private AudioButton mAudioButton;
private ImageButton mVideoButton;
private TextView mMissingImage;
public MediaLayout(Context c) {
super(c);
mView_Text = null;
mAudioButton = null;
mMissingImage = null;
mVideoButton = null;
}
public void setAVT(TextView text, String audioURI, String imageURI,
final String videoURI, final String bigImageURI) {
setAVT(text, audioURI, imageURI, videoURI, bigImageURI, null, null);
}
public void setAVT(TextView text, String audioURI, String imageURI,
final String videoURI, final String bigImageURI,
final String qrCodeContent, String inlineVideoURI) {
mView_Text = text;
RelativeLayout.LayoutParams textParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams audioParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams videoParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams questionTextPaneParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams mediaPaneParams =
new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
RelativeLayout questionTextPane = new RelativeLayout(this.getContext());
questionTextPane.setId(QUESTION_TEXT_PANE_ID);
if (audioURI != null) {
mAudioButton = new AudioButton(getContext(), audioURI, true);
// random ID to be used by the relative layout.
mAudioButton.setId(AUDIO_BUTTON_ID);
}
// Then set up the video button
if (videoURI != null) {
mVideoButton = new ImageButton(getContext());
mVideoButton.setImageResource(android.R.drawable.ic_media_play);
mVideoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String videoFilename = "";
try {
videoFilename =
ReferenceManager._().DeriveReference(videoURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(TAG, "Invalid reference exception");
e.printStackTrace();
}
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
// We should have a video clip, but the file doesn't exist.
String errorMsg =
getContext().getString(R.string.file_missing, videoFilename);
Log.e(TAG, errorMsg);
Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(videoFile), "video/*");
try {
String uri = Uri.fromFile(videoFile).getPath().replaceAll("^.*\\/", "");
Logger.log("media", "start " + uri);
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view video"),
Toast.LENGTH_SHORT).show();
}
}
});
mVideoButton.setId(VIDEO_BUTTON_ID);
}
// Add the audioButton and videoButton (if applicable) and view
// (containing text) to the relative layout.
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
questionTextPane.addView(mAudioButton, audioParams);
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
questionTextPane.addView(mVideoButton, videoParams);
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
questionTextPane.addView(mAudioButton, audioParams);
questionTextPane.addView(mVideoButton, videoParams);
} else {
//Audio and Video are both null, let text bleed to right
textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
boolean textVisible = (mView_Text.getVisibility() != GONE);
if (textVisible) {
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
questionTextPane.addView(mView_Text, textParams);
}
// Now set up the center view, it is either an image, a QR Code, or an inline video
String errorMsg = null;
View mediaPane = null;
if (inlineVideoURI != null) {
mediaPane = getInlineVideoView(inlineVideoURI, mediaPaneParams);
} else if (qrCodeContent != null) {
Bitmap image;
Display display =
((WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
//see if we're doing a new QR code display
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
int minimumDim = Math.min(screenWidth, screenHeight);
try {
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrCodeContent, minimumDim);
image = qrCodeEncoder.encodeAsBitmap();
ImageView mImageView = new ImageView(getContext());
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageBitmap(image);
mImageView.setId(IMAGE_VIEW_ID);
mediaPane = mImageView;
} catch (Exception e) {
e.printStackTrace();
}
} else if (imageURI != null) {
try {
int[] maxBounds = getMaxCenterViewBounds();
final String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), imageURI, maxBounds[0],
maxBounds[1]);
if (b != null) {
ImageView mImageView = new ImageView(getContext());
if (useResizingImageView()) {
mImageView = new ResizingImageView(getContext(), imageURI, bigImageURI);
mImageView.setAdjustViewBounds(true);
mImageView.setMaxWidth(maxBounds[0]);
mImageView.setMaxHeight(maxBounds[1]);
} else {
mImageView.setScaleType(ImageView.ScaleType.CENTER);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setImageBitmap(b);
mImageView.setId(IMAGE_VIEW_ID);
mediaPane = mImageView;
}
} else {
// An error hasn't been logged. We should have an image, but the file doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(TAG, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(MISSING_IMAGE_ID);
mediaPane = mMissingImage;
}
} catch (InvalidReferenceException e) {
Log.e(TAG, "image invalid reference exception");
e.printStackTrace();
}
}
if (mediaPane != null) {
if (!textVisible) {
this.addView(questionTextPane, questionTextPaneParams);
if (mAudioButton != null) {
mediaPaneParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
questionTextPane.addView(mediaPane, mediaPaneParams);
}
if (mVideoButton != null) {
mediaPaneParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
questionTextPane.addView(mediaPane, mediaPaneParams);
}
} else {
if (DeveloperPreferences.imageAboveTextEnabled()) {
mediaPaneParams.addRule(CENTER_HORIZONTAL);
this.addView(mediaPane, mediaPaneParams);
questionTextPaneParams.addRule(RelativeLayout.BELOW, mediaPane.getId());
this.addView(questionTextPane, questionTextPaneParams);
} else {
this.addView(questionTextPane, questionTextPaneParams);
mediaPaneParams.addRule(RelativeLayout.BELOW, questionTextPane.getId());
mediaPaneParams.addRule(CENTER_HORIZONTAL);
this.addView(mediaPane, mediaPaneParams);
}
}
} else {
this.addView(questionTextPane, questionTextPaneParams);
}
}
/**
* Creates a video view for the provided URI or an error view elaborating why the video
* couldn't be displayed.
*
* @param inlineVideoURI JavaRosa Reference URI
* @param viewLayoutParams the layout params that will be applied to the view. Expect to be
* mutated by this method
*/
private View getInlineVideoView(String inlineVideoURI, RelativeLayout.LayoutParams viewLayoutParams) {
try {
final String videoFilename = ReferenceManager._().DeriveReference(inlineVideoURI).getLocalURI();
int[] maxBounds = getMaxCenterViewBounds();
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
return getMissingImageView("No video file found at: " + videoFilename);
} else {
//NOTE: This has odd behavior when you have a text input on the screen
//since clicking the video view to bring up controls has weird effects.
//since we shotgun grab the focus for the input widget.
final MediaController ctrl = new MediaController(this.getContext());
VideoView videoView = new VideoView(this.getContext());
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
ctrl.show();
}
});
videoView.setVideoPath(videoFilename);
videoView.setMediaController(ctrl);
ctrl.setAnchorView(videoView);
//These surprisingly get re-jiggered as soon as the video is loaded, so we
//just want to give it the _max_ bounds, it'll pick the limiter and shrink
//itself when it's ready.
viewLayoutParams.width = maxBounds[0];
viewLayoutParams.height = maxBounds[1];
videoView.setId(INLINE_VIDEO_PANE_ID);
return videoView;
}
} catch (InvalidReferenceException ire) {
Log.e(TAG, "invalid video reference exception");
ire.printStackTrace();
return getMissingImageView("Invalid reference: " + ire.getReferenceString());
}
}
private TextView getMissingImageView(String errorMessage) {
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMessage);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(MISSING_IMAGE_ID);
return mMissingImage;
}
private boolean useResizingImageView() {
// only allow ResizingImageView to be used if not also using smart inflation
return !CommCarePreferences.isSmartInflationEnabled() &&
(ResizingImageView.resizeMethod != null &&
(ResizingImageView.resizeMethod.equals("full") ||
ResizingImageView.resizeMethod.equals("half") ||
ResizingImageView.resizeMethod.equals("width")));
}
/**
* @return The appropriate max size of an image view pane in this widget. returned as an int
* array of [width, height]
*/
private int[] getMaxCenterViewBounds() {
DisplayMetrics metrics = this.getContext().getResources().getDisplayMetrics();
int maxWidth = metrics.widthPixels;
int maxHeight = metrics.heightPixels;
// subtract height for textview and buttons, if present
if (mView_Text != null) {
maxHeight = maxHeight - mView_Text.getHeight();
}
if (mVideoButton != null) {
maxHeight = maxHeight - mVideoButton.getHeight();
} else if (mAudioButton != null) {
maxHeight = maxHeight - mAudioButton.getHeight();
}
// reduce by third for safety
return new int[]{maxWidth, (2 * maxHeight) / 3};
}
/**
* This adds a divider at the bottom of this layout. Used to separate
* fields in lists.
*/
public void addDivider(ImageView v) {
RelativeLayout.LayoutParams dividerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (mMissingImage != null) {
dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId());
} else if (mVideoButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId());
} else if (mAudioButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else if (mView_Text != null) {
// No picture
dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
Log.e(TAG, "Tried to add divider to uninitialized ATVWidget");
return;
}
addView(v, dividerParams);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility != View.VISIBLE) {
if (mAudioButton != null) {
mAudioButton.endPlaying();
}
}
}
}
| app/src/org/commcare/views/media/MediaLayout.java | package org.commcare.views.media;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.IdRes;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import org.commcare.dalvik.R;
import org.commcare.preferences.CommCarePreferences;
import org.commcare.preferences.DeveloperPreferences;
import org.commcare.utils.MediaUtil;
import org.commcare.utils.QRCodeEncoder;
import org.commcare.views.ResizingImageView;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.services.Logger;
import java.io.File;
/**
* This layout is used anywhere we can have image/audio/video/text.
* TODO: Put this in a layout file!!!!
*
* @author carlhartung
*/
public class MediaLayout extends RelativeLayout {
private static final String TAG = MediaLayout.class.getSimpleName();
@IdRes
public static final int INLINE_VIDEO_PANE_ID = 99999;
private TextView mView_Text;
private AudioButton mAudioButton;
private ImageButton mVideoButton;
private TextView mMissingImage;
public MediaLayout(Context c) {
super(c);
mView_Text = null;
mAudioButton = null;
mMissingImage = null;
mVideoButton = null;
}
public void setAVT(TextView text, String audioURI, String imageURI,
final String videoURI, final String bigImageURI) {
setAVT(text, audioURI, imageURI, videoURI, bigImageURI, null, null);
}
public void setAVT(TextView text, String audioURI, String imageURI,
final String videoURI, final String bigImageURI,
final String qrCodeContent, String inlineVideoURI) {
mView_Text = text;
RelativeLayout.LayoutParams textParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams audioParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams videoParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams questionTextPaneParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams mediaPaneParams =
new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
RelativeLayout questionTextPane = new RelativeLayout(this.getContext());
questionTextPane.setId(2342134);
if (audioURI != null) {
mAudioButton = new AudioButton(getContext(), audioURI, true);
// random ID to be used by the relative layout.
mAudioButton.setId(3245345);
}
// Then set up the video button
if (videoURI != null) {
mVideoButton = new ImageButton(getContext());
mVideoButton.setImageResource(android.R.drawable.ic_media_play);
mVideoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String videoFilename = "";
try {
videoFilename =
ReferenceManager._().DeriveReference(videoURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(TAG, "Invalid reference exception");
e.printStackTrace();
}
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
// We should have a video clip, but the file doesn't exist.
String errorMsg =
getContext().getString(R.string.file_missing, videoFilename);
Log.e(TAG, errorMsg);
Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(videoFile), "video/*");
try {
String uri = Uri.fromFile(videoFile).getPath().replaceAll("^.*\\/", "");
Logger.log("media", "start " + uri);
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view video"),
Toast.LENGTH_SHORT).show();
}
}
});
mVideoButton.setId(234982340);
}
// Add the audioButton and videoButton (if applicable) and view
// (containing text) to the relative layout.
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
questionTextPane.addView(mAudioButton, audioParams);
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
questionTextPane.addView(mVideoButton, videoParams);
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
questionTextPane.addView(mAudioButton, audioParams);
questionTextPane.addView(mVideoButton, videoParams);
} else {
//Audio and Video are both null, let text bleed to right
textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
boolean textVisible = (mView_Text.getVisibility() != GONE);
if (textVisible) {
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
questionTextPane.addView(mView_Text, textParams);
}
// Now set up the center view, it is either an image, a QR Code, or an inline video
String errorMsg = null;
View mediaPane = null;
if (inlineVideoURI != null) {
mediaPane = getInlineVideoView(inlineVideoURI, mediaPaneParams);
} else if (qrCodeContent != null) {
Bitmap image;
Display display =
((WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
//see if we're doing a new QR code display
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
int minimumDim = Math.min(screenWidth, screenHeight);
try {
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrCodeContent, minimumDim);
image = qrCodeEncoder.encodeAsBitmap();
ImageView mImageView = new ImageView(getContext());
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
mImageView.setImageBitmap(image);
mImageView.setId(23423534);
mediaPane = mImageView;
} catch (Exception e) {
e.printStackTrace();
}
} else if (imageURI != null) {
try {
int[] maxBounds = getMaxCenterViewBounds();
final String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = MediaUtil.inflateDisplayImage(getContext(), imageURI, maxBounds[0],
maxBounds[1]);
if (b != null) {
ImageView mImageView = new ImageView(getContext());
if (useResizingImageView()) {
mImageView = new ResizingImageView(getContext(), imageURI, bigImageURI);
mImageView.setAdjustViewBounds(true);
mImageView.setMaxWidth(maxBounds[0]);
mImageView.setMaxHeight(maxBounds[1]);
} else{
mImageView.setScaleType(ImageView.ScaleType.CENTER);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setImageBitmap(b);
mImageView.setId(23423534);
mediaPane = mImageView;
}
} else {
// An error hasn't been logged. We should have an image, but the file doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(TAG, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(234873453);
mediaPane = mMissingImage;
}
} catch (InvalidReferenceException e) {
Log.e(TAG, "image invalid reference exception");
e.printStackTrace();
}
}
if (mediaPane != null) {
if (!textVisible) {
this.addView(questionTextPane, questionTextPaneParams);
if (mAudioButton != null) {
mediaPaneParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
questionTextPane.addView(mediaPane, mediaPaneParams);
}
if (mVideoButton != null) {
mediaPaneParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
questionTextPane.addView(mediaPane, mediaPaneParams);
}
} else {
if (DeveloperPreferences.imageAboveTextEnabled()) {
mediaPaneParams.addRule(CENTER_HORIZONTAL);
this.addView(mediaPane, mediaPaneParams);
questionTextPaneParams.addRule(RelativeLayout.BELOW, mediaPane.getId());
this.addView(questionTextPane, questionTextPaneParams);
} else {
this.addView(questionTextPane, questionTextPaneParams);
mediaPaneParams.addRule(RelativeLayout.BELOW, questionTextPane.getId());
mediaPaneParams.addRule(CENTER_HORIZONTAL);
this.addView(mediaPane, mediaPaneParams);
}
}
} else {
this.addView(questionTextPane, questionTextPaneParams);
}
}
/**
* Creates a video view for the provided URI or an error view elaborating why the video
* couldn't be displayed.
*
* @param inlineVideoURI JavaRosa Reference URI
* @param viewLayoutParams the layout params that will be applied to the view. Expect to be
* mutated by this method
*/
private View getInlineVideoView(String inlineVideoURI, RelativeLayout.LayoutParams viewLayoutParams) {
try {
final String videoFilename = ReferenceManager._().DeriveReference(inlineVideoURI).getLocalURI();
int[] maxBounds = getMaxCenterViewBounds();
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
return getMissingImageView("No video file found at: " + videoFilename);
} else {
//NOTE: This has odd behavior when you have a text input on the screen
//since clicking the video view to bring up controls has weird effects.
//since we shotgun grab the focus for the input widget.
final MediaController ctrl = new MediaController(this.getContext());
VideoView videoView = new VideoView(this.getContext());
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
ctrl.show();
}
});
videoView.setVideoPath(videoFilename);
videoView.setMediaController(ctrl);
ctrl.setAnchorView(videoView);
//These surprisingly get re-jiggered as soon as the video is loaded, so we
//just want to give it the _max_ bounds, it'll pick the limiter and shrink
//itself when it's ready.
viewLayoutParams.width = maxBounds[0];
viewLayoutParams.height = maxBounds[1];
videoView.setId(INLINE_VIDEO_PANE_ID);
return videoView;
}
} catch (InvalidReferenceException ire) {
Log.e(TAG, "invalid video reference exception");
ire.printStackTrace();
return getMissingImageView("Invalid reference: " + ire.getReferenceString());
}
}
private TextView getMissingImageView(String errorMessage) {
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMessage);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(234873453);
return mMissingImage;
}
private boolean useResizingImageView() {
// only allow ResizingImageView to be used if not also using smart inflation
return !CommCarePreferences.isSmartInflationEnabled() &&
(ResizingImageView.resizeMethod != null &&
(ResizingImageView.resizeMethod.equals("full") ||
ResizingImageView.resizeMethod.equals("half") ||
ResizingImageView.resizeMethod.equals("width")));
}
/**
* @return The appropriate max size of an image view pane in this widget. returned as an int
* array of [width, height]
*/
private int[] getMaxCenterViewBounds() {
DisplayMetrics metrics = this.getContext().getResources().getDisplayMetrics();
int maxWidth = metrics.widthPixels;
int maxHeight = metrics.heightPixels;
// subtract height for textview and buttons, if present
if (mView_Text != null) {
maxHeight = maxHeight - mView_Text.getHeight();
}
if (mVideoButton != null) {
maxHeight = maxHeight - mVideoButton.getHeight();
} else if (mAudioButton != null) {
maxHeight = maxHeight - mAudioButton.getHeight();
}
// reduce by third for safety
return new int[]{maxWidth, (2 * maxHeight) / 3};
}
/**
* This adds a divider at the bottom of this layout. Used to separate
* fields in lists.
*/
public void addDivider(ImageView v) {
RelativeLayout.LayoutParams dividerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if (mMissingImage != null) {
dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId());
} else if (mVideoButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId());
} else if (mAudioButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else if (mView_Text != null) {
// No picture
dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
Log.e(TAG, "Tried to add divider to uninitialized ATVWidget");
return;
}
addView(v, dividerParams);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility != View.VISIBLE) {
if (mAudioButton != null) {
mAudioButton.endPlaying();
}
}
}
}
| Use ints marked as resources
| app/src/org/commcare/views/media/MediaLayout.java | Use ints marked as resources | <ide><path>pp/src/org/commcare/views/media/MediaLayout.java
<ide> @IdRes
<ide> public static final int INLINE_VIDEO_PANE_ID = 99999;
<ide>
<add> @IdRes
<add> private static final int QUESTION_TEXT_PANE_ID = 2342134;
<add>
<add> @IdRes
<add> private static final int AUDIO_BUTTON_ID = 3245345;
<add>
<add> @IdRes
<add> private static final int VIDEO_BUTTON_ID = 234982340;
<add>
<add> @IdRes
<add> private static final int IMAGE_VIEW_ID = 23423534;
<add>
<add> @IdRes
<add> private static final int MISSING_IMAGE_ID = 234873453;
<add>
<ide> private TextView mView_Text;
<ide> private AudioButton mAudioButton;
<ide> private ImageButton mVideoButton;
<ide> new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
<ide>
<ide> RelativeLayout questionTextPane = new RelativeLayout(this.getContext());
<del> questionTextPane.setId(2342134);
<add> questionTextPane.setId(QUESTION_TEXT_PANE_ID);
<ide>
<ide> if (audioURI != null) {
<ide> mAudioButton = new AudioButton(getContext(), audioURI, true);
<ide> // random ID to be used by the relative layout.
<del> mAudioButton.setId(3245345);
<add> mAudioButton.setId(AUDIO_BUTTON_ID);
<ide> }
<ide>
<ide> // Then set up the video button
<ide> }
<ide> }
<ide> });
<del> mVideoButton.setId(234982340);
<add> mVideoButton.setId(VIDEO_BUTTON_ID);
<ide> }
<ide>
<ide> // Add the audioButton and videoButton (if applicable) and view
<ide> mImageView.setAdjustViewBounds(true);
<ide> mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
<ide> mImageView.setImageBitmap(image);
<del> mImageView.setId(23423534);
<add> mImageView.setId(IMAGE_VIEW_ID);
<ide>
<ide> mediaPane = mImageView;
<ide> } catch (Exception e) {
<ide> mImageView.setAdjustViewBounds(true);
<ide> mImageView.setMaxWidth(maxBounds[0]);
<ide> mImageView.setMaxHeight(maxBounds[1]);
<del> } else{
<add> } else {
<ide> mImageView.setScaleType(ImageView.ScaleType.CENTER);
<ide> }
<ide> mImageView.setPadding(10, 10, 10, 10);
<ide> mImageView.setImageBitmap(b);
<del> mImageView.setId(23423534);
<add> mImageView.setId(IMAGE_VIEW_ID);
<ide> mediaPane = mImageView;
<ide> }
<ide> } else {
<ide> mMissingImage = new TextView(getContext());
<ide> mMissingImage.setText(errorMsg);
<ide> mMissingImage.setPadding(10, 10, 10, 10);
<del> mMissingImage.setId(234873453);
<add> mMissingImage.setId(MISSING_IMAGE_ID);
<ide> mediaPane = mMissingImage;
<ide> }
<ide> } catch (InvalidReferenceException e) {
<ide> mMissingImage = new TextView(getContext());
<ide> mMissingImage.setText(errorMessage);
<ide> mMissingImage.setPadding(10, 10, 10, 10);
<del> mMissingImage.setId(234873453);
<add> mMissingImage.setId(MISSING_IMAGE_ID);
<ide> return mMissingImage;
<ide> }
<ide> |
|
Java | mit | da1f1bbec4285eb595205e26a5109e567157ac48 | 0 | thelinmichael/spotify-web-api-java,thelinmichael/spotify-web-api-java | package com.wrapper.spotify.enums;
import java.util.HashMap;
import java.util.Map;
/**
* An enumeration with the two modality types.
*
* @see <a href="https://en.wikipedia.org/wiki/Mode_(music)">Wikipedia: Mode (Music)</a>
*/
public enum Modality {
MINOR(0),
MAJOR(1);
public final int mode;
private static Map<Integer, Modality> map = new HashMap<>();
static {
for (Modality modality : Modality.values()) {
map.put(modality.mode, modality);
}
}
Modality(final int mode) {
this.mode = mode;
}
public static Modality valueOf(int mode) {
return map.get(mode);
}
/**
* Get the {@link Modality} type as a string.
*
* @return {@link Modality} type as a string.
*/
public int getType() {
return this.mode;
}
}
| src/main/java/com/wrapper/spotify/enums/Modality.java | package com.wrapper.spotify.enums;
/**
* An enumeration with the two modality types.
*
* @see <a href="https://en.wikipedia.org/wiki/Mode_(music)">Wikipedia: Mode (Music)</a>
*/
public enum Modality {
MINOR(0),
MAJOR(1);
public final int mode;
Modality(final int mode) {
this.mode = mode;
}
/**
* Get the {@link Modality} type as a string.
*
* @return {@link Modality} type as a string.
*/
public int getType() {
return this.mode;
}
}
| Enum Mapping
+ Modality map to enable value -> key resolution | src/main/java/com/wrapper/spotify/enums/Modality.java | Enum Mapping | <ide><path>rc/main/java/com/wrapper/spotify/enums/Modality.java
<ide> package com.wrapper.spotify.enums;
<add>
<add>import java.util.HashMap;
<add>import java.util.Map;
<ide>
<ide> /**
<ide> * An enumeration with the two modality types.
<ide> MAJOR(1);
<ide>
<ide> public final int mode;
<add> private static Map<Integer, Modality> map = new HashMap<>();
<add>
<add> static {
<add> for (Modality modality : Modality.values()) {
<add> map.put(modality.mode, modality);
<add> }
<add> }
<ide>
<ide> Modality(final int mode) {
<ide> this.mode = mode;
<add> }
<add>
<add> public static Modality valueOf(int mode) {
<add> return map.get(mode);
<ide> }
<ide>
<ide> /** |
|
Java | mit | d0a6ebe51463a9a057a3c9df624154a5e6caea19 | 0 | touist/touist,touist/touist,olzd/touist,olzd/touist,olzd/touist,touist/touist,FredMaris/touist,FredMaris/touist,FredMaris/touist,touist/touist | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui.editionView;
import gui.MainFrame;
import gui.State;
import gui.editionView.editor.Editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
/**
*
* @author Skander
*/
public class InsertionButton extends JButton {
private final Editor editorTextArea;
private final String codeToInsert;
private ArrayList<Integer> snipets;
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets) {
this.editorTextArea = editorTextArea;
this.codeToInsert = codeToInsert;
this.snipets = snipets;
this.setText(codeToInsert);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
((MainFrame)(getRootPane().getParent())).state = State.EDITION;
insertAtCaret(codeToInsert);
break;
case EDITION_ERROR :
((MainFrame)(getRootPane().getParent())).state = State.EDITION_ERROR;
insertAtCaret(codeToInsert);
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + ((MainFrame)(getRootPane().getParent())).state);
}
}
});
this.setFocusable(false);
this.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
this.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide) {
this(editorTextArea, codeToInsert, snipets);
setToolTipText(aide);
}
/**
* Insert text at the caret position in the textArea.
* @param text
*/
private void insertAtCaret(String text) {
if (editorTextArea.hasFocus()) {
Integer caretPosition = editorTextArea.getCaretPosition();
// insert is better than setText: setText entirely remove previous text then make an insert operation
editorTextArea.insert(text, caretPosition);
for(int snippetBegin = 0; snippetBegin < snipets.size(); snippetBegin+=2) {
int snippetEnd = snippetBegin + 1;
editorTextArea.addSnipet(caretPosition+snipets.get(snippetBegin),caretPosition+snipets.get(snippetEnd));
}
}
//TODO update latex schematic area
}
}
| ui/gui/editionView/InsertionButton.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui.editionView;
import gui.MainFrame;
import gui.State;
import gui.editionView.editor.Editor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
/**
*
* @author Skander
*/
public class InsertionButton extends JButton {
private final Editor editorTextArea;
private final String codeToInsert;
public InsertionButton(Editor editorTextArea, String codeToInsert) {
this.editorTextArea = editorTextArea;
this.codeToInsert = codeToInsert;
this.setText(codeToInsert);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
((MainFrame)(getRootPane().getParent())).state = State.EDITION;
insertAtCaret(codeToInsert);
break;
case EDITION_ERROR :
((MainFrame)(getRootPane().getParent())).state = State.EDITION_ERROR;
insertAtCaret(codeToInsert);
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + ((MainFrame)(getRootPane().getParent())).state);
}
}
});
this.setFocusable(false);
this.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
this.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
}
public InsertionButton(Editor editorTextArea, String codeToInsert, String aide) {
this(editorTextArea, codeToInsert);
setToolTipText(aide);
}
/**
* Insert text at the caret position in the textArea.
* @param text
*/
private void insertAtCaret(String text) {
if (editorTextArea.hasFocus()) {
String newText = editorTextArea.getText().substring(0, editorTextArea.getCaretPosition())
+ text
+ editorTextArea.getText().substring(editorTextArea.getCaretPosition());
editorTextArea.setText(newText);
}
//TODO update latex schematic area
}
}
| #36 Added private attribute for InsertionButton, recording the delimiters of the snippets for each formula.
Changed insertAtCaret method, to increase performance (setText entirely remove the text then insert the new one, creating a remove event (making snippets informations lost) and an insert event). | ui/gui/editionView/InsertionButton.java | #36 Added private attribute for InsertionButton, recording the delimiters of the snippets for each formula. Changed insertAtCaret method, to increase performance (setText entirely remove the text then insert the new one, creating a remove event (making snippets informations lost) and an insert event). | <ide><path>i/gui/editionView/InsertionButton.java
<ide> import gui.editionView.editor.Editor;
<ide> import java.awt.event.ActionEvent;
<ide> import java.awt.event.ActionListener;
<add>import java.util.ArrayList;
<ide> import javax.swing.JButton;
<ide>
<ide> /**
<ide>
<ide> private final Editor editorTextArea;
<ide> private final String codeToInsert;
<add> private ArrayList<Integer> snipets;
<ide>
<del> public InsertionButton(Editor editorTextArea, String codeToInsert) {
<add> public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets) {
<ide> this.editorTextArea = editorTextArea;
<ide> this.codeToInsert = codeToInsert;
<add> this.snipets = snipets;
<ide>
<ide> this.setText(codeToInsert);
<ide>
<ide> this.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
<ide> }
<ide>
<del> public InsertionButton(Editor editorTextArea, String codeToInsert, String aide) {
<del> this(editorTextArea, codeToInsert);
<add> public InsertionButton(Editor editorTextArea, String codeToInsert, ArrayList<Integer> snipets, String aide) {
<add> this(editorTextArea, codeToInsert, snipets);
<ide> setToolTipText(aide);
<ide>
<ide> }
<ide> */
<ide> private void insertAtCaret(String text) {
<ide> if (editorTextArea.hasFocus()) {
<del> String newText = editorTextArea.getText().substring(0, editorTextArea.getCaretPosition())
<del> + text
<del> + editorTextArea.getText().substring(editorTextArea.getCaretPosition());
<del> editorTextArea.setText(newText);
<add>
<add> Integer caretPosition = editorTextArea.getCaretPosition();
<add>
<add> // insert is better than setText: setText entirely remove previous text then make an insert operation
<add> editorTextArea.insert(text, caretPosition);
<add>
<add> for(int snippetBegin = 0; snippetBegin < snipets.size(); snippetBegin+=2) {
<add> int snippetEnd = snippetBegin + 1;
<add> editorTextArea.addSnipet(caretPosition+snipets.get(snippetBegin),caretPosition+snipets.get(snippetEnd));
<add> }
<ide> }
<ide> //TODO update latex schematic area
<ide> } |
|
JavaScript | mit | 6e0ee1348189f623847c100700c482cf72b78d1b | 0 | jmccutchanwd/nutalk,jmccutchanwd/nutalk,jmccutchanwd/nutalk | /* John McCutchan ========================================= */
console.log('ChatCtrl-on');
app.controller('ChatCtrl', function($location, $scope, $rootScope, PostServices, LoginServices, userUID){ // arg 1 is name of control, arg 2 is function with scope name
$scope.name = $rootScope.name;
//get uid and assign it to $scope
$scope.uid = userUID.uid()
console.log("$scope UID: ",$scope.uid)
//assign local $scope uid to global scope
$rootScope.uid = $scope.uid
console.log("$rootScope UID: ",$rootScope.uid)
//build chat object
$scope.chat = {
"uid":$rootScope.uid,
"name": $scope.name,
"conversation": $scope.conversation,
}
//function to post chat to firebase
$scope.chatSend = ()=> {
PostServices
.chatSend($scope.chat)
}
$scope.getChat = ()=> {
PostServices
.getChat()
.then((response)=>{
console.log("GetChat: ", response);
$rootScope.list = response;
console.log("GetChat Global: ", $rootScope.list);
})
.then($scope.chatSend())
}
$scope.logout = ()=> {
LoginServices
.logout()
}
})
| app/controllers/chat.js | /* John McCutchan ========================================= */
console.log('ChatCtrl-on');
app.controller('ChatCtrl', function($location, $scope, $rootScope, PostServices, LoginServices, userUID){ // arg 1 is name of control, arg 2 is function with scope name
$scope.name = $rootScope.name;
//get uid and assign it to $scope
$scope.uid = userUID.uid()
console.log("$scope UID: ",$scope.uid)
//assign local $scope uid to global scope
$rootScope.uid = $scope.uid
console.log("$rootScope UID: ",$rootScope.uid)
//check to see name is global
console.log("Test2: ", $rootScope.name)
//build chat object
$scope.chat = {
"uid":$rootScope.uid,
"name": $scope.name,
"conversation": $scope.conversation,
}
//function to post chat to firebase
$scope.chatSend = ()=> {
PostServices
.chatSend($scope.chat)
}
$scope.logout = ()=> {
LoginServices
.logout()
}
})
| removed console.log
| app/controllers/chat.js | removed console.log | <ide><path>pp/controllers/chat.js
<ide> //assign local $scope uid to global scope
<ide> $rootScope.uid = $scope.uid
<ide> console.log("$rootScope UID: ",$rootScope.uid)
<del> //check to see name is global
<del> console.log("Test2: ", $rootScope.name)
<ide> //build chat object
<ide> $scope.chat = {
<ide> "uid":$rootScope.uid,
<ide> PostServices
<ide> .chatSend($scope.chat)
<ide> }
<add> $scope.getChat = ()=> {
<add> PostServices
<add> .getChat()
<add> .then((response)=>{
<add> console.log("GetChat: ", response);
<add> $rootScope.list = response;
<add> console.log("GetChat Global: ", $rootScope.list);
<add> })
<add> .then($scope.chatSend())
<add> }
<ide> $scope.logout = ()=> {
<ide> LoginServices
<ide> .logout() |
|
Java | apache-2.0 | fc603092a08e308caff5ff7bfd356879bb907b71 | 0 | microcks/microcks,microcks/microcks,microcks/microcks,microcks/microcks,microcks/microcks | /*
* Licensed to Laurent Broudoux (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author 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.github.microcks.web;
import io.github.microcks.domain.Header;
import io.github.microcks.domain.Operation;
import io.github.microcks.domain.ParameterConstraint;
import io.github.microcks.domain.ParameterLocation;
import io.github.microcks.domain.Response;
import io.github.microcks.domain.Service;
import io.github.microcks.repository.ResponseRepository;
import io.github.microcks.repository.ServiceRepository;
import io.github.microcks.util.DispatchCriteriaHelper;
import io.github.microcks.util.DispatchStyles;
import io.github.microcks.util.IdBuilder;
import io.github.microcks.util.ParameterConstraintUtil;
import io.github.microcks.util.dispatcher.FallbackSpecification;
import io.github.microcks.util.dispatcher.JsonEvaluationSpecification;
import io.github.microcks.util.dispatcher.JsonExpressionEvaluator;
import io.github.microcks.util.dispatcher.JsonMappingException;
import io.github.microcks.util.soapui.SoapUIScriptEngineBinder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* A controller for mocking Rest responses.
* @author laurent
*/
@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest")
public class RestController {
/** A simple logger for diagnostic messages. */
private static Logger log = LoggerFactory.getLogger(RestController.class);
@Autowired
private ServiceRepository serviceRepository;
@Autowired
private ResponseRepository responseRepository;
@Autowired
private ApplicationContext applicationContext;
@Value("${mocks.enable-invocation-stats}")
private final Boolean enableInvocationStats = null;
@Value("${mocks.rest.enable-cors-policy}")
private final Boolean enableCorsPolicy = null;
@RequestMapping(value = "/{service}/{version}/**", method = { RequestMethod.HEAD, RequestMethod.OPTIONS,
RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE })
public ResponseEntity<?> execute(
@PathVariable("service") String serviceName,
@PathVariable("version") String version,
@RequestParam(value="delay", required=false) Long delay,
@RequestBody(required=false) String body,
HttpServletRequest request
) {
log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}",
serviceName, version, request.getRequestURI(), request.getMethod());
log.debug("Request body: {}", body);
long startTime = System.currentTimeMillis();
// Extract resourcePath for matching with correct operation.
String requestURI = request.getRequestURI();
String serviceAndVersion = null;
String resourcePath = null;
// Build the encoded URI fragment to retrieve simple resourcePath.
serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
//resourcePath = UriUtils.decode(resourcePath, "UTF-8");
log.debug("Found resourcePath: {}", resourcePath);
// If serviceName was encoded with '+' instead of '%20', remove them.
if (serviceName.contains("+")) {
serviceName = serviceName.replace('+', ' ');
}
// If resourcePath was encoded with '+' instead of '%20', replace them .
if (resourcePath.contains("+")) {
resourcePath = resourcePath.replace("+", "%20");
}
// Remove trailing '/' if any.
String trimmedResourcePath = resourcePath;
if (trimmedResourcePath.endsWith("/")) {
trimmedResourcePath = resourcePath.substring(0, resourcePath.length() - 1);
}
Service service = serviceRepository.findByNameAndVersion(serviceName, version);
Operation rOperation = null;
for (Operation operation : service.getOperations()) {
// Select operation based onto Http verb (GET, POST, PUT, etc ...)
if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
// ... then check is we have a matching resource path.
if (operation.getResourcePaths() != null && (operation.getResourcePaths().contains(resourcePath)
|| operation.getResourcePaths().contains(trimmedResourcePath)) ) {
rOperation = operation;
break;
}
}
}
// We may not have found an Operation because of not exact resource path matching with an operation
// using a Fallback dispatcher. Try again, just considering the verb and path pattern of operation.
if (rOperation == null) {
for (Operation operation : service.getOperations()) {
// Select operation based onto Http verb (GET, POST, PUT, etc ...)
if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
// ... then check is current resource path matches operation path pattern.
if (operation.getResourcePaths() != null) {
// Produce a matching regexp removing {part} and :part from pattern.
String operationPattern = getURIPattern(operation.getName());
//operationPattern = operationPattern.replaceAll("\\{.+\\}", "([^/])+");
operationPattern = operationPattern.replaceAll("\\{\\w+\\}", "([^/])+");
operationPattern = operationPattern.replaceAll("(/:[^:^/]+)", "\\/([^/]+)");
if (resourcePath.matches(operationPattern)) {
rOperation = operation;
break;
}
}
}
}
}
if (rOperation != null) {
log.debug("Found a valid operation {} with rules: {}", rOperation.getName(), rOperation.getDispatcherRules());
String violationMsg = validateParameterConstraintsIfAny(rOperation, request);
if (violationMsg != null) {
return new ResponseEntity<Object>(violationMsg + ". Check parameter constraints.", HttpStatus.BAD_REQUEST);
}
// We must find dispatcher and its rules. Default to operation ones but
// if we have a Fallback this is the one who is holding the first pass rules.
String dispatcher = rOperation.getDispatcher();
String dispatcherRules = rOperation.getDispatcherRules();
FallbackSpecification fallback = MockControllerCommons.getFallbackIfAny(rOperation);
if (fallback != null) {
dispatcher = fallback.getDispatcher();
dispatcherRules = fallback.getDispatcherRules();
}
//
String dispatchCriteria = computeDispatchCriteria(dispatcher, dispatcherRules,
getURIPattern(rOperation.getName()), UriUtils.decode(resourcePath, "UTF-8"), request, body);
log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
Response response = null;
// Filter depending on requested media type.
// TODO: validate disptachCriteria with dispatcherRules
List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
response = getResponseByMediaType(responses, request);
if (response == null) {
// When using the SCRIPT or JSON_BODY dispatchers, return of evaluation may be the name of response.
responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
response = getResponseByMediaType(responses, request);
}
if (response == null && fallback != null) {
// If we've found nothing and got a fallback, that's the moment!
responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), fallback.getFallback());
response = getResponseByMediaType(responses, request);
}
if (response == null) {
// In case no response found (because dispatcher is null for example), just get one for the operation.
// This will allow also OPTIONS operations (like pre-flight requests) with no dispatch criteria to work.
log.debug("No responses found so far, tempting with just bare operationId...");
responses = responseRepository.findByOperationId(IdBuilder.buildOperationId(service, rOperation));
if (!responses.isEmpty()) {
response = getResponseByMediaType(responses, request);
}
}
if (response != null) {
HttpStatus status = (response.getStatus() != null ?
HttpStatus.valueOf(Integer.parseInt(response.getStatus())) : HttpStatus.OK);
// Deal with specific headers (content-type and redirect directive).
HttpHeaders responseHeaders = new HttpHeaders();
if (response.getMediaType() != null) {
responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
}
// Deal with headers from parameter constraints if any?
recopyHeadersFromParameterConstraints(rOperation, request, responseHeaders);
// Adding other generic headers (caching directives and so on...)
if (response.getHeaders() != null) {
for (Header header : response.getHeaders()) {
if ("Location".equals(header.getName())) {
// We should process location in order to make relative URI specified an absolute one from
// the client perspective.
String location = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/rest" + serviceAndVersion + header.getValues().iterator().next();
responseHeaders.add(header.getName(), location);
} else {
if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
}
}
}
}
// Render response content before waiting and returning.
String responseContent = MockControllerCommons.renderResponseContent(body, resourcePath, request, response);
// Setting delay to default one if not set.
if (delay == null && rOperation.getDefaultDelay() != null) {
delay = rOperation.getDefaultDelay();
}
MockControllerCommons.waitForDelay(startTime, delay);
// Publish an invocation event before returning if enabled.
if (enableInvocationStats) {
MockControllerCommons.publishMockInvocation(applicationContext, this, service, response, startTime);
}
return new ResponseEntity<Object>(responseContent, responseHeaders, status);
}
return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
}
// Handle OPTIONS request if CORS policy is enabled.
else if (enableCorsPolicy && "OPTIONS".equals(request.getMethod().toUpperCase())) {
log.debug("No valid operation found but Microcks configured to apply CORS policy");
return handleCorsRequest(request);
}
log.debug("No valid operation found and Microcks configured to not apply CORS policy...");
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
/** Validate the parameter constraints and return a single string with violation message if any. */
private String validateParameterConstraintsIfAny(Operation rOperation, HttpServletRequest request) {
if (rOperation.getParameterConstraints() != null) {
for (ParameterConstraint constraint : rOperation.getParameterConstraints()) {
String violationMsg = ParameterConstraintUtil.validateConstraint(request, constraint);
if (violationMsg != null) {
return violationMsg;
}
}
}
return null;
}
/** Create a dispatchCriteria string from type, rules and request elements. */
private String computeDispatchCriteria(String dispatcher, String dispatcherRules, String uriPattern,
String resourcePath, HttpServletRequest request, String body) {
String dispatchCriteria = null;
// Depending on dispatcher, evaluate request with rules.
if (dispatcher != null) {
switch (dispatcher) {
case DispatchStyles.SEQUENCE:
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
break;
case DispatchStyles.SCRIPT:
ScriptEngineManager sem = new ScriptEngineManager();
try {
// Evaluating request with script coming from operation dispatcher rules.
ScriptEngine se = sem.getEngineByExtension("groovy");
SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
dispatchCriteria = (String) se.eval(dispatcherRules);
} catch (Exception e) {
log.error("Error during Script evaluation", e);
}
break;
case DispatchStyles.URI_PARAMS:
String fullURI = request.getRequestURL() + "?" + request.getQueryString();
dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(dispatcherRules, fullURI);
break;
case DispatchStyles.URI_PARTS:
// /tenantId?t1/userId=x
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
break;
case DispatchStyles.URI_ELEMENTS:
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
fullURI = request.getRequestURL() + "?" + request.getQueryString();
dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(dispatcherRules, fullURI);
break;
case DispatchStyles.JSON_BODY:
try {
JsonEvaluationSpecification specification = JsonEvaluationSpecification.buildFromJsonString(dispatcherRules);
dispatchCriteria = JsonExpressionEvaluator.evaluate(body, specification);
} catch (JsonMappingException jme) {
log.error("Dispatching rules of operation cannot be interpreted as JsonEvaluationSpecification", jme);
}
break;
}
}
return dispatchCriteria;
}
/** Recopy headers defined with parameter constraints. */
private void recopyHeadersFromParameterConstraints(Operation rOperation, HttpServletRequest request, HttpHeaders responseHeaders) {
if (rOperation.getParameterConstraints() != null) {
for (ParameterConstraint constraint : rOperation.getParameterConstraints()) {
if (ParameterLocation.header == constraint.getIn() && constraint.isRecopy()) {
String value = request.getHeader(constraint.getName());
if (value != null) {
responseHeaders.set(constraint.getName(), value);
}
}
}
}
}
/** Filter responses using the Accept header for content-type, default to the first. Return null if no responses to filter. */
private Response getResponseByMediaType(List<Response> responses, HttpServletRequest request) {
if (!responses.isEmpty()) {
String accept = request.getHeader("Accept");
return responses.stream().filter(r -> StringUtils.isNotEmpty(accept) ?
accept.equals(r.getMediaType()) : true).findFirst().orElse(responses.get(0));
}
return null;
}
/** Retrieve URI Pattern from operation name (remove starting verb name). */
private String getURIPattern(String operationName) {
if (operationName.startsWith("GET ") || operationName.startsWith("POST ")
|| operationName.startsWith("PUT ") || operationName.startsWith("DELETE ")
|| operationName.startsWith("PATCH ") || operationName.startsWith("OPTIONS ")) {
return operationName.substring(operationName.indexOf(' ') + 1);
}
return operationName;
}
/** Handle a CORS request putting the correct headers in response entity. */
private ResponseEntity<Object> handleCorsRequest(HttpServletRequest request) {
// Retrieve and set access control headers from those coming in request.
List<String> accessControlHeaders = new ArrayList<>();
Collections.list(request.getHeaders("Access-Control-Request-Headers")).forEach(
header -> accessControlHeaders.add(header)
);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccessControlAllowHeaders(accessControlHeaders);
requestHeaders.setAccessControlExposeHeaders(accessControlHeaders);
// Apply CORS headers to response with 204 response code.
ResponseEntity<Object> response = ResponseEntity.noContent()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE, PATCH")
.headers(requestHeaders)
.header("Access-Allow-Credentials", "true")
.header("Access-Control-Max-Age", "3600")
.header("Vary", "Accept-Encoding, Origin")
.build();
return response;
}
}
| webapp/src/main/java/io/github/microcks/web/RestController.java | /*
* Licensed to Laurent Broudoux (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author 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.github.microcks.web;
import io.github.microcks.domain.Header;
import io.github.microcks.domain.Operation;
import io.github.microcks.domain.ParameterConstraint;
import io.github.microcks.domain.ParameterLocation;
import io.github.microcks.domain.Response;
import io.github.microcks.domain.Service;
import io.github.microcks.repository.ResponseRepository;
import io.github.microcks.repository.ServiceRepository;
import io.github.microcks.util.DispatchCriteriaHelper;
import io.github.microcks.util.DispatchStyles;
import io.github.microcks.util.IdBuilder;
import io.github.microcks.util.ParameterConstraintUtil;
import io.github.microcks.util.dispatcher.FallbackSpecification;
import io.github.microcks.util.dispatcher.JsonEvaluationSpecification;
import io.github.microcks.util.dispatcher.JsonExpressionEvaluator;
import io.github.microcks.util.dispatcher.JsonMappingException;
import io.github.microcks.util.soapui.SoapUIScriptEngineBinder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* A controller for mocking Rest responses.
* @author laurent
*/
@org.springframework.web.bind.annotation.RestController
@RequestMapping("/rest")
public class RestController {
/** A simple logger for diagnostic messages. */
private static Logger log = LoggerFactory.getLogger(RestController.class);
@Autowired
private ServiceRepository serviceRepository;
@Autowired
private ResponseRepository responseRepository;
@Autowired
private ApplicationContext applicationContext;
@Value("${mocks.enable-invocation-stats}")
private final Boolean enableInvocationStats = null;
@Value("${mocks.rest.enable-cors-policy}")
private final Boolean enableCorsPolicy = null;
@RequestMapping(value = "/{service}/{version}/**", method = { RequestMethod.HEAD, RequestMethod.OPTIONS,
RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE })
public ResponseEntity<?> execute(
@PathVariable("service") String serviceName,
@PathVariable("version") String version,
@RequestParam(value="delay", required=false) Long delay,
@RequestBody(required=false) String body,
HttpServletRequest request
) {
log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}",
serviceName, version, request.getRequestURI(), request.getMethod());
log.debug("Request body: {}", body);
long startTime = System.currentTimeMillis();
// Extract resourcePath for matching with correct operation.
String requestURI = request.getRequestURI();
String serviceAndVersion = null;
String resourcePath = null;
// Build the encoded URI fragment to retrieve simple resourcePath.
serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
//resourcePath = UriUtils.decode(resourcePath, "UTF-8");
log.debug("Found resourcePath: {}", resourcePath);
// If serviceName was encoded with '+' instead of '%20', remove them.
if (serviceName.contains("+")) {
serviceName = serviceName.replace('+', ' ');
}
// If resourcePath was encoded with '+' instead of '%20', replace them .
if (resourcePath.contains("+")) {
resourcePath = resourcePath.replace("+", "%20");
}
Service service = serviceRepository.findByNameAndVersion(serviceName, version);
Operation rOperation = null;
for (Operation operation : service.getOperations()) {
// Select operation based onto Http verb (GET, POST, PUT, etc ...)
if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
// ... then check is we have a matching resource path.
if (operation.getResourcePaths() != null && operation.getResourcePaths().contains(resourcePath)) {
rOperation = operation;
break;
}
}
}
// We may not have found an Operation because of not exact resource path matching with an operation
// using a Fallback dispatcher. Try again, just considering the verb and path pattern of operation.
if (rOperation == null) {
for (Operation operation : service.getOperations()) {
// Select operation based onto Http verb (GET, POST, PUT, etc ...)
if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
// ... then check is current resource path matches operation path pattern.
if (operation.getResourcePaths() != null) {
// Produce a matching regexp removing {part} and :part from pattern.
String operationPattern = getURIPattern(operation.getName());
//operationPattern = operationPattern.replaceAll("\\{.+\\}", "([^/])+");
operationPattern = operationPattern.replaceAll("\\{\\w+\\}", "([^/])+");
operationPattern = operationPattern.replaceAll("(/:[^:^/]+)", "\\/([^/]+)");
if (resourcePath.matches(operationPattern)) {
rOperation = operation;
break;
}
}
}
}
}
if (rOperation != null) {
log.debug("Found a valid operation {} with rules: {}", rOperation.getName(), rOperation.getDispatcherRules());
String violationMsg = validateParameterConstraintsIfAny(rOperation, request);
if (violationMsg != null) {
return new ResponseEntity<Object>(violationMsg + ". Check parameter constraints.", HttpStatus.BAD_REQUEST);
}
// We must find dispatcher and its rules. Default to operation ones but
// if we have a Fallback this is the one who is holding the first pass rules.
String dispatcher = rOperation.getDispatcher();
String dispatcherRules = rOperation.getDispatcherRules();
FallbackSpecification fallback = MockControllerCommons.getFallbackIfAny(rOperation);
if (fallback != null) {
dispatcher = fallback.getDispatcher();
dispatcherRules = fallback.getDispatcherRules();
}
//
String dispatchCriteria = computeDispatchCriteria(dispatcher, dispatcherRules,
getURIPattern(rOperation.getName()), UriUtils.decode(resourcePath, "UTF-8"), request, body);
log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
Response response = null;
// Filter depending on requested media type.
// TODO: validate disptachCriteria with dispatcherRules
List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
response = getResponseByMediaType(responses, request);
if (response == null) {
// When using the SCRIPT or JSON_BODY dispatchers, return of evaluation may be the name of response.
responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
response = getResponseByMediaType(responses, request);
}
if (response == null && fallback != null) {
// If we've found nothing and got a fallback, that's the moment!
responses = responseRepository.findByOperationIdAndName(IdBuilder.buildOperationId(service, rOperation), fallback.getFallback());
response = getResponseByMediaType(responses, request);
}
if (response == null) {
// In case no response found (because dispatcher is null for example), just get one for the operation.
// This will allow also OPTIONS operations (like pre-flight requests) with no dispatch criteria to work.
log.debug("No responses found so far, tempting with just bare operationId...");
responses = responseRepository.findByOperationId(IdBuilder.buildOperationId(service, rOperation));
if (!responses.isEmpty()) {
response = getResponseByMediaType(responses, request);
}
}
if (response != null) {
HttpStatus status = (response.getStatus() != null ?
HttpStatus.valueOf(Integer.parseInt(response.getStatus())) : HttpStatus.OK);
// Deal with specific headers (content-type and redirect directive).
HttpHeaders responseHeaders = new HttpHeaders();
if (response.getMediaType() != null) {
responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
}
// Deal with headers from parameter constraints if any?
recopyHeadersFromParameterConstraints(rOperation, request, responseHeaders);
// Adding other generic headers (caching directives and so on...)
if (response.getHeaders() != null) {
for (Header header : response.getHeaders()) {
if ("Location".equals(header.getName())) {
// We should process location in order to make relative URI specified an absolute one from
// the client perspective.
String location = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/rest" + serviceAndVersion + header.getValues().iterator().next();
responseHeaders.add(header.getName(), location);
} else {
if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
}
}
}
}
// Render response content before waiting and returning.
String responseContent = MockControllerCommons.renderResponseContent(body, resourcePath, request, response);
// Setting delay to default one if not set.
if (delay == null && rOperation.getDefaultDelay() != null) {
delay = rOperation.getDefaultDelay();
}
MockControllerCommons.waitForDelay(startTime, delay);
// Publish an invocation event before returning if enabled.
if (enableInvocationStats) {
MockControllerCommons.publishMockInvocation(applicationContext, this, service, response, startTime);
}
return new ResponseEntity<Object>(responseContent, responseHeaders, status);
}
return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
}
// Handle OPTIONS request if CORS policy is enabled.
else if (enableCorsPolicy && "OPTIONS".equals(request.getMethod().toUpperCase())) {
log.debug("No valid operation found but Microcks configured to apply CORS policy");
return handleCorsRequest(request);
}
log.debug("No valid operation found and Microcks configured to not apply CORS policy...");
return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}
/** Validate the parameter constraints and return a single string with violation message if any. */
private String validateParameterConstraintsIfAny(Operation rOperation, HttpServletRequest request) {
if (rOperation.getParameterConstraints() != null) {
for (ParameterConstraint constraint : rOperation.getParameterConstraints()) {
String violationMsg = ParameterConstraintUtil.validateConstraint(request, constraint);
if (violationMsg != null) {
return violationMsg;
}
}
}
return null;
}
/** Create a dispatchCriteria string from type, rules and request elements. */
private String computeDispatchCriteria(String dispatcher, String dispatcherRules, String uriPattern,
String resourcePath, HttpServletRequest request, String body) {
String dispatchCriteria = null;
// Depending on dispatcher, evaluate request with rules.
if (dispatcher != null) {
switch (dispatcher) {
case DispatchStyles.SEQUENCE:
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
break;
case DispatchStyles.SCRIPT:
ScriptEngineManager sem = new ScriptEngineManager();
try {
// Evaluating request with script coming from operation dispatcher rules.
ScriptEngine se = sem.getEngineByExtension("groovy");
SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
dispatchCriteria = (String) se.eval(dispatcherRules);
} catch (Exception e) {
log.error("Error during Script evaluation", e);
}
break;
case DispatchStyles.URI_PARAMS:
String fullURI = request.getRequestURL() + "?" + request.getQueryString();
dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(dispatcherRules, fullURI);
break;
case DispatchStyles.URI_PARTS:
// /tenantId?t1/userId=x
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
break;
case DispatchStyles.URI_ELEMENTS:
dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(dispatcherRules, uriPattern, resourcePath);
fullURI = request.getRequestURL() + "?" + request.getQueryString();
dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(dispatcherRules, fullURI);
break;
case DispatchStyles.JSON_BODY:
try {
JsonEvaluationSpecification specification = JsonEvaluationSpecification.buildFromJsonString(dispatcherRules);
dispatchCriteria = JsonExpressionEvaluator.evaluate(body, specification);
} catch (JsonMappingException jme) {
log.error("Dispatching rules of operation cannot be interpreted as JsonEvaluationSpecification", jme);
}
break;
}
}
return dispatchCriteria;
}
/** Recopy headers defined with parameter constraints. */
private void recopyHeadersFromParameterConstraints(Operation rOperation, HttpServletRequest request, HttpHeaders responseHeaders) {
if (rOperation.getParameterConstraints() != null) {
for (ParameterConstraint constraint : rOperation.getParameterConstraints()) {
if (ParameterLocation.header == constraint.getIn() && constraint.isRecopy()) {
String value = request.getHeader(constraint.getName());
if (value != null) {
responseHeaders.set(constraint.getName(), value);
}
}
}
}
}
/** Filter responses using the Accept header for content-type, default to the first. Return null if no responses to filter. */
private Response getResponseByMediaType(List<Response> responses, HttpServletRequest request) {
if (!responses.isEmpty()) {
String accept = request.getHeader("Accept");
return responses.stream().filter(r -> StringUtils.isNotEmpty(accept) ?
accept.equals(r.getMediaType()) : true).findFirst().orElse(responses.get(0));
}
return null;
}
/** Retrieve URI Pattern from operation name (remove starting verb name). */
private String getURIPattern(String operationName) {
if (operationName.startsWith("GET ") || operationName.startsWith("POST ")
|| operationName.startsWith("PUT ") || operationName.startsWith("DELETE ")
|| operationName.startsWith("PATCH ") || operationName.startsWith("OPTIONS ")) {
return operationName.substring(operationName.indexOf(' ') + 1);
}
return operationName;
}
/** Handle a CORS request putting the correct headers in response entity. */
private ResponseEntity<Object> handleCorsRequest(HttpServletRequest request) {
// Retrieve and set access control headers from those coming in request.
List<String> accessControlHeaders = new ArrayList<>();
Collections.list(request.getHeaders("Access-Control-Request-Headers")).forEach(
header -> accessControlHeaders.add(header)
);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccessControlAllowHeaders(accessControlHeaders);
requestHeaders.setAccessControlExposeHeaders(accessControlHeaders);
// Apply CORS headers to response with 204 response code.
ResponseEntity<Object> response = ResponseEntity.noContent()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE, PATCH")
.headers(requestHeaders)
.header("Access-Allow-Credentials", "true")
.header("Access-Control-Max-Age", "3600")
.header("Vary", "Accept-Encoding, Origin")
.build();
return response;
}
}
| feat: #659 santize trailing / if any
| webapp/src/main/java/io/github/microcks/web/RestController.java | feat: #659 santize trailing / if any | <ide><path>ebapp/src/main/java/io/github/microcks/web/RestController.java
<ide> if (resourcePath.contains("+")) {
<ide> resourcePath = resourcePath.replace("+", "%20");
<ide> }
<add> // Remove trailing '/' if any.
<add> String trimmedResourcePath = resourcePath;
<add> if (trimmedResourcePath.endsWith("/")) {
<add> trimmedResourcePath = resourcePath.substring(0, resourcePath.length() - 1);
<add> }
<ide> Service service = serviceRepository.findByNameAndVersion(serviceName, version);
<ide> Operation rOperation = null;
<ide> for (Operation operation : service.getOperations()) {
<ide> // Select operation based onto Http verb (GET, POST, PUT, etc ...)
<ide> if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
<ide> // ... then check is we have a matching resource path.
<del> if (operation.getResourcePaths() != null && operation.getResourcePaths().contains(resourcePath)) {
<add> if (operation.getResourcePaths() != null && (operation.getResourcePaths().contains(resourcePath)
<add> || operation.getResourcePaths().contains(trimmedResourcePath)) ) {
<ide> rOperation = operation;
<ide> break;
<ide> } |
|
Java | mit | 654b30ede5455c20c0a21ea380fcd521819f2c29 | 0 | VeryGame/gdx-surface | package de.verygame.square.core.scene2d.widget;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
/**
* @author Rico Schrage
*/
public class Panel extends WidgetGroup {
private Drawable background;
private float xPadding = 0f;
private float yPadding = 0f;
Matrix4 oldM = new Matrix4();
public Panel() {
this(null);
}
public Panel(Drawable background) {
setBackground(background);
}
public void setXPadding(float xPadding) {
this.xPadding = xPadding;
}
public void setYPadding(float yPadding) {
this.yPadding = yPadding;
}
public void setAlpha(float alpha) {
this.getColor().a = alpha;
}
public void setBackground(Drawable background) {
this.background = background;
}
@Override
public void draw(Batch batch, float parentAlpha) {
if (background != null) {
batch.setColor(getColor());
background.draw(batch, getX(), getY(), getWidth(), getHeight());
batch.setColor(Color.WHITE);
}
float absoluteXPadding = xPadding * getWidth();
float absoluteYPadding = yPadding * getHeight();
oldM.set(batch.getProjectionMatrix());
batch.getProjectionMatrix().translate(absoluteXPadding, absoluteYPadding, 0);
super.draw(batch, parentAlpha);
batch.setProjectionMatrix(oldM);
}
}
| scene2d/widget/Panel.java | package de.verygame.square.core.scene2d.widget;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
/**
* @author Rico Schrage
*/
public class Panel extends WidgetGroup {
private Drawable background;
private float xPadding = 0f;
private float yPadding = 0f;
public Panel() {
this(null);
}
public Panel(Drawable background) {
setBackground(background);
}
public void setXPadding(float xPadding) {
this.xPadding = xPadding;
}
public void setYPadding(float yPadding) {
this.yPadding = yPadding;
}
public void setAlpha(float alpha) {
this.getColor().a = alpha;
}
public void setBackground(Drawable background) {
this.background = background;
}
@Override
public void draw(Batch batch, float parentAlpha) {
if (background != null) {
batch.setColor(getColor());
background.draw(batch, getX(), getY(), getWidth(), getHeight());
batch.setColor(Color.WHITE);
}
float absoluteXPadding = xPadding * getWidth();
float absoluteYPadding = yPadding * getHeight();
batch.getProjectionMatrix().translate(absoluteXPadding, absoluteYPadding, 0);
super.draw(batch, parentAlpha);
batch.getProjectionMatrix().translate(-absoluteXPadding, -absoluteYPadding, 0);
}
}
| Made panel transformation more stable.
| scene2d/widget/Panel.java | Made panel transformation more stable. | <ide><path>cene2d/widget/Panel.java
<ide>
<ide> import com.badlogic.gdx.graphics.Color;
<ide> import com.badlogic.gdx.graphics.g2d.Batch;
<add>import com.badlogic.gdx.math.Matrix4;
<ide> import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
<ide> import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
<ide>
<ide>
<ide> private float xPadding = 0f;
<ide> private float yPadding = 0f;
<add>
<add> Matrix4 oldM = new Matrix4();
<ide>
<ide> public Panel() {
<ide> this(null);
<ide> float absoluteXPadding = xPadding * getWidth();
<ide> float absoluteYPadding = yPadding * getHeight();
<ide>
<add> oldM.set(batch.getProjectionMatrix());
<ide> batch.getProjectionMatrix().translate(absoluteXPadding, absoluteYPadding, 0);
<ide> super.draw(batch, parentAlpha);
<del> batch.getProjectionMatrix().translate(-absoluteXPadding, -absoluteYPadding, 0);
<add> batch.setProjectionMatrix(oldM);
<ide> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | 50769f90a48fc15422e6e5e4fa602f3b1b11ca82 | 0 | OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs,OPENDAP/olfs | /*
* /////////////////////////////////////////////////////////////////////////////
* // This file is part of the "Hyrax Data Server" project.
* //
* //
* // Copyright (c) 2013 OPeNDAP, Inc.
* // Author: Nathan David Potter <[email protected]>
* //
* // 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.
* //
* // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* //
* // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
* /////////////////////////////////////////////////////////////////////////////
*/
package opendap.io;
import opendap.ppt.NewPPTClient;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* User: ndp
* Date: Dec 19, 2007
* Time: 9:14:01 AM
*/
public class ChunkedInputStream {
private Logger log;
private static int defaultBufferSize = 10240;
private static int MaxBufferSize = 16777216;
protected InputStream is;
protected boolean isClosed;
private byte[] currentChunkHeader;
private byte[] chunkBuffer;
private int largestChunkDataSize;
private int currentChunkDataSize;
private int chunkReadPosition;
private int currentChunkType;
//private ChunkProtocol chunkProtocol;
private Socket _mySock = null;
/**
* Wraps an input stream and interprets it as a chunked stream.
* @param stream to wrap
* @param s Underlying socket connection
*/
public ChunkedInputStream(InputStream stream, Socket s){
this(stream);
_mySock = s;
}
/**
* Wraps an input stream and interprets it as a chunked stream.
* @param stream to wrap
*/
public ChunkedInputStream(InputStream stream){
super();
log = org.slf4j.LoggerFactory.getLogger(getClass());
is = stream;
currentChunkHeader = new byte[Chunk.HEADER_SIZE];
currentChunkType = Chunk.DATA;
isClosed = false;
largestChunkDataSize = 0;
chunkBuffer = new byte[defaultBufferSize];
}
/**
* Reads the next chunk header.
*
* @return The number of bytes in the chunk, or -1 if the underlying stream
* has no more bytes to read.
* @throws java.io.IOException When the underlying stream does, or if the header is bogus
*
*/
public int readChunkHeader() throws IOException {
if(isClosed) throw new IOException("Cannot read from a closed stream.");
log.info(NewPPTClient.showConnectionProperties(_mySock));
// Read the header
currentChunkDataSize = Chunk.readChunkHeader(is,currentChunkHeader,0);
if(currentChunkDataSize==-1)
return currentChunkDataSize;
// Cache the chunk size the header
//currentChunkDataSize = Chunk.getDataSize(currentChunkHeader);
// Cache the Chunk Type.
currentChunkType = Chunk.getType(currentChunkHeader);
log.debug("Chunk Data Size: " + currentChunkDataSize +
" Chunk Type: "+ (char)currentChunkType);
chunkReadPosition = 0;
if(largestChunkDataSize< currentChunkDataSize)
largestChunkDataSize = currentChunkDataSize;
return currentChunkDataSize;
}
public int getCurrentChunkType() {
return currentChunkType;
}
public int availableInChunk(){
return currentChunkDataSize - chunkReadPosition;
}
public int available() throws IOException {
if(availableInChunk()<=0){
int ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
return 0;
}
}
return availableInChunk();
}
public void close() throws IOException {
isClosed = true;
currentChunkDataSize = 0;
chunkReadPosition = 0;
is.close();
}
/**
*
* @return True if current chunk is the last chunk in the message.
*/
public boolean isLastChunk(){
return currentChunkDataSize==0 && currentChunkType==Chunk.DATA;
}
/**
* Reads a chunked message from the underlying InputStream and transmits to the passed OutputStream,
* <code>dstream</code>. If an error condition is encountered in the chunked message then the error content
* will be written to the OutputStream <code>errStream</code>.
*
* @param dStream The stream into which to transfer the message data.
* @param errStream The stream into which to transfer error content if the
* message contains it.
* @return False if the chunked message contained an extension with status equal to
* error (Which is another way of saying that the source passed an error
* message in the stream). True otherwise.
* @throws IOException When there are problems reading from or interpreting
* the chunked message stream.
*/
public boolean readChunkedMessage(OutputStream dStream, OutputStream errStream) throws IOException {
int ret;
int bytesReceived;
boolean isError = false;
boolean moreData = true;
String extensionContent;
while(moreData && !isClosed){
if(availableInChunk()<=0){
ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
moreData = false;
}
else {
// Check to see if the chunk size is bigger than the buffer
if(chunkBuffer.length < currentChunkDataSize){
// If the new chunk size is too big, bail.
if(currentChunkDataSize > MaxBufferSize){
String msg = "Found a chunk size larger than I support. My max size " +
MaxBufferSize + " bytes, currentChunkDataSize: "+currentChunkDataSize;
log.error(msg);
throw new IOException(msg);
}
else {
// Since it's safe to do so, upgrade the chunk buffer.
log.debug("Increasing chunkBuffer size to: {} bytes.",currentChunkDataSize);
chunkBuffer = new byte[currentChunkDataSize];
}
}
}
}
else {
// read the chunk body
bytesReceived = Chunk.readFully(is,chunkBuffer,0, availableInChunk());
// update the read pointer.
chunkReadPosition += bytesReceived;
switch (getCurrentChunkType()){
case Chunk.DATA:
// write the data out to the appropriate stream,
// depending on the error status.
(isError?errStream:dStream).write(chunkBuffer,0,bytesReceived);
(isError?errStream:dStream).flush();
break;
case Chunk.EXTENSION:
// Build a String from the content of the chunk extension.
extensionContent = new String(chunkBuffer,0,bytesReceived,HyraxStringEncoding.getCharset());
// Process the extension content & preserve any previously encountered errors found in the message.
isError = processExtensionContent(extensionContent) || isError;
break;
default:
throw new IOException("Unknown Chunk Type.");
}
}
}
return !isError;
}
/**
*
*
* @param e The content of the chunk extension held in a String.
* @return True if the extension contains the "status=error;"
* extension name value pair, false otherwise.
*
* @throws IOException When there are problems reading from or interpreting
* the message stream.
*/
private boolean processExtensionContent(String e) throws IOException {
boolean isError = false;
String[] extensions = e.split(";");
// Evaluate the extension information
for(String extension : extensions){
// Is it a "status" extension?
if(extension.startsWith(Chunk.STATUS_EXTENSION)){
String status = extension.substring(extension.indexOf('=')+1,extension.length());
//log.debug("status: "+status);
// Is the status an error?
if(status.equalsIgnoreCase(Chunk.ERROR_STATUS)){
//log.error("status: error");
isError = true;
}
// Is the status an emergency exit?
else if(status.equalsIgnoreCase(Chunk.EMERGENCY_EXIT_STATUS)){
log.error("Stream source requested an emergency exit! Closing connection immediately.");
isClosed = true;
is.close();
}
// Is the status a mandatory exit?
else if(status.equalsIgnoreCase(Chunk.EXIT_STATUS)){
int ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
isClosed = true;
}
log.debug("Stream closed by Source.");
}
else {
log.debug("Received status extension: "+extension);
}
}
else {
log.debug("Received extension: "+extension);
}
}
return isError;
}
public int getChunkedReadBufferSize(){
return chunkBuffer.length;
}
}
| src/opendap/io/ChunkedInputStream.java | /*
* /////////////////////////////////////////////////////////////////////////////
* // This file is part of the "Hyrax Data Server" project.
* //
* //
* // Copyright (c) 2013 OPeNDAP, Inc.
* // Author: Nathan David Potter <[email protected]>
* //
* // 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.
* //
* // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* //
* // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
* /////////////////////////////////////////////////////////////////////////////
*/
package opendap.io;
import opendap.ppt.NewPPTClient;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* User: ndp
* Date: Dec 19, 2007
* Time: 9:14:01 AM
*/
public class ChunkedInputStream {
private Logger log;
private static int defaultBufferSize = 10240;
private static int MaxBufferSize = 16777216;
protected InputStream is;
protected boolean isClosed;
private byte[] currentChunkHeader;
private byte[] chunkBuffer;
private int largestChunkDataSize;
private int currentChunkDataSize;
private int chunkReadPosition;
private int currentChunkType;
//private ChunkProtocol chunkProtocol;
private Socket _mySock = null;
/**
* Wraps an input stream and interprets it as a chunked stream.
* @param stream to wrap
* @param s Underlying socket connection
*/
public ChunkedInputStream(InputStream stream, Socket s){
this(stream);
_mySock = s;
}
/**
* Wraps an input stream and interprets it as a chunked stream.
* @param stream to wrap
*/
public ChunkedInputStream(InputStream stream){
super();
log = org.slf4j.LoggerFactory.getLogger(getClass());
is = stream;
currentChunkHeader = new byte[Chunk.HEADER_SIZE];
currentChunkType = Chunk.DATA;
isClosed = false;
largestChunkDataSize = 0;
chunkBuffer = new byte[defaultBufferSize];
}
/**
* Reads the next chunk header.
*
* @return The number of bytes in the chunk, or -1 if the underlying stream
* has no more bytes to read.
* @throws java.io.IOException When the underlying stream does, or if the header is bogus
*
*/
public int readChunkHeader() throws IOException {
if(isClosed) throw new IOException("Cannot read from a closed stream.");
log.debug(NewPPTClient.showConnectionProperties(_mySock));
// Read the header
currentChunkDataSize = Chunk.readChunkHeader(is,currentChunkHeader,0);
if(currentChunkDataSize==-1)
return currentChunkDataSize;
// Cache the chunk size the header
//currentChunkDataSize = Chunk.getDataSize(currentChunkHeader);
// Cache the Chunk Type.
currentChunkType = Chunk.getType(currentChunkHeader);
log.debug("Chunk Data Size: " + currentChunkDataSize +
" Chunk Type: "+ (char)currentChunkType);
chunkReadPosition = 0;
if(largestChunkDataSize< currentChunkDataSize)
largestChunkDataSize = currentChunkDataSize;
return currentChunkDataSize;
}
public int getCurrentChunkType() {
return currentChunkType;
}
public int availableInChunk(){
return currentChunkDataSize - chunkReadPosition;
}
public int available() throws IOException {
if(availableInChunk()<=0){
int ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
return 0;
}
}
return availableInChunk();
}
public void close() throws IOException {
isClosed = true;
currentChunkDataSize = 0;
chunkReadPosition = 0;
is.close();
}
/**
*
* @return True if current chunk is the last chunk in the message.
*/
public boolean isLastChunk(){
return currentChunkDataSize==0 && currentChunkType==Chunk.DATA;
}
/**
* Reads a chunked message from the underlying InputStream and transmits to the passed OutputStream,
* <code>dstream</code>. If an error condition is encountered in the chunked message then the error content
* will be written to the OutputStream <code>errStream</code>.
*
* @param dStream The stream into which to transfer the message data.
* @param errStream The stream into which to transfer error content if the
* message contains it.
* @return False if the chunked message contained an extension with status equal to
* error (Which is another way of saying that the source passed an error
* message in the stream). True otherwise.
* @throws IOException When there are problems reading from or interpreting
* the chunked message stream.
*/
public boolean readChunkedMessage(OutputStream dStream, OutputStream errStream) throws IOException {
int ret;
int bytesReceived;
boolean isError = false;
boolean moreData = true;
String extensionContent;
while(moreData && !isClosed){
if(availableInChunk()<=0){
ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
moreData = false;
}
else {
// Check to see if the chunk size is bigger than the buffer
if(chunkBuffer.length < currentChunkDataSize){
// If the new chunk size is too big, bail.
if(currentChunkDataSize > MaxBufferSize){
String msg = "Found a chunk size larger than I support. My max size " +
MaxBufferSize + " bytes, currentChunkDataSize: "+currentChunkDataSize;
log.error(msg);
throw new IOException(msg);
}
else {
// Since it's safe to do so, upgrade the chunk buffer.
log.debug("Increasing chunkBuffer size to: {} bytes.",currentChunkDataSize);
chunkBuffer = new byte[currentChunkDataSize];
}
}
}
}
else {
// read the chunk body
bytesReceived = Chunk.readFully(is,chunkBuffer,0, availableInChunk());
// update the read pointer.
chunkReadPosition += bytesReceived;
switch (getCurrentChunkType()){
case Chunk.DATA:
// write the data out to the appropriate stream,
// depending on the error status.
(isError?errStream:dStream).write(chunkBuffer,0,bytesReceived);
(isError?errStream:dStream).flush();
break;
case Chunk.EXTENSION:
// Build a String from the content of the chunk extension.
extensionContent = new String(chunkBuffer,0,bytesReceived,HyraxStringEncoding.getCharset());
// Process the extension content & preserve any previously encountered errors found in the message.
isError = processExtensionContent(extensionContent) || isError;
break;
default:
throw new IOException("Unknown Chunk Type.");
}
}
}
return !isError;
}
/**
*
*
* @param e The content of the chunk extension held in a String.
* @return True if the extension contains the "status=error;"
* extension name value pair, false otherwise.
*
* @throws IOException When there are problems reading from or interpreting
* the message stream.
*/
private boolean processExtensionContent(String e) throws IOException {
boolean isError = false;
String[] extensions = e.split(";");
// Evaluate the extension information
for(String extension : extensions){
// Is it a "status" extension?
if(extension.startsWith(Chunk.STATUS_EXTENSION)){
String status = extension.substring(extension.indexOf('=')+1,extension.length());
//log.debug("status: "+status);
// Is the status an error?
if(status.equalsIgnoreCase(Chunk.ERROR_STATUS)){
//log.error("status: error");
isError = true;
}
// Is the status an emergency exit?
else if(status.equalsIgnoreCase(Chunk.EMERGENCY_EXIT_STATUS)){
log.error("Stream source requested an emergency exit! Closing connection immediately.");
isClosed = true;
is.close();
}
// Is the status a mandatory exit?
else if(status.equalsIgnoreCase(Chunk.EXIT_STATUS)){
int ret = readChunkHeader();
if(ret == -1 || isLastChunk()){
isClosed = true;
}
log.debug("Stream closed by Source.");
}
else {
log.debug("Received status extension: "+extension);
}
}
else {
log.debug("Received extension: "+extension);
}
}
return isError;
}
public int getChunkedReadBufferSize(){
return chunkBuffer.length;
}
}
| hack 1a
| src/opendap/io/ChunkedInputStream.java | hack 1a | <ide><path>rc/opendap/io/ChunkedInputStream.java
<ide> public int readChunkHeader() throws IOException {
<ide> if(isClosed) throw new IOException("Cannot read from a closed stream.");
<ide>
<del> log.debug(NewPPTClient.showConnectionProperties(_mySock));
<add> log.info(NewPPTClient.showConnectionProperties(_mySock));
<ide>
<ide> // Read the header
<ide> currentChunkDataSize = Chunk.readChunkHeader(is,currentChunkHeader,0); |
|
Java | agpl-3.0 | 3853f9b017901847d444c9a0d7c4f8cdf51b9144 | 0 | jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft,jspacco/Knoxcraft | package edu.knox.minecraft.serverturtle;
import net.canarymod.Canary;
import net.canarymod.api.world.World;
import net.canarymod.api.world.blocks.BlockType;
import net.canarymod.api.world.position.Direction;
import net.canarymod.api.world.position.Position;
import net.canarymod.chat.MessageReceiver;
import net.canarymod.commandsys.Command;
import net.canarymod.commandsys.CommandDependencyException;
import net.canarymod.commandsys.CommandListener;
import net.canarymod.hook.HookHandler;
import net.canarymod.logger.Logman;
import net.canarymod.plugin.Plugin;
import net.canarymod.plugin.PluginListener;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import edu.knoxcraft.hooks.KCTUploadHook;
import edu.knoxcraft.http.server.HttpUploadServer;
import edu.knoxcraft.turtle3d.KCTCommand;
import edu.knoxcraft.turtle3d.KCTScript;
/*TODO: should most of these commands really happen in Turtle,
and this class just call those versions? Like in TurtleMove(). */
//Things need to be overly simple during testing for ease of use
//In time, need to build in string verification for correct input style (ie. All caps, etc)
public class TurtleAPI extends Plugin implements CommandListener, PluginListener {
//POSITION VARIABLES
//in world position/direction of player at turtle on --> (0,0,0) for Turtle's relative coord system.
private Position originPos;
private Direction originDir;
//current relative position
private Position relPos;
private Direction relDir;
//true current position in game coords(made by combining relative and real)
private Position gamePos;
private Direction gameDir; //TODO: I don't think this is ever updated... //true Facts
//MODE TOGGLES
private boolean tt = false; //Turtle on/off
private boolean bp = false; //Block Place on/off
//OTHER VARIABLES
private Turtle turtle = new Turtle();
private BlockType bt = BlockType.Stone; //default turtle block type
private World world; //World in which all actions occur
private HttpUploadServer httpServer;
public static Logman logger;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
public TurtleAPI() {
TurtleAPI.logger = getLogman();
}
/**
* Called when plugin is disabled.
*/
@Override
public void disable() {
httpServer.disable();
}
/**
* Called when plugin is enabled.
* @return
*/
@Override
public boolean enable() {
try {
getLogman().info("Registering plugin");
Canary.hooks().registerListener(this, this);
httpServer=new HttpUploadServer();
httpServer.enable();
//getName() returns the class name, in this case TurtleAPI
getLogman().info("Enabling "+getName() + " Version " + getVersion());
getLogman().info("Authored by "+getAuthor());
Canary.commands().registerCommands(this, this, false);
return true;
} catch (CommandDependencyException e){
throw new RuntimeException(e);
}
}
//API TIME
/**
* Turn on turtle mode. Sets up relative position.
* (0,0,0) is player position. Forward is player direction.
* @param sender
* @param args
*/
@Command(
aliases = { "ton", "TurtleOn" },
description = "Turtle Mode On",
permissions = { "" },
toolTip = "/ton")
public void TurtleOn(MessageReceiver sender, String[] args)
{
//Make Turtle
turtle = new Turtle();
//GET WORLD
world = sender.asPlayer().getWorld();
//Relative pos stuff
//Get True Position and Direction
originPos = sender.asPlayer().getPosition();
originDir = sender.asPlayer().getCardinalDirection();
//Make the Relative Position
relPos = new Position(0,0,0);
relDir = Direction.getFromIntValue(0);
//updateCurPos(); //these two methods got renamed- change them if this gets uncommented
//updateCurDir();
//Faces player direction
//Need to build in safety checks
//Also, better way?
//If doesn't work-> set to North ONLY, as way to start debugging
relDir = originDir; //??
//Turning on Turtle
tt = true;
getString(sender, originPos);
getString(sender, originDir);
getString(sender, tt);
}
/**
* Turn off turtle mode.
* @param sender
* @param args
*/
@Command(
aliases = { "toff", "TurtleOff" },
description = "Turtle Mode Off",
permissions = { "" },
toolTip = "/toff")
public void TurtleOff(MessageReceiver sender, String[] args)
{
//Turning off Turtle
tt = false;
turtle = null;
getString(sender, tt);
}
/**
* Toggle turtle mode on/off.
* @param sender
* @param args
*/
@Command(
aliases = { "tt", "TurtleToggle" },
description = "Toggle Turtle Mode",
permissions = { "" },
toolTip = "/tt")
public void TurtleToggle(MessageReceiver sender, String[] args)
{
if (tt)
{ //if On, Turning off Turtle
TurtleOff(sender, args);
}
else
{ //if Off, Turning on Turtle
TurtleOn(sender, args);
}
}
/**
* Output a message to the player console.
* Expects args[0] = "c"
* @param sender
* @param args
*/
@Command(
aliases = { "c", "TurtleConsole" },
description = "Displays a message on the turtle console",
permissions = { "" },
toolTip = "/c <message>")
public void TurtleConsole(MessageReceiver sender, String[] args)
{
//Display string in console
String message = "";
for (int i=1; i<args.length; i++) { //skip the command, just send the message
message = message + args[i]+ " ";
}
sender.message(message);
}
/**
* Toggle block placement mode on/off.
*
* TODO: IF placement off -> dont change vs AIr placement
* @param sender
* @param args
*/
@Command(
aliases = { "bp", "BlockPlacement" },
description = "Toggle Turtle block placement mode",
permissions = { "" },
toolTip = "/bp")
public void TurtleBlockPlace(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
bp = !bp;
TurtleBlockPlaceStatus(sender, args);
}
/**
* Checks whether block placement mode is on.
* @param sender
* @param args
*/
@Command(
aliases = { "bp?", "CheckBlockPlacement" },
description = "Checks Turtle block placement mode",
permissions = { "" },
toolTip = "/bp?")
public void TurtleBlockPlaceStatus(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
getString(sender, bp);
}
/**
* Set turtle position (relative coords)
* @param sender
* @param args
*/
@Command(
aliases = { "srp", "SetPosition" },
description = "Set Turtle position",
permissions = { "" },
toolTip = "/srp")
public void TurtleSetRelPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//Change location to new location based on relative coordinates
relPos = new Position (Integer.parseInt(args[1]), Integer.parseInt(args[2]),Integer.parseInt(args[3]));
}
/**
* Set turtle direction. Textbased (North, South, East, West)
* Number based for simplicity in early tests?
* @param sender
* @param args
*/
@Command(
aliases = { "sd", "SetDirection" },
description = "Set turtle direction",
permissions = { "" },
toolTip = "/sd")
public void TurtleSetDirection(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
relDir = Direction.getFromIntValue(Integer.parseInt(args[1]));
// 0 = NORTH
// 2 = EAST
// 4 = SOUTH
// 6 = WEST
// Else = ERROR
}
/**
* Get current position (relative)
* @param sender
* @param args
*/
@Command(
aliases = { "gp", "GetPosition" },
description = "Get Turtle position",
permissions = { "" },
toolTip = "/gp")
public void TurtleGetPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle (relative position)
// getRelPos();
getString(sender, relPos);
}
/**
* Get current position of Turtle in game coords
* @param sender
* @param args
*/
@Command(
aliases = { "ggp", "GetGamePosition" },
description = "Get Turtle position in game coords",
permissions = { "" },
toolTip = "/ggp")
public void TurtleGetGamePosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle (game coord position)
getString(sender, gamePos);
}
/**
* Get position of relative origin (Player's pos at Turtle on) in game coords
* @param sender
* @param args
*/
@Command(
aliases = { "gop", "GetOriginPosition" },
description = "Get origin position in game coords",
permissions = { "" },
toolTip = "/gop")
public void TurtleGetOriginPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of origin (game coord position)
getString(sender, originPos);
}
/**
* Get current direction (relative)
* @param sender
* @param args
*/
@Command(
aliases = { "gd", "GetDirection" },
description = "Get Turtle direction",
permissions = { "" },
toolTip = "/gd")
public void TurtleGetDirection(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle
getString(sender, relDir);
}
/**
* Set block type (int based)
* @param sender
* @param args
*/
@Command(
aliases = { "sbt", "SetBlockType" },
description = "Set Turtle block type",
permissions = { "" },
toolTip = "/sbt")
public void TurtleSetBlockType(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
if (!checkBP(sender)) //don't allow if block placement mode isn't on either
return;
BlockType temp;
//set current BT of turtle
if (!(args.length == 3))
{
temp = BlockType.fromId(Integer.parseInt(args[1]));
}else{
temp = BlockType.fromIdAndData(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}
bt = temp;
}
/**
* set Block type (string/BlockType based)
* @param sender
* @param args
*/
//TODO implementation
/**
* Get current block type
* @param sender
* @param args
*/
@Command(
aliases = { "gbt", "GetBlockType" },
description = "Get Turtle block type",
permissions = { "" },
toolTip = "/gbt")
public void TurtleGetBlockType(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
if (!checkBP(sender)) //don't allow if block placement mode isn't on either
return;
//report current BT of turtle
getString(sender, bt);
}
/**
* Move (forward/back)
* @param sender
* @param args
*/
@Command(
aliases = { "m" , "f", "b", "move", "forward", "back"},
description = "Turtle move forward/back",
permissions = { "" },
toolTip = "/m or /f or /b")
public void TurtleMove(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
int x = Integer.parseInt(args[1]); //get desired move distance
boolean fd = false; //flipped direction (for moving backward)
//check if distance is negative (going backward)
if (x < 0){
//if so, reverse turtle direction
x = -x;
flipDir();
fd = true;
}
for (int i = x; i > 0; i--){
//Place block if block placement mode on
if (bp) {
world.setBlockAt(relPos, bt);
//TODO: keep track of this block to undo
}
//update turtle position
relPos = turtle.move(relPos, relDir, false, false);
}
//if reversed turtle direction, reset to original
if (fd == true){
fd = false;
flipDir();
}
}
/**
* Moves turtle up/down
* @param sender
* @param args
*/
@Command(
aliases = { "u", "d", "up", "down" },
description = "Turtle up/down",
permissions = { "" },
toolTip = "/u or /d")
public void TurtleUpDown(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
int x = Integer.parseInt(args[1]); //get desired move distance
boolean up = true; //default direction is up
//check if distance is negative (going down)
if (x < 0){
//if so, reverse turtle direction
x = -x;
up = false;
}
for (int i = x; i > 0; i--){
//Place block if block placement mode on
if (bp) {
world.setBlockAt(gamePos, bt);
//TODO: keep track of this block to undo
}
//update turtle position
gamePos = turtle.move(gamePos, relDir, up, !up); //only moving vertically--> relDir doesn't matter
updateRelPos();
}
}
/**
* Turn (Right/Left) (text based)(degrees)
* @param sender
* @param args
*/
@Command(
aliases = { "t", "turn" },
description = "Turtle turn",
permissions = { "" },
toolTip = "/t")
public void TurtleTurn(MessageReceiver sender, String[] args)
{
//TODO implementation -> will allow diagonals
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//turn turtle (left or right)
}
@HookHandler
public void uploadJSON(KCTUploadHook hook) {
logger.info("Hook called, json is "+hook.getJSON());
JSONParser parser=new JSONParser();
try {
logger.info(hook.getJSON());
JSONObject json=(JSONObject)parser.parse(hook.getJSON());
String scriptname=(String)json.get("scriptname");
KCTScript script=new KCTScript(scriptname);
logger.info(String.format("%s\n", scriptname));
JSONArray lang= (JSONArray) json.get("commands");
for (int i=0; i<lang.size(); i++) {
JSONObject cmd=(JSONObject)lang.get(i);
script.addCommand(cmd);
logger.info(String.format("script %s has command %s", script.getScriptName(), cmd.get(KCTCommand.CMD)));
}
// TODO: Put script someplace now that we've created it
} catch (ParseException e) {
// TODO: log better? handle better?
throw new RuntimeException(e);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PRIVATE HELPER FUNCTIONS
/**
* Updates game position by combining origin position and current relative position.
*/
private void updateGamePos(){
//get origin coords
int xo = originPos.getBlockX();
int yo = originPos.getBlockY();
int zo = originPos.getBlockZ();
//get relative coords
int xr = relPos.getBlockX();
int yr = relPos.getBlockY();
int zr = relPos.getBlockZ();
//update game position
//gamePos = originPos + relPos;
gamePos.setX(xo+xr);
gamePos.setY(yo+yr);
gamePos.setZ(zo+zr);
}
private void updateGameDir(){
//TODO: implement this
}
/*TODO: should this be called updateRelPos? It doesn't return/print anything...
Also when would we need to call this? */
private void updateRelPos(){
int xg = gamePos.getBlockX();
int yg = gamePos.getBlockY();
int zg = gamePos.getBlockZ();
int xo = originPos.getBlockX();
int yo = originPos.getBlockY();
int zo = originPos.getBlockZ();
relPos.setX(xg-xo);
relPos.setY(yg-yo);
relPos.setZ(zg-zo);
}
/**
* Reverses relative direction (turn 180 degrees). Used when moving backward.
*/
private void flipDir(){
//get current direction (N, NE, ... , S --> 0, 1, ... , 7)
int dirInt = relDir.getIntValue();
//calculate new direction
dirInt = (dirInt + 4) % 8;
//update relDir
relDir = Direction.getFromIntValue(dirInt);
}
/*TODO: We need to add Javadoc comments for these methods and possibly rename them
with more descriptive titles. I'm a little confused by them at the moment. */
private void getString(MessageReceiver sender, boolean b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, BlockType b){
//Get the Boolean value
String []str = new String [2];
str[0] = "/c";
str[1] = b.toString() + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, Direction b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b.toString() + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, Position b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b.toString() + ""; //Need to overload / fix this output
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
/**
* Checks whether turtle mode is on. If so, returns true. If not, alerts user and returns false.
* @return Status of turtle mode
*/
private boolean checkTT(MessageReceiver sender) {
if (tt) { //turtle mode is on-- no problems
return true;
} else { //turtle mode is off-- need to alert user
String [] str = new String [2];
str[0] = "/c";
str[1] = "Turtle mode is not on.";
TurtleConsole(sender, str);
return false;
}
}
/**
* Checks whether block placement mode is on. If so, returns true. If not, alerts user and returns false.
* @return Status of block placement mode
*/
private boolean checkBP(MessageReceiver sender) {
if (bp) { //block placement mode is on-- no problems
return true;
} else { //block placement mode is off-- need to alert user
String [] str = new String [2];
str[0] = "/c";
str[1] = "Block placement mode is not on.";
TurtleConsole(sender, str);
return false;
}
}
} | Turtles3D/src/edu/knox/minecraft/serverturtle/TurtleAPI.java | package edu.knox.minecraft.serverturtle;
import net.canarymod.Canary;
import net.canarymod.api.world.World;
import net.canarymod.api.world.blocks.BlockType;
import net.canarymod.api.world.position.Direction;
import net.canarymod.api.world.position.Position;
import net.canarymod.chat.MessageReceiver;
import net.canarymod.commandsys.Command;
import net.canarymod.commandsys.CommandDependencyException;
import net.canarymod.commandsys.CommandListener;
import net.canarymod.hook.HookHandler;
import net.canarymod.logger.Logman;
import net.canarymod.plugin.Plugin;
import net.canarymod.plugin.PluginListener;
//import org.json.simple.JSONArray;
//import org.json.simple.JSONObject;
//import org.json.simple.parser.JSONParser;
//import org.json.simple.parser.ParseException;
//
//import edu.knoxcraft.hooks.KCTUploadHook;
//import edu.knoxcraft.http.server.HttpUploadServer;
//import edu.knoxcraft.turtle3d.KCTCommand;
//import edu.knoxcraft.turtle3d.KCTScript;
/*TODO: should most of these commands really happen in Turtle,
and this class just call those versions? Like in TurtleMove(). */
//Things need to be overly simple during testing for ease of use
//In time, need to build in string verification for correct input style (ie. All caps, etc)
public class TurtleAPI extends Plugin implements CommandListener, PluginListener {
//POSITION VARIABLES
//in world position/direction of player at turtle on --> (0,0,0) for Turtle's relative coord system.
private Position originPos;
private Direction originDir;
//current relative position
private Position relPos;
private Direction relDir;
//true current position in game coords(made by combining relative and real)
private Position gamePos;
private Direction gameDir; //TODO: I don't think this is ever updated... //true Facts
//MODE TOGGLES
private boolean tt = false; //Turtle on/off
private boolean bp = false; //Block Place on/off
//OTHER VARIABLES
private Turtle turtle = new Turtle();
private BlockType bt = BlockType.Stone; //default turtle block type
private World world; //World in which all actions occur
// private HttpUploadServer httpServer;
public static Logman logger;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
public TurtleAPI() {
TurtleAPI.logger = getLogman();
}
/**
* Called when plugin is disabled.
*/
@Override
public void disable() {
// httpServer.disable();
}
/**
* Called when plugin is enabled.
* @return
*/
@Override
public boolean enable() {
try {
getLogman().info("Registering plugin");
Canary.hooks().registerListener(this, this);
// httpServer=new HttpUploadServer();
// httpServer.enable();
//getName() returns the class name, in this case TurtleAPI
getLogman().info("Enabling "+getName() + " Version " + getVersion());
getLogman().info("Authored by "+getAuthor());
Canary.commands().registerCommands(this, this, false);
return true;
} catch (CommandDependencyException e){
throw new RuntimeException(e);
}
}
//API TIME
/**
* Turn on turtle mode. Sets up relative position.
* (0,0,0) is player position. Forward is player direction.
* @param sender
* @param args
*/
@Command(
aliases = { "ton", "TurtleOn" },
description = "Turtle Mode On",
permissions = { "" },
toolTip = "/ton")
public void TurtleOn(MessageReceiver sender, String[] args)
{
//Make Turtle
turtle = new Turtle();
//GET WORLD
world = sender.asPlayer().getWorld();
//Relative pos stuff
//Get True Position and Direction
originPos = sender.asPlayer().getPosition();
originDir = sender.asPlayer().getCardinalDirection();
//Make the Relative Position
relPos = new Position(0,0,0);
relDir = Direction.getFromIntValue(0);
//updateCurPos(); //these two methods got renamed- change them if this gets uncommented
//updateCurDir();
//Faces player direction
//Need to build in safety checks
//Also, better way?
//If doesn't work-> set to North ONLY, as way to start debugging
relDir = originDir; //??
//Turning on Turtle
tt = true;
getString(sender, originPos);
getString(sender, originDir);
getString(sender, tt);
}
/**
* Turn off turtle mode.
* @param sender
* @param args
*/
@Command(
aliases = { "toff", "TurtleOff" },
description = "Turtle Mode Off",
permissions = { "" },
toolTip = "/toff")
public void TurtleOff(MessageReceiver sender, String[] args)
{
//Turning off Turtle
tt = false;
turtle = null;
getString(sender, tt);
}
/**
* Toggle turtle mode on/off.
* @param sender
* @param args
*/
@Command(
aliases = { "tt", "TurtleToggle" },
description = "Toggle Turtle Mode",
permissions = { "" },
toolTip = "/tt")
public void TurtleToggle(MessageReceiver sender, String[] args)
{
if (tt)
{ //if On, Turning off Turtle
TurtleOff(sender, args);
}
else
{ //if Off, Turning on Turtle
TurtleOn(sender, args);
}
}
/**
* Output a message to the player console.
* Expects args[0] = "c"
* @param sender
* @param args
*/
@Command(
aliases = { "c", "TurtleConsole" },
description = "Displays a message on the turtle console",
permissions = { "" },
toolTip = "/c <message>")
public void TurtleConsole(MessageReceiver sender, String[] args)
{
//Display string in console
String message = "";
for (int i=1; i<args.length; i++) { //skip the command, just send the message
message = message + args[i]+ " ";
}
sender.message(message);
}
/**
* Toggle block placement mode on/off.
*
* TODO: IF placement off -> dont change vs AIr placement
* @param sender
* @param args
*/
@Command(
aliases = { "bp", "BlockPlacement" },
description = "Toggle Turtle block placement mode",
permissions = { "" },
toolTip = "/bp")
public void TurtleBlockPlace(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
bp = !bp;
TurtleBlockPlaceStatus(sender, args);
}
/**
* Checks whether block placement mode is on.
* @param sender
* @param args
*/
@Command(
aliases = { "bp?", "CheckBlockPlacement" },
description = "Checks Turtle block placement mode",
permissions = { "" },
toolTip = "/bp?")
public void TurtleBlockPlaceStatus(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
getString(sender, bp);
}
/**
* Set turtle position (relative coords)
* @param sender
* @param args
*/
@Command(
aliases = { "srp", "SetPosition" },
description = "Set Turtle position",
permissions = { "" },
toolTip = "/srp")
public void TurtleSetRelPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//Change location to new location based on relative coordinates
relPos = new Position (Integer.parseInt(args[1]), Integer.parseInt(args[2]),Integer.parseInt(args[3]));
}
/**
* Set turtle direction. Textbased (North, South, East, West)
* Number based for simplicity in early tests?
* @param sender
* @param args
*/
@Command(
aliases = { "sd", "SetDirection" },
description = "Set turtle direction",
permissions = { "" },
toolTip = "/sd")
public void TurtleSetDirection(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
relDir = Direction.getFromIntValue(Integer.parseInt(args[1]));
// 0 = NORTH
// 2 = EAST
// 4 = SOUTH
// 6 = WEST
// Else = ERROR
}
/**
* Get current position (relative)
* @param sender
* @param args
*/
@Command(
aliases = { "gp", "GetPosition" },
description = "Get Turtle position",
permissions = { "" },
toolTip = "/gp")
public void TurtleGetPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle (relative position)
// getRelPos();
getString(sender, relPos);
}
/**
* Get current position of Turtle in game coords
* @param sender
* @param args
*/
@Command(
aliases = { "ggp", "GetGamePosition" },
description = "Get Turtle position in game coords",
permissions = { "" },
toolTip = "/ggp")
public void TurtleGetGamePosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle (game coord position)
getString(sender, gamePos);
}
/**
* Get position of relative origin (Player's pos at Turtle on) in game coords
* @param sender
* @param args
*/
@Command(
aliases = { "gop", "GetOriginPosition" },
description = "Get origin position in game coords",
permissions = { "" },
toolTip = "/gop")
public void TurtleGetOriginPosition(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of origin (game coord position)
getString(sender, originPos);
}
/**
* Get current direction (relative)
* @param sender
* @param args
*/
@Command(
aliases = { "gd", "GetDirection" },
description = "Get Turtle direction",
permissions = { "" },
toolTip = "/gd")
public void TurtleGetDirection(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//report position of turtle
getString(sender, relDir);
}
/**
* Set block type (int based)
* @param sender
* @param args
*/
@Command(
aliases = { "sbt", "SetBlockType" },
description = "Set Turtle block type",
permissions = { "" },
toolTip = "/sbt")
public void TurtleSetBlockType(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
if (!checkBP(sender)) //don't allow if block placement mode isn't on either
return;
BlockType temp;
//set current BT of turtle
if (!(args.length == 3))
{
temp = BlockType.fromId(Integer.parseInt(args[1]));
}else{
temp = BlockType.fromIdAndData(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
}
bt = temp;
}
/**
* set Block type (string/BlockType based)
* @param sender
* @param args
*/
//TODO implementation
/**
* Get current block type
* @param sender
* @param args
*/
@Command(
aliases = { "gbt", "GetBlockType" },
description = "Get Turtle block type",
permissions = { "" },
toolTip = "/gbt")
public void TurtleGetBlockType(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
if (!checkBP(sender)) //don't allow if block placement mode isn't on either
return;
//report current BT of turtle
getString(sender, bt);
}
/**
* Move (forward/back)
* @param sender
* @param args
*/
@Command(
aliases = { "m" , "f", "b", "move", "forward", "back"},
description = "Turtle move forward/back",
permissions = { "" },
toolTip = "/m or /f or /b")
public void TurtleMove(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
int x = Integer.parseInt(args[1]); //get desired move distance
boolean fd = false; //flipped direction (for moving backward)
//check if distance is negative (going backward)
if (x < 0){
//if so, reverse turtle direction
x = -x;
flipDir();
fd = true;
}
for (int i = x; i > 0; i--){
//Place block if block placement mode on
if (bp) {
world.setBlockAt(relPos, bt);
//TODO: keep track of this block to undo
}
//update turtle position
relPos = turtle.move(relPos, relDir, false, false);
}
//if reversed turtle direction, reset to original
if (fd == true){
fd = false;
flipDir();
}
}
/**
* Moves turtle up/down
* @param sender
* @param args
*/
@Command(
aliases = { "u", "d", "up", "down" },
description = "Turtle up/down",
permissions = { "" },
toolTip = "/u or /d")
public void TurtleUpDown(MessageReceiver sender, String[] args)
{
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
int x = Integer.parseInt(args[1]); //get desired move distance
boolean up = true; //default direction is up
//check if distance is negative (going down)
if (x < 0){
//if so, reverse turtle direction
x = -x;
up = false;
}
for (int i = x; i > 0; i--){
//Place block if block placement mode on
if (bp) {
world.setBlockAt(gamePos, bt);
//TODO: keep track of this block to undo
}
//update turtle position
gamePos = turtle.move(gamePos, relDir, up, !up); //only moving vertically--> relDir doesn't matter
updateRelPos();
}
}
/**
* Turn (Right/Left) (text based)(degrees)
* @param sender
* @param args
*/
@Command(
aliases = { "t", "turn" },
description = "Turtle turn",
permissions = { "" },
toolTip = "/t")
public void TurtleTurn(MessageReceiver sender, String[] args)
{
//TODO implementation -> will allow diagonals
if (!checkTT(sender)) //Don't allow if turtle mode is not on
return;
//turn turtle (left or right)
}
// @HookHandler
// public void uploadJSON(KCTUploadHook hook) {
// logger.info("Hook called, json is "+hook.getJSON());
// JSONParser parser=new JSONParser();
// try {
// logger.info(hook.getJSON());
// JSONObject json=(JSONObject)parser.parse(hook.getJSON());
//
// String scriptname=(String)json.get("scriptname");
//
// KCTScript script=new KCTScript(scriptname);
//
// logger.info(String.format("%s\n", scriptname));
//
// JSONArray lang= (JSONArray) json.get("commands");
// for (int i=0; i<lang.size(); i++) {
// JSONObject cmd=(JSONObject)lang.get(i);
// script.addCommand(cmd);
// logger.info(String.format("script %s has command %s", script.getScriptName(), cmd.get(KCTCommand.CMD)));
// }
// // TODO: Put script someplace now that we've created it
// } catch (ParseException e) {
// // TODO: log better? handle better?
// throw new RuntimeException(e);
// }
// }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PRIVATE HELPER FUNCTIONS
/**
* Updates game position by combining origin position and current relative position.
*/
private void updateGamePos(){
//get origin coords
int xo = originPos.getBlockX();
int yo = originPos.getBlockY();
int zo = originPos.getBlockZ();
//get relative coords
int xr = relPos.getBlockX();
int yr = relPos.getBlockY();
int zr = relPos.getBlockZ();
//update game position
//gamePos = originPos + relPos;
gamePos.setX(xo+xr);
gamePos.setY(yo+yr);
gamePos.setZ(zo+zr);
}
private void updateGameDir(){
//TODO: implement this
}
/*TODO: should this be called updateRelPos? It doesn't return/print anything...
Also when would we need to call this? */
private void updateRelPos(){
int xg = gamePos.getBlockX();
int yg = gamePos.getBlockY();
int zg = gamePos.getBlockZ();
int xo = originPos.getBlockX();
int yo = originPos.getBlockY();
int zo = originPos.getBlockZ();
relPos.setX(xg-xo);
relPos.setY(yg-yo);
relPos.setZ(zg-zo);
}
/**
* Reverses relative direction (turn 180 degrees). Used when moving backward.
*/
private void flipDir(){
//get current direction (N, NE, ... , S --> 0, 1, ... , 7)
int dirInt = relDir.getIntValue();
//calculate new direction
dirInt = (dirInt + 4) % 8;
//update relDir
relDir = Direction.getFromIntValue(dirInt);
}
/*TODO: We need to add Javadoc comments for these methods and possibly rename them
with more descriptive titles. I'm a little confused by them at the moment. */
private void getString(MessageReceiver sender, boolean b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, BlockType b){
//Get the Boolean value
String []str = new String [2];
str[0] = "/c";
str[1] = b.toString() + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, Direction b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b.toString() + "";
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
private void getString(MessageReceiver sender, Position b){
//Get the Boolean value
String [] str = new String [2];
str[0] = "/c";
str[1] = b.toString() + ""; //Need to overload / fix this output
//return status of BP using TurtleConsole
TurtleConsole(sender, str);
}
/**
* Checks whether turtle mode is on. If so, returns true. If not, alerts user and returns false.
* @return Status of turtle mode
*/
private boolean checkTT(MessageReceiver sender) {
if (tt) { //turtle mode is on-- no problems
return true;
} else { //turtle mode is off-- need to alert user
String [] str = new String [2];
str[0] = "/c";
str[1] = "Turtle mode is not on.";
TurtleConsole(sender, str);
return false;
}
}
/**
* Checks whether block placement mode is on. If so, returns true. If not, alerts user and returns false.
* @return Status of block placement mode
*/
private boolean checkBP(MessageReceiver sender) {
if (bp) { //block placement mode is on-- no problems
return true;
} else { //block placement mode is off-- need to alert user
String [] str = new String [2];
str[0] = "/c";
str[1] = "Block placement mode is not on.";
TurtleConsole(sender, str);
return false;
}
}
} | undid comments- still broke
| Turtles3D/src/edu/knox/minecraft/serverturtle/TurtleAPI.java | undid comments- still broke | <ide><path>urtles3D/src/edu/knox/minecraft/serverturtle/TurtleAPI.java
<ide> import net.canarymod.plugin.Plugin;
<ide> import net.canarymod.plugin.PluginListener;
<ide>
<del>//import org.json.simple.JSONArray;
<del>//import org.json.simple.JSONObject;
<del>//import org.json.simple.parser.JSONParser;
<del>//import org.json.simple.parser.ParseException;
<del>//
<del>//import edu.knoxcraft.hooks.KCTUploadHook;
<del>//import edu.knoxcraft.http.server.HttpUploadServer;
<del>//import edu.knoxcraft.turtle3d.KCTCommand;
<del>//import edu.knoxcraft.turtle3d.KCTScript;
<add>import org.json.simple.JSONArray;
<add>import org.json.simple.JSONObject;
<add>import org.json.simple.parser.JSONParser;
<add>import org.json.simple.parser.ParseException;
<add>
<add>import edu.knoxcraft.hooks.KCTUploadHook;
<add>import edu.knoxcraft.http.server.HttpUploadServer;
<add>import edu.knoxcraft.turtle3d.KCTCommand;
<add>import edu.knoxcraft.turtle3d.KCTScript;
<ide>
<ide> /*TODO: should most of these commands really happen in Turtle,
<ide> and this class just call those versions? Like in TurtleMove(). */
<ide> private Turtle turtle = new Turtle();
<ide> private BlockType bt = BlockType.Stone; //default turtle block type
<ide> private World world; //World in which all actions occur
<del>// private HttpUploadServer httpServer;
<add> private HttpUploadServer httpServer;
<ide> public static Logman logger;
<ide>
<ide> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<ide> */
<ide> @Override
<ide> public void disable() {
<del>// httpServer.disable();
<add> httpServer.disable();
<ide> }
<ide>
<ide> /**
<ide> try {
<ide> getLogman().info("Registering plugin");
<ide> Canary.hooks().registerListener(this, this);
<del>// httpServer=new HttpUploadServer();
<del>// httpServer.enable();
<add> httpServer=new HttpUploadServer();
<add> httpServer.enable();
<ide> //getName() returns the class name, in this case TurtleAPI
<ide> getLogman().info("Enabling "+getName() + " Version " + getVersion());
<ide> getLogman().info("Authored by "+getAuthor());
<ide>
<ide> }
<ide>
<del>// @HookHandler
<del>// public void uploadJSON(KCTUploadHook hook) {
<del>// logger.info("Hook called, json is "+hook.getJSON());
<del>// JSONParser parser=new JSONParser();
<del>// try {
<del>// logger.info(hook.getJSON());
<del>// JSONObject json=(JSONObject)parser.parse(hook.getJSON());
<del>//
<del>// String scriptname=(String)json.get("scriptname");
<del>//
<del>// KCTScript script=new KCTScript(scriptname);
<del>//
<del>// logger.info(String.format("%s\n", scriptname));
<del>//
<del>// JSONArray lang= (JSONArray) json.get("commands");
<del>// for (int i=0; i<lang.size(); i++) {
<del>// JSONObject cmd=(JSONObject)lang.get(i);
<del>// script.addCommand(cmd);
<del>// logger.info(String.format("script %s has command %s", script.getScriptName(), cmd.get(KCTCommand.CMD)));
<del>// }
<del>// // TODO: Put script someplace now that we've created it
<del>// } catch (ParseException e) {
<del>// // TODO: log better? handle better?
<del>// throw new RuntimeException(e);
<del>// }
<del>// }
<add> @HookHandler
<add> public void uploadJSON(KCTUploadHook hook) {
<add> logger.info("Hook called, json is "+hook.getJSON());
<add> JSONParser parser=new JSONParser();
<add> try {
<add> logger.info(hook.getJSON());
<add> JSONObject json=(JSONObject)parser.parse(hook.getJSON());
<add>
<add> String scriptname=(String)json.get("scriptname");
<add>
<add> KCTScript script=new KCTScript(scriptname);
<add>
<add> logger.info(String.format("%s\n", scriptname));
<add>
<add> JSONArray lang= (JSONArray) json.get("commands");
<add> for (int i=0; i<lang.size(); i++) {
<add> JSONObject cmd=(JSONObject)lang.get(i);
<add> script.addCommand(cmd);
<add> logger.info(String.format("script %s has command %s", script.getScriptName(), cmd.get(KCTCommand.CMD)));
<add> }
<add> // TODO: Put script someplace now that we've created it
<add> } catch (ParseException e) {
<add> // TODO: log better? handle better?
<add> throw new RuntimeException(e);
<add> }
<add> }
<ide>
<ide> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<ide> //PRIVATE HELPER FUNCTIONS |
|
Java | apache-2.0 | d98d80f031f46be0aad4a92c2e5266504acbc44a | 0 | millmanorama/autopsy,dgrove727/autopsy,APriestman/autopsy,APriestman/autopsy,millmanorama/autopsy,wschaeferB/autopsy,narfindustries/autopsy,wschaeferB/autopsy,rcordovano/autopsy,APriestman/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,dgrove727/autopsy,rcordovano/autopsy,dgrove727/autopsy,APriestman/autopsy,millmanorama/autopsy,millmanorama/autopsy,APriestman/autopsy,wschaeferB/autopsy,narfindustries/autopsy,rcordovano/autopsy,esaunders/autopsy,rcordovano/autopsy,narfindustries/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy,esaunders/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2016 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.datamodel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.core.UserPreferences;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.ingest.IngestManager;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentVisitor;
import org.sleuthkit.datamodel.DerivedFile;
import org.sleuthkit.datamodel.Directory;
import org.sleuthkit.datamodel.File;
import org.sleuthkit.datamodel.LayoutFile;
import org.sleuthkit.datamodel.LocalFile;
import org.sleuthkit.datamodel.SlackFile;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Class which contains the Nodes for the 'By Mime Type' view located in the
* File Types view, shows all files with a mime type. Will initially be empty
* until file type identification has been performed. Contains a Property Change
* Listener which is checking for changes in IngestJobEvent Completed or
* Cancelled and IngestModuleEvent Content Changed.
*/
public final class FileTypesByMimeType extends Observable implements AutopsyVisitableItem {
private final SleuthkitCase skCase;
/**
* The nodes of this tree will be determined dynamically by the mimetypes
* which exist in the database. This hashmap will store them with the media
* type as the key and a list of media subtypes as the value.
*/
private final HashMap<String, List<String>> existingMimeTypes = new HashMap<>();
private static final Logger LOGGER = Logger.getLogger(FileTypesByMimeType.class.getName());
private void removeListeners() {
deleteObservers();
IngestManager.getInstance().removeIngestJobEventListener(pcl);
Case.removePropertyChangeListener(pcl);
}
/*
* The pcl is in the class because it has the easiest mechanisms to add and
* remove itself during its life cycles.
*/
private final PropertyChangeListener pcl = (PropertyChangeEvent evt) -> {
String eventType = evt.getPropertyName();
if (eventType.equals(IngestManager.IngestJobEvent.COMPLETED.toString())
|| eventType.equals(IngestManager.IngestJobEvent.CANCELLED.toString())) {
/**
* Checking for a current case is a stop gap measure until a
* different way of handling the closing of cases is worked out.
* Currently, remote events may be received for a case that is
* already closed.
*/
try {
Case.getCurrentCase();
populateHashMap();
} catch (IllegalStateException notUsed) {
/**
* Case is closed, do nothing.
*/
}
} else if (eventType.equals(Case.Events.CURRENT_CASE.toString())) {
if (evt.getNewValue() == null) {
removeListeners();
}
}
};
/**
* Retrieve the media types by retrieving the keyset from the hashmap.
*
* @return mediaTypes - a list of strings representing all distinct media
* types of files for this case
*/
private List<String> getMediaTypeList() {
synchronized (existingMimeTypes) {
List<String> mediaTypes = new ArrayList<>(existingMimeTypes.keySet());
Collections.sort(mediaTypes);
return mediaTypes;
}
}
/**
* Performs the query on the database to get all distinct MIME types of
* files in it, and populate the hashmap with those results.
*/
private void populateHashMap() {
StringBuilder allDistinctMimeTypesQuery = new StringBuilder();
allDistinctMimeTypesQuery.append("SELECT DISTINCT mime_type from tsk_files where mime_type IS NOT null"); //NON-NLS
allDistinctMimeTypesQuery.append(" AND dir_type = ").append(TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue()); //NON-NLS
allDistinctMimeTypesQuery.append(" AND (type IN (").append(TskData.TSK_DB_FILES_TYPE_ENUM.FS.ordinal()).append(","); //NON-NLS
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.CARVED.ordinal()).append(",");
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.DERIVED.ordinal()).append(",");
if (!UserPreferences.hideSlackFilesInViewsTree()) {
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK.ordinal()).append(",");
}
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL.ordinal()).append("))");
synchronized (existingMimeTypes) {
existingMimeTypes.clear();
if (skCase == null) {
return;
}
try (SleuthkitCase.CaseDbQuery dbQuery = skCase.executeQuery(allDistinctMimeTypesQuery.toString())) {
ResultSet resultSet = dbQuery.getResultSet();
while (resultSet.next()) {
final String mime_type = resultSet.getString("mime_type"); //NON-NLS
if (!mime_type.isEmpty()) {
String mimeType[] = mime_type.split("/");
//Note: Users are able to define custom mime types in Autopsy that do not
//contain a "/" or possibly have multiple slashes
if (mimeType.length > 1 && !mimeType[0].isEmpty() && !mimeType[1].isEmpty()) {
if (!existingMimeTypes.containsKey(mimeType[0])) {
existingMimeTypes.put(mimeType[0], new ArrayList<>());
}
existingMimeTypes.get(mimeType[0]).add(mimeType[1]);
}
}
}
} catch (TskCoreException | SQLException ex) {
LOGGER.log(Level.SEVERE, "Unable to populate File Types by MIME Type tree view from DB: ", ex); //NON-NLS
}
}
setChanged();
notifyObservers();
}
FileTypesByMimeType(SleuthkitCase skCase) {
IngestManager.getInstance().addIngestJobEventListener(pcl);
Case.addPropertyChangeListener(pcl);
this.skCase = skCase;
populateHashMap();
}
@Override
public <T> T accept(AutopsyItemVisitor<T> v) {
return v.visit(this);
}
/**
* Method to check if the node in question is a ByMimeTypeNode which is
* empty.
*
* @param node the Node which you wish to check.
*
* @return True if originNode is an instance of ByMimeTypeNode and is empty,
* false otherwise.
*/
public static boolean isEmptyMimeTypeNode(Node node) {
boolean isEmptyMimeNode = false;
if (node instanceof FileTypesByMimeType.ByMimeTypeNode && ((FileTypesByMimeType.ByMimeTypeNode) node).isEmpty()) {
isEmptyMimeNode = true;
}
return isEmptyMimeNode;
}
/**
* Class which represents the root node of the "By MIME Type" tree, will
* have children of each media type present in the database or no children
* when the file detection module has not been run and MIME type is
* currently unknown.
*/
class ByMimeTypeNode extends DisplayableItemNode {
@NbBundle.Messages("FileTypesByMimeType.name.text=By MIME Type")
final String NAME = Bundle.FileTypesByMimeType_name_text();
ByMimeTypeNode() {
super(Children.create(new ByMimeTypeNodeChildren(), true));
super.setName(NAME);
super.setDisplayName(NAME);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png");
}
@Override
public boolean isLeafTypeNode() {
return false;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
boolean isEmpty() {
return existingMimeTypes.isEmpty();
}
}
/**
* Creates the children for the "By MIME Type" node these children will each
* represent a distinct media type present in the DB
*/
private class ByMimeTypeNodeChildren extends ChildFactory<String> implements Observer {
private ByMimeTypeNodeChildren() {
super();
addObserver(this);
}
@Override
protected boolean createKeys(List<String> mediaTypeNodes) {
if (!existingMimeTypes.isEmpty()) {
mediaTypeNodes.addAll(getMediaTypeList());
}
return true;
}
@Override
protected Node createNodeForKey(String key) {
return new MediaTypeNode(key);
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
}
/**
* The Media type node created by the ByMimeTypeNodeChildren and contains
* one of the unique media types present in the database for this case.
*/
class MediaTypeNode extends DisplayableItemNode {
MediaTypeNode(String name) {
super(Children.create(new MediaTypeNodeChildren(name), true));
setName(name);
setDisplayName(name);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png");
}
@Override
public boolean isLeafTypeNode() {
return false;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
}
/**
* Creates children for media type nodes, children will be MediaSubTypeNodes
* and represent one of the subtypes which are present in the database of
* their media type.
*/
private class MediaTypeNodeChildren extends ChildFactory<String> implements Observer {
String mediaType;
MediaTypeNodeChildren(String name) {
addObserver(this);
this.mediaType = name;
}
@Override
protected boolean createKeys(List<String> mediaTypeNodes) {
mediaTypeNodes.addAll(existingMimeTypes.get(mediaType));
return true;
}
@Override
protected Node createNodeForKey(String subtype) {
String mimeType = mediaType + "/" + subtype;
return new MediaSubTypeNode(mimeType);
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
}
/**
* Node which represents the media sub type in the By MIME type tree, the
* media subtype is the portion of the MIME type following the /.
*/
class MediaSubTypeNode extends DisplayableItemNode implements Observer {
private MediaSubTypeNode(String mimeType) {
super(Children.create(new MediaSubTypeNodeChildren(mimeType), true));
addObserver(this);
init(mimeType);
}
private void init(String mimeType) {
super.setName(mimeType);
updateDisplayName(mimeType);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file-filter-icon.png"); //NON-NLS
}
/**
* Updates the display name of the mediaSubTypeNode to include the count
* of files which it represents.
*
* @param mimeType - the complete MimeType, needed for accurate query
* results
*/
private void updateDisplayName(String mimeType) {
final long count = new MediaSubTypeNodeChildren(mimeType).calculateItems(skCase, mimeType);
super.setDisplayName(mimeType.split("/")[1] + " (" + count + ")");
}
/**
* This returns true because any MediaSubTypeNode that exists is going
* to be a bottom level node in the Tree view on the left of Autopsy.
*
* @return true
*/
@Override
public boolean isLeafTypeNode() {
return true;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
@Override
public void update(Observable o, Object arg) {
updateDisplayName(getName());
}
}
/**
* Factory for populating the contents of the Media Sub Type Node with the
* files that match MimeType which is represented by this position in the
* tree.
*/
private class MediaSubTypeNodeChildren extends ChildFactory.Detachable<Content> implements Observer {
private final String mimeType;
private MediaSubTypeNodeChildren(String mimeType) {
super();
addObserver(this);
this.mimeType = mimeType;
}
/**
* Get children count without actually loading all nodes
*
* @return count(*) - the number of items that will be shown in this
* items Directory Listing
*/
private long calculateItems(SleuthkitCase sleuthkitCase, String mime_type) {
try {
return sleuthkitCase.countFilesWhere(createQuery(mime_type));
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Error getting file search view count", ex); //NON-NLS
return 0;
}
}
/**
* Uses the createQuery method to complete the query, Select * from
* tsk_files WHERE. The results from the database will contain the files
* which match this mime type and their information.
*
* @param list - will contain all files and their attributes from the
* tsk_files table where mime_type matches the one specified
*
* @return true
*/
@Override
protected boolean createKeys(List<Content> list) {
try {
List<AbstractFile> files = skCase.findAllFilesWhere(createQuery(mimeType));
list.addAll(files);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Couldn't get search results", ex); //NON-NLS
}
return true;
}
/**
* Create the portion of the query following WHERE for a query of the
* database for each file which matches the complete MIME type
* represented by this node. Matches against the mime_type column in
* tsk_files.
*
* @param mimeType - the complete mimetype of the file mediatype/subtype
*
* @return query.toString - portion of SQL query which will follow a
* WHERE clause.
*/
private String createQuery(String mime_type) {
StringBuilder query = new StringBuilder();
query.append("(dir_type = ").append(TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue()).append(")"); //NON-NLS
query.append(" AND (type IN (").append(TskData.TSK_DB_FILES_TYPE_ENUM.FS.ordinal()).append(","); //NON-NLS
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.CARVED.ordinal()).append(",");
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.DERIVED.ordinal()).append(",");
if (!UserPreferences.hideSlackFilesInViewsTree()) {
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK.ordinal()).append(",");
}
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL.ordinal()).append("))");
if (UserPreferences.hideKnownFilesInViewsTree()) {
query.append(" AND (known IS NULL OR known != ").append(TskData.FileKnown.KNOWN.getFileKnownValue()).append(")"); //NON-NLS
}
query.append(" AND mime_type = '").append(mime_type).append("'"); //NON-NLS
return query.toString();
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
/**
* Creates the content to populate the Directory Listing Table view for
* each file
*
* @param key
*
* @return
*/
@Override
protected Node createNodeForKey(Content key) {
return key.accept(new ContentVisitor.Default<AbstractNode>() {
@Override
public FileNode visit(File f) {
return new FileNode(f, false);
}
@Override
public DirectoryNode visit(Directory d) {
return new DirectoryNode(d);
}
@Override
public LayoutFileNode visit(LayoutFile lf) {
return new LayoutFileNode(lf);
}
@Override
public LocalFileNode visit(DerivedFile df) {
return new LocalFileNode(df);
}
@Override
public LocalFileNode visit(LocalFile lf) {
return new LocalFileNode(lf);
}
@Override
public SlackFileNode visit(SlackFile sf) {
return new SlackFileNode(sf, false);
}
@Override
protected AbstractNode defaultVisit(Content di) {
throw new UnsupportedOperationException(NbBundle.getMessage(this.getClass(), "FileTypeChildren.exception.notSupported.msg", di.toString()));
}
});
}
}
}
| Core/src/org/sleuthkit/autopsy/datamodel/FileTypesByMimeType.java | /*
* Autopsy Forensic Browser
*
* Copyright 2011-2016 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.datamodel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.core.UserPreferences;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.ingest.IngestManager;
import org.sleuthkit.datamodel.AbstractFile;
import org.sleuthkit.datamodel.Content;
import org.sleuthkit.datamodel.ContentVisitor;
import org.sleuthkit.datamodel.DerivedFile;
import org.sleuthkit.datamodel.Directory;
import org.sleuthkit.datamodel.File;
import org.sleuthkit.datamodel.LayoutFile;
import org.sleuthkit.datamodel.LocalFile;
import org.sleuthkit.datamodel.SlackFile;
import org.sleuthkit.datamodel.SleuthkitCase;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.datamodel.TskData;
/**
* Class which contains the Nodes for the 'By Mime Type' view located in the
* File Types view, shows all files with a mime type. Will initially be empty
* until file type identification has been performed. Contains a Property Change
* Listener which is checking for changes in IngestJobEvent Completed or
* Cancelled and IngestModuleEvent Content Changed.
*/
public final class FileTypesByMimeType extends Observable implements AutopsyVisitableItem {
private final SleuthkitCase skCase;
/**
* The nodes of this tree will be determined dynamically by the mimetypes
* which exist in the database. This hashmap will store them with the media
* type as the key and a list of media subtypes as the value.
*/
private final HashMap<String, List<String>> existingMimeTypes = new HashMap<>();
private static final Logger LOGGER = Logger.getLogger(FileTypesByMimeType.class.getName());
private void removeListeners() {
deleteObservers();
IngestManager.getInstance().removeIngestJobEventListener(pcl);
Case.removePropertyChangeListener(pcl);
}
/*
* The pcl is in the class because it has the easiest mechanisms to add and
* remove itself during its life cycles.
*/
private final PropertyChangeListener pcl = (PropertyChangeEvent evt) -> {
String eventType = evt.getPropertyName();
if (eventType.equals(IngestManager.IngestJobEvent.COMPLETED.toString())
|| eventType.equals(IngestManager.IngestJobEvent.CANCELLED.toString())) {
/**
* Checking for a current case is a stop gap measure until a
* different way of handling the closing of cases is worked out.
* Currently, remote events may be received for a case that is
* already closed.
*/
try {
Case.getCurrentCase();
populateHashMap();
} catch (IllegalStateException notUsed) {
/**
* Case is closed, do nothing.
*/
}
} else if (eventType.equals(Case.Events.CURRENT_CASE.toString())) {
if (evt.getNewValue() == null) {
removeListeners();
}
}
};
/**
* Retrieve the media types by retrieving the keyset from the hashmap.
*
* @return mediaTypes - a list of strings representing all distinct media
* types of files for this case
*/
private List<String> getMediaTypeList() {
synchronized (existingMimeTypes) {
List<String> mediaTypes = new ArrayList<>(existingMimeTypes.keySet());
Collections.sort(mediaTypes);
return mediaTypes;
}
}
/**
* Performs the query on the database to get all distinct MIME types of
* files in it, and populate the hashmap with those results.
*/
private void populateHashMap() {
StringBuilder allDistinctMimeTypesQuery = new StringBuilder();
allDistinctMimeTypesQuery.append("SELECT DISTINCT mime_type from tsk_files where mime_type IS NOT null"); //NON-NLS
allDistinctMimeTypesQuery.append(" AND dir_type = ").append(TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue()); //NON-NLS
allDistinctMimeTypesQuery.append(" AND (type IN (").append(TskData.TSK_DB_FILES_TYPE_ENUM.FS.ordinal()).append(","); //NON-NLS
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.CARVED.ordinal()).append(",");
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.DERIVED.ordinal()).append(",");
if (!UserPreferences.hideSlackFilesInViewsTree()) {
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK.ordinal()).append(",");
}
allDistinctMimeTypesQuery.append(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL.ordinal()).append("))");
synchronized (existingMimeTypes) {
existingMimeTypes.clear();
if (skCase == null) {
return;
}
try (SleuthkitCase.CaseDbQuery dbQuery = skCase.executeQuery(allDistinctMimeTypesQuery.toString())) {
ResultSet resultSet = dbQuery.getResultSet();
while (resultSet.next()) {
final String mime_type = resultSet.getString("mime_type"); //NON-NLS
if (!mime_type.isEmpty()) {
String mimeType[] = mime_type.split("/");
if (!mimeType[0].isEmpty() && !mimeType[1].isEmpty()) {
if (!existingMimeTypes.containsKey(mimeType[0])) {
existingMimeTypes.put(mimeType[0], new ArrayList<>());
}
existingMimeTypes.get(mimeType[0]).add(mimeType[1]);
}
}
}
} catch (TskCoreException | SQLException ex) {
LOGGER.log(Level.SEVERE, "Unable to populate File Types by MIME Type tree view from DB: ", ex); //NON-NLS
}
}
setChanged();
notifyObservers();
}
FileTypesByMimeType(SleuthkitCase skCase) {
IngestManager.getInstance().addIngestJobEventListener(pcl);
Case.addPropertyChangeListener(pcl);
this.skCase = skCase;
populateHashMap();
}
@Override
public <T> T accept(AutopsyItemVisitor<T> v) {
return v.visit(this);
}
/**
* Method to check if the node in question is a ByMimeTypeNode which is
* empty.
*
* @param node the Node which you wish to check.
*
* @return True if originNode is an instance of ByMimeTypeNode and is empty,
* false otherwise.
*/
public static boolean isEmptyMimeTypeNode(Node node) {
boolean isEmptyMimeNode = false;
if (node instanceof FileTypesByMimeType.ByMimeTypeNode && ((FileTypesByMimeType.ByMimeTypeNode) node).isEmpty()) {
isEmptyMimeNode = true;
}
return isEmptyMimeNode;
}
/**
* Class which represents the root node of the "By MIME Type" tree, will
* have children of each media type present in the database or no children
* when the file detection module has not been run and MIME type is
* currently unknown.
*/
class ByMimeTypeNode extends DisplayableItemNode {
@NbBundle.Messages("FileTypesByMimeType.name.text=By MIME Type")
final String NAME = Bundle.FileTypesByMimeType_name_text();
ByMimeTypeNode() {
super(Children.create(new ByMimeTypeNodeChildren(), true));
super.setName(NAME);
super.setDisplayName(NAME);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png");
}
@Override
public boolean isLeafTypeNode() {
return false;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
boolean isEmpty() {
return existingMimeTypes.isEmpty();
}
}
/**
* Creates the children for the "By MIME Type" node these children will each
* represent a distinct media type present in the DB
*/
private class ByMimeTypeNodeChildren extends ChildFactory<String> implements Observer {
private ByMimeTypeNodeChildren() {
super();
addObserver(this);
}
@Override
protected boolean createKeys(List<String> mediaTypeNodes) {
if (!existingMimeTypes.isEmpty()) {
mediaTypeNodes.addAll(getMediaTypeList());
}
return true;
}
@Override
protected Node createNodeForKey(String key) {
return new MediaTypeNode(key);
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
}
/**
* The Media type node created by the ByMimeTypeNodeChildren and contains
* one of the unique media types present in the database for this case.
*/
class MediaTypeNode extends DisplayableItemNode {
MediaTypeNode(String name) {
super(Children.create(new MediaTypeNodeChildren(name), true));
setName(name);
setDisplayName(name);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file_types.png");
}
@Override
public boolean isLeafTypeNode() {
return false;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
}
/**
* Creates children for media type nodes, children will be MediaSubTypeNodes
* and represent one of the subtypes which are present in the database of
* their media type.
*/
private class MediaTypeNodeChildren extends ChildFactory<String> implements Observer {
String mediaType;
MediaTypeNodeChildren(String name) {
addObserver(this);
this.mediaType = name;
}
@Override
protected boolean createKeys(List<String> mediaTypeNodes) {
mediaTypeNodes.addAll(existingMimeTypes.get(mediaType));
return true;
}
@Override
protected Node createNodeForKey(String subtype) {
String mimeType = mediaType + "/" + subtype;
return new MediaSubTypeNode(mimeType);
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
}
/**
* Node which represents the media sub type in the By MIME type tree, the
* media subtype is the portion of the MIME type following the /.
*/
class MediaSubTypeNode extends DisplayableItemNode implements Observer {
private MediaSubTypeNode(String mimeType) {
super(Children.create(new MediaSubTypeNodeChildren(mimeType), true));
addObserver(this);
init(mimeType);
}
private void init(String mimeType) {
super.setName(mimeType);
updateDisplayName(mimeType);
this.setIconBaseWithExtension("org/sleuthkit/autopsy/images/file-filter-icon.png"); //NON-NLS
}
/**
* Updates the display name of the mediaSubTypeNode to include the count
* of files which it represents.
*
* @param mimeType - the complete MimeType, needed for accurate query
* results
*/
private void updateDisplayName(String mimeType) {
final long count = new MediaSubTypeNodeChildren(mimeType).calculateItems(skCase, mimeType);
super.setDisplayName(mimeType.split("/")[1] + " (" + count + ")");
}
/**
* This returns true because any MediaSubTypeNode that exists is going
* to be a bottom level node in the Tree view on the left of Autopsy.
*
* @return true
*/
@Override
public boolean isLeafTypeNode() {
return true;
}
@Override
public <T> T accept(DisplayableItemNodeVisitor<T> v) {
return v.visit(this);
}
@Override
public String getItemType() {
return getClass().getName();
}
@Override
public void update(Observable o, Object arg) {
updateDisplayName(getName());
}
}
/**
* Factory for populating the contents of the Media Sub Type Node with the
* files that match MimeType which is represented by this position in the
* tree.
*/
private class MediaSubTypeNodeChildren extends ChildFactory.Detachable<Content> implements Observer {
private final String mimeType;
private MediaSubTypeNodeChildren(String mimeType) {
super();
addObserver(this);
this.mimeType = mimeType;
}
/**
* Get children count without actually loading all nodes
*
* @return count(*) - the number of items that will be shown in this
* items Directory Listing
*/
private long calculateItems(SleuthkitCase sleuthkitCase, String mime_type) {
try {
return sleuthkitCase.countFilesWhere(createQuery(mime_type));
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Error getting file search view count", ex); //NON-NLS
return 0;
}
}
/**
* Uses the createQuery method to complete the query, Select * from
* tsk_files WHERE. The results from the database will contain the files
* which match this mime type and their information.
*
* @param list - will contain all files and their attributes from the
* tsk_files table where mime_type matches the one specified
*
* @return true
*/
@Override
protected boolean createKeys(List<Content> list) {
try {
List<AbstractFile> files = skCase.findAllFilesWhere(createQuery(mimeType));
list.addAll(files);
} catch (TskCoreException ex) {
LOGGER.log(Level.SEVERE, "Couldn't get search results", ex); //NON-NLS
}
return true;
}
/**
* Create the portion of the query following WHERE for a query of the
* database for each file which matches the complete MIME type
* represented by this node. Matches against the mime_type column in
* tsk_files.
*
* @param mimeType - the complete mimetype of the file mediatype/subtype
*
* @return query.toString - portion of SQL query which will follow a
* WHERE clause.
*/
private String createQuery(String mime_type) {
StringBuilder query = new StringBuilder();
query.append("(dir_type = ").append(TskData.TSK_FS_NAME_TYPE_ENUM.REG.getValue()).append(")"); //NON-NLS
query.append(" AND (type IN (").append(TskData.TSK_DB_FILES_TYPE_ENUM.FS.ordinal()).append(","); //NON-NLS
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.CARVED.ordinal()).append(",");
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.DERIVED.ordinal()).append(",");
if (!UserPreferences.hideSlackFilesInViewsTree()) {
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.SLACK.ordinal()).append(",");
}
query.append(TskData.TSK_DB_FILES_TYPE_ENUM.LOCAL.ordinal()).append("))");
if (UserPreferences.hideKnownFilesInViewsTree()) {
query.append(" AND (known IS NULL OR known != ").append(TskData.FileKnown.KNOWN.getFileKnownValue()).append(")"); //NON-NLS
}
query.append(" AND mime_type = '").append(mime_type).append("'"); //NON-NLS
return query.toString();
}
@Override
public void update(Observable o, Object arg) {
refresh(true);
}
/**
* Creates the content to populate the Directory Listing Table view for
* each file
*
* @param key
*
* @return
*/
@Override
protected Node createNodeForKey(Content key) {
return key.accept(new ContentVisitor.Default<AbstractNode>() {
@Override
public FileNode visit(File f) {
return new FileNode(f, false);
}
@Override
public DirectoryNode visit(Directory d) {
return new DirectoryNode(d);
}
@Override
public LayoutFileNode visit(LayoutFile lf) {
return new LayoutFileNode(lf);
}
@Override
public LocalFileNode visit(DerivedFile df) {
return new LocalFileNode(df);
}
@Override
public LocalFileNode visit(LocalFile lf) {
return new LocalFileNode(lf);
}
@Override
public SlackFileNode visit(SlackFile sf) {
return new SlackFileNode(sf, false);
}
@Override
protected AbstractNode defaultVisit(Content di) {
throw new UnsupportedOperationException(NbBundle.getMessage(this.getClass(), "FileTypeChildren.exception.notSupported.msg", di.toString()));
}
});
}
}
}
| 2306 File Types Tree will no longer blow up and disappear with non standard mimeTypes
| Core/src/org/sleuthkit/autopsy/datamodel/FileTypesByMimeType.java | 2306 File Types Tree will no longer blow up and disappear with non standard mimeTypes | <ide><path>ore/src/org/sleuthkit/autopsy/datamodel/FileTypesByMimeType.java
<ide> final String mime_type = resultSet.getString("mime_type"); //NON-NLS
<ide> if (!mime_type.isEmpty()) {
<ide> String mimeType[] = mime_type.split("/");
<del> if (!mimeType[0].isEmpty() && !mimeType[1].isEmpty()) {
<add> //Note: Users are able to define custom mime types in Autopsy that do not
<add> //contain a "/" or possibly have multiple slashes
<add> if (mimeType.length > 1 && !mimeType[0].isEmpty() && !mimeType[1].isEmpty()) {
<ide> if (!existingMimeTypes.containsKey(mimeType[0])) {
<ide> existingMimeTypes.put(mimeType[0], new ArrayList<>());
<ide> } |
|
JavaScript | mit | 2669f9fdc26788e0148c2e3ffa6b55c537d791e0 | 0 | florinn/typemoq,florinn/typemoq,florinn/typemoq | var fs = require('fs');
module.exports = function (config) {
// Use ENV vars on Travis and sauce.json locally to get credentials
if (!process.env.SAUCE_USERNAME) {
if (!fs.existsSync('sauce.json')) {
console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
process.exit(1);
} else {
process.env.SAUCE_USERNAME = require('./sauce').username;
process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey;
}
}
// Browsers to run on Sauce Labs
var customLaunchers = {
'SL_Chrome': {
base: 'SauceLabs',
browserName: 'chrome'
},
'SL_Firefox': {
base: 'SauceLabs',
browserName: 'firefox'
},
'SL_IE_11': {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11'
},
'SL_Edge': {
base: 'SauceLabs',
browserName: 'microsoftedge'
},
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: ['./node_modules/lodash/lodash.js', './.tmp/src/typemoq.js', './.tmp/test/Mock.test.js', './.tmp/test/GlobalMock.test.js'],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'saucelabs'],
// web server port
port: 9876,
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
//sauceLabs: {
// testName: 'Karma and Sauce Labs demo'
//},
captureTimeout: 120000,
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
singleRun: true
});
};
| karma.conf-ci.js | var fs = require('fs');
module.exports = function (config) {
// Use ENV vars on Travis and sauce.json locally to get credentials
if (!process.env.SAUCE_USERNAME) {
if (!fs.existsSync('sauce.json')) {
console.log('Create a sauce.json with your credentials based on the sauce-sample.json file.');
process.exit(1);
} else {
process.env.SAUCE_USERNAME = require('./sauce').username;
process.env.SAUCE_ACCESS_KEY = require('./sauce').accessKey;
}
}
// Browsers to run on Sauce Labs
var customLaunchers = {
'SL_Chrome': {
base: 'SauceLabs',
browserName: 'chrome'
},
'SL_Firefox': {
base: 'SauceLabs',
browserName: 'firefox'
},
'SL_IE_9': {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9'
},
'SL_IE_10': {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '10'
},
'SL_IE_11': {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11'
},
'SL_Edge': {
base: 'SauceLabs',
browserName: 'microsoftedge'
},
};
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: ['./node_modules/lodash/lodash.js', './.tmp/src/typemoq.js', './.tmp/test/Mock.test.js', './.tmp/test/GlobalMock.test.js'],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'saucelabs'],
// web server port
port: 9876,
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
//sauceLabs: {
// testName: 'Karma and Sauce Labs demo'
//},
captureTimeout: 120000,
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
singleRun: true
});
};
| BREAKING CHANGE: drop support for IE9, IE10 due to missing Object.setPrototypeOf
| karma.conf-ci.js | BREAKING CHANGE: drop support for IE9, IE10 due to missing Object.setPrototypeOf | <ide><path>arma.conf-ci.js
<ide> 'SL_Firefox': {
<ide> base: 'SauceLabs',
<ide> browserName: 'firefox'
<del> },
<del> 'SL_IE_9': {
<del> base: 'SauceLabs',
<del> browserName: 'internet explorer',
<del> version: '9'
<del> },
<del> 'SL_IE_10': {
<del> base: 'SauceLabs',
<del> browserName: 'internet explorer',
<del> version: '10'
<ide> },
<ide> 'SL_IE_11': {
<ide> base: 'SauceLabs', |
|
Java | apache-2.0 | 29e7e9ba0a0a05601d81535f383ffb0b3f642fd8 | 0 | finmath/finmath-lib,finmath/finmath-lib | /*
* (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected].
*
* Created on 15.06.2016
*/
package net.finmath.montecarlo.assetderivativevaluation;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.montecarlo.AbstractRandomVariableFactory;
import net.finmath.montecarlo.BrownianMotion;
import net.finmath.montecarlo.RandomVariableFactory;
import net.finmath.montecarlo.assetderivativevaluation.products.DigitalOption;
import net.finmath.montecarlo.assetderivativevaluation.products.EuropeanOption;
import net.finmath.montecarlo.automaticdifferentiation.RandomVariableDifferentiableInterface;
import net.finmath.montecarlo.automaticdifferentiation.backward.RandomVariableDifferentiableAADFactory;
import net.finmath.montecarlo.model.AbstractModel;
import net.finmath.montecarlo.process.AbstractProcess;
import net.finmath.montecarlo.process.ProcessEulerScheme;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
/**
* @author Christian Fries
*
*/
public class MonteCarloBlackScholesModelDigitalOptionSensitivitiesTest {
// Model properties
private final double modelInitialValue = 1.0;
private final double modelRiskFreeRate = 0.05;
private final double modelVolatility = 0.30;
// Process discretization properties
private final int numberOfPaths = 1000000;
private final int numberOfTimeSteps = 10;
private final double deltaT = 0.5;
private final int seed = 31415;
// Product properties
private final int assetIndex = 0;
private final double optionMaturity = 2.0;
private final double optionStrike = 1.05;
@Test
public void testProductAADSensitivities() throws CalculationException {
RandomVariableDifferentiableAADFactory randomVariableFactory = new RandomVariableDifferentiableAADFactory(new RandomVariableFactory());
// Generate independent variables (quantities w.r.t. to which we like to differentiate)
RandomVariableDifferentiableInterface initialValue = randomVariableFactory.createRandomVariable(modelInitialValue);
RandomVariableDifferentiableInterface riskFreeRate = randomVariableFactory.createRandomVariable(modelRiskFreeRate);
RandomVariableDifferentiableInterface volatility = randomVariableFactory.createRandomVariable(modelVolatility);
// Create a model
AbstractModel model = new BlackScholesModel(initialValue, riskFreeRate, volatility, randomVariableFactory);
// Create a time discretization
TimeDiscretizationInterface timeDiscretization = new TimeDiscretization(0.0 /* initial */, numberOfTimeSteps, deltaT);
// Create a corresponding MC process
AbstractProcess process = new ProcessEulerScheme(new BrownianMotion(timeDiscretization, 1 /* numberOfFactors */, numberOfPaths, seed));
// Using the process (Euler scheme), create an MC simulation of a Black-Scholes model
AssetModelMonteCarloSimulationInterface monteCarloBlackScholesModel = new MonteCarloAssetModel(model, process);
/*
* Value a call option (using the product implementation)
*/
DigitalOption digitalOption = new DigitalOption(optionMaturity, optionStrike);
RandomVariableInterface value = (RandomVariableDifferentiableInterface) digitalOption.getValue(0.0, monteCarloBlackScholesModel);
/*
* Calculate sensitivities using AAD
*/
Map<Long, RandomVariableInterface> derivative = ((RandomVariableDifferentiableInterface)value).getGradient();
double valueMonteCarlo = value.getAverage();
double deltaAAD = derivative.get(initialValue.getID()).getAverage();
double rhoAAD = derivative.get(riskFreeRate.getID()).getAverage();
double vegaAAD = derivative.get(volatility.getID()).getAverage();
/*
* Calculate sensitivities using finite differences
*/
double eps = 1E-3;
double epsDelta = eps;
Map<String, Object> dataModifiedInitialValue = new HashMap<String, Object>();
dataModifiedInitialValue.put("initialValue", modelInitialValue+eps);
double deltaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedInitialValue)) - valueMonteCarlo)/epsDelta;
double epsRho = eps/100;
Map<String, Object> dataModifiedRiskFreeRate = new HashMap<String, Object>();
dataModifiedRiskFreeRate.put("riskFreeRate", modelRiskFreeRate+epsRho);
double rhoFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedRiskFreeRate)) - valueMonteCarlo)/epsRho ;
double epsVega = eps/10;
Map<String, Object> dataModifiedVolatility = new HashMap<String, Object>();
dataModifiedVolatility.put("volatility", modelVolatility+epsVega);
double vegaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedVolatility)) - valueMonteCarlo)/epsVega ;
/*
* Calculate sensitivities using analytic formulas
*/
double valueAnalytic = AnalyticFormulas.blackScholesDigitalOptionValue(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double deltaAnalytic = AnalyticFormulas.blackScholesDigitalOptionDelta(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double rhoAnalytic = AnalyticFormulas.blackScholesDigitalOptionRho(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double vegaAnalytic = AnalyticFormulas.blackScholesDigitalOptionVega(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
System.out.println("value using Monte-Carlo.......: " + valueMonteCarlo);
System.out.println("value using analytic formula..: " + valueAnalytic);
System.out.println("");
System.out.println("delta using adj. auto diff....: " + deltaAAD);
System.out.println("delta using finite differences: " + deltaFiniteDifference);
System.out.println("delta using analytic formula..: " + deltaAnalytic);
System.out.println("");
System.out.println("rho using adj. auto diff....: " + rhoAAD);
System.out.println("rho using finite differences: " + rhoFiniteDifference);
System.out.println("rho using analytic formula..: " + rhoAnalytic);
System.out.println("");
System.out.println("vega using Madj. auto diff...: " + vegaAAD);
System.out.println("vega using finite differences: " + vegaFiniteDifference);
System.out.println("vega using analytic formula..: " + vegaAnalytic);
System.out.println("");
// Assert.assertEquals(valueAnalytic, value, 0.005);
}
}
| src/test/java/net/finmath/montecarlo/assetderivativevaluation/MonteCarloBlackScholesModelDigitalOptionSensitivitiesTest.java | /*
* (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: [email protected].
*
* Created on 15.06.2016
*/
package net.finmath.montecarlo.assetderivativevaluation;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.montecarlo.AbstractRandomVariableFactory;
import net.finmath.montecarlo.BrownianMotion;
import net.finmath.montecarlo.RandomVariableFactory;
import net.finmath.montecarlo.assetderivativevaluation.products.DigitalOption;
import net.finmath.montecarlo.assetderivativevaluation.products.EuropeanOption;
import net.finmath.montecarlo.automaticdifferentiation.RandomVariableDifferentiableInterface;
import net.finmath.montecarlo.automaticdifferentiation.backward.RandomVariableDifferentiableAADFactory;
import net.finmath.montecarlo.model.AbstractModel;
import net.finmath.montecarlo.process.AbstractProcess;
import net.finmath.montecarlo.process.ProcessEulerScheme;
import net.finmath.stochastic.RandomVariableInterface;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationInterface;
/**
* @author Christian Fries
*
*/
public class MonteCarloBlackScholesModelDigitalOptionSensitivitiesTest {
// Model properties
private final double modelInitialValue = 1.0;
private final double modelRiskFreeRate = 0.05;
private final double modelVolatility = 0.30;
// Process discretization properties
private final int numberOfPaths = 20000;
private final int numberOfTimeSteps = 10;
private final double deltaT = 0.5;
private final int seed = 31415;
// Product properties
private final int assetIndex = 0;
private final double optionMaturity = 2.0;
private final double optionStrike = 1.05;
@Test
public void testProductAADSensitivities() throws CalculationException {
RandomVariableDifferentiableAADFactory randomVariableFactory = new RandomVariableDifferentiableAADFactory(new RandomVariableFactory());
// Generate independent variables (quantities w.r.t. to which we like to differentiate)
RandomVariableDifferentiableInterface initialValue = randomVariableFactory.createRandomVariable(modelInitialValue);
RandomVariableDifferentiableInterface riskFreeRate = randomVariableFactory.createRandomVariable(modelRiskFreeRate);
RandomVariableDifferentiableInterface volatility = randomVariableFactory.createRandomVariable(modelVolatility);
// Create a model
AbstractModel model = new BlackScholesModel(initialValue, riskFreeRate, volatility, randomVariableFactory);
// Create a time discretization
TimeDiscretizationInterface timeDiscretization = new TimeDiscretization(0.0 /* initial */, numberOfTimeSteps, deltaT);
// Create a corresponding MC process
AbstractProcess process = new ProcessEulerScheme(new BrownianMotion(timeDiscretization, 1 /* numberOfFactors */, numberOfPaths, seed));
// Using the process (Euler scheme), create an MC simulation of a Black-Scholes model
AssetModelMonteCarloSimulationInterface monteCarloBlackScholesModel = new MonteCarloAssetModel(model, process);
/*
* Value a call option (using the product implementation)
*/
DigitalOption digitalOption = new DigitalOption(optionMaturity, optionStrike);
RandomVariableInterface value = (RandomVariableDifferentiableInterface) digitalOption.getValue(0.0, monteCarloBlackScholesModel);
/*
* Calculate sensitivities using AAD
*/
Map<Long, RandomVariableInterface> derivative = ((RandomVariableDifferentiableInterface)value).getGradient();
double valueMonteCarlo = value.getAverage();
double deltaAAD = derivative.get(initialValue.getID()).getAverage();
double rhoAAD = derivative.get(riskFreeRate.getID()).getAverage();
double vegaAAD = derivative.get(volatility.getID()).getAverage();
/*
* Calculate sensitivities using finite differences
*/
double eps = 1E-3;
Map<String, Object> dataModifiedInitialValue = new HashMap<String, Object>();
dataModifiedInitialValue.put("initialValue", modelInitialValue+eps);
double deltaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedInitialValue)) - valueMonteCarlo)/eps ;
Map<String, Object> dataModifiedRiskFreeRate = new HashMap<String, Object>();
dataModifiedRiskFreeRate.put("riskFreeRate", modelRiskFreeRate+eps);
double rhoFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedRiskFreeRate)) - valueMonteCarlo)/eps ;
Map<String, Object> dataModifiedVolatility = new HashMap<String, Object>();
dataModifiedVolatility.put("volatility", modelVolatility+eps);
double vegaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedVolatility)) - valueMonteCarlo)/eps ;
/*
* Calculate sensitivities using analytic formulas
*/
double valueAnalytic = AnalyticFormulas.blackScholesDigitalOptionValue(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double deltaAnalytic = AnalyticFormulas.blackScholesDigitalOptionDelta(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double rhoAnalytic = Double.NaN;//AnalyticFormulas.blackScholesDigitalOptionRho(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
double vegaAnalytic = Double.NaN;//AnalyticFormulas.blackScholesDigitalOptionVega(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
System.out.println("value using Monte-Carlo.......: " + valueMonteCarlo);
System.out.println("value using analytic formula..: " + valueAnalytic);
System.out.println("");
System.out.println("delta using adj. auto diff....: " + deltaAAD);
System.out.println("delta using finite differences: " + deltaFiniteDifference);
System.out.println("delta using analytic formula..: " + deltaAnalytic);
System.out.println("");
System.out.println("rho using adj. auto diff....: " + rhoAAD);
System.out.println("rho using finite differences: " + rhoFiniteDifference);
System.out.println("rho using analytic formula..: " + rhoAnalytic);
System.out.println("");
System.out.println("vega using Madj. auto diff...: " + vegaAAD);
System.out.println("vega using finite differences: " + vegaFiniteDifference);
System.out.println("vega using analytic formula..: " + vegaAnalytic);
System.out.println("");
// Assert.assertEquals(valueAnalytic, value, 0.005);
}
}
| Added benchmark for rho and vega. | src/test/java/net/finmath/montecarlo/assetderivativevaluation/MonteCarloBlackScholesModelDigitalOptionSensitivitiesTest.java | Added benchmark for rho and vega. | <ide><path>rc/test/java/net/finmath/montecarlo/assetderivativevaluation/MonteCarloBlackScholesModelDigitalOptionSensitivitiesTest.java
<ide> private final double modelVolatility = 0.30;
<ide>
<ide> // Process discretization properties
<del> private final int numberOfPaths = 20000;
<add> private final int numberOfPaths = 1000000;
<ide> private final int numberOfTimeSteps = 10;
<ide> private final double deltaT = 0.5;
<ide>
<ide>
<ide> double eps = 1E-3;
<ide>
<add> double epsDelta = eps;
<ide> Map<String, Object> dataModifiedInitialValue = new HashMap<String, Object>();
<ide> dataModifiedInitialValue.put("initialValue", modelInitialValue+eps);
<del> double deltaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedInitialValue)) - valueMonteCarlo)/eps ;
<add> double deltaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedInitialValue)) - valueMonteCarlo)/epsDelta;
<ide>
<add> double epsRho = eps/100;
<ide> Map<String, Object> dataModifiedRiskFreeRate = new HashMap<String, Object>();
<del> dataModifiedRiskFreeRate.put("riskFreeRate", modelRiskFreeRate+eps);
<del> double rhoFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedRiskFreeRate)) - valueMonteCarlo)/eps ;
<add> dataModifiedRiskFreeRate.put("riskFreeRate", modelRiskFreeRate+epsRho);
<add> double rhoFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedRiskFreeRate)) - valueMonteCarlo)/epsRho ;
<ide>
<add> double epsVega = eps/10;
<ide> Map<String, Object> dataModifiedVolatility = new HashMap<String, Object>();
<del> dataModifiedVolatility.put("volatility", modelVolatility+eps);
<del> double vegaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedVolatility)) - valueMonteCarlo)/eps ;
<add> dataModifiedVolatility.put("volatility", modelVolatility+epsVega);
<add> double vegaFiniteDifference = (digitalOption.getValue(monteCarloBlackScholesModel.getCloneWithModifiedData(dataModifiedVolatility)) - valueMonteCarlo)/epsVega ;
<ide>
<ide> /*
<ide> * Calculate sensitivities using analytic formulas
<ide> */
<ide> double valueAnalytic = AnalyticFormulas.blackScholesDigitalOptionValue(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<ide> double deltaAnalytic = AnalyticFormulas.blackScholesDigitalOptionDelta(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<del> double rhoAnalytic = Double.NaN;//AnalyticFormulas.blackScholesDigitalOptionRho(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<del> double vegaAnalytic = Double.NaN;//AnalyticFormulas.blackScholesDigitalOptionVega(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<add> double rhoAnalytic = AnalyticFormulas.blackScholesDigitalOptionRho(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<add> double vegaAnalytic = AnalyticFormulas.blackScholesDigitalOptionVega(modelInitialValue, modelRiskFreeRate, modelVolatility, optionMaturity, optionStrike);
<ide>
<ide> System.out.println("value using Monte-Carlo.......: " + valueMonteCarlo);
<ide> System.out.println("value using analytic formula..: " + valueAnalytic); |
|
JavaScript | mit | 360d4b6df9eb05333b66e31278f126493092d667 | 0 | nchelluri/qsutil,nchelluri/qsutil | var QsUtil = (function() {
var queryStringParams = function(queryString) {
var params = {};
if (queryString.length == 0) {
return params;
}
var indicatorIndex = queryString.indexOf('?');
if (indicatorIndex !== -1) {
queryString = queryString.slice(indicatorIndex + 1);
}
if (queryString.indexOf('=') !== -1) {
queryString.split('&').forEach(function(val) {
var param = val.split('=');
var key = decodeURIComponent(param[0]);
var value = decodeURIComponent(param[1]);
if (key.slice(-2) == '[]') {
key = key.slice(0, -2);
if (Array.isArray(params[key])) {
params[key].push(value);
} else {
params[key] = [value];
}
} else {
params[key] = value;
}
});
}
return params;
};
var buildQueryString = function(params) {
var queryString = '?';
Object.keys(params).forEach(function(key) {
if (Array.isArray(params[key])) {
params[key].forEach(function(value) {
queryString += encodeURIComponent(key + '[]') + '=' + encodeURIComponent(value) + '&';
});
} else {
queryString += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
}
});
if(queryString[queryString.length - 1] == '&') {
queryString = queryString.slice(0, -1);
}
return queryString;
};
var updateQueryString = function(url, params) {
var queryString = buildQueryString(params);
var indicatorIndex = url.indexOf('?');
if (indicatorIndex !== -1) {
url = url.substring(0, indicatorIndex);
}
return url + queryString;
};
// TODO: Find a way to test this.
var replaceLocation = function(url) {
window.history.replaceState({}, '', url);
};
return {
queryStringParams: queryStringParams,
buildQueryString: buildQueryString,
updateQueryString: updateQueryString,
replaceLocation: replaceLocation
};
}());
| qsutil.js | var QsUtil = (function() {
var queryStringParams = function(queryString) {
var params = {};
if (queryString.length == 0) {
return params;
}
var indicatorIndex = queryString.indexOf('?');
if (indicatorIndex !== -1) {
queryString = queryString.slice(indicatorIndex + 1);
}
if (queryString.indexOf('=') !== -1) {
queryString.split('&').forEach(function(val) {
var param = val.split('=');
var key = decodeURIComponent(param[0]);
var value = decodeURIComponent(param[1]);
if (key.slice(-2) == '[]') {
key = key.slice(0, -2);
if (Array.isArray(params[key])) {
params[key].push(value);
} else {
params[key] = [value];
}
} else {
params[key] = value;
}
});
}
return params;
};
var buildQueryString = function(params) {
var queryString = '?';
Object.keys(params).forEach(function(key) {
if (Array.isArray(params[key])) {
params[key].forEach(function(value) {
queryString += encodeURIComponent(key + '[]') + '=' + encodeURIComponent(value) + '&';
});
} else {
queryString += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&';
}
});
if(queryString[queryString.length - 1] == '&') {
queryString = queryString.slice(0, -1);
}
return queryString;
};
var updateQueryString = function(url, params) {
var queryString = buildQueryString(params);
var indicatorIndex = url.indexOf('?');
if (indicatorIndex !== -1) {
url = url.substring(0, indicatorIndex);
}
return url + queryString;
};
var replaceLocation = function(url) {
window.history.replaceState({}, '', url);
};
return {
queryStringParams: queryStringParams,
buildQueryString: buildQueryString,
updateQueryString: updateQueryString,
replaceLocation: replaceLocation
};
}());
| Added TODO
| qsutil.js | Added TODO | <ide><path>sutil.js
<ide> return url + queryString;
<ide> };
<ide>
<add> // TODO: Find a way to test this.
<ide> var replaceLocation = function(url) {
<ide> window.history.replaceState({}, '', url);
<ide> }; |
|
JavaScript | mit | 270c2960b2379634a32aad7a2b73c3cb6dbf8867 | 0 | aaroncox/chainbb,aaroncox/chainbb | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux'
import { Button, Grid, Header, Icon, Menu, Message, Segment, Table } from 'semantic-ui-react'
import * as accountActions from '../../actions/accountActions'
import * as forumActions from '../../actions/forumActions'
import * as statusActions from '../../actions/statusActions'
import * as preferenceActions from '../../actions/preferenceActions'
import ForumCreateButton from './create/button'
class ForumCreate extends React.Component {
render() {
return(
<div>
<Segment textAlign='center' padded='very' color='blue'>
<Header as='h2'>
Choose what type of forum you'd like to create
<Header.Subheader>
Select which chainBB forum package that fits the needs of this new community.
</Header.Subheader>
</Header>
</Segment>
<Message
content='The pricing below is subject to change as more features become available and as chainBB leaves beta.'
header='Beta Price Availability'
icon='hourglass start'
info
/>
<Table definition celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Basic Forum
</Header>
</Table.HeaderCell>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Moderated Forum
</Header>
</Table.HeaderCell>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Premium Forum
</Header>
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>Price</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
1 STEEM
<Header.Subheader>
one time
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
50 STEEM
<Header.Subheader>
per year
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
250 STEEM
<Header.Subheader>
per year
</Header.Subheader>
</Header>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Hosting
<Header.Subheader>
Hosted on chainBB.com
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Unique URL
<Header.Subheader>
chainbb.com/f/<strong>forum-name</strong>
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Moderation
<Header.Subheader>
Tools to let you keep the forum free of spam and on-topic.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
{/* <Table.Row>
<Table.Cell>
<Header>
Subforums
<Header.Subheader>
Additional subforums within the main forum.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
2
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
5
</Header>
</Table.Cell>
</Table.Row> */}
<Table.Row>
<Table.Cell>
<Header>
Beneficiary Rewards
<Header.Subheader>
Earn a portion of rewards from evert post in this forum.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
5%
</Header>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
account: state.account,
forum: state.forum,
preferences: state.preferences,
status: state.status
}
}
function mapDispatchToProps(dispatch) {
return {actions: bindActionCreators({
...accountActions,
...forumActions,
...preferenceActions,
...statusActions,
}, dispatch)}
}
export default connect(mapStateToProps, mapDispatchToProps)(ForumCreate);
| services/frontend/src/containers/forum/create.js | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux'
import { Button, Grid, Header, Icon, Menu, Message, Segment, Table } from 'semantic-ui-react'
import * as accountActions from '../../actions/accountActions'
import * as forumActions from '../../actions/forumActions'
import * as statusActions from '../../actions/statusActions'
import * as preferenceActions from '../../actions/preferenceActions'
import ForumCreateButton from './create/button'
class ForumCreate extends React.Component {
render() {
return(
<div>
<Segment textAlign='center' padded='very' color='blue'>
<Header as='h2'>
Choose what type of forum you'd like to create
<Header.Subheader>
Select which chainBB forum package that fits the needs of this new community.
</Header.Subheader>
</Header>
</Segment>
<Message
content='The pricing below is subject to change as more features become available and as chainBB leaves beta.'
header='Beta Price Availability'
icon='hourglass start'
info
/>
<Table definition celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell/>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Basic Forum
</Header>
</Table.HeaderCell>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Moderated Forum
</Header>
</Table.HeaderCell>
<Table.HeaderCell width={4}>
<Header textAlign='center'>
Premium Forum
</Header>
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>Price</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
1 STEEM
<Header.Subheader>
one time
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
50 STEEM
<Header.Subheader>
per year
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center' verticalAlign='top'>
<Header>
250 STEEM
<Header.Subheader>
per year
</Header.Subheader>
</Header>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Hosting
<Header.Subheader>
Hosted on chainBB.com
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Unique URL
<Header.Subheader>
chainbb.com/f/<strong>forum-name</strong>
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Moderation
<Header.Subheader>
Tools to let you keep the forum free of spam and on-topic.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
<Table.Cell textAlign='center'>
<Icon size='big' name='checkmark box' color='green' />
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Subforums
<Header.Subheader>
Additional subforums within the main forum.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
2
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
5
</Header>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
<Header>
Beneficiary Rewards
<Header.Subheader>
Earn a portion of rewards from evert post in this forum.
</Header.Subheader>
</Header>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
</Table.Cell>
<Table.Cell textAlign='center'>
<Header color='black'>
5%
</Header>
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
<Table.Cell textAlign='center'>
<ForumCreateButton />
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
</div>
);
}
}
function mapStateToProps(state, ownProps) {
return {
account: state.account,
forum: state.forum,
preferences: state.preferences,
status: state.status
}
}
function mapDispatchToProps(dispatch) {
return {actions: bindActionCreators({
...accountActions,
...forumActions,
...preferenceActions,
...statusActions,
}, dispatch)}
}
export default connect(mapStateToProps, mapDispatchToProps)(ForumCreate);
| Remove subforums row (not available in MVP)
| services/frontend/src/containers/forum/create.js | Remove subforums row (not available in MVP) | <ide><path>ervices/frontend/src/containers/forum/create.js
<ide> <Icon size='big' name='checkmark box' color='green' />
<ide> </Table.Cell>
<ide> </Table.Row>
<del> <Table.Row>
<add> {/* <Table.Row>
<ide> <Table.Cell>
<ide> <Header>
<ide> Subforums
<ide> 5
<ide> </Header>
<ide> </Table.Cell>
<del> </Table.Row>
<add> </Table.Row> */}
<ide> <Table.Row>
<ide> <Table.Cell>
<ide> <Header> |
|
JavaScript | mit | 7a370fb56cc9a67356d005877eca1ea7f7d066f9 | 0 | shrikrishnaholla/nptel-micronotes | var mysql = require('mysql');
var crypto = require('crypto');
var salt = 'F%^$heFTY#r4y&^#@T%VVgu^T&*yh7tw78Tyug76R&^FGYUt76t%^fh';
function md5(s) {
var hash = crypto.createHash('md5').update(s).digest('hex');
return hash;
}
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'resistant'
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
connection.query('USE nptel', function(err) {
if (err) {
console.log(err);
}
});
exports.login = function(req, callback) {
var usn = req.body.usn
, passwd = req.body.password;
var query = connection.query('SELECT * FROM users WHERE USN='+mysql.escape(usn.toUpperCase()), function(err, rows) {
var user={};
var flag = true;
var gerr;
if(err) {
gerr = err;
}
else {
var hashedpwd = md5(passwd+salt);
// console.log(hashedpwd);
if (rows && rows.length && rows.length === 1) {
//console.log('asd');
if (rows[0].password === hashedpwd) {
//console.log('dhgf');
user = {name:rows[0].name, usn:rows[0].USN};
console.log(user);
flag = false;
}
else {
gerr = 'wrong password';
}
}
else {
gerr = 'wrong creds';
}
}
if (!flag){
console.log(user);
req.session.user = user;
req.session.isLoggedin = 1;
callback(gerr);
}
else {
req.session.isLoggedin = 0;
callback();
}});
//callback({'failed':true});
}
| models/login_user.js | var mysql = require('mysql');
var crypto = require('crypto');
var salt = 'F%^$heFTY#r4y&^#@T%VVgu^T&*yh7tw78Tyug76R&^FGYUt76t%^fh';
function md5(s) {
var hash = crypto.createHash('md5').update(s).digest('hex');
return hash;
}
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'resistant'
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
connection.query('USE nptel', function(err) {
if (err) {
console.log(err);
}
});
exports.login = function(req, callback) {
var usn = req.body.usn
, passwd = req.body.password;
var details;
var flag = true;
var gerr;
connection.query('SELECT * FROM users WHERE USN='+mysql.escape(usn.toUpperCase()), function(err, rows) {
if(err) {
gerr = err;
}
else {
var hashedpwd = md5(passwd+salt);
console.log(hashedpwd);
if (rows && rows.length && rows.length === 1) {
console.log('asd');
if (rows[0].password === hashedpwd) {
console.log('dhgf');
req.session.isLoggedin = true;
req.session.user = {name:rows[0].name, usn:rows[0].usn};
flag = false;
}
else {
gerr = 'wrong password';
}
}
else {
gerr = 'wrong creds';
}
}
});
if (flag){
req.session.isLoggedin = true;
callback(gerr);
}
else {
req.session.isLoggedin = false;
callback();
}
//callback({'failed':true});
}
| Fix bugs in setting user session while logging in
| models/login_user.js | Fix bugs in setting user session while logging in | <ide><path>odels/login_user.js
<ide> exports.login = function(req, callback) {
<ide> var usn = req.body.usn
<ide> , passwd = req.body.password;
<del> var details;
<del> var flag = true;
<del> var gerr;
<del> connection.query('SELECT * FROM users WHERE USN='+mysql.escape(usn.toUpperCase()), function(err, rows) {
<add>
<add> var query = connection.query('SELECT * FROM users WHERE USN='+mysql.escape(usn.toUpperCase()), function(err, rows) {
<add> var user={};
<add> var flag = true;
<add> var gerr;
<ide> if(err) {
<ide> gerr = err;
<ide> }
<ide> else {
<ide> var hashedpwd = md5(passwd+salt);
<del> console.log(hashedpwd);
<add> // console.log(hashedpwd);
<ide> if (rows && rows.length && rows.length === 1) {
<del> console.log('asd');
<del> if (rows[0].password === hashedpwd) {
<del> console.log('dhgf');
<del> req.session.isLoggedin = true;
<del> req.session.user = {name:rows[0].name, usn:rows[0].usn};
<del> flag = false;
<del> }
<del> else {
<del> gerr = 'wrong password';
<del> }
<add>
<add> //console.log('asd');
<add> if (rows[0].password === hashedpwd) {
<add>
<add> //console.log('dhgf');
<add>
<add> user = {name:rows[0].name, usn:rows[0].USN};
<add> console.log(user);
<add> flag = false;
<add> }
<add> else {
<add> gerr = 'wrong password';
<add> }
<ide> }
<ide> else {
<ide> gerr = 'wrong creds';
<ide> }
<ide> }
<del> });
<del> if (flag){
<del> req.session.isLoggedin = true;
<del> callback(gerr);
<del> }
<del> else {
<del> req.session.isLoggedin = false;
<del> callback();
<del> }
<add>
<add> if (!flag){
<add> console.log(user);
<add> req.session.user = user;
<add> req.session.isLoggedin = 1;
<add> callback(gerr);
<add> }
<add> else {
<add> req.session.isLoggedin = 0;
<add> callback();
<add> }});
<ide> //callback({'failed':true});
<ide> } |
|
JavaScript | unknown | 85fdf9fc811228cf2048317b686706be94103dd5 | 0 | MikeBull94/zoom.ts,michaelbull/zoom.ts,michaelbull/zoom.ts,MikeBull94/zoom.ts,MikeBull94/zoom.ts | /*!
* zoom.ts v6.0.0
* https://www.michael-bull.com/projects/zoom.ts
*
* Copyright (c) 2017 Michael Bull (https://www.michael-bull.com)
* @license ISC
*/
!function(t){function e(i){if(n[i])return n[i].exports;var o=n[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="dist/",e(e.s=12)}([function(t,e,n){"use strict";function i(t){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){return t()}):t()}function o(){return(document.documentElement||document.body).clientWidth}function r(){return(document.documentElement||document.body).clientHeight}function s(){return void 0===window.pageYOffset?(document.documentElement||document.body).scrollTop:window.pageYOffset}Object.defineProperty(e,"__esModule",{value:!0}),e.ready=i,e.viewportWidth=o,e.viewportHeight=r,e.scrollY=s},function(t,e,n){"use strict";function i(t){t.offsetHeight}function o(t,e){var i=n(10);return i?"translate3d("+t+"px, "+e+"px, 0)":"translate("+t+"px, "+e+"px)"}function r(t){var e=t.getBoundingClientRect();return new u.Dimension(e.left,e.top,t.clientWidth,t.clientHeight)}function s(t,e){var i=n(9);if(i)for(var o=0,r=f;o<r.length;o++){var s=r[o];t.addEventListener(s,e)}else e(new Event(f[0]))}function a(t,e){for(var n=0,i=f;n<i.length;n++){var o=i[n];t.removeEventListener(o,e)}}function c(t){var e=t.parentElement;if(null!==e){var n=e.getAttribute("data-src");if(null!==n)return n}return t.src}function l(t,e){var n=Number(t.getAttribute("data-width")||1/0),i=Number(t.getAttribute("data-height")||1/0),o=Math.min(d.viewportWidth(),n)/e.width,r=Math.min(d.viewportHeight(),i)/e.height;return Math.min(o,r)}Object.defineProperty(e,"__esModule",{value:!0});var u=n(5),d=n(0),f=["transitionend","webkitTransitionEnd","oTransitionEnd","MSTransitionEnd"];e.repaint=i,e.translate=o,e.dimensions=r,e.addTransitionEndListener=s,e.removeTransitionEndListener=a,e.srcAttribute=c,e.fillViewportScale=l},function(t,e){for(var n,i=["webkitTransform","MozTransform","msTransform","OTransform","transform"],o=document.createElement("p"),r=0;r<i.length;r++)if(n=i[r],null!=o.style[n]){t.exports=n;break}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),o=n(6),r=n(2),s=function(){function t(){var t=this;this.overlay=document.createElement("div"),this.clickListener=function(e){var n=e.target;n instanceof HTMLImageElement&&n.classList.contains("zoom__element")&&(e.preventDefault(),!r||e.metaKey||e.ctrlKey?window.open(i.srcAttribute(n),"_blank"):t.zoom(n))}}return t.prototype.start=function(){this.overlay.classList.add("zoom__overlay"),document.body.addEventListener("click",this.clickListener)},t.prototype.zoom=function(t){var e=t.parentElement;if(null!==e){var n=e.classList;if(n.contains("zoom")&&!n.contains("zoom--active")){var i=new o.Zoom(this.overlay,e,t);i.show()}}},t}();e.Listener=s},function(t,e,n){var i=n(7);"string"==typeof i&&(i=[[t.i,i,""]]);n(11)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e,n,i){this.left=t,this.top=e,this.width=n,this.height=i}return t}();e.Dimension=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),o=n(0),r=27,s=50,a=function(){function t(t,e,n){var a=this;this.transforming=!1,this.finishedExpandingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedExpandingContainer),a.container.style.transition="initial",a.transforming=!1,a.scaleContainer(),i.repaint(a.container),a.container.style.transition=""},this.finishedCollapsingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedCollapsingContainer),document.body.removeChild(a.overlay),a.container.classList.remove("zoom--active"),a.element.classList.remove("zoom__element--active"),a.removeClone()},this.finishedLoadingClone=function(){a.container.appendChild(a.clone),a.element.style.opacity="0"},this.resizeListener=function(){a.scaleContainer()},this.scrollListener=function(){Math.abs(a.initialScrollY-o.scrollY())>s&&a.hide()},this.clickListener=function(){a.hide()},this.keyboardListener=function(t){t.keyCode===r&&a.hide()},this.overlay=t,this.container=e,this.element=n,this.original=i.dimensions(n)}return t.prototype.show=function(){this.showOverlay(),this.expandContainer(),this.addClone(),this.addEventListeners()},t.prototype.hide=function(){this.removeEventListeners(),this.hideOverlay(),this.collapseContainer()},t.prototype.scaleContainer=function(){var t=i.fillViewportScale(this.container,this.original),e=this.original.width*t,n=this.original.height*t,r=(o.viewportWidth()-e)/2,s=(o.viewportHeight()-n)/2,a=this.original.left+(this.original.width-e)/2,c=this.original.top+(this.original.height-n)/2;if(this.transforming){var l=(r-a)/t,u=(s-c)/t;this.container.style.transform="scale("+t+") "+i.translate(l,u)}else this.container.style.transform="",this.container.style.left=r-this.original.left+"px",this.container.style.top=s-this.original.top+"px",this.container.style.width=e+"px",this.container.style.maxWidth=e+"px",this.container.style.height=n+"px"},t.prototype.showOverlay=function(){document.body.appendChild(this.overlay),i.repaint(this.overlay),this.overlay.classList.add("zoom__overlay--visible")},t.prototype.hideOverlay=function(){this.overlay.classList.remove("zoom__overlay--visible"),i.removeTransitionEndListener(this.container,this.finishedExpandingContainer)},t.prototype.expandContainer=function(){this.container.classList.add("zoom--active"),this.element.classList.add("zoom__element--active"),i.addTransitionEndListener(this.container,this.finishedExpandingContainer),this.transforming=!0,this.scaleContainer()},t.prototype.collapseContainer=function(){i.addTransitionEndListener(this.container,this.finishedCollapsingContainer),this.container.style.transition="initial",this.transforming=!0,this.scaleContainer(),i.repaint(this.container),this.container.style.transition="",this.container.style.transform="",this.container.style.left="",this.container.style.top="",this.container.style.width="",this.container.style.maxWidth="",this.container.style.height=""},t.prototype.addClone=function(){this.clone=document.createElement("img"),this.clone.classList.add("zoom__clone"),this.clone.addEventListener("load",this.finishedLoadingClone),this.clone.src=i.srcAttribute(this.element)},t.prototype.removeClone=function(){this.clone.removeEventListener("load",this.finishedLoadingClone),this.element.style.opacity="",this.container.contains(this.clone)&&this.container.removeChild(this.clone)},t.prototype.addEventListeners=function(){this.initialScrollY=o.scrollY(),window.addEventListener("resize",this.resizeListener),window.addEventListener("scroll",this.scrollListener),document.addEventListener("keyup",this.keyboardListener),this.container.addEventListener("click",this.clickListener)},t.prototype.removeEventListeners=function(){window.removeEventListener("resize",this.resizeListener),window.removeEventListener("scroll",this.scrollListener),document.removeEventListener("keyup",this.keyboardListener),this.container.removeEventListener("click",this.clickListener)},t}();e.Zoom=a},function(t,e,n){e=t.exports=n(8)(),e.push([t.i,'.zoom{position:relative;line-height:0;text-align:center;-webkit-transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1),-webkit-transform .3s cubic-bezier(.2,0,.2,1);will-change:transition}.zoom--active{z-index:2}.zoom__element{cursor:pointer;cursor:-moz-zoom-in;cursor:-webkit-zoom-in}.zoom__element--active{width:100%}.zoom__clone{position:absolute;cursor:pointer;cursor:-moz-zoom-out;cursor:-webkit-zoom-out}.zoom__clone,.zoom__overlay{top:0;right:0;bottom:0;left:0}.zoom__overlay{position:fixed;z-index:1;background:#fff;opacity:0;filter:"alpha(opacity=0)";-webkit-transition:opacity .3s;transition:opacity .3s;will-change:opacity,filter}.zoom__overlay--visible{opacity:1;filter:"alpha(opacity=100)"}',""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},o=0;o<this.length;o++){var r=this[o][0];"number"==typeof r&&(i[r]=!0)}for(o=0;o<e.length;o++){var s=e[o];"number"==typeof s[0]&&i[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),t.push(s))}},t}},function(t,e){function n(t){if(!i)return!1;if(!t)return null!=i;var e=getComputedStyle(t)[i];return""!==e&&0!==parseFloat(e)}for(var i,o=["transitionDuration","MozTransitionDuration","webkitTransitionDuration"];o.length;){var r=o.shift();r in document.body.style&&(i=r)}t.exports=n},function(t,e,n){var i=n(2);if(i&&window.getComputedStyle){var o={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"},r=document.createElement("div");r.style[i]="translate3d(1px,1px,1px)",document.body.insertBefore(r,null);var s=getComputedStyle(r).getPropertyValue(o[i]);document.body.removeChild(r),t.exports=null!=s&&s.length&&"none"!=s}else t.exports=!1},function(t,e){function n(t,e){for(var n=0;n<t.length;n++){var i=t[n],o=f[i.id];if(o){o.refs++;for(var r=0;r<o.parts.length;r++)o.parts[r](i.parts[r]);for(;r<i.parts.length;r++)o.parts.push(c(i.parts[r],e))}else{for(var s=[],r=0;r<i.parts.length;r++)s.push(c(i.parts[r],e));f[i.id]={id:i.id,refs:1,parts:s}}}}function i(t){for(var e=[],n={},i=0;i<t.length;i++){var o=t[i],r=o[0],s=o[1],a=o[2],c=o[3],l={css:s,media:a,sourceMap:c};n[r]?n[r].parts.push(l):e.push(n[r]={id:r,parts:[l]})}return e}function o(t,e){var n=m(),i=g[g.length-1];if("top"===t.insertAt)i?i.nextSibling?n.insertBefore(e,i.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function r(t){t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function s(t){var e=document.createElement("style");return e.type="text/css",o(t,e),e}function a(t){var e=document.createElement("link");return e.rel="stylesheet",o(t,e),e}function c(t,e){var n,i,o;if(e.singleton){var c=y++;n=v||(v=s(e)),i=l.bind(null,n,c,!1),o=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(e),i=d.bind(null,n),o=function(){r(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(e),i=u.bind(null,n),o=function(){r(n)});return i(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;i(t=e)}else o()}}function l(t,e,n,i){var o=n?"":i.css;if(t.styleSheet)t.styleSheet.cssText=b(e,o);else{var r=document.createTextNode(o),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(r,s[e]):t.appendChild(r)}}function u(t,e){var n=e.css,i=e.media;if(i&&t.setAttribute("media",i),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e){var n=e.css,i=e.sourceMap;i&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var o=new Blob([n],{type:"text/css"}),r=t.href;t.href=URL.createObjectURL(o),r&&URL.revokeObjectURL(r)}var f={},h=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},p=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,y=0,g=[];t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},"undefined"==typeof e.singleton&&(e.singleton=p()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var o=i(t);return n(o,e),function(t){for(var r=[],s=0;s<o.length;s++){var a=o[s],c=f[a.id];c.refs--,r.push(c)}if(t){var l=i(t);n(l,e)}for(var s=0;s<r.length;s++){var c=r[s];if(0===c.refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete f[c.id]}}}};var b=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(4);var i=n(0),o=n(3),r=new o.Listener;i.ready(function(){return r.start()})}]); | dist/zoom.js | /*!
* zoom.ts v6.0.0
* https://www.michael-bull.com/projects/zoom.ts
*
* Copyright (c) 2017 Michael Bull (https://www.michael-bull.com)
* @license ISC
*/
!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="dist/",e(e.s=12)}([function(t,e,n){"use strict";function i(t){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){return t()}):t()}function r(){return(document.documentElement||document.body).clientWidth}function o(){return(document.documentElement||document.body).clientHeight}function s(){return void 0===window.pageYOffset?(document.documentElement||document.body).scrollTop:window.pageYOffset}Object.defineProperty(e,"__esModule",{value:!0}),e.ready=i,e.viewportWidth=r,e.viewportHeight=o,e.scrollY=s},function(t,e,n){"use strict";function i(t){t.offsetHeight}function r(t,e){var i=n(10);return i?"translate3d("+t+"px, "+e+"px, 0)":"translate("+t+"px, "+e+"px)"}function o(t){var e=t.getBoundingClientRect();return new u.Dimension(e.left,e.top,t.clientWidth,t.clientHeight)}function s(t,e){var i=n(9);if(i)for(var r=0,o=f;r<o.length;r++){var s=o[r];t.addEventListener(s,e)}else e(new Event(f[0]))}function a(t,e){for(var n=0,i=f;n<i.length;n++){var r=i[n];t.removeEventListener(r,e)}}function c(t){var e=t.parentElement;if(null!==e){var n=e.getAttribute("data-src");if(null!==n)return n}return t.src}function l(t,e){var n=Number(t.getAttribute("data-width")||1/0),i=Number(t.getAttribute("data-height")||1/0),r=Math.min(d.viewportWidth(),n)/e.width,o=Math.min(d.viewportHeight(),i)/e.height;return Math.min(r,o)}Object.defineProperty(e,"__esModule",{value:!0});var u=n(5),d=n(0),f=["transitionend","webkitTransitionEnd","oTransitionEnd","MSTransitionEnd"];e.repaint=i,e.translate=r,e.dimensions=o,e.addTransitionEndListener=s,e.removeTransitionEndListener=a,e.srcAttribute=c,e.fillViewportScale=l},function(t,e){for(var n,i=["webkitTransform","MozTransform","msTransform","OTransform","transform"],r=document.createElement("p"),o=0;o<i.length;o++)if(n=i[o],null!=r.style[n]){t.exports=n;break}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=n(6),o=n(2),s=function(){function t(){var t=this;this.overlay=document.createElement("div"),this.clickListener=function(e){var n=e.target;n instanceof HTMLImageElement&&n.classList.contains("zoom__element")&&(e.preventDefault(),!o||e.metaKey||e.ctrlKey?window.open(i.srcAttribute(n),"_blank"):t.zoom(n))}}return t.prototype.start=function(){this.overlay.classList.add("zoom__overlay"),document.body.addEventListener("click",this.clickListener)},t.prototype.zoom=function(t){var e=t.parentElement;if(null!==e){var n=e.classList;if(n.contains("zoom")&&!n.contains("zoom--active")){var i=new r.Zoom(this.overlay,e,t);i.show()}}},t}();e.Listener=s},function(t,e,n){var i=n(7);"string"==typeof i&&(i=[[t.i,i,""]]);n(11)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e,n,i){this.left=t,this.top=e,this.width=n,this.height=i}return t}();e.Dimension=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=n(0),o=27,s=50,a=function(){function t(t,e,n){var a=this;this.transforming=!1,this.finishedExpandingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedExpandingContainer),a.container.style.transition="initial",a.transforming=!1,a.scaleContainer(),i.repaint(a.container),a.container.style.transition=""},this.finishedCollapsingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedCollapsingContainer),document.body.removeChild(a.overlay),a.element.style.opacity="",a.container.classList.remove("zoom--active"),a.removeClone()},this.resizeListener=function(){a.scaleContainer()},this.scrollListener=function(){Math.abs(a.initialScrollY-r.scrollY())>s&&a.hide()},this.clickListener=function(){a.hide()},this.keyboardListener=function(t){t.keyCode===o&&a.hide()},this.overlay=t,this.container=e,this.element=n,this.original=i.dimensions(n)}return t.prototype.show=function(){this.showOverlay(),this.expandContainer(),this.addClone(),this.addEventListeners()},t.prototype.hide=function(){this.removeEventListeners(),this.hideOverlay(),this.collapseContainer()},t.prototype.scaleContainer=function(){var t=i.fillViewportScale(this.container,this.original),e=this.original.width*t,n=this.original.height*t,o=(r.viewportWidth()-e)/2,s=(r.viewportHeight()-n)/2,a=this.original.left+(this.original.width-e)/2,c=this.original.top+(this.original.height-n)/2;if(this.transforming){var l=(o-a)/t,u=(s-c)/t;this.container.style.transform="scale("+t+") "+i.translate(l,u)}else this.container.style.transform="",this.container.style.left=o-this.original.left+"px",this.container.style.top=s-this.original.top+"px",this.container.style.width=e+"px",this.container.style.maxWidth=e+"px",this.container.style.height=n+"px"},t.prototype.showOverlay=function(){document.body.appendChild(this.overlay),i.repaint(this.overlay),this.overlay.classList.add("zoom__overlay--visible")},t.prototype.hideOverlay=function(){this.overlay.classList.remove("zoom__overlay--visible"),i.removeTransitionEndListener(this.container,this.finishedExpandingContainer)},t.prototype.expandContainer=function(){this.container.classList.add("zoom--active"),i.addTransitionEndListener(this.container,this.finishedExpandingContainer),this.transforming=!0,this.scaleContainer()},t.prototype.collapseContainer=function(){i.addTransitionEndListener(this.container,this.finishedCollapsingContainer),this.container.style.transition="initial",this.transforming=!0,this.scaleContainer(),i.repaint(this.container),this.container.style.transition="",this.container.style.transform="",this.container.style.left="",this.container.style.top="",this.container.style.width="",this.container.style.maxWidth="",this.container.style.height=""},t.prototype.addClone=function(){var t=this;this.clone=document.createElement("img"),this.clone.classList.add("zoom__clone"),this.clone.onload=function(){t.element.style.opacity="0",t.container.appendChild(t.clone)},this.clone.src=i.srcAttribute(this.element)},t.prototype.removeClone=function(){this.container.contains(this.clone)&&this.container.removeChild(this.clone)},t.prototype.addEventListeners=function(){this.initialScrollY=r.scrollY(),window.addEventListener("resize",this.resizeListener),window.addEventListener("scroll",this.scrollListener),document.addEventListener("keyup",this.keyboardListener),this.container.addEventListener("click",this.clickListener)},t.prototype.removeEventListeners=function(){window.removeEventListener("resize",this.resizeListener),window.removeEventListener("scroll",this.scrollListener),document.removeEventListener("keyup",this.keyboardListener),this.container.removeEventListener("click",this.clickListener)},t}();e.Zoom=a},function(t,e,n){e=t.exports=n(8)(),e.push([t.i,'.zoom{position:relative;line-height:0;text-align:center;-webkit-transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1),-webkit-transform .3s cubic-bezier(.2,0,.2,1);will-change:transition}.zoom--active{z-index:2}.zoom__element{cursor:pointer;cursor:-moz-zoom-in;cursor:-webkit-zoom-in}.zoom__clone{position:absolute;cursor:pointer;cursor:-moz-zoom-out;cursor:-webkit-zoom-out}.zoom__clone,.zoom__overlay{top:0;right:0;bottom:0;left:0}.zoom__overlay{position:fixed;z-index:1;background:#fff;opacity:0;filter:"alpha(opacity=0)";-webkit-transition:opacity .3s;transition:opacity .3s;will-change:opacity,filter}.zoom__overlay--visible{opacity:1;filter:"alpha(opacity=100)"}',""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},r=0;r<this.length;r++){var o=this[r][0];"number"==typeof o&&(i[o]=!0)}for(r=0;r<e.length;r++){var s=e[r];"number"==typeof s[0]&&i[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),t.push(s))}},t}},function(t,e){function n(t){if(!i)return!1;if(!t)return null!=i;var e=getComputedStyle(t)[i];return""!==e&&0!==parseFloat(e)}for(var i,r=["transitionDuration","MozTransitionDuration","webkitTransitionDuration"];r.length;){var o=r.shift();o in document.body.style&&(i=o)}t.exports=n},function(t,e,n){var i=n(2);if(i&&window.getComputedStyle){var r={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"},o=document.createElement("div");o.style[i]="translate3d(1px,1px,1px)",document.body.insertBefore(o,null);var s=getComputedStyle(o).getPropertyValue(r[i]);document.body.removeChild(o),t.exports=null!=s&&s.length&&"none"!=s}else t.exports=!1},function(t,e){function n(t,e){for(var n=0;n<t.length;n++){var i=t[n],r=f[i.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](i.parts[o]);for(;o<i.parts.length;o++)r.parts.push(c(i.parts[o],e))}else{for(var s=[],o=0;o<i.parts.length;o++)s.push(c(i.parts[o],e));f[i.id]={id:i.id,refs:1,parts:s}}}}function i(t){for(var e=[],n={},i=0;i<t.length;i++){var r=t[i],o=r[0],s=r[1],a=r[2],c=r[3],l={css:s,media:a,sourceMap:c};n[o]?n[o].parts.push(l):e.push(n[o]={id:o,parts:[l]})}return e}function r(t,e){var n=m(),i=g[g.length-1];if("top"===t.insertAt)i?i.nextSibling?n.insertBefore(e,i.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function o(t){t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function s(t){var e=document.createElement("style");return e.type="text/css",r(t,e),e}function a(t){var e=document.createElement("link");return e.rel="stylesheet",r(t,e),e}function c(t,e){var n,i,r;if(e.singleton){var c=y++;n=v||(v=s(e)),i=l.bind(null,n,c,!1),r=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(e),i=d.bind(null,n),r=function(){o(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(e),i=u.bind(null,n),r=function(){o(n)});return i(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;i(t=e)}else r()}}function l(t,e,n,i){var r=n?"":i.css;if(t.styleSheet)t.styleSheet.cssText=b(e,r);else{var o=document.createTextNode(r),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(o,s[e]):t.appendChild(o)}}function u(t,e){var n=e.css,i=e.media;if(i&&t.setAttribute("media",i),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e){var n=e.css,i=e.sourceMap;i&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var r=new Blob([n],{type:"text/css"}),o=t.href;t.href=URL.createObjectURL(r),o&&URL.revokeObjectURL(o)}var f={},h=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},p=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,y=0,g=[];t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},"undefined"==typeof e.singleton&&(e.singleton=p()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var r=i(t);return n(r,e),function(t){for(var o=[],s=0;s<r.length;s++){var a=r[s],c=f[a.id];c.refs--,o.push(c)}if(t){var l=i(t);n(l,e)}for(var s=0;s<o.length;s++){var c=o[s];if(0===c.refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete f[c.id]}}}};var b=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(4);var i=n(0),r=n(3),o=new r.Listener;i.ready(function(){return o.start()})}]); | Rebuild distribution
| dist/zoom.js | Rebuild distribution | <ide><path>ist/zoom.js
<ide> * Copyright (c) 2017 Michael Bull (https://www.michael-bull.com)
<ide> * @license ISC
<ide> */
<del>!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={i:i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,e),r.l=!0,r.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="dist/",e(e.s=12)}([function(t,e,n){"use strict";function i(t){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){return t()}):t()}function r(){return(document.documentElement||document.body).clientWidth}function o(){return(document.documentElement||document.body).clientHeight}function s(){return void 0===window.pageYOffset?(document.documentElement||document.body).scrollTop:window.pageYOffset}Object.defineProperty(e,"__esModule",{value:!0}),e.ready=i,e.viewportWidth=r,e.viewportHeight=o,e.scrollY=s},function(t,e,n){"use strict";function i(t){t.offsetHeight}function r(t,e){var i=n(10);return i?"translate3d("+t+"px, "+e+"px, 0)":"translate("+t+"px, "+e+"px)"}function o(t){var e=t.getBoundingClientRect();return new u.Dimension(e.left,e.top,t.clientWidth,t.clientHeight)}function s(t,e){var i=n(9);if(i)for(var r=0,o=f;r<o.length;r++){var s=o[r];t.addEventListener(s,e)}else e(new Event(f[0]))}function a(t,e){for(var n=0,i=f;n<i.length;n++){var r=i[n];t.removeEventListener(r,e)}}function c(t){var e=t.parentElement;if(null!==e){var n=e.getAttribute("data-src");if(null!==n)return n}return t.src}function l(t,e){var n=Number(t.getAttribute("data-width")||1/0),i=Number(t.getAttribute("data-height")||1/0),r=Math.min(d.viewportWidth(),n)/e.width,o=Math.min(d.viewportHeight(),i)/e.height;return Math.min(r,o)}Object.defineProperty(e,"__esModule",{value:!0});var u=n(5),d=n(0),f=["transitionend","webkitTransitionEnd","oTransitionEnd","MSTransitionEnd"];e.repaint=i,e.translate=r,e.dimensions=o,e.addTransitionEndListener=s,e.removeTransitionEndListener=a,e.srcAttribute=c,e.fillViewportScale=l},function(t,e){for(var n,i=["webkitTransform","MozTransform","msTransform","OTransform","transform"],r=document.createElement("p"),o=0;o<i.length;o++)if(n=i[o],null!=r.style[n]){t.exports=n;break}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=n(6),o=n(2),s=function(){function t(){var t=this;this.overlay=document.createElement("div"),this.clickListener=function(e){var n=e.target;n instanceof HTMLImageElement&&n.classList.contains("zoom__element")&&(e.preventDefault(),!o||e.metaKey||e.ctrlKey?window.open(i.srcAttribute(n),"_blank"):t.zoom(n))}}return t.prototype.start=function(){this.overlay.classList.add("zoom__overlay"),document.body.addEventListener("click",this.clickListener)},t.prototype.zoom=function(t){var e=t.parentElement;if(null!==e){var n=e.classList;if(n.contains("zoom")&&!n.contains("zoom--active")){var i=new r.Zoom(this.overlay,e,t);i.show()}}},t}();e.Listener=s},function(t,e,n){var i=n(7);"string"==typeof i&&(i=[[t.i,i,""]]);n(11)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e,n,i){this.left=t,this.top=e,this.width=n,this.height=i}return t}();e.Dimension=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),r=n(0),o=27,s=50,a=function(){function t(t,e,n){var a=this;this.transforming=!1,this.finishedExpandingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedExpandingContainer),a.container.style.transition="initial",a.transforming=!1,a.scaleContainer(),i.repaint(a.container),a.container.style.transition=""},this.finishedCollapsingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedCollapsingContainer),document.body.removeChild(a.overlay),a.element.style.opacity="",a.container.classList.remove("zoom--active"),a.removeClone()},this.resizeListener=function(){a.scaleContainer()},this.scrollListener=function(){Math.abs(a.initialScrollY-r.scrollY())>s&&a.hide()},this.clickListener=function(){a.hide()},this.keyboardListener=function(t){t.keyCode===o&&a.hide()},this.overlay=t,this.container=e,this.element=n,this.original=i.dimensions(n)}return t.prototype.show=function(){this.showOverlay(),this.expandContainer(),this.addClone(),this.addEventListeners()},t.prototype.hide=function(){this.removeEventListeners(),this.hideOverlay(),this.collapseContainer()},t.prototype.scaleContainer=function(){var t=i.fillViewportScale(this.container,this.original),e=this.original.width*t,n=this.original.height*t,o=(r.viewportWidth()-e)/2,s=(r.viewportHeight()-n)/2,a=this.original.left+(this.original.width-e)/2,c=this.original.top+(this.original.height-n)/2;if(this.transforming){var l=(o-a)/t,u=(s-c)/t;this.container.style.transform="scale("+t+") "+i.translate(l,u)}else this.container.style.transform="",this.container.style.left=o-this.original.left+"px",this.container.style.top=s-this.original.top+"px",this.container.style.width=e+"px",this.container.style.maxWidth=e+"px",this.container.style.height=n+"px"},t.prototype.showOverlay=function(){document.body.appendChild(this.overlay),i.repaint(this.overlay),this.overlay.classList.add("zoom__overlay--visible")},t.prototype.hideOverlay=function(){this.overlay.classList.remove("zoom__overlay--visible"),i.removeTransitionEndListener(this.container,this.finishedExpandingContainer)},t.prototype.expandContainer=function(){this.container.classList.add("zoom--active"),i.addTransitionEndListener(this.container,this.finishedExpandingContainer),this.transforming=!0,this.scaleContainer()},t.prototype.collapseContainer=function(){i.addTransitionEndListener(this.container,this.finishedCollapsingContainer),this.container.style.transition="initial",this.transforming=!0,this.scaleContainer(),i.repaint(this.container),this.container.style.transition="",this.container.style.transform="",this.container.style.left="",this.container.style.top="",this.container.style.width="",this.container.style.maxWidth="",this.container.style.height=""},t.prototype.addClone=function(){var t=this;this.clone=document.createElement("img"),this.clone.classList.add("zoom__clone"),this.clone.onload=function(){t.element.style.opacity="0",t.container.appendChild(t.clone)},this.clone.src=i.srcAttribute(this.element)},t.prototype.removeClone=function(){this.container.contains(this.clone)&&this.container.removeChild(this.clone)},t.prototype.addEventListeners=function(){this.initialScrollY=r.scrollY(),window.addEventListener("resize",this.resizeListener),window.addEventListener("scroll",this.scrollListener),document.addEventListener("keyup",this.keyboardListener),this.container.addEventListener("click",this.clickListener)},t.prototype.removeEventListeners=function(){window.removeEventListener("resize",this.resizeListener),window.removeEventListener("scroll",this.scrollListener),document.removeEventListener("keyup",this.keyboardListener),this.container.removeEventListener("click",this.clickListener)},t}();e.Zoom=a},function(t,e,n){e=t.exports=n(8)(),e.push([t.i,'.zoom{position:relative;line-height:0;text-align:center;-webkit-transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1),-webkit-transform .3s cubic-bezier(.2,0,.2,1);will-change:transition}.zoom--active{z-index:2}.zoom__element{cursor:pointer;cursor:-moz-zoom-in;cursor:-webkit-zoom-in}.zoom__clone{position:absolute;cursor:pointer;cursor:-moz-zoom-out;cursor:-webkit-zoom-out}.zoom__clone,.zoom__overlay{top:0;right:0;bottom:0;left:0}.zoom__overlay{position:fixed;z-index:1;background:#fff;opacity:0;filter:"alpha(opacity=0)";-webkit-transition:opacity .3s;transition:opacity .3s;will-change:opacity,filter}.zoom__overlay--visible{opacity:1;filter:"alpha(opacity=100)"}',""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},r=0;r<this.length;r++){var o=this[r][0];"number"==typeof o&&(i[o]=!0)}for(r=0;r<e.length;r++){var s=e[r];"number"==typeof s[0]&&i[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),t.push(s))}},t}},function(t,e){function n(t){if(!i)return!1;if(!t)return null!=i;var e=getComputedStyle(t)[i];return""!==e&&0!==parseFloat(e)}for(var i,r=["transitionDuration","MozTransitionDuration","webkitTransitionDuration"];r.length;){var o=r.shift();o in document.body.style&&(i=o)}t.exports=n},function(t,e,n){var i=n(2);if(i&&window.getComputedStyle){var r={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"},o=document.createElement("div");o.style[i]="translate3d(1px,1px,1px)",document.body.insertBefore(o,null);var s=getComputedStyle(o).getPropertyValue(r[i]);document.body.removeChild(o),t.exports=null!=s&&s.length&&"none"!=s}else t.exports=!1},function(t,e){function n(t,e){for(var n=0;n<t.length;n++){var i=t[n],r=f[i.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](i.parts[o]);for(;o<i.parts.length;o++)r.parts.push(c(i.parts[o],e))}else{for(var s=[],o=0;o<i.parts.length;o++)s.push(c(i.parts[o],e));f[i.id]={id:i.id,refs:1,parts:s}}}}function i(t){for(var e=[],n={},i=0;i<t.length;i++){var r=t[i],o=r[0],s=r[1],a=r[2],c=r[3],l={css:s,media:a,sourceMap:c};n[o]?n[o].parts.push(l):e.push(n[o]={id:o,parts:[l]})}return e}function r(t,e){var n=m(),i=g[g.length-1];if("top"===t.insertAt)i?i.nextSibling?n.insertBefore(e,i.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function o(t){t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function s(t){var e=document.createElement("style");return e.type="text/css",r(t,e),e}function a(t){var e=document.createElement("link");return e.rel="stylesheet",r(t,e),e}function c(t,e){var n,i,r;if(e.singleton){var c=y++;n=v||(v=s(e)),i=l.bind(null,n,c,!1),r=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(e),i=d.bind(null,n),r=function(){o(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(e),i=u.bind(null,n),r=function(){o(n)});return i(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;i(t=e)}else r()}}function l(t,e,n,i){var r=n?"":i.css;if(t.styleSheet)t.styleSheet.cssText=b(e,r);else{var o=document.createTextNode(r),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(o,s[e]):t.appendChild(o)}}function u(t,e){var n=e.css,i=e.media;if(i&&t.setAttribute("media",i),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e){var n=e.css,i=e.sourceMap;i&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var r=new Blob([n],{type:"text/css"}),o=t.href;t.href=URL.createObjectURL(r),o&&URL.revokeObjectURL(o)}var f={},h=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},p=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,y=0,g=[];t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},"undefined"==typeof e.singleton&&(e.singleton=p()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var r=i(t);return n(r,e),function(t){for(var o=[],s=0;s<r.length;s++){var a=r[s],c=f[a.id];c.refs--,o.push(c)}if(t){var l=i(t);n(l,e)}for(var s=0;s<o.length;s++){var c=o[s];if(0===c.refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete f[c.id]}}}};var b=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(4);var i=n(0),r=n(3),o=new r.Listener;i.ready(function(){return o.start()})}]);
<add>!function(t){function e(i){if(n[i])return n[i].exports;var o=n[i]={i:i,l:!1,exports:{}};return t[i].call(o.exports,o,o.exports,e),o.l=!0,o.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,i){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:i})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="dist/",e(e.s=12)}([function(t,e,n){"use strict";function i(t){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",function(){return t()}):t()}function o(){return(document.documentElement||document.body).clientWidth}function r(){return(document.documentElement||document.body).clientHeight}function s(){return void 0===window.pageYOffset?(document.documentElement||document.body).scrollTop:window.pageYOffset}Object.defineProperty(e,"__esModule",{value:!0}),e.ready=i,e.viewportWidth=o,e.viewportHeight=r,e.scrollY=s},function(t,e,n){"use strict";function i(t){t.offsetHeight}function o(t,e){var i=n(10);return i?"translate3d("+t+"px, "+e+"px, 0)":"translate("+t+"px, "+e+"px)"}function r(t){var e=t.getBoundingClientRect();return new u.Dimension(e.left,e.top,t.clientWidth,t.clientHeight)}function s(t,e){var i=n(9);if(i)for(var o=0,r=f;o<r.length;o++){var s=r[o];t.addEventListener(s,e)}else e(new Event(f[0]))}function a(t,e){for(var n=0,i=f;n<i.length;n++){var o=i[n];t.removeEventListener(o,e)}}function c(t){var e=t.parentElement;if(null!==e){var n=e.getAttribute("data-src");if(null!==n)return n}return t.src}function l(t,e){var n=Number(t.getAttribute("data-width")||1/0),i=Number(t.getAttribute("data-height")||1/0),o=Math.min(d.viewportWidth(),n)/e.width,r=Math.min(d.viewportHeight(),i)/e.height;return Math.min(o,r)}Object.defineProperty(e,"__esModule",{value:!0});var u=n(5),d=n(0),f=["transitionend","webkitTransitionEnd","oTransitionEnd","MSTransitionEnd"];e.repaint=i,e.translate=o,e.dimensions=r,e.addTransitionEndListener=s,e.removeTransitionEndListener=a,e.srcAttribute=c,e.fillViewportScale=l},function(t,e){for(var n,i=["webkitTransform","MozTransform","msTransform","OTransform","transform"],o=document.createElement("p"),r=0;r<i.length;r++)if(n=i[r],null!=o.style[n]){t.exports=n;break}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),o=n(6),r=n(2),s=function(){function t(){var t=this;this.overlay=document.createElement("div"),this.clickListener=function(e){var n=e.target;n instanceof HTMLImageElement&&n.classList.contains("zoom__element")&&(e.preventDefault(),!r||e.metaKey||e.ctrlKey?window.open(i.srcAttribute(n),"_blank"):t.zoom(n))}}return t.prototype.start=function(){this.overlay.classList.add("zoom__overlay"),document.body.addEventListener("click",this.clickListener)},t.prototype.zoom=function(t){var e=t.parentElement;if(null!==e){var n=e.classList;if(n.contains("zoom")&&!n.contains("zoom--active")){var i=new o.Zoom(this.overlay,e,t);i.show()}}},t}();e.Listener=s},function(t,e,n){var i=n(7);"string"==typeof i&&(i=[[t.i,i,""]]);n(11)(i,{});i.locals&&(t.exports=i.locals)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e,n,i){this.left=t,this.top=e,this.width=n,this.height=i}return t}();e.Dimension=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var i=n(1),o=n(0),r=27,s=50,a=function(){function t(t,e,n){var a=this;this.transforming=!1,this.finishedExpandingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedExpandingContainer),a.container.style.transition="initial",a.transforming=!1,a.scaleContainer(),i.repaint(a.container),a.container.style.transition=""},this.finishedCollapsingContainer=function(){i.removeTransitionEndListener(a.container,a.finishedCollapsingContainer),document.body.removeChild(a.overlay),a.container.classList.remove("zoom--active"),a.element.classList.remove("zoom__element--active"),a.removeClone()},this.finishedLoadingClone=function(){a.container.appendChild(a.clone),a.element.style.opacity="0"},this.resizeListener=function(){a.scaleContainer()},this.scrollListener=function(){Math.abs(a.initialScrollY-o.scrollY())>s&&a.hide()},this.clickListener=function(){a.hide()},this.keyboardListener=function(t){t.keyCode===r&&a.hide()},this.overlay=t,this.container=e,this.element=n,this.original=i.dimensions(n)}return t.prototype.show=function(){this.showOverlay(),this.expandContainer(),this.addClone(),this.addEventListeners()},t.prototype.hide=function(){this.removeEventListeners(),this.hideOverlay(),this.collapseContainer()},t.prototype.scaleContainer=function(){var t=i.fillViewportScale(this.container,this.original),e=this.original.width*t,n=this.original.height*t,r=(o.viewportWidth()-e)/2,s=(o.viewportHeight()-n)/2,a=this.original.left+(this.original.width-e)/2,c=this.original.top+(this.original.height-n)/2;if(this.transforming){var l=(r-a)/t,u=(s-c)/t;this.container.style.transform="scale("+t+") "+i.translate(l,u)}else this.container.style.transform="",this.container.style.left=r-this.original.left+"px",this.container.style.top=s-this.original.top+"px",this.container.style.width=e+"px",this.container.style.maxWidth=e+"px",this.container.style.height=n+"px"},t.prototype.showOverlay=function(){document.body.appendChild(this.overlay),i.repaint(this.overlay),this.overlay.classList.add("zoom__overlay--visible")},t.prototype.hideOverlay=function(){this.overlay.classList.remove("zoom__overlay--visible"),i.removeTransitionEndListener(this.container,this.finishedExpandingContainer)},t.prototype.expandContainer=function(){this.container.classList.add("zoom--active"),this.element.classList.add("zoom__element--active"),i.addTransitionEndListener(this.container,this.finishedExpandingContainer),this.transforming=!0,this.scaleContainer()},t.prototype.collapseContainer=function(){i.addTransitionEndListener(this.container,this.finishedCollapsingContainer),this.container.style.transition="initial",this.transforming=!0,this.scaleContainer(),i.repaint(this.container),this.container.style.transition="",this.container.style.transform="",this.container.style.left="",this.container.style.top="",this.container.style.width="",this.container.style.maxWidth="",this.container.style.height=""},t.prototype.addClone=function(){this.clone=document.createElement("img"),this.clone.classList.add("zoom__clone"),this.clone.addEventListener("load",this.finishedLoadingClone),this.clone.src=i.srcAttribute(this.element)},t.prototype.removeClone=function(){this.clone.removeEventListener("load",this.finishedLoadingClone),this.element.style.opacity="",this.container.contains(this.clone)&&this.container.removeChild(this.clone)},t.prototype.addEventListeners=function(){this.initialScrollY=o.scrollY(),window.addEventListener("resize",this.resizeListener),window.addEventListener("scroll",this.scrollListener),document.addEventListener("keyup",this.keyboardListener),this.container.addEventListener("click",this.clickListener)},t.prototype.removeEventListeners=function(){window.removeEventListener("resize",this.resizeListener),window.removeEventListener("scroll",this.scrollListener),document.removeEventListener("keyup",this.keyboardListener),this.container.removeEventListener("click",this.clickListener)},t}();e.Zoom=a},function(t,e,n){e=t.exports=n(8)(),e.push([t.i,'.zoom{position:relative;line-height:0;text-align:center;-webkit-transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:-webkit-transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1);transition:transform .3s cubic-bezier(.2,0,.2,1),-webkit-transform .3s cubic-bezier(.2,0,.2,1);will-change:transition}.zoom--active{z-index:2}.zoom__element{cursor:pointer;cursor:-moz-zoom-in;cursor:-webkit-zoom-in}.zoom__element--active{width:100%}.zoom__clone{position:absolute;cursor:pointer;cursor:-moz-zoom-out;cursor:-webkit-zoom-out}.zoom__clone,.zoom__overlay{top:0;right:0;bottom:0;left:0}.zoom__overlay{position:fixed;z-index:1;background:#fff;opacity:0;filter:"alpha(opacity=0)";-webkit-transition:opacity .3s;transition:opacity .3s;will-change:opacity,filter}.zoom__overlay--visible{opacity:1;filter:"alpha(opacity=100)"}',""])},function(t,e){t.exports=function(){var t=[];return t.toString=function(){for(var t=[],e=0;e<this.length;e++){var n=this[e];n[2]?t.push("@media "+n[2]+"{"+n[1]+"}"):t.push(n[1])}return t.join("")},t.i=function(e,n){"string"==typeof e&&(e=[[null,e,""]]);for(var i={},o=0;o<this.length;o++){var r=this[o][0];"number"==typeof r&&(i[r]=!0)}for(o=0;o<e.length;o++){var s=e[o];"number"==typeof s[0]&&i[s[0]]||(n&&!s[2]?s[2]=n:n&&(s[2]="("+s[2]+") and ("+n+")"),t.push(s))}},t}},function(t,e){function n(t){if(!i)return!1;if(!t)return null!=i;var e=getComputedStyle(t)[i];return""!==e&&0!==parseFloat(e)}for(var i,o=["transitionDuration","MozTransitionDuration","webkitTransitionDuration"];o.length;){var r=o.shift();r in document.body.style&&(i=r)}t.exports=n},function(t,e,n){var i=n(2);if(i&&window.getComputedStyle){var o={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"},r=document.createElement("div");r.style[i]="translate3d(1px,1px,1px)",document.body.insertBefore(r,null);var s=getComputedStyle(r).getPropertyValue(o[i]);document.body.removeChild(r),t.exports=null!=s&&s.length&&"none"!=s}else t.exports=!1},function(t,e){function n(t,e){for(var n=0;n<t.length;n++){var i=t[n],o=f[i.id];if(o){o.refs++;for(var r=0;r<o.parts.length;r++)o.parts[r](i.parts[r]);for(;r<i.parts.length;r++)o.parts.push(c(i.parts[r],e))}else{for(var s=[],r=0;r<i.parts.length;r++)s.push(c(i.parts[r],e));f[i.id]={id:i.id,refs:1,parts:s}}}}function i(t){for(var e=[],n={},i=0;i<t.length;i++){var o=t[i],r=o[0],s=o[1],a=o[2],c=o[3],l={css:s,media:a,sourceMap:c};n[r]?n[r].parts.push(l):e.push(n[r]={id:r,parts:[l]})}return e}function o(t,e){var n=m(),i=g[g.length-1];if("top"===t.insertAt)i?i.nextSibling?n.insertBefore(e,i.nextSibling):n.appendChild(e):n.insertBefore(e,n.firstChild),g.push(e);else{if("bottom"!==t.insertAt)throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");n.appendChild(e)}}function r(t){t.parentNode.removeChild(t);var e=g.indexOf(t);e>=0&&g.splice(e,1)}function s(t){var e=document.createElement("style");return e.type="text/css",o(t,e),e}function a(t){var e=document.createElement("link");return e.rel="stylesheet",o(t,e),e}function c(t,e){var n,i,o;if(e.singleton){var c=y++;n=v||(v=s(e)),i=l.bind(null,n,c,!1),o=l.bind(null,n,c,!0)}else t.sourceMap&&"function"==typeof URL&&"function"==typeof URL.createObjectURL&&"function"==typeof URL.revokeObjectURL&&"function"==typeof Blob&&"function"==typeof btoa?(n=a(e),i=d.bind(null,n),o=function(){r(n),n.href&&URL.revokeObjectURL(n.href)}):(n=s(e),i=u.bind(null,n),o=function(){r(n)});return i(t),function(e){if(e){if(e.css===t.css&&e.media===t.media&&e.sourceMap===t.sourceMap)return;i(t=e)}else o()}}function l(t,e,n,i){var o=n?"":i.css;if(t.styleSheet)t.styleSheet.cssText=b(e,o);else{var r=document.createTextNode(o),s=t.childNodes;s[e]&&t.removeChild(s[e]),s.length?t.insertBefore(r,s[e]):t.appendChild(r)}}function u(t,e){var n=e.css,i=e.media;if(i&&t.setAttribute("media",i),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}function d(t,e){var n=e.css,i=e.sourceMap;i&&(n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */");var o=new Blob([n],{type:"text/css"}),r=t.href;t.href=URL.createObjectURL(o),r&&URL.revokeObjectURL(r)}var f={},h=function(t){var e;return function(){return"undefined"==typeof e&&(e=t.apply(this,arguments)),e}},p=h(function(){return/msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase())}),m=h(function(){return document.head||document.getElementsByTagName("head")[0]}),v=null,y=0,g=[];t.exports=function(t,e){if("undefined"!=typeof DEBUG&&DEBUG&&"object"!=typeof document)throw new Error("The style-loader cannot be used in a non-browser environment");e=e||{},"undefined"==typeof e.singleton&&(e.singleton=p()),"undefined"==typeof e.insertAt&&(e.insertAt="bottom");var o=i(t);return n(o,e),function(t){for(var r=[],s=0;s<o.length;s++){var a=o[s],c=f[a.id];c.refs--,r.push(c)}if(t){var l=i(t);n(l,e)}for(var s=0;s<r.length;s++){var c=r[s];if(0===c.refs){for(var u=0;u<c.parts.length;u++)c.parts[u]();delete f[c.id]}}}};var b=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n(4);var i=n(0),o=n(3),r=new o.Listener;i.ready(function(){return r.start()})}]); |
|
Java | lgpl-2.1 | 4c411c3b9b8e1c4a89e156a5e03b9ae33abf2207 | 0 | ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror,ekiwi/jade-mirror | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
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,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package demo.MeetingScheduler.Ontology;
import jade.onto.*;
import jade.onto.basic.*;
public class MSOntology {
/**
A symbolic constant, containing the name of this ontology.
*/
public static final String NAME = "Meeting-Scheduling-Ontology";
public static final String PERSON = "Person";
public static final String APPOINTMENT = "Appointment";
private static Ontology theInstance = new DefaultOntology();
static {
initInstance();
}
/**
This method grants access to the unique instance of the
ontology.
@return An <code>Ontology</code> object, containing the concepts
of the ontology.
*/
public static Ontology instance() {
return theInstance;
}
private static void initInstance() {
try {
// Adds the roles of the basic ontology (ACTION, AID,...)
theInstance.joinOntology(BasicOntology.instance());
theInstance.addRole(PERSON, new SlotDescriptor[] {
new SlotDescriptor("name", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
new SlotDescriptor("AID", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O),
new SlotDescriptor("DFName", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O)
}, Person.class);
theInstance.addRole(APPOINTMENT, new SlotDescriptor[] {
new SlotDescriptor("inviter", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.M),
new SlotDescriptor("description", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
new SlotDescriptor("starting-on", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("ending-with", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("fixed-date", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("invited-persons", Ontology.SET_SLOT, PERSON, Ontology.O),
new SlotDescriptor("possible-dates", Ontology.SET_SLOT, Ontology.DATE_TYPE, Ontology.O)
}, Appointment.class);
} catch (OntologyException oe) {
oe.printStackTrace();
}
}
}
| src/demo/MeetingScheduler/Ontology/MSOntology.java | /*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
GNU Lesser General Public License
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,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package demo.MeetingScheduler.Ontology;
import jade.onto.*;
import jade.onto.basic.*;
public class MSOntology {
/**
A symbolic constant, containing the name of this ontology.
*/
public static final String NAME = "Meeting-Scheduling-Ontology";
public static final String PERSON = "Person";
public static final String APPOINTMENT = "Appointment";
private static Ontology theInstance = new DefaultOntology();
static {
initInstance();
}
/**
This method grants access to the unique instance of the
ontology.
@return An <code>Ontology</code> object, containing the concepts
of the ontology.
*/
public static Ontology instance() {
return theInstance;
}
private static void initInstance() {
try {
// Adds the roles of the basic ontology (ACTION, AID,...)
theInstance.joinOntology(BasicOntology.instance());
theInstance.addRole(PERSON, new SlotDescriptor[] {
new SlotDescriptor("name", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
new SlotDescriptor("AID", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O),
new SlotDescriptor("DFName", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O)
}, new RoleEntityFactory() {
public Object create(Frame f) { return new Person(); }
public Class getClassForRole() { return Person.class; }
});
theInstance.addRole(APPOINTMENT, new SlotDescriptor[] {
new SlotDescriptor("inviter", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.M),
new SlotDescriptor("description", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
new SlotDescriptor("starting-on", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("ending-with", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("fixed-date", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
new SlotDescriptor("invited-persons", Ontology.SET_SLOT, PERSON, Ontology.O),
new SlotDescriptor("possible-dates", Ontology.SET_SLOT, Ontology.DATE_TYPE, Ontology.O)
}, new RoleEntityFactory() {
public Object create(Frame f) { return new Appointment(); }
public Class getClassForRole() { return Appointment.class; }
});
} catch (OntologyException oe) {
oe.printStackTrace();
}
}
}
| update ontology (remove roleEntityFactory)
| src/demo/MeetingScheduler/Ontology/MSOntology.java | update ontology (remove roleEntityFactory) | <ide><path>rc/demo/MeetingScheduler/Ontology/MSOntology.java
<ide> new SlotDescriptor("name", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
<ide> new SlotDescriptor("AID", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O),
<ide> new SlotDescriptor("DFName", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.O)
<del> }, new RoleEntityFactory() {
<del> public Object create(Frame f) { return new Person(); }
<del> public Class getClassForRole() { return Person.class; }
<del> });
<add> }, Person.class);
<ide> theInstance.addRole(APPOINTMENT, new SlotDescriptor[] {
<ide> new SlotDescriptor("inviter", Ontology.FRAME_SLOT, BasicOntology.AGENTIDENTIFIER, Ontology.M),
<ide> new SlotDescriptor("description", Ontology.PRIMITIVE_SLOT, Ontology.STRING_TYPE, Ontology.M),
<ide> new SlotDescriptor("fixed-date", Ontology.PRIMITIVE_SLOT, Ontology.DATE_TYPE, Ontology.O),
<ide> new SlotDescriptor("invited-persons", Ontology.SET_SLOT, PERSON, Ontology.O),
<ide> new SlotDescriptor("possible-dates", Ontology.SET_SLOT, Ontology.DATE_TYPE, Ontology.O)
<del> }, new RoleEntityFactory() {
<del> public Object create(Frame f) { return new Appointment(); }
<del> public Class getClassForRole() { return Appointment.class; }
<del> });
<add> }, Appointment.class);
<ide> } catch (OntologyException oe) {
<ide> oe.printStackTrace();
<ide> } |
|
Java | bsd-3-clause | 218cb1395c9d766b66f5593d905f31d379696548 | 0 | ConnCollege/cas,ConnCollege/cas,ConnCollege/cas | /*
* Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.AuthenticationManager;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.ExpirationPolicy;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketCreationException;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.TicketGrantingTicketImpl;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.TicketValidationException;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.ImmutableAssertionImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* Concrete implementation of a CentralAuthenticationService, and also the
* central, organizing component of CAS's internal implementation.
* <p>
* This class is threadsafe.
* <p>
* This class has the following properties that must be set:
* <ul>
* <li> <code>ticketRegistry</code> - The Ticket Registry to maintain the list
* of available tickets.</li>
* <li> <code>authenticationManager</code> - The service that will handle
* authentication.</li>
* <li> <code>ticketGrantingTicketUniqueTicketIdGenerator</code> - Plug in to
* generate unique secure ids for TicketGrantingTickets.</li>
* <li> <code>serviceTicketUniqueTicketIdGenerator</code> - Plug in to
* generate unique secure ids for ServiceTickets.</li>
* <li> <code>ticketGrantingTicketExpirationPolicy</code> - The expiration
* policy for TicketGrantingTickets.</li>
* <li> <code>serviceTicketExpirationPolicy</code> - The expiration policy for
* ServiceTickets.</li>
* </ul>
*
* @author William G. Thompson, Jr.
* @author Scott Battaglia
* @author Dmitry Kopylenko
* @version $Revision$ $Date$
* @since 3.0
*/
public final class CentralAuthenticationServiceImpl implements
CentralAuthenticationService, InitializingBean {
/** Log instance for logging events, info, warnings, errors, etc. */
private final Log log = LogFactory.getLog(this.getClass());
/** TicketRegistry for storing and retrieving tickets as needed. */
private TicketRegistry ticketRegistry;
/**
* AuthenticationManager for authenticating credentials for purposes of
* obtaining tickets.
*/
private AuthenticationManager authenticationManager;
/**
* UniqueTicketIdGenerator to generate ids for TicketGrantingTickets
* created.
*/
private UniqueTicketIdGenerator ticketGrantingTicketUniqueTicketIdGenerator;
/** UniqueTicketIdGenerator to generate ids for ServiceTickets created. */
private UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator;
/** Expiration policy for ticket granting tickets. */
private ExpirationPolicy ticketGrantingTicketExpirationPolicy;
/** ExpirationPolicy for Service Tickets. */
private ExpirationPolicy serviceTicketExpirationPolicy;
/**
* Implementation of destoryTicketGrantingTicket expires the ticket provided
* and removes it from the TicketRegistry.
*
* @throws IllegalArgumentException if the TicketGrantingTicket ID is null.
*/
public void destroyTicketGrantingTicket(final String ticketGrantingTicketId) {
Assert.notNull(ticketGrantingTicketId);
if (log.isDebugEnabled()) {
log.debug("Removing ticket [" + ticketGrantingTicketId
+ "] from registry.");
}
final TicketGrantingTicket ticket = (TicketGrantingTicket) this.ticketRegistry
.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
if (ticket != null) {
if (log.isDebugEnabled()) {
log.debug("Ticket found. Expiring and then deleting.");
}
ticket.expire();
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
}
}
/**
* @throws IllegalArgumentException if TicketGrantingTicket ID, Credentials
* or Service are null.
*/
public String grantServiceTicket(final String ticketGrantingTicketId,
final Service service, final Credentials credentials)
throws TicketException {
Assert.notNull(ticketGrantingTicketId, "ticketGrantingticketId cannot be null");
Assert.notNull(service, "service cannot be null");
final TicketGrantingTicket ticketGrantingTicket;
ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
if (ticketGrantingTicket == null) {
throw new InvalidTicketException();
}
// XXX is synchronization needed here?
synchronized (ticketGrantingTicket) {
if (ticketGrantingTicket.isExpired()) {
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
throw new InvalidTicketException();
}
}
if (credentials != null) {
try {
Authentication authentication = this.authenticationManager
.authenticate(credentials);
final Principal originalPrincipal = ticketGrantingTicket
.getAuthentication().getPrincipal();
final Principal newPrincipal = authentication.getPrincipal();
if (!newPrincipal.equals(originalPrincipal)) {
throw new TicketCreationException();
}
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
final ServiceTicket serviceTicket = ticketGrantingTicket
.grantServiceTicket(this.serviceTicketUniqueTicketIdGenerator
.getNewTicketId(ServiceTicket.PREFIX), service,
this.serviceTicketExpirationPolicy, credentials != null);
this.ticketRegistry.addTicket(serviceTicket);
if (log.isInfoEnabled()) {
log.info("Granted service ticket ["
+ serviceTicket.getId()
+ "] for service ["
+ service.getId()
+ "] for user ["
+ serviceTicket.getGrantingTicket().getAuthentication()
.getPrincipal().getId() + "]");
}
return serviceTicket.getId();
}
public String grantServiceTicket(final String ticketGrantingTicketId,
final Service service) throws TicketException {
return this.grantServiceTicket(ticketGrantingTicketId, service, null);
}
/**
* @throws IllegalArgumentException if the ServiceTicketId or the
* Credentials are null.
*/
public String delegateTicketGrantingTicket(final String serviceTicketId,
final Credentials credentials) throws TicketException {
Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
Assert.notNull(credentials, "credentials cannot be null");
try {
final Authentication authentication = this.authenticationManager
.authenticate(credentials);
final ServiceTicket serviceTicket;
serviceTicket = (ServiceTicket) this.ticketRegistry.getTicket(
serviceTicketId, ServiceTicket.class);
if (serviceTicket == null || serviceTicket.isExpired()) {
throw new InvalidTicketException();
}
TicketGrantingTicket ticketGrantingTicket = serviceTicket
.grantTicketGrantingTicket(
this.ticketGrantingTicketUniqueTicketIdGenerator
.getNewTicketId(TicketGrantingTicket.PREFIX),
authentication, this.ticketGrantingTicketExpirationPolicy);
this.ticketRegistry.addTicket(ticketGrantingTicket);
return ticketGrantingTicket.getId();
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
/**
* @throws IllegalArgumentException if the ServiceTicketId or the Service
* are null.
*/
public Assertion validateServiceTicket(final String serviceTicketId,
final Service service) throws TicketException {
Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
Assert.notNull(service, "service cannot be null");
final ServiceTicket serviceTicket = (ServiceTicket) this.ticketRegistry
.getTicket(serviceTicketId, ServiceTicket.class);
if (serviceTicket == null) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] does not exist.");
}
throw new InvalidTicketException();
}
try {
synchronized (serviceTicket) {
if (serviceTicket.isExpired()) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] has expired.");
}
throw new InvalidTicketException();
}
if (!serviceTicket.isValidFor(service)) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] does not match supplied service: " + service);
}
throw new TicketValidationException();
}
}
return new ImmutableAssertionImpl(serviceTicket.getGrantingTicket()
.getChainedAuthentications(), serviceTicket.getService(),
serviceTicket.isFromNewLogin());
} finally {
if (serviceTicket.isExpired()) {
this.ticketRegistry.deleteTicket(serviceTicketId);
}
}
}
/**
* @throws IllegalArgumentException if the credentials are null.
*/
public String createTicketGrantingTicket(final Credentials credentials)
throws TicketCreationException {
Assert.notNull(credentials, "credentials cannot be null");
if (log.isDebugEnabled()) {
log.debug("Attempting to create TicketGrantingTicket for "
+ credentials);
}
try {
final Authentication authentication = this.authenticationManager
.authenticate(credentials);
final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
this.ticketGrantingTicketUniqueTicketIdGenerator
.getNewTicketId(TicketGrantingTicket.PREFIX),
authentication, this.ticketGrantingTicketExpirationPolicy);
this.ticketRegistry.addTicket(ticketGrantingTicket);
return ticketGrantingTicket.getId();
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
/**
* Method to set the TicketRegistry.
*
* @param ticketRegistry the TicketRegistry to set.
*/
public void setTicketRegistry(final TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
/**
* Method to inject the AuthenticationManager into the class.
*
* @param authenticationManager The authenticationManager to set.
*/
public void setAuthenticationManager(
final AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* Method to inject the TicketGrantingTicket Expiration Policy.
*
* @param ticketGrantingTicketExpirationPolicy The
* ticketGrantingTicketExpirationPolicy to set.
*/
public void setTicketGrantingTicketExpirationPolicy(
final ExpirationPolicy ticketGrantingTicketExpirationPolicy) {
this.ticketGrantingTicketExpirationPolicy = ticketGrantingTicketExpirationPolicy;
}
/**
* Method to inject the Unique Ticket Id Generator into the class.
*
* @param uniqueTicketIdGenerator The uniqueTicketIdGenerator to use
*/
public void setTicketGrantingTicketUniqueTicketIdGenerator(
final UniqueTicketIdGenerator uniqueTicketIdGenerator) {
this.ticketGrantingTicketUniqueTicketIdGenerator = uniqueTicketIdGenerator;
}
/**
* Method to inject the TicketGrantingTicket Expiration Policy.
*
* @param serviceTicketExpirationPolicy The serviceTicketExpirationPolicy to
* set.
*/
public void setServiceTicketExpirationPolicy(
final ExpirationPolicy serviceTicketExpirationPolicy) {
this.serviceTicketExpirationPolicy = serviceTicketExpirationPolicy;
}
public void afterPropertiesSet() throws Exception {
final String name = this.getClass().getName();
Assert.notNull(this.ticketRegistry, "ticketRegistry cannot be null on "
+ name);
Assert.notNull(this.authenticationManager,
"authenticationManager cannot be null on " + name);
Assert.notNull(this.ticketGrantingTicketUniqueTicketIdGenerator,
"ticketGrantingTicketUniqueTicketIdGenerator cannot be null on "
+ name);
Assert.notNull(this.serviceTicketUniqueTicketIdGenerator,
"serviceTicketUniqueTicketIdGenerator cannot be null on " + name);
Assert.notNull(this.ticketGrantingTicketExpirationPolicy,
"ticketGrantingTicketExpirationPolicy cannot be null on " + name);
Assert.notNull(this.serviceTicketExpirationPolicy,
"serviceTicketExpirationPolicy cannot be null on " + name);
}
public void setServiceTicketUniqueTicketIdGenerator(
final UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator) {
this.serviceTicketUniqueTicketIdGenerator = serviceTicketUniqueTicketIdGenerator;
}
}
| core/src/main/java/org/jasig/cas/CentralAuthenticationServiceImpl.java | /*
* Copyright 2005 The JA-SIG Collaborative. All rights reserved. See license
* distributed with this file and available online at
* http://www.uportal.org/license.html
*/
package org.jasig.cas;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.AuthenticationManager;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.ticket.ExpirationPolicy;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.ticket.TicketCreationException;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.TicketGrantingTicketImpl;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.TicketValidationException;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.jasig.cas.util.UniqueTicketIdGenerator;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.validation.ImmutableAssertionImpl;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
/**
* Concrete implementation of a CentralAuthenticationService, and also the
* central, organizing component of CAS's internal implementation.
* <p>
* This class is threadsafe.
* <p>
* This class has the following properties that must be set:
* <ul>
* <li> <code>ticketRegistry</code> - The Ticket Registry to maintain the list
* of available tickets.</li>
* <li> <code>authenticationManager</code> - The service that will handle
* authentication.</li>
* <li> <code>ticketGrantingTicketUniqueTicketIdGenerator</code> - Plug in to
* generate unique secure ids for TicketGrantingTickets.</li>
* <li> <code>serviceTicketUniqueTicketIdGenerator</code> - Plug in to
* generate unique secure ids for ServiceTickets.</li>
* <li> <code>ticketGrantingTicketExpirationPolicy</code> - The expiration
* policy for TicketGrantingTickets.</li>
* <li> <code>serviceTicketExpirationPolicy</code> - The expiration policy for
* ServiceTickets.</li>
* </ul>
*
* @author William G. Thompson, Jr.
* @author Scott Battaglia
* @author Dmitry Kopylenko
* @version $Revision$ $Date$
* @since 3.0
*/
public final class CentralAuthenticationServiceImpl implements
CentralAuthenticationService, InitializingBean {
/** Log instance for logging events, info, warnings, errors, etc. */
private final Log log = LogFactory.getLog(this.getClass());
/** TicketRegistry for storing and retrieving tickets as needed. */
private TicketRegistry ticketRegistry;
/**
* AuthenticationManager for authenticating credentials for purposes of
* obtaining tickets.
*/
private AuthenticationManager authenticationManager;
/**
* UniqueTicketIdGenerator to generate ids for TicketGrantingTickets
* created.
*/
private UniqueTicketIdGenerator ticketGrantingTicketUniqueTicketIdGenerator;
/** UniqueTicketIdGenerator to generate ids for ServiceTickets created. */
private UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator;
/** Expiration policy for ticket granting tickets. */
private ExpirationPolicy ticketGrantingTicketExpirationPolicy;
/** ExpirationPolicy for Service Tickets. */
private ExpirationPolicy serviceTicketExpirationPolicy;
/**
* Implementation of destoryTicketGrantingTicket expires the ticket provided
* and removes it from the TicketRegistry.
*
* @throws IllegalArgumentException if the TicketGrantingTicket ID is null.
*/
public void destroyTicketGrantingTicket(final String ticketGrantingTicketId) {
Assert.notNull(ticketGrantingTicketId);
if (log.isDebugEnabled()) {
log.debug("Removing ticket [" + ticketGrantingTicketId
+ "] from registry.");
}
final TicketGrantingTicket ticket = (TicketGrantingTicket) this.ticketRegistry
.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
if (ticket != null) {
if (log.isDebugEnabled()) {
log.debug("Ticket found. Expiring and then deleting.");
}
ticket.expire();
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
}
}
/**
* @throws IllegalArgumentException if TicketGrantingTicket ID, Credentials
* or Service are null.
*/
public String grantServiceTicket(final String ticketGrantingTicketId,
final Service service, final Credentials credentials)
throws TicketException {
Assert.notNull(ticketGrantingTicketId, "ticketGrantingticketId cannot be null");
Assert.notNull(service, "service cannot be null");
final TicketGrantingTicket ticketGrantingTicket;
ticketGrantingTicket = (TicketGrantingTicket) this.ticketRegistry
.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
if (ticketGrantingTicket == null) {
throw new InvalidTicketException();
}
// XXX is synchronization needed here?
synchronized (ticketGrantingTicket) {
if (ticketGrantingTicket.isExpired()) {
this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
throw new InvalidTicketException();
}
}
if (credentials != null) {
try {
Authentication authentication = this.authenticationManager
.authenticate(credentials);
final Principal originalPrincipal = ticketGrantingTicket
.getAuthentication().getPrincipal();
final Principal newPrincipal = authentication.getPrincipal();
if (!newPrincipal.equals(originalPrincipal)) {
throw new TicketCreationException();
}
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
final ServiceTicket serviceTicket = ticketGrantingTicket
.grantServiceTicket(this.serviceTicketUniqueTicketIdGenerator
.getNewTicketId(ServiceTicket.PREFIX), service,
this.serviceTicketExpirationPolicy, credentials != null);
this.ticketRegistry.addTicket(serviceTicket);
if (log.isInfoEnabled()) {
log.info("Granted service ticket ["
+ serviceTicket.getId()
+ "] for service ["
+ service.getId()
+ "] for user ["
+ serviceTicket.getGrantingTicket().getAuthentication()
.getPrincipal().getId() + "]");
}
return serviceTicket.getId();
}
public String grantServiceTicket(final String ticketGrantingTicketId,
final Service service) throws TicketException {
return this.grantServiceTicket(ticketGrantingTicketId, service, null);
}
/**
* @throws IllegalArgumentException if the ServiceTicketId or the
* Credentials are null.
*/
public String delegateTicketGrantingTicket(final String serviceTicketId,
final Credentials credentials) throws TicketException {
Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
Assert.notNull(credentials, "credentials cannot be null");
try {
final Authentication authentication = this.authenticationManager
.authenticate(credentials);
final ServiceTicket serviceTicket;
serviceTicket = (ServiceTicket) this.ticketRegistry.getTicket(
serviceTicketId, ServiceTicket.class);
if (serviceTicket == null || serviceTicket.isExpired()) {
throw new InvalidTicketException();
}
TicketGrantingTicket ticketGrantingTicket = serviceTicket
.grantTicketGrantingTicket(
this.ticketGrantingTicketUniqueTicketIdGenerator
.getNewTicketId(TicketGrantingTicket.PREFIX),
authentication, this.ticketGrantingTicketExpirationPolicy);
this.ticketRegistry.addTicket(ticketGrantingTicket);
return ticketGrantingTicket.getId();
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
/**
* @throws IllegalArgumentException if the ServiceTicketId or the Service
* are null.
*/
public Assertion validateServiceTicket(final String serviceTicketId,
final Service service) throws TicketException {
Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
Assert.notNull(service, "service cannot be null");
final ServiceTicket serviceTicket = (ServiceTicket) this.ticketRegistry
.getTicket(serviceTicketId, ServiceTicket.class);
if (serviceTicket == null) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] does not exist.");
}
throw new InvalidTicketException();
}
try {
synchronized (serviceTicket) {
if (serviceTicket.isExpired()) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] has expired.");
}
throw new InvalidTicketException();
}
if (!serviceTicket.isValidFor(service)) {
if (log.isDebugEnabled()) {
log.debug("ServiceTicket [" + serviceTicketId
+ "] does not match supplied service.");
}
throw new TicketValidationException();
}
}
return new ImmutableAssertionImpl(serviceTicket.getGrantingTicket()
.getChainedAuthentications(), serviceTicket.getService(),
serviceTicket.isFromNewLogin());
} finally {
if (serviceTicket.isExpired()) {
this.ticketRegistry.deleteTicket(serviceTicketId);
}
}
}
/**
* @throws IllegalArgumentException if the credentials are null.
*/
public String createTicketGrantingTicket(final Credentials credentials)
throws TicketCreationException {
Assert.notNull(credentials, "credentials cannot be null");
if (log.isDebugEnabled()) {
log.debug("Attempting to create TicketGrantingTicket for "
+ credentials);
}
try {
final Authentication authentication = this.authenticationManager
.authenticate(credentials);
final TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(
this.ticketGrantingTicketUniqueTicketIdGenerator
.getNewTicketId(TicketGrantingTicket.PREFIX),
authentication, this.ticketGrantingTicketExpirationPolicy);
this.ticketRegistry.addTicket(ticketGrantingTicket);
return ticketGrantingTicket.getId();
} catch (final AuthenticationException e) {
throw new TicketCreationException(e);
}
}
/**
* Method to set the TicketRegistry.
*
* @param ticketRegistry the TicketRegistry to set.
*/
public void setTicketRegistry(final TicketRegistry ticketRegistry) {
this.ticketRegistry = ticketRegistry;
}
/**
* Method to inject the AuthenticationManager into the class.
*
* @param authenticationManager The authenticationManager to set.
*/
public void setAuthenticationManager(
final AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
/**
* Method to inject the TicketGrantingTicket Expiration Policy.
*
* @param ticketGrantingTicketExpirationPolicy The
* ticketGrantingTicketExpirationPolicy to set.
*/
public void setTicketGrantingTicketExpirationPolicy(
final ExpirationPolicy ticketGrantingTicketExpirationPolicy) {
this.ticketGrantingTicketExpirationPolicy = ticketGrantingTicketExpirationPolicy;
}
/**
* Method to inject the Unique Ticket Id Generator into the class.
*
* @param uniqueTicketIdGenerator The uniqueTicketIdGenerator to use
*/
public void setTicketGrantingTicketUniqueTicketIdGenerator(
final UniqueTicketIdGenerator uniqueTicketIdGenerator) {
this.ticketGrantingTicketUniqueTicketIdGenerator = uniqueTicketIdGenerator;
}
/**
* Method to inject the TicketGrantingTicket Expiration Policy.
*
* @param serviceTicketExpirationPolicy The serviceTicketExpirationPolicy to
* set.
*/
public void setServiceTicketExpirationPolicy(
final ExpirationPolicy serviceTicketExpirationPolicy) {
this.serviceTicketExpirationPolicy = serviceTicketExpirationPolicy;
}
public void afterPropertiesSet() throws Exception {
final String name = this.getClass().getName();
Assert.notNull(this.ticketRegistry, "ticketRegistry cannot be null on "
+ name);
Assert.notNull(this.authenticationManager,
"authenticationManager cannot be null on " + name);
Assert.notNull(this.ticketGrantingTicketUniqueTicketIdGenerator,
"ticketGrantingTicketUniqueTicketIdGenerator cannot be null on "
+ name);
Assert.notNull(this.serviceTicketUniqueTicketIdGenerator,
"serviceTicketUniqueTicketIdGenerator cannot be null on " + name);
Assert.notNull(this.ticketGrantingTicketExpirationPolicy,
"ticketGrantingTicketExpirationPolicy cannot be null on " + name);
Assert.notNull(this.serviceTicketExpirationPolicy,
"serviceTicketExpirationPolicy cannot be null on " + name);
}
public void setServiceTicketUniqueTicketIdGenerator(
final UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator) {
this.serviceTicketUniqueTicketIdGenerator = serviceTicketUniqueTicketIdGenerator;
}
}
| CAS-383
added message about what supplied service was
| core/src/main/java/org/jasig/cas/CentralAuthenticationServiceImpl.java | CAS-383 | <ide><path>ore/src/main/java/org/jasig/cas/CentralAuthenticationServiceImpl.java
<ide> if (!serviceTicket.isValidFor(service)) {
<ide> if (log.isDebugEnabled()) {
<ide> log.debug("ServiceTicket [" + serviceTicketId
<del> + "] does not match supplied service.");
<add> + "] does not match supplied service: " + service);
<ide> }
<ide>
<ide> throw new TicketValidationException(); |
|
Java | bsd-2-clause | 52893dbab4de193af17dfb86274dbbfeb5129923 | 0 | llwanghong/jslint4java,nikgoodley-ibboost/jslint4java,rsingla/jslint4java,nikgoodley-ibboost/jslint4java,nikgoodley-ibboost/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,llwanghong/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java,mmayorivera/jslint4java,rsingla/jslint4java,llwanghong/jslint4java,nikgoodley-ibboost/jslint4java,nikgoodley-ibboost/jslint4java | package com.googlecode.jslint4java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
/**
* A command line interface to {@link JSLint}.
*
* @author dom
* @version $Id$
*/
public class Main {
private static final String PROGNAME = "jslint";
/**
* The main entry point. Try passing in "--help" for more details.
*
* @param args
* One or more JavaScript files.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Main main = new Main();
List<String> files = main.processOptions(args);
if (files.size() == 0) {
main.help();
}
for (String file : files) {
main.lintFile(file);
}
System.exit(main.isErrored() ? 1 : 0);
}
private boolean errored = false;
private JSLint lint;
private Main() throws IOException {
lint = new JSLintBuilder().fromDefault();
}
/**
* Apply a set of options to the current JSLint.
*/
private void applyOptions(Map<Option, String> options) {
for (Entry<Option, String> entry : options.entrySet()) {
String value = entry.getValue();
if (value == null) {
lint.addOption(entry.getKey());
} else {
lint.addOption(entry.getKey(), value);
}
}
}
private void die(String message) {
System.err.println(PROGNAME + ": " + message);
System.exit(1);
}
private void err(String message) {
System.out.println(PROGNAME + ":" + message);
setErrored(true);
}
/**
* Fetch the named {@link Option}, or null if there is no matching one.
*/
private Option getOption(String optName) {
try {
return Option.valueOf(optName.toUpperCase(Locale.getDefault()));
} catch (IllegalArgumentException e) {
return null;
}
}
private void help() {
info("usage: jslint [options] file.js ...");
String fmt = " --%-" + Option.maximumNameLength() + "s %s";
for (Option o : Option.values()) {
info(String.format(fmt, o.getLowerName(), o.getDescription()));
}
info("");
info(String.format(fmt, "help", "Show this help"));
info("");
info("using jslint version " + lint.getEdition());
System.exit(0);
}
private void info(String message) {
System.out.println(message);
}
private boolean isErrored() {
return errored;
}
private void lintFile(String file) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
List<Issue> issues = lint.lint(file, reader);
for (Issue issue : issues) {
err(issue.toString());
}
} catch (FileNotFoundException e) {
die(file + ": No such file or directory.");
} finally {
if (reader != null) {
reader.close();
}
}
}
private List<String> processOptions(String[] args) {
boolean inFiles = false;
List<String> files = new ArrayList<String>();
Map<Option, String> options = new HashMap<Option, String>();
for (String arg : args) {
if (inFiles) {
files.add(arg);
}
// End of arguments.
else if ("--".equals(arg)) {
inFiles = true;
continue;
}
// Hayelp!
else if ("--help".equals(arg)) {
help();
}
// Specify an alternative jslint.
else if (arg.startsWith("--jslint")) {
String[] bits = arg.substring(2).split("=", 2);
if (bits.length != 2) {
die("Must specify file with --jslint=/some/where/jslint.js");
}
try {
lint = new JSLintBuilder().fromFile(new File(bits[1]));
} catch (IOException e) {
die(e.getMessage());
}
}
// Longopt.
else if (arg.startsWith("--")) {
String[] bits = arg.substring(2).split("=", 2);
try {
Option o = getOption(bits[0]);
if (o == null) {
die("unknown option " + arg);
}
if (bits.length == 2) {
options.put(o, bits[1]);
} else {
options.put(o, null);
}
} catch (IllegalArgumentException e) {
die(bits[0] + ": " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
// File
else {
inFiles = true;
files.add(arg);
}
}
applyOptions(options);
return files;
}
private void setErrored(boolean errored) {
this.errored = errored;
}
}
| jslint4java/src/main/java/com/googlecode/jslint4java/Main.java | package com.googlecode.jslint4java;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* A command line interface to {@link JSLint}.
*
* @author dom
* @version $Id$
*/
public class Main {
private static final String PROGNAME = "jslint";
/**
* The main entry point. Try passing in "--help" for more details.
*
* @param args
* One or more JavaScript files.
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Main main = new Main();
List<String> files = main.processOptions(args);
if (files.size() == 0) {
main.help();
}
for (String file : files) {
main.lintFile(file);
}
System.exit(main.isErrored() ? 1 : 0);
}
private boolean errored = false;
private JSLint lint;
private Main() throws IOException {
lint = new JSLintBuilder().fromDefault();
}
private void die(String message) {
System.err.println(PROGNAME + ": " + message);
System.exit(1);
}
private void err(String message) {
System.out.println(PROGNAME + ":" + message);
setErrored(true);
}
/**
* Fetch the named {@link Option}, or null if there is no matching one.
*/
private Option getOption(String optName) {
try {
return Option.valueOf(optName.toUpperCase(Locale.getDefault()));
} catch (IllegalArgumentException e) {
return null;
}
}
private void help() {
info("usage: jslint [options] file.js ...");
String fmt = " --%-" + Option.maximumNameLength() + "s %s";
for (Option o : Option.values()) {
info(String.format(fmt, o.getLowerName(), o.getDescription()));
}
info("");
info(String.format(fmt, "help", "Show this help"));
info("");
info("using jslint version " + lint.getEdition());
System.exit(0);
}
private void info(String message) {
System.out.println(message);
}
private boolean isErrored() {
return errored;
}
private void lintFile(String file) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
List<Issue> issues = lint.lint(file, reader);
for (Issue issue : issues) {
err(issue.toString());
}
} catch (FileNotFoundException e) {
die(file + ": No such file or directory.");
} finally {
if (reader != null) {
reader.close();
}
}
}
private List<String> processOptions(String[] args) {
boolean inFiles = false;
List<String> files = new ArrayList<String>();
for (String arg : args) {
if (inFiles) {
files.add(arg);
}
// End of arguments.
else if ("--".equals(arg)) {
inFiles = true;
continue;
}
// Hayelp!
else if ("--help".equals(arg)) {
help();
}
// Specify an alternative jslint.
else if (arg.startsWith("--jslint")) {
String[] bits = arg.substring(2).split("=", 2);
if (bits.length != 2) {
die("Must specify file with --jslint=/some/where/jslint.js");
}
try {
// TODO Don't wipe out existing options that have been set.
lint = new JSLintBuilder().fromFile(new File(bits[1]));
} catch (IOException e) {
die(e.getMessage());
}
}
// Longopt.
else if (arg.startsWith("--")) {
String[] bits = arg.substring(2).split("=", 2);
try {
Option o = getOption(bits[0]);
if (o == null) {
die("unknown option " + arg);
}
if (bits.length == 2) {
lint.addOption(o, bits[1]);
} else {
lint.addOption(o);
}
} catch (IllegalArgumentException e) {
die(bits[0] + ": " + e.getClass().getName() + ": "
+ e.getMessage());
}
}
// File
else {
inFiles = true;
files.add(arg);
}
}
return files;
}
private void setErrored(boolean errored) {
this.errored = errored;
}
}
| issue 18: Apply options after all other CLI args.
This means that switching the jslint in use will pick up all options no matter where they come on the command line. | jslint4java/src/main/java/com/googlecode/jslint4java/Main.java | issue 18: Apply options after all other CLI args. | <ide><path>slint4java/src/main/java/com/googlecode/jslint4java/Main.java
<ide> import java.io.IOException;
<ide> import java.io.InputStreamReader;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Locale;
<add>import java.util.Map;
<add>import java.util.Map.Entry;
<ide>
<ide> /**
<ide> * A command line interface to {@link JSLint}.
<ide>
<ide> private Main() throws IOException {
<ide> lint = new JSLintBuilder().fromDefault();
<add> }
<add>
<add> /**
<add> * Apply a set of options to the current JSLint.
<add> */
<add> private void applyOptions(Map<Option, String> options) {
<add> for (Entry<Option, String> entry : options.entrySet()) {
<add> String value = entry.getValue();
<add> if (value == null) {
<add> lint.addOption(entry.getKey());
<add> } else {
<add> lint.addOption(entry.getKey(), value);
<add> }
<add> }
<ide> }
<ide>
<ide> private void die(String message) {
<ide> private List<String> processOptions(String[] args) {
<ide> boolean inFiles = false;
<ide> List<String> files = new ArrayList<String>();
<add> Map<Option, String> options = new HashMap<Option, String>();
<ide> for (String arg : args) {
<ide> if (inFiles) {
<ide> files.add(arg);
<ide> die("Must specify file with --jslint=/some/where/jslint.js");
<ide> }
<ide> try {
<del> // TODO Don't wipe out existing options that have been set.
<ide> lint = new JSLintBuilder().fromFile(new File(bits[1]));
<ide> } catch (IOException e) {
<ide> die(e.getMessage());
<ide> die("unknown option " + arg);
<ide> }
<ide> if (bits.length == 2) {
<del> lint.addOption(o, bits[1]);
<add> options.put(o, bits[1]);
<ide> } else {
<del> lint.addOption(o);
<add> options.put(o, null);
<ide> }
<ide> } catch (IllegalArgumentException e) {
<ide> die(bits[0] + ": " + e.getClass().getName() + ": "
<ide> files.add(arg);
<ide> }
<ide> }
<add> applyOptions(options);
<ide> return files;
<ide> }
<ide> |
|
Java | mit | 7ba1840fabb9204ac9a8a34b5ca20461caadffe3 | 0 | mozack/abra2,mozack/abra2,mozack/abra2,mozack/abra2 | /* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
/**
* Utility class for shifting Indels into leftmost position.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public class IndelShifter {
public Cigar shiftAllIndelsLeft(int refStart, int refEnd, String chromosome, Cigar cigar, String seq, CompareToReference2 c2r) {
try {
List<CigarElement> elems = new ArrayList<CigarElement>(cigar.getCigarElements());
int elemSize = elems.size();
for (int i=1; i<elemSize-1; i++) {
int refOffset = 0;
int readOffset = 0;
for (int j=0; j<i-1; j++) {
refOffset += getRefOffset(elems.get(j));
readOffset += getReadOffset(elems.get(j));
}
CigarElement prev = elems.get(i-1);
CigarElement elem = elems.get(i);
CigarElement next = elems.get(i+1);
if ((elem.getOperator() == CigarOperator.DELETION || elem.getOperator() == CigarOperator.INSERTION) &&
prev.getOperator() == CigarOperator.MATCH_OR_MISMATCH && next.getOperator() == CigarOperator.MATCH_OR_MISMATCH) {
// subset cigar here and attempt to shift
Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
chromosome, subCigar, subSeq, c2r);
//TODO: Merge abutting indels if applicable
elems.set(i-1, newCigar.getCigarElement(0));
elems.set(i, newCigar.getCigarElement(1));
if (newCigar.getCigarElements().size() == 3) {
elems.set(i+1, newCigar.getCigarElement(2));
} else {
elemSize -= 1;
}
}
}
return new Cigar(elems);
} catch (RuntimeException e) {
e.printStackTrace();
Logger.error("Error on: " + refStart + ", " + refEnd + "," + chromosome + ", " + cigar + ", " + seq);
throw e;
}
}
private int getRefOffset(CigarElement elem) {
int offset = -1;
switch(elem.getOperator()) {
case M:
case D:
offset = elem.getLength();
break;
case I:
offset = 0;
break;
default:
throw new IllegalArgumentException("Unexpected Cigar operator: " + elem.getOperator());
}
return offset;
}
private int getReadOffset(CigarElement elem) {
int offset = -1;
switch(elem.getOperator()) {
case M:
case I:
offset = elem.getLength();
break;
case D:
offset = 0;
break;
default:
throw new IllegalArgumentException("Unexpected Cigar operator: " + elem.getOperator());
}
return offset;
}
public Cigar shiftIndelsLeft(int refStart, int refEnd, String chromosome, Cigar cigar, String seq, CompareToReference2 c2r) {
try {
if (containsIndel(cigar)) {
int indelPos = firstIndelOffset(cigar);
String origReadAltRef = c2r.getAlternateReference(refStart, refEnd, chromosome, seq, cigar);
// System.out.println("o: " + origReadAltRef);
if (origReadAltRef != null) {
for (int i=indelPos; i>0; i--) {
Cigar newCigar = shiftCigarLeft(cigar, i);
String shiftedReadAltRef = c2r.getAlternateReference(refStart, refEnd, chromosome, seq, newCigar);
if ((shiftedReadAltRef != null) && (origReadAltRef.equals(shiftedReadAltRef))) {
return newCigar;
}
}
}
}
} catch (RuntimeException e) {
Logger.error("Error processing: " + seq + ", " + cigar.toString());
throw e;
}
return cigar;
}
private SAMRecord cloneRead(SAMRecord read) {
try {
return (SAMRecord) read.clone();
} catch (CloneNotSupportedException e) {
// Infamous "this should never happen" comment here.
e.printStackTrace();
throw new RuntimeException(e);
}
}
protected Cigar shiftCigarLeft(Cigar cigar, int positionsToShift) {
Cigar newCigar = new Cigar();
for (int i=0; i<cigar.getCigarElements().size(); i++) {
CigarElement elem = cigar.getCigarElement(i);
if (isFirstNonSoftClippedElem(i, cigar)) {
int newLen = elem.getLength() - positionsToShift;
if (newLen > 0) {
CigarElement newElem = new CigarElement(newLen, elem.getOperator());
newCigar.add(newElem);
}
} else if (isLastNonSoftClippedElem(i, cigar)) {
if (elem.getOperator() == CigarOperator.M) {
CigarElement newElem = new CigarElement(elem.getLength() + positionsToShift, CigarOperator.M);
newCigar.add(newElem);
} else {
CigarElement newElem = new CigarElement(positionsToShift, CigarOperator.M);
newCigar.add(elem);
newCigar.add(newElem);
}
} else {
newCigar.add(elem);
}
}
return newCigar;
}
private boolean isFirstNonSoftClippedElem(int idx, Cigar cigar) {
// First element, not soft clipped
if ((idx == 0) && (cigar.getCigarElement(0).getOperator() != CigarOperator.S)) {
return true;
}
// Second element, with first element soft clipped
if ((idx == 1) && (cigar.getCigarElement(0).getOperator() == CigarOperator.S)) {
return true;
}
return false;
}
private boolean isLastNonSoftClippedElem(int idx, Cigar cigar) {
int numElems = cigar.getCigarElements().size();
// Last element, not soft clipped.
if ((idx == numElems-1) && (cigar.getCigarElement(idx).getOperator() != CigarOperator.S)) {
return true;
}
// Second to last element, with last element soft clipped.
if ((idx == numElems-2) && (cigar.getCigarElement(numElems-1).getOperator() == CigarOperator.S)) {
return true;
}
return false;
}
private boolean containsIndel(Cigar cigar) {
for (CigarElement elem : cigar.getCigarElements()) {
if ((elem.getOperator() == CigarOperator.D) || (elem.getOperator() == CigarOperator.I)) {
return true;
}
}
return false;
}
private int firstIndelOffset(Cigar cigar) {
int pos = 0;
for (CigarElement elem : cigar.getCigarElements()) {
if ((elem.getOperator() == CigarOperator.D) || (elem.getOperator() == CigarOperator.I)) {
return pos;
} else if (elem.getOperator() != CigarOperator.S) {
pos += elem.getLength();
}
}
throw new IllegalArgumentException("No indel for record: [" + cigar + "]");
}
public static void main(String[] args) throws IOException {
String in = args[0];
String out = args[1];
String ref = args[2];
// String in = "/home/lmose/dev/abra/leftalign.sam";
// String out = "/home/lmose/dev/abra/la.out.sam";
// String ref = "/home/lmose/reference/chr1/chr1.fa";
SamReader reader = SAMRecordUtils.getSamReader(in);
SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(
reader.getFileHeader(), false, new File(out));
CompareToReference2 c2r = new CompareToReference2();
c2r.init(ref);
IndelShifter indelShifter = new IndelShifter();
for (SAMRecord read : reader) {
// SAMRecord shiftedRead = indelShifter.shiftIndelsLeft(read, c2r);
// writer.addAlignment(shiftedRead);
}
writer.close();
reader.close();
}
}
| src/main/java/abra/IndelShifter.java | /* Copyright 2013 University of North Carolina at Chapel Hill. All rights reserved. */
package abra;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
/**
* Utility class for shifting Indels into leftmost position.
*
* @author Lisle E. Mose (lmose at unc dot edu)
*/
public class IndelShifter {
public Cigar shiftAllIndelsLeft(int refStart, int refEnd, String chromosome, Cigar cigar, String seq, CompareToReference2 c2r) {
List<CigarElement> elems = new ArrayList<CigarElement>(cigar.getCigarElements());
int elemSize = elems.size();
for (int i=1; i<elemSize-1; i++) {
int refOffset = 0;
int readOffset = 0;
for (int j=0; j<i-1; j++) {
refOffset += getRefOffset(elems.get(j));
readOffset += getReadOffset(elems.get(j));
}
CigarElement prev = elems.get(i-1);
CigarElement elem = elems.get(i);
CigarElement next = elems.get(i+1);
if ((elem.getOperator() == CigarOperator.DELETION || elem.getOperator() == CigarOperator.INSERTION) &&
prev.getOperator() == CigarOperator.MATCH_OR_MISMATCH && next.getOperator() == CigarOperator.MATCH_OR_MISMATCH) {
// subset cigar here and attempt to shift
Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
chromosome, subCigar, subSeq, c2r);
//TODO: Merge abutting indels if applicable
elems.set(i-1, newCigar.getCigarElement(0));
elems.set(i, newCigar.getCigarElement(1));
if (newCigar.getCigarElements().size() == 3) {
elems.set(i+1, newCigar.getCigarElement(2));
} else {
elemSize -= 1;
}
}
}
return new Cigar(elems);
}
private int getRefOffset(CigarElement elem) {
int offset = -1;
switch(elem.getOperator()) {
case M:
case D:
offset = elem.getLength();
break;
case I:
offset = 0;
break;
default:
throw new IllegalArgumentException("Unexpected Cigar operator: " + elem.getOperator());
}
return offset;
}
private int getReadOffset(CigarElement elem) {
int offset = -1;
switch(elem.getOperator()) {
case M:
case I:
offset = elem.getLength();
break;
case D:
offset = 0;
break;
default:
throw new IllegalArgumentException("Unexpected Cigar operator: " + elem.getOperator());
}
return offset;
}
public Cigar shiftIndelsLeft(int refStart, int refEnd, String chromosome, Cigar cigar, String seq, CompareToReference2 c2r) {
try {
if (containsIndel(cigar)) {
int indelPos = firstIndelOffset(cigar);
String origReadAltRef = c2r.getAlternateReference(refStart, refEnd, chromosome, seq, cigar);
// System.out.println("o: " + origReadAltRef);
if (origReadAltRef != null) {
for (int i=indelPos; i>0; i--) {
Cigar newCigar = shiftCigarLeft(cigar, i);
String shiftedReadAltRef = c2r.getAlternateReference(refStart, refEnd, chromosome, seq, newCigar);
if ((shiftedReadAltRef != null) && (origReadAltRef.equals(shiftedReadAltRef))) {
return newCigar;
}
}
}
}
} catch (RuntimeException e) {
Logger.error("Error processing: " + seq + ", " + cigar.toString());
throw e;
}
return cigar;
}
private SAMRecord cloneRead(SAMRecord read) {
try {
return (SAMRecord) read.clone();
} catch (CloneNotSupportedException e) {
// Infamous "this should never happen" comment here.
e.printStackTrace();
throw new RuntimeException(e);
}
}
protected Cigar shiftCigarLeft(Cigar cigar, int positionsToShift) {
Cigar newCigar = new Cigar();
for (int i=0; i<cigar.getCigarElements().size(); i++) {
CigarElement elem = cigar.getCigarElement(i);
if (isFirstNonSoftClippedElem(i, cigar)) {
int newLen = elem.getLength() - positionsToShift;
if (newLen > 0) {
CigarElement newElem = new CigarElement(newLen, elem.getOperator());
newCigar.add(newElem);
}
} else if (isLastNonSoftClippedElem(i, cigar)) {
if (elem.getOperator() == CigarOperator.M) {
CigarElement newElem = new CigarElement(elem.getLength() + positionsToShift, CigarOperator.M);
newCigar.add(newElem);
} else {
CigarElement newElem = new CigarElement(positionsToShift, CigarOperator.M);
newCigar.add(elem);
newCigar.add(newElem);
}
} else {
newCigar.add(elem);
}
}
return newCigar;
}
private boolean isFirstNonSoftClippedElem(int idx, Cigar cigar) {
// First element, not soft clipped
if ((idx == 0) && (cigar.getCigarElement(0).getOperator() != CigarOperator.S)) {
return true;
}
// Second element, with first element soft clipped
if ((idx == 1) && (cigar.getCigarElement(0).getOperator() == CigarOperator.S)) {
return true;
}
return false;
}
private boolean isLastNonSoftClippedElem(int idx, Cigar cigar) {
int numElems = cigar.getCigarElements().size();
// Last element, not soft clipped.
if ((idx == numElems-1) && (cigar.getCigarElement(idx).getOperator() != CigarOperator.S)) {
return true;
}
// Second to last element, with last element soft clipped.
if ((idx == numElems-2) && (cigar.getCigarElement(numElems-1).getOperator() == CigarOperator.S)) {
return true;
}
return false;
}
private boolean containsIndel(Cigar cigar) {
for (CigarElement elem : cigar.getCigarElements()) {
if ((elem.getOperator() == CigarOperator.D) || (elem.getOperator() == CigarOperator.I)) {
return true;
}
}
return false;
}
private int firstIndelOffset(Cigar cigar) {
int pos = 0;
for (CigarElement elem : cigar.getCigarElements()) {
if ((elem.getOperator() == CigarOperator.D) || (elem.getOperator() == CigarOperator.I)) {
return pos;
} else if (elem.getOperator() != CigarOperator.S) {
pos += elem.getLength();
}
}
throw new IllegalArgumentException("No indel for record: [" + cigar + "]");
}
public static void main(String[] args) throws IOException {
String in = args[0];
String out = args[1];
String ref = args[2];
// String in = "/home/lmose/dev/abra/leftalign.sam";
// String out = "/home/lmose/dev/abra/la.out.sam";
// String ref = "/home/lmose/reference/chr1/chr1.fa";
SamReader reader = SAMRecordUtils.getSamReader(in);
SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(
reader.getFileHeader(), false, new File(out));
CompareToReference2 c2r = new CompareToReference2();
c2r.init(ref);
IndelShifter indelShifter = new IndelShifter();
for (SAMRecord read : reader) {
// SAMRecord shiftedRead = indelShifter.shiftIndelsLeft(read, c2r);
// writer.addAlignment(shiftedRead);
}
writer.close();
reader.close();
}
}
| Capture and log indel shift error. | src/main/java/abra/IndelShifter.java | Capture and log indel shift error. | <ide><path>rc/main/java/abra/IndelShifter.java
<ide>
<ide> public Cigar shiftAllIndelsLeft(int refStart, int refEnd, String chromosome, Cigar cigar, String seq, CompareToReference2 c2r) {
<ide>
<del> List<CigarElement> elems = new ArrayList<CigarElement>(cigar.getCigarElements());
<del>
<del> int elemSize = elems.size();
<del>
<del> for (int i=1; i<elemSize-1; i++) {
<del>
<del> int refOffset = 0;
<del> int readOffset = 0;
<del>
<del> for (int j=0; j<i-1; j++) {
<del> refOffset += getRefOffset(elems.get(j));
<del> readOffset += getReadOffset(elems.get(j));
<del> }
<del>
<del> CigarElement prev = elems.get(i-1);
<del> CigarElement elem = elems.get(i);
<del> CigarElement next = elems.get(i+1);
<del>
<del> if ((elem.getOperator() == CigarOperator.DELETION || elem.getOperator() == CigarOperator.INSERTION) &&
<del> prev.getOperator() == CigarOperator.MATCH_OR_MISMATCH && next.getOperator() == CigarOperator.MATCH_OR_MISMATCH) {
<del>
<del> // subset cigar here and attempt to shift
<del> Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
<del> String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
<del> Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
<del> chromosome, subCigar, subSeq, c2r);
<del>
<del> //TODO: Merge abutting indels if applicable
<del> elems.set(i-1, newCigar.getCigarElement(0));
<del> elems.set(i, newCigar.getCigarElement(1));
<del> if (newCigar.getCigarElements().size() == 3) {
<del> elems.set(i+1, newCigar.getCigarElement(2));
<del> } else {
<del> elemSize -= 1;
<del> }
<del> }
<del> }
<del>
<del> return new Cigar(elems);
<add> try {
<add>
<add> List<CigarElement> elems = new ArrayList<CigarElement>(cigar.getCigarElements());
<add>
<add> int elemSize = elems.size();
<add>
<add> for (int i=1; i<elemSize-1; i++) {
<add>
<add> int refOffset = 0;
<add> int readOffset = 0;
<add>
<add> for (int j=0; j<i-1; j++) {
<add> refOffset += getRefOffset(elems.get(j));
<add> readOffset += getReadOffset(elems.get(j));
<add> }
<add>
<add> CigarElement prev = elems.get(i-1);
<add> CigarElement elem = elems.get(i);
<add> CigarElement next = elems.get(i+1);
<add>
<add> if ((elem.getOperator() == CigarOperator.DELETION || elem.getOperator() == CigarOperator.INSERTION) &&
<add> prev.getOperator() == CigarOperator.MATCH_OR_MISMATCH && next.getOperator() == CigarOperator.MATCH_OR_MISMATCH) {
<add>
<add> // subset cigar here and attempt to shift
<add> Cigar subCigar = new Cigar(Arrays.asList(prev, elem, next));
<add> String subSeq = seq.substring(readOffset, readOffset+subCigar.getReadLength());
<add> Cigar newCigar = shiftIndelsLeft(refStart + refOffset, refStart + refOffset + subCigar.getReferenceLength(),
<add> chromosome, subCigar, subSeq, c2r);
<add>
<add> //TODO: Merge abutting indels if applicable
<add> elems.set(i-1, newCigar.getCigarElement(0));
<add> elems.set(i, newCigar.getCigarElement(1));
<add> if (newCigar.getCigarElements().size() == 3) {
<add> elems.set(i+1, newCigar.getCigarElement(2));
<add> } else {
<add> elemSize -= 1;
<add> }
<add> }
<add> }
<add>
<add> return new Cigar(elems);
<add> } catch (RuntimeException e) {
<add> e.printStackTrace();
<add> Logger.error("Error on: " + refStart + ", " + refEnd + "," + chromosome + ", " + cigar + ", " + seq);
<add> throw e;
<add> }
<ide> }
<ide>
<ide> private int getRefOffset(CigarElement elem) { |
|
Java | apache-2.0 | 0eb5649dc15df033d1492843d42f9910fbc89724 | 0 | etnetera/jmeter,ham1/jmeter,benbenw/jmeter,apache/jmeter,etnetera/jmeter,benbenw/jmeter,benbenw/jmeter,etnetera/jmeter,apache/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter,ham1/jmeter,ham1/jmeter,apache/jmeter,ham1/jmeter,apache/jmeter,apache/jmeter,benbenw/jmeter | /*
* 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.jmeter.protocol.http.proxy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang3.CharUtils;
import org.apache.jmeter.protocol.http.config.MultipartUrlConfig;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.gui.HeaderPanel;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerFactory;
import org.apache.jmeter.protocol.http.util.ConversionUtils;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
//For unit tests, @see TestHttpRequestHdr
/**
* The headers of the client HTTP request.
*
*/
public class HttpRequestHdr {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final String HTTP = "http"; // $NON-NLS-1$
private static final String HTTPS = "https"; // $NON-NLS-1$
private static final String PROXY_CONNECTION = "proxy-connection"; // $NON-NLS-1$
public static final String CONTENT_TYPE = "content-type"; // $NON-NLS-1$
public static final String CONTENT_LENGTH = "content-length"; // $NON-NLS-1$
/**
* Http Request method, uppercased, e.g. GET or POST.
*/
private String method = ""; // $NON-NLS-1$
/** CONNECT url. */
private String paramHttps = ""; // $NON-NLS-1$
/**
* The requested url. The universal resource locator that hopefully uniquely
* describes the object or service the client is requesting.
*/
private String url = ""; // $NON-NLS-1$
/**
* Version of http being used. Such as HTTP/1.0.
*/
private String version = ""; // NOTREAD // $NON-NLS-1$
private byte[] rawPostData;
private final Map<String, Header> headers = new HashMap<String, Header>();
private final String httpSamplerName;
private HeaderManager headerManager;
public HttpRequestHdr() {
this.httpSamplerName = ""; // $NON-NLS-1$
}
/**
* @param httpSamplerName the http sampler name
*/
public HttpRequestHdr(String httpSamplerName) {
this.httpSamplerName = httpSamplerName;
}
/**
* Parses a http header from a stream.
*
* @param in
* the stream to parse.
* @return array of bytes from client.
*/
public byte[] parse(InputStream in) throws IOException {
boolean inHeaders = true;
int readLength = 0;
int dataLength = 0;
boolean firstLine = true;
ByteArrayOutputStream clientRequest = new ByteArrayOutputStream();
ByteArrayOutputStream line = new ByteArrayOutputStream();
int x;
while ((inHeaders || readLength < dataLength) && ((x = in.read()) != -1)) {
line.write(x);
clientRequest.write(x);
if (firstLine && !CharUtils.isAscii((char) x)){// includes \n
throw new IllegalArgumentException("Only ASCII supported in headers (perhaps SSL was used?)");
}
if (inHeaders && (byte) x == (byte) '\n') { // $NON-NLS-1$
if (line.size() < 3) {
inHeaders = false;
firstLine = false; // cannot be first line either
}
if (firstLine) {
parseFirstLine(line.toString());
firstLine = false;
} else {
// parse other header lines, looking for Content-Length
final int contentLen = parseLine(line.toString());
if (contentLen > 0) {
dataLength = contentLen; // Save the last valid content length one
}
}
if (log.isDebugEnabled()){
log.debug("Client Request Line: " + line.toString());
}
line.reset();
} else if (!inHeaders) {
readLength++;
}
}
// Keep the raw post data
rawPostData = line.toByteArray();
if (log.isDebugEnabled()){
log.debug("rawPostData in default JRE encoding: " + new String(rawPostData)); // TODO - charset?
log.debug("Request: " + clientRequest.toString());
}
return clientRequest.toByteArray();
}
private void parseFirstLine(String firstLine) {
if (log.isDebugEnabled()) {
log.debug("browser request: " + firstLine);
}
StringTokenizer tz = new StringTokenizer(firstLine);
method = getToken(tz).toUpperCase(java.util.Locale.ENGLISH);
url = getToken(tz);
version = getToken(tz);
if (log.isDebugEnabled()) {
log.debug("parser input: " + firstLine);
log.debug("parsed method: " + method);
log.debug("parsed url: " + url);
log.debug("parsed version:" + version);
}
// SSL connection
if (getMethod().startsWith(HTTPConstants.CONNECT)) {
paramHttps = url;
}
/* The next line looks odd, but proxied HTTP requests look like:
* GET http://www.apache.org/foundation/ HTTP/1.1
* i.e. url starts with "http:", not "/"
* whereas HTTPS proxy requests look like:
* CONNECT www.google.co.uk:443 HTTP/1.1
* followed by
* GET /?gws_rd=cr HTTP/1.1
*/
if (url.startsWith("/")) { // it must be a proxied HTTPS request
url = HTTPS + "://" + paramHttps + url; // $NON-NLS-1$
}
// JAVA Impl accepts URLs with unsafe characters so don't do anything
if(HTTPSamplerFactory.IMPL_JAVA.equals(httpSamplerName)) {
log.debug("First Line: " + url);
return;
}
try {
// See Bug 54482
URI testCleanUri = new URI(url);
if(log.isDebugEnabled()) {
log.debug("Successfully built URI from url:"+url+" => " + testCleanUri.toString());
}
} catch (URISyntaxException e) {
log.warn("Url '" + url + "' contains unsafe characters, will escape it, message:"+e.getMessage());
try {
String escapedUrl = ConversionUtils.escapeIllegalURLCharacters(url);
if(log.isDebugEnabled()) {
log.debug("Successfully escaped url:'"+url +"' to:'"+escapedUrl+"'");
}
url = escapedUrl;
} catch (Exception e1) {
log.error("Error escaping URL:'"+url+"', message:"+e1.getMessage());
}
}
log.debug("First Line: " + url);
}
/*
* Split line into name/value pairs and store in headers if relevant
* If name = "content-length", then return value as int, else return 0
*/
private int parseLine(String nextLine) {
int colon = nextLine.indexOf(':');
if (colon <= 0){
return 0; // Nothing to do
}
String name = nextLine.substring(0, colon).trim();
String value = nextLine.substring(colon+1).trim();
headers.put(name.toLowerCase(java.util.Locale.ENGLISH), new Header(name, value));
if (name.equalsIgnoreCase(CONTENT_LENGTH)) {
return Integer.parseInt(value);
}
return 0;
}
private HeaderManager createHeaderManager() {
HeaderManager manager = new HeaderManager();
for (String key : headers.keySet()) {
if (!key.equals(PROXY_CONNECTION)
&& !key.equals(CONTENT_LENGTH)
&& !key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
manager.add(headers.get(key));
}
}
manager.setName(JMeterUtils.getResString("header_manager_title")); // $NON-NLS-1$
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
return manager;
}
public HeaderManager getHeaderManager() {
if(headerManager == null) {
headerManager = createHeaderManager();
}
return headerManager;
}
public String getContentType() {
Header contentTypeHeader = headers.get(CONTENT_TYPE);
if (contentTypeHeader != null) {
return contentTypeHeader.getValue();
}
return null;
}
private boolean isMultipart(String contentType) {
if (contentType != null && contentType.startsWith(HTTPConstants.MULTIPART_FORM_DATA)) {
return true;
}
return false;
}
public MultipartUrlConfig getMultipartConfig(String contentType) {
if(isMultipart(contentType)) {
// Get the boundary string for the multiparts from the content type
String boundaryString = contentType.substring(contentType.toLowerCase(java.util.Locale.ENGLISH).indexOf("boundary=") + "boundary=".length());
return new MultipartUrlConfig(boundaryString);
}
return null;
}
//
// Parsing Methods
//
/**
* Find the //server.name from an url.
*
* @return server's internet name
*/
public String serverName() {
// chop to "server.name:x/thing"
String str = url;
int i = str.indexOf("//"); // $NON-NLS-1$
if (i > 0) {
str = str.substring(i + 2);
}
// chop to server.name:xx
i = str.indexOf('/'); // $NON-NLS-1$
if (0 < i) {
str = str.substring(0, i);
}
// chop to server.name
i = str.lastIndexOf(':'); // $NON-NLS-1$
if (0 < i) {
str = str.substring(0, i);
}
// Handle IPv6 urls
if(str.startsWith("[")&& str.endsWith("]")) {
return str.substring(1, str.length()-1);
}
return str;
}
// TODO replace repeated substr() above and below with more efficient method.
/**
* Find the :PORT from http://server.ect:PORT/some/file.xxx
*
* @return server's port (or UNSPECIFIED if not found)
*/
public int serverPort() {
String str = url;
// chop to "server.name:x/thing"
int i = str.indexOf("//");
if (i > 0) {
str = str.substring(i + 2);
}
// chop to server.name:xx
i = str.indexOf('/');
if (0 < i) {
str = str.substring(0, i);
}
// chop to server.name
i = str.lastIndexOf(':');
if (0 < i) {
return Integer.parseInt(str.substring(i + 1).trim());
}
return HTTPSamplerBase.UNSPECIFIED_PORT;
}
/**
* Find the /some/file.xxxx from http://server.ect:PORT/some/file.xxx
*
* @return the path
*/
public String getPath() {
String str = url;
int i = str.indexOf("//");
if (i > 0) {
str = str.substring(i + 2);
}
i = str.indexOf('/');
if (i < 0) {
return "";
}
return str.substring(i);
}
/**
* Returns the url string extracted from the first line of the client request.
*
* @return the url
*/
public String getUrl(){
return url;
}
/**
* Returns the method string extracted from the first line of the client request.
*
* @return the method (will always be upper case)
*/
public String getMethod(){
return method;
}
/**
* Returns the next token in a string.
*
* @param tk
* String that is partially tokenized.
* @return The remainder
*/
private String getToken(StringTokenizer tk) {
if (tk.hasMoreTokens()) {
return tk.nextToken();
}
return "";// $NON-NLS-1$
}
// /**
// * Returns the remainder of a tokenized string.
// *
// * @param tk
// * String that is partially tokenized.
// * @return The remainder
// */
// private String getRemainder(StringTokenizer tk) {
// StringBuilder strBuff = new StringBuilder();
// if (tk.hasMoreTokens()) {
// strBuff.append(tk.nextToken());
// }
// while (tk.hasMoreTokens()) {
// strBuff.append(" "); // $NON-NLS-1$
// strBuff.append(tk.nextToken());
// }
// return strBuff.toString();
// }
public String getUrlWithoutQuery(URL _url) {
String fullUrl = _url.toString();
String urlWithoutQuery = fullUrl;
String query = _url.getQuery();
if(query != null) {
// Get rid of the query and the ?
urlWithoutQuery = urlWithoutQuery.substring(0, urlWithoutQuery.length() - query.length() - 1);
}
return urlWithoutQuery;
}
/**
* @return the httpSamplerName
*/
public String getHttpSamplerName() {
return httpSamplerName;
}
/**
* @return byte[] Raw post data
*/
public byte[] getRawPostData() {
return rawPostData;
}
/**
* @param sampler {@link HTTPSamplerBase}
* @return String Protocol (http or https)
*/
public String getProtocol(HTTPSamplerBase sampler) {
if (url.indexOf("//") > -1) {
String protocol = url.substring(0, url.indexOf(':'));
if (log.isDebugEnabled()) {
log.debug("Proxy: setting protocol to : " + protocol);
}
return protocol;
} else if (sampler.getPort() == HTTPConstants.DEFAULT_HTTPS_PORT) {
if (log.isDebugEnabled()) {
log.debug("Proxy: setting protocol to https");
}
return HTTPS;
} else {
if (log.isDebugEnabled()) {
log.debug("Proxy setting default protocol to: http");
}
return HTTP;
}
}
}
| src/protocol/http/org/apache/jmeter/protocol/http/proxy/HttpRequestHdr.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.jmeter.protocol.http.proxy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.lang3.CharUtils;
import org.apache.jmeter.protocol.http.config.MultipartUrlConfig;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.gui.HeaderPanel;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase;
import org.apache.jmeter.protocol.http.sampler.HTTPSamplerFactory;
import org.apache.jmeter.protocol.http.util.ConversionUtils;
import org.apache.jmeter.protocol.http.util.HTTPConstants;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
//For unit tests, @see TestHttpRequestHdr
/**
* The headers of the client HTTP request.
*
*/
public class HttpRequestHdr {
private static final Logger log = LoggingManager.getLoggerForClass();
private static final String HTTP = "http"; // $NON-NLS-1$
private static final String HTTPS = "https"; // $NON-NLS-1$
private static final String PROXY_CONNECTION = "proxy-connection"; // $NON-NLS-1$
public static final String CONTENT_TYPE = "content-type"; // $NON-NLS-1$
public static final String CONTENT_LENGTH = "content-length"; // $NON-NLS-1$
/**
* Http Request method, uppercased, e.g. GET or POST.
*/
private String method = ""; // $NON-NLS-1$
/** CONNECT url. */
private String paramHttps = ""; // $NON-NLS-1$
/**
* The requested url. The universal resource locator that hopefully uniquely
* describes the object or service the client is requesting.
*/
private String url = ""; // $NON-NLS-1$
/**
* Version of http being used. Such as HTTP/1.0.
*/
private String version = ""; // NOTREAD // $NON-NLS-1$
private byte[] rawPostData;
private final Map<String, Header> headers = new HashMap<String, Header>();
private final String httpSamplerName;
private HeaderManager headerManager;
public HttpRequestHdr() {
this.httpSamplerName = ""; // $NON-NLS-1$
}
/**
* @param httpSamplerName the http sampler name
*/
public HttpRequestHdr(String httpSamplerName) {
this.httpSamplerName = httpSamplerName;
}
/**
* Parses a http header from a stream.
*
* @param in
* the stream to parse.
* @return array of bytes from client.
*/
public byte[] parse(InputStream in) throws IOException {
boolean inHeaders = true;
int readLength = 0;
int dataLength = 0;
boolean firstLine = true;
ByteArrayOutputStream clientRequest = new ByteArrayOutputStream();
ByteArrayOutputStream line = new ByteArrayOutputStream();
int x;
while ((inHeaders || readLength < dataLength) && ((x = in.read()) != -1)) {
line.write(x);
clientRequest.write(x);
if (firstLine && !CharUtils.isAscii((char) x)){// includes \n
throw new IllegalArgumentException("Only ASCII supported in headers (perhaps SSL was used?)");
}
if (inHeaders && (byte) x == (byte) '\n') { // $NON-NLS-1$
if (line.size() < 3) {
inHeaders = false;
firstLine = false; // cannot be first line either
}
if (firstLine) {
parseFirstLine(line.toString());
firstLine = false;
} else {
// parse other header lines, looking for Content-Length
final int contentLen = parseLine(line.toString());
if (contentLen > 0) {
dataLength = contentLen; // Save the last valid content length one
}
}
if (log.isDebugEnabled()){
log.debug("Client Request Line: " + line.toString());
}
line.reset();
} else if (!inHeaders) {
readLength++;
}
}
// Keep the raw post data
rawPostData = line.toByteArray();
if (log.isDebugEnabled()){
log.debug("rawPostData in default JRE encoding: " + new String(rawPostData)); // TODO - charset?
log.debug("Request: " + clientRequest.toString());
}
return clientRequest.toByteArray();
}
private void parseFirstLine(String firstLine) {
if (log.isDebugEnabled()) {
log.debug("browser request: " + firstLine);
}
StringTokenizer tz = new StringTokenizer(firstLine);
method = getToken(tz).toUpperCase(java.util.Locale.ENGLISH);
url = getToken(tz);
version = getToken(tz);
if (log.isDebugEnabled()) {
log.debug("parser input: " + firstLine);
log.debug("parsed method: " + method);
log.debug("parsed url: " + url);
log.debug("parsed version:" + version);
}
// SSL connection
if (getMethod().startsWith(HTTPConstants.CONNECT)) {
paramHttps = url;
}
if (url.startsWith("/")) {
url = HTTPS + "://" + paramHttps + url; // $NON-NLS-1$
}
// JAVA Impl accepts URLs with unsafe characters so don't do anything
if(HTTPSamplerFactory.IMPL_JAVA.equals(httpSamplerName)) {
log.debug("First Line: " + url);
return;
}
try {
// See Bug 54482
URI testCleanUri = new URI(url);
if(log.isDebugEnabled()) {
log.debug("Successfully built URI from url:"+url+" => " + testCleanUri.toString());
}
} catch (URISyntaxException e) {
log.warn("Url '" + url + "' contains unsafe characters, will escape it, message:"+e.getMessage());
try {
String escapedUrl = ConversionUtils.escapeIllegalURLCharacters(url);
if(log.isDebugEnabled()) {
log.debug("Successfully escaped url:'"+url +"' to:'"+escapedUrl+"'");
}
url = escapedUrl;
} catch (Exception e1) {
log.error("Error escaping URL:'"+url+"', message:"+e1.getMessage());
}
}
log.debug("First Line: " + url);
}
/*
* Split line into name/value pairs and store in headers if relevant
* If name = "content-length", then return value as int, else return 0
*/
private int parseLine(String nextLine) {
int colon = nextLine.indexOf(':');
if (colon <= 0){
return 0; // Nothing to do
}
String name = nextLine.substring(0, colon).trim();
String value = nextLine.substring(colon+1).trim();
headers.put(name.toLowerCase(java.util.Locale.ENGLISH), new Header(name, value));
if (name.equalsIgnoreCase(CONTENT_LENGTH)) {
return Integer.parseInt(value);
}
return 0;
}
private HeaderManager createHeaderManager() {
HeaderManager manager = new HeaderManager();
for (String key : headers.keySet()) {
if (!key.equals(PROXY_CONNECTION)
&& !key.equals(CONTENT_LENGTH)
&& !key.equalsIgnoreCase(HTTPConstants.HEADER_CONNECTION)) {
manager.add(headers.get(key));
}
}
manager.setName(JMeterUtils.getResString("header_manager_title")); // $NON-NLS-1$
manager.setProperty(TestElement.TEST_CLASS, HeaderManager.class.getName());
manager.setProperty(TestElement.GUI_CLASS, HeaderPanel.class.getName());
return manager;
}
public HeaderManager getHeaderManager() {
if(headerManager == null) {
headerManager = createHeaderManager();
}
return headerManager;
}
public String getContentType() {
Header contentTypeHeader = headers.get(CONTENT_TYPE);
if (contentTypeHeader != null) {
return contentTypeHeader.getValue();
}
return null;
}
private boolean isMultipart(String contentType) {
if (contentType != null && contentType.startsWith(HTTPConstants.MULTIPART_FORM_DATA)) {
return true;
}
return false;
}
public MultipartUrlConfig getMultipartConfig(String contentType) {
if(isMultipart(contentType)) {
// Get the boundary string for the multiparts from the content type
String boundaryString = contentType.substring(contentType.toLowerCase(java.util.Locale.ENGLISH).indexOf("boundary=") + "boundary=".length());
return new MultipartUrlConfig(boundaryString);
}
return null;
}
//
// Parsing Methods
//
/**
* Find the //server.name from an url.
*
* @return server's internet name
*/
public String serverName() {
// chop to "server.name:x/thing"
String str = url;
int i = str.indexOf("//"); // $NON-NLS-1$
if (i > 0) {
str = str.substring(i + 2);
}
// chop to server.name:xx
i = str.indexOf('/'); // $NON-NLS-1$
if (0 < i) {
str = str.substring(0, i);
}
// chop to server.name
i = str.lastIndexOf(':'); // $NON-NLS-1$
if (0 < i) {
str = str.substring(0, i);
}
// Handle IPv6 urls
if(str.startsWith("[")&& str.endsWith("]")) {
return str.substring(1, str.length()-1);
}
return str;
}
// TODO replace repeated substr() above and below with more efficient method.
/**
* Find the :PORT from http://server.ect:PORT/some/file.xxx
*
* @return server's port (or UNSPECIFIED if not found)
*/
public int serverPort() {
String str = url;
// chop to "server.name:x/thing"
int i = str.indexOf("//");
if (i > 0) {
str = str.substring(i + 2);
}
// chop to server.name:xx
i = str.indexOf('/');
if (0 < i) {
str = str.substring(0, i);
}
// chop to server.name
i = str.lastIndexOf(':');
if (0 < i) {
return Integer.parseInt(str.substring(i + 1).trim());
}
return HTTPSamplerBase.UNSPECIFIED_PORT;
}
/**
* Find the /some/file.xxxx from http://server.ect:PORT/some/file.xxx
*
* @return the path
*/
public String getPath() {
String str = url;
int i = str.indexOf("//");
if (i > 0) {
str = str.substring(i + 2);
}
i = str.indexOf('/');
if (i < 0) {
return "";
}
return str.substring(i);
}
/**
* Returns the url string extracted from the first line of the client request.
*
* @return the url
*/
public String getUrl(){
return url;
}
/**
* Returns the method string extracted from the first line of the client request.
*
* @return the method (will always be upper case)
*/
public String getMethod(){
return method;
}
/**
* Returns the next token in a string.
*
* @param tk
* String that is partially tokenized.
* @return The remainder
*/
private String getToken(StringTokenizer tk) {
if (tk.hasMoreTokens()) {
return tk.nextToken();
}
return "";// $NON-NLS-1$
}
// /**
// * Returns the remainder of a tokenized string.
// *
// * @param tk
// * String that is partially tokenized.
// * @return The remainder
// */
// private String getRemainder(StringTokenizer tk) {
// StringBuilder strBuff = new StringBuilder();
// if (tk.hasMoreTokens()) {
// strBuff.append(tk.nextToken());
// }
// while (tk.hasMoreTokens()) {
// strBuff.append(" "); // $NON-NLS-1$
// strBuff.append(tk.nextToken());
// }
// return strBuff.toString();
// }
public String getUrlWithoutQuery(URL _url) {
String fullUrl = _url.toString();
String urlWithoutQuery = fullUrl;
String query = _url.getQuery();
if(query != null) {
// Get rid of the query and the ?
urlWithoutQuery = urlWithoutQuery.substring(0, urlWithoutQuery.length() - query.length() - 1);
}
return urlWithoutQuery;
}
/**
* @return the httpSamplerName
*/
public String getHttpSamplerName() {
return httpSamplerName;
}
/**
* @return byte[] Raw post data
*/
public byte[] getRawPostData() {
return rawPostData;
}
/**
* @param sampler {@link HTTPSamplerBase}
* @return String Protocol (http or https)
*/
public String getProtocol(HTTPSamplerBase sampler) {
if (url.indexOf("//") > -1) {
String protocol = url.substring(0, url.indexOf(':'));
if (log.isDebugEnabled()) {
log.debug("Proxy: setting protocol to : " + protocol);
}
return protocol;
} else if (sampler.getPort() == HTTPConstants.DEFAULT_HTTPS_PORT) {
if (log.isDebugEnabled()) {
log.debug("Proxy: setting protocol to https");
}
return HTTPS;
} else {
if (log.isDebugEnabled()) {
log.debug("Proxy setting default protocol to: http");
}
return HTTP;
}
}
}
| Add code docn
git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1511538 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 775eda63f54ddc13a1d31a6936c6b15940c9427e | src/protocol/http/org/apache/jmeter/protocol/http/proxy/HttpRequestHdr.java | Add code docn | <ide><path>rc/protocol/http/org/apache/jmeter/protocol/http/proxy/HttpRequestHdr.java
<ide> if (getMethod().startsWith(HTTPConstants.CONNECT)) {
<ide> paramHttps = url;
<ide> }
<del> if (url.startsWith("/")) {
<add> /* The next line looks odd, but proxied HTTP requests look like:
<add> * GET http://www.apache.org/foundation/ HTTP/1.1
<add> * i.e. url starts with "http:", not "/"
<add> * whereas HTTPS proxy requests look like:
<add> * CONNECT www.google.co.uk:443 HTTP/1.1
<add> * followed by
<add> * GET /?gws_rd=cr HTTP/1.1
<add> */
<add> if (url.startsWith("/")) { // it must be a proxied HTTPS request
<ide> url = HTTPS + "://" + paramHttps + url; // $NON-NLS-1$
<ide> }
<ide> // JAVA Impl accepts URLs with unsafe characters so don't do anything |
|
Java | mit | 19c8d3aa322c47b8ca793ce9c76e3c1f5f80f83f | 0 | ulriknyman/H-Uppaal | package SW9.controllers;
import SW9.HUPPAAL;
import SW9.abstractions.Component;
import SW9.abstractions.Edge;
import SW9.abstractions.Location;
import SW9.backend.UPPAALDriver;
import SW9.presentations.CanvasPresentation;
import SW9.presentations.HUPPAALPresentation;
import SW9.presentations.ProjectPanePresentation;
import SW9.presentations.QueryPanePresentation;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.EnabledColor;
import SW9.utility.helpers.SelectHelper;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXRippler;
import com.jfoenix.controls.JFXTextField;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.util.Pair;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class HUPPAALController implements Initializable {
public StackPane root;
public BorderPane bottomStatusBar;
public QueryPanePresentation queryPane;
public ProjectPanePresentation filePane;
public StackPane toolbar;
public MenuBar menuBar;
public Label queryPaneFillerElement;
public Label filePaneFillerElement;
public CanvasPresentation canvas;
public StackPane dialogContainer;
public JFXDialog dialog;
public StackPane modalBar;
public JFXTextField queryTextField;
public JFXTextField commentTextField;
public JFXRippler generateUppaalModel;
public JFXRippler colorSelected;
public JFXRippler deleteSelected;
public JFXRippler undo;
public JFXRippler redo;
public JFXRippler delete;
public ImageView logo;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
// Keybind for toggling the query pane
KeyboardTracker.registerKeybind(KeyboardTracker.TOGGLE_QUERY_PANE, new Keybind(new KeyCodeCombination(KeyCode.Q), () -> {
((HUPPAALPresentation) root).toggleQueryPane();
}));
// Keybind for toggling the file pane
KeyboardTracker.registerKeybind(KeyboardTracker.TOGGLE_FILE_PANE, new Keybind(new KeyCodeCombination(KeyCode.F), () -> {
((HUPPAALPresentation) root).toggleFilePane();
}));
dialog.setDialogContainer(dialogContainer);
dialogContainer.opacityProperty().bind(dialog.getChildren().get(0).scaleXProperty());
dialog.setOnDialogClosed(event -> dialogContainer.setVisible(false));
// Keybind for showing dialog // todo: remove this when done with testing
KeyboardTracker.registerKeybind("DIALOG", new Keybind(new KeyCodeCombination(KeyCode.I), () -> {
dialogContainer.setVisible(true);
dialog.show();
}));
// Keybind for deleting the selected elements
KeyboardTracker.registerKeybind(KeyboardTracker.DELETE_SELECTED, new Keybind(new KeyCodeCombination(KeyCode.DELETE), this::deleteSelectedClicked));
// Keybinds for coloring the selected elements
EnabledColor.enabledColors.forEach(enabledColor -> {
KeyboardTracker.registerKeybind(KeyboardTracker.COLOR_SELECTED + "_" + enabledColor.keyCode.getName(), new Keybind(new KeyCodeCombination(enabledColor.keyCode), () -> {
final List<Pair<SelectHelper.ColorSelectable, EnabledColor>> previousColor = new ArrayList<>();
SelectHelper.getSelectedElements().forEach(selectable -> {
previousColor.add(new Pair<>(selectable, new EnabledColor(selectable.getColor(), selectable.getColorIntensity())));
});
UndoRedoStack.push(() -> { // Perform
SelectHelper.getSelectedElements().forEach(selectable -> {
selectable.color(enabledColor.color, enabledColor.intensity);
});
}, () -> { // Undo
previousColor.forEach(selectableEnabledColorPair -> {
selectableEnabledColorPair.getKey().color(selectableEnabledColorPair.getValue().color, selectableEnabledColorPair.getValue().intensity);
});
}, String.format("Changed the color of %d elements to %s", previousColor.size(), enabledColor.color.name()), "color-lens");
SelectHelper.clearSelectedElements();
}));
});
final BooleanProperty hasChanged = new SimpleBooleanProperty(false);
HUPPAAL.getProject().getComponents().addListener(new ListChangeListener<Component>() {
@Override
public void onChanged(final Change<? extends Component> c) {
if (!hasChanged.get()) {
CanvasController.setActiveComponent(HUPPAAL.getProject().getComponents().get(0));
hasChanged.set(true);
}
}
});
}
@FXML
private void generateUppaalModelClicked() {
UPPAALDriver.verify("E<> true", // todo: consider creating an interface for generating the model instead of this query
aBoolean -> {
// success
System.out.println("Generated UPPAAL file!");
},
e -> {
System.out.println("ERROR");
},
HUPPAAL.getProject().getComponents()
);
}
@FXML
private void deleteSelectedClicked() {
if (SelectHelper.getSelectedElements().size() == 0) return;
// Run through the selected elements and look for something that we can delete
SelectHelper.getSelectedElements().forEach(selectable -> {
if (selectable instanceof LocationController) {
final Component component = ((LocationController) selectable).getComponent();
final Location location = ((LocationController) selectable).getLocation();
final double previousX = location.getX();
final double previousY = location.getY();
final Location initialLocation = component.getInitialLocation();
final Location finalLocation = component.getFinalLocation();
if (location.equals(initialLocation) || location.equals(finalLocation)) {
return; // Do not delete initial or final locations
}
UndoRedoStack.push(() -> { // Perform
// Remove the location
component.getLocations().remove(location);
}, () -> { // Undo
// Re-all the location
component.getLocations().add(location);
location.xProperty().unbind();
location.xProperty().set(previousX);
location.yProperty().unbind();
location.yProperty().set(previousY);
}, String.format("Deleted %s", selectable.toString()), "delete");
} else if (selectable instanceof EdgeController) {
final Component component = ((EdgeController) selectable).getComponent();
final Edge edge = ((EdgeController) selectable).getEdge();
UndoRedoStack.push(() -> { // Perform
// Remove the edge
component.getEdges().remove(edge);
}, () -> { // Undo
// Re-all the edge
component.getEdges().add(edge);
}, String.format("Deleted %s", selectable.toString()), "delete");
}
});
SelectHelper.clearSelectedElements();
}
@FXML
private void undoClicked() {
UndoRedoStack.undo();
}
@FXML
private void redoClicked() {
UndoRedoStack.redo();
}
@FXML
private void deleteClicked() {
// todo: add a confirmation dialog
final Component activeComponent = CanvasController.getActiveComponent();
if (activeComponent == null) return;
UndoRedoStack.push(() -> { // Perform
HUPPAAL.getProject().getComponents().remove(activeComponent);
}, () -> { // Undo
HUPPAAL.getProject().getComponents().add(activeComponent);
CanvasController.setActiveComponent(activeComponent);
}, String.format("Deleted component %s", activeComponent.getName()), "delete");
}
}
| src/main/java/SW9/controllers/HUPPAALController.java | package SW9.controllers;
import SW9.HUPPAAL;
import SW9.abstractions.Component;
import SW9.abstractions.Edge;
import SW9.abstractions.Location;
import SW9.backend.UPPAALDriver;
import SW9.presentations.CanvasPresentation;
import SW9.presentations.HUPPAALPresentation;
import SW9.presentations.ProjectPanePresentation;
import SW9.presentations.QueryPanePresentation;
import SW9.utility.UndoRedoStack;
import SW9.utility.colors.EnabledColor;
import SW9.utility.helpers.SelectHelper;
import SW9.utility.keyboard.Keybind;
import SW9.utility.keyboard.KeyboardTracker;
import com.jfoenix.controls.JFXDialog;
import com.jfoenix.controls.JFXRippler;
import com.jfoenix.controls.JFXTextField;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.util.Pair;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
public class HUPPAALController implements Initializable {
public StackPane root;
public BorderPane bottomStatusBar;
public QueryPanePresentation queryPane;
public ProjectPanePresentation filePane;
public StackPane toolbar;
public MenuBar menuBar;
public Label queryPaneFillerElement;
public Label filePaneFillerElement;
public CanvasPresentation canvas;
public StackPane dialogContainer;
public JFXDialog dialog;
public StackPane modalBar;
public JFXTextField queryTextField;
public JFXTextField commentTextField;
public JFXRippler generateUppaalModel;
public JFXRippler colorSelected;
public JFXRippler deleteSelected;
public JFXRippler undo;
public JFXRippler redo;
public JFXRippler delete;
public ImageView logo;
@Override
public void initialize(final URL location, final ResourceBundle resources) {
// Keybind for toggling the query pane
KeyboardTracker.registerKeybind(KeyboardTracker.TOGGLE_QUERY_PANE, new Keybind(new KeyCodeCombination(KeyCode.Q), () -> {
((HUPPAALPresentation) root).toggleQueryPane();
}));
// Keybind for toggling the file pane
KeyboardTracker.registerKeybind(KeyboardTracker.TOGGLE_FILE_PANE, new Keybind(new KeyCodeCombination(KeyCode.F), () -> {
((HUPPAALPresentation) root).toggleFilePane();
}));
dialog.setDialogContainer(dialogContainer);
dialogContainer.opacityProperty().bind(dialog.getChildren().get(0).scaleXProperty());
dialog.setOnDialogClosed(event -> dialogContainer.setVisible(false));
// Keybind for showing dialog // todo: remove this when done with testing
KeyboardTracker.registerKeybind("DIALOG", new Keybind(new KeyCodeCombination(KeyCode.I), () -> {
dialogContainer.setVisible(true);
dialog.show();
}));
// Keybind for deleting the selected elements
KeyboardTracker.registerKeybind(KeyboardTracker.DELETE_SELECTED, new Keybind(new KeyCodeCombination(KeyCode.DELETE), this::deleteSelectedClicked));
// Keybinds for coloring the selected elements
EnabledColor.enabledColors.forEach(enabledColor -> {
KeyboardTracker.registerKeybind(KeyboardTracker.COLOR_SELECTED + "_" + enabledColor.keyCode.getName(), new Keybind(new KeyCodeCombination(enabledColor.keyCode), () -> {
final List<Pair<SelectHelper.ColorSelectable, EnabledColor>> previousColor = new ArrayList<>();
SelectHelper.getSelectedElements().forEach(selectable -> {
previousColor.add(new Pair<>(selectable, new EnabledColor(selectable.getColor(), selectable.getColorIntensity())));
});
UndoRedoStack.push(() -> { // Perform
SelectHelper.getSelectedElements().forEach(selectable -> {
selectable.color(enabledColor.color, enabledColor.intensity);
});
}, () -> { // Undo
previousColor.forEach(selectableEnabledColorPair -> {
selectableEnabledColorPair.getKey().color(selectableEnabledColorPair.getValue().color, selectableEnabledColorPair.getValue().intensity);
});
}, String.format("Changed the color of %d elements to %s", previousColor.size(), enabledColor.color.name()), "color-lens");
SelectHelper.clearSelectedElements();
}));
});
final BooleanProperty hasChanged = new SimpleBooleanProperty(false);
HUPPAAL.getProject().getComponents().addListener(new ListChangeListener<Component>() {
@Override
public void onChanged(final Change<? extends Component> c) {
if (!hasChanged.get()) {
CanvasController.setActiveComponent(HUPPAAL.getProject().getComponents().get(0));
hasChanged.set(true);
}
}
});
}
@FXML
private void generateUppaalModelClicked() {
UPPAALDriver.verify("E<> true", // todo: consider creating an interface for generating the model instead of this query
aBoolean -> {
// success
System.out.println("Generated UPPAAL file!");
},
e -> {
System.out.println("ERROR");
},
HUPPAAL.getProject().getComponents()
);
}
@FXML
private void deleteSelectedClicked() {
if (SelectHelper.getSelectedElements().size() == 0) return;
// Run through the selected elements and look for something that we can delete
SelectHelper.getSelectedElements().forEach(selectable -> {
if (selectable instanceof LocationController) {
final Component component = ((LocationController) selectable).getComponent();
final Location location = ((LocationController) selectable).getLocation();
final double previousX = location.getX();
final double previousY = location.getY();
final Location initialLocation = component.getInitialLocation();
final Location finalLocation = component.getFinalLocation();
if (location.equals(initialLocation) || location.equals(finalLocation))
return; // Do not delete initial or final locations
UndoRedoStack.push(() -> { // Perform
// Remove the location
component.getLocations().remove(location);
}, () -> { // Undo
// Re-all the location
component.getLocations().add(location);
location.xProperty().unbind();
location.xProperty().set(previousX);
location.yProperty().unbind();
location.yProperty().set(previousY);
}, String.format("Deleted %s", selectable.toString()), "delete");
} else if (selectable instanceof EdgeController) {
final Component component = ((EdgeController) selectable).getComponent();
final Edge edge = ((EdgeController) selectable).getEdge();
UndoRedoStack.push(() -> { // Perform
// Remove the edge
component.getEdges().remove(edge);
}, () -> { // Undo
// Re-all the edge
component.getEdges().add(edge);
}, String.format("Deleted %s", selectable.toString()), "delete");
}
});
SelectHelper.clearSelectedElements();
}
@FXML
private void undoClicked() {
UndoRedoStack.undo();
}
@FXML
private void redoClicked() {
UndoRedoStack.redo();
}
@FXML
private void deleteClicked() {
// todo: add a confirmation dialog
final Component activeComponent = CanvasController.getActiveComponent();
if (activeComponent == null) return;
UndoRedoStack.push(() -> { // Perform
HUPPAAL.getProject().getComponents().remove(activeComponent);
}, () -> { // Undo
HUPPAAL.getProject().getComponents().add(activeComponent);
CanvasController.setActiveComponent(activeComponent);
}, String.format("Deleted component %s", activeComponent.getName()), "delete");
}
}
| Add { }
| src/main/java/SW9/controllers/HUPPAALController.java | Add { } | <ide><path>rc/main/java/SW9/controllers/HUPPAALController.java
<ide> final Location initialLocation = component.getInitialLocation();
<ide> final Location finalLocation = component.getFinalLocation();
<ide>
<del> if (location.equals(initialLocation) || location.equals(finalLocation))
<add> if (location.equals(initialLocation) || location.equals(finalLocation)) {
<ide> return; // Do not delete initial or final locations
<add> }
<ide>
<ide> UndoRedoStack.push(() -> { // Perform
<ide> // Remove the location |
|
Java | apache-2.0 | 9bcd51d37fc21b7a8d528dd4dcee077c026c70fb | 0 | kam6512/RxPermission | package com.orca.kam.rxpermission.listener;
import java.util.List;
/**
* Project RxPermission
*
* @author Kang Young Won
* @create 2016-08-29 - 오전 11:17
*/
public interface PermissionListener {
/**
* Call From Permission Activity...
* When All Permissions Granted
*/
void permissionGranted();
/**
* Call From Permission Activity....
* When Permissions Denied
*
* @param deniedPermissions The Denied Permissions from PermissionActivity
*/
void permissionDenied(List<String> deniedPermissions);
} | rxpermission/src/main/java/com/orca/kam/rxpermission/listener/PermissionListener.java | package com.orca.kam.rxpermission.listener;
import java.util.ArrayList;
/**
* Project RxPermission
*
* @author Kang Young Won
* @create 2016-08-29 - 오전 11:17
*/
public interface PermissionListener {
/**
* Call From Permission Activity...
* When All Permissions Granted
*/
void permissionGranted();
/**
* Call From Permission Activity....
* When Permissions Denied
*
* @param deniedPermissions The Denied Permissions from PermissionActivity
*/
void permissionDenied(ArrayList<String> deniedPermissions);
} | PermissionListener 의 permissionDenied 인자 자료형 수정
PermissionListener.java :
- ArrayList -> List
| rxpermission/src/main/java/com/orca/kam/rxpermission/listener/PermissionListener.java | PermissionListener 의 permissionDenied 인자 자료형 수정 | <ide><path>xpermission/src/main/java/com/orca/kam/rxpermission/listener/PermissionListener.java
<ide> package com.orca.kam.rxpermission.listener;
<ide>
<del>import java.util.ArrayList;
<add>import java.util.List;
<ide>
<ide> /**
<ide> * Project RxPermission
<ide> *
<ide> * @param deniedPermissions The Denied Permissions from PermissionActivity
<ide> */
<del> void permissionDenied(ArrayList<String> deniedPermissions);
<add> void permissionDenied(List<String> deniedPermissions);
<ide> } |
|
Java | mit | 53c0c20c8a4aeb0f46dbecea6fd254598a8c9e9e | 0 | cgmb/renderdoc,Yours3lf/renderdoc,michaelrgb/renderdoc,cgmb/renderdoc,Lssikkes/renderdoc,victor-moya/renderdoc,TurtleRockStudios/renderdoc_public,baldurk/renderdoc,victor-moya/renderdoc,googlestadia/renderdoc,Yours3lf/renderdoc,michaelrgb/renderdoc,Zorro666/renderdoc,baldurk/renderdoc,baldurk/renderdoc,Yours3lf/renderdoc,Lssikkes/renderdoc,googlestadia/renderdoc,googlestadia/renderdoc,baldurk/renderdoc,googlestadia/renderdoc,etnlGD/renderdoc,etnlGD/renderdoc,Zorro666/renderdoc,Velro/renderdoc,victor-moya/renderdoc,etnlGD/renderdoc,Lssikkes/renderdoc,michaelrgb/renderdoc,victor-moya/renderdoc,victor-moya/renderdoc,baldurk/renderdoc,michaelrgb/renderdoc,TurtleRockStudios/renderdoc_public,TurtleRockStudios/renderdoc_public,Yours3lf/renderdoc,cgmb/renderdoc,Zorro666/renderdoc,baldurk/renderdoc,Zorro666/renderdoc,etnlGD/renderdoc,Zorro666/renderdoc,googlestadia/renderdoc,Yours3lf/renderdoc,TurtleRockStudios/renderdoc_public,Velro/renderdoc,Velro/renderdoc,TurtleRockStudios/renderdoc_public,victor-moya/renderdoc,TurtleRockStudios/renderdoc_public,cgmb/renderdoc,etnlGD/renderdoc,cgmb/renderdoc,Lssikkes/renderdoc,Zorro666/renderdoc,Yours3lf/renderdoc,Velro/renderdoc,etnlGD/renderdoc,Lssikkes/renderdoc,Velro/renderdoc,Velro/renderdoc,michaelrgb/renderdoc,Lssikkes/renderdoc,googlestadia/renderdoc | package org.renderdoc.renderdoccmd;
import android.app.Activity;
public class Loader extends android.app.NativeActivity
{
/* load our native library */
static {
System.loadLibrary("renderdoc");
}
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Popup a dialog if we haven't granted Android storage permissions.
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
// Request is asynchronous, so prevent connection to server until permissions granted.
while(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= android.content.pm.PackageManager.PERMISSION_GRANTED)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}
| renderdoccmd/android/src/org/renderdoc/renderdoccmd/Loader.java | package org.renderdoc.renderdoccmd;
import android.app.Activity;
public class Loader extends android.app.NativeActivity
{
/* load our native library */
static {
System.loadLibrary("renderdoc");
}
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Popup a dialog if we haven't granted Android storage permissions.
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
| Prevent connection to server until Android permissions granted.
Server pops up dialog requesting file system access when the server is
launched. This is only obvious when the device is unlocked, otherwise this
pop up is never displayed.
Fixed by waiting for the user to grant permissions by preventing starting
a target app until the server is ready to open captures.
| renderdoccmd/android/src/org/renderdoc/renderdoccmd/Loader.java | Prevent connection to server until Android permissions granted. | <ide><path>enderdoccmd/android/src/org/renderdoc/renderdoccmd/Loader.java
<ide> super.onCreate(savedInstanceState);
<ide> // Popup a dialog if we haven't granted Android storage permissions.
<ide> requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
<add> // Request is asynchronous, so prevent connection to server until permissions granted.
<add> while(checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
<add> != android.content.pm.PackageManager.PERMISSION_GRANTED)
<add> {
<add> try {
<add> Thread.sleep(1000);
<add> } catch (InterruptedException e) {
<add> break;
<add> }
<add> }
<ide> }
<ide> } |
|
JavaScript | mit | 1cf7c4cebc1d085495ff922c59be4f14d758ec63 | 0 | samsteam/samsteam.github.io,samsteam/samsteam.github.io | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict'
var angular = require('angular');
var angularRouter = require('angular-ui-router');
var app = angular.module('sams', ['sams.controllers', 'sams.locales', 'ui.router']);
app.config(function($stateProvider, $urlRouterProvider){
if ( navigator.userAgent === 'samsteam-app-agent' ) {
$urlRouterProvider.otherwise('/step/requirements');
} else {
$urlRouterProvider.otherwise('/home');
}
/*
| ---------------------------------------------------------------------------
| Routes
| ---------------------------------------------------------------------------
*/
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'HomeController'
});
$stateProvider
.state('about', {
url: '/about',
templateUrl: 'templates/about.html',
controller: 'AboutController'
});
$stateProvider
.state('step', {
url: '/step',
abstract: true,
template: '<ui-view/>'
})
.state('step.requirements', {
url: '/requirements',
templateUrl: 'templates/requirements.html',
controller: 'RequirementsController'
})
.state('step.policies', {
url: '/policies',
templateUrl: 'templates/policies.html',
controller: 'PoliciesController'
})
.state('step.resolution', {
url: '/resolution',
templateUrl: 'templates/resolution.html',
controller: 'ResolutionController',
resolve: {
checkData: function( SchedulerService ){
return SchedulerService.isValidData();
}
}
})
.state('fifo', {
url: '/algorithms/fifo',
templateUrl: 'templates/fifo.html',
controller: 'FifoController'
});
});
},{"angular":9,"angular-ui-router":7}],2:[function(require,module,exports){
'use strict'
var angular = require('angular');
angular.module('sams.controllers', ['sams.services', 'sams.filters'])
/*
| ---------------------------------------------------------------------------
| Main Controller (contains below controllers as childrens)
| ---------------------------------------------------------------------------
*/
.controller('MainController', function($scope, $state, SamsService, $translate){
console.info('In Main Controller');
$scope.locales = SamsService.getLocales();
$scope.locale = SamsService.getDefaultLocale();
$translate.use($scope.locale);
console.log($scope.locale)
$scope.is = function(routeName) {
return $state.is(routeName);
}
$scope.changeLocale = function(val){
$scope.locale = val;
$translate.use($scope.locale);
SamsService.setDefaultLocale($scope.locale)
}
$scope.isDesktopApp = (navigator.userAgent === 'samsteam-app-agent');
})
/*
| ---------------------------------------------------------------------------
| Home Controller
| ---------------------------------------------------------------------------
*/
.controller('HomeController', function($scope){
console.info('In HomeController');
})
/*
| ---------------------------------------------------------------------------
| About Controller
| ---------------------------------------------------------------------------
*/
.controller('AboutController', function($scope, $filter){
console.info('In AboutController');
var devTeam = [
{
'name' : 'Babbini, Ignacio',
'github' : 'https://github.com/inbabbini',
'photo' : 'images/portraits/ignacio_babbini.png'
},
{
'name' : 'Eusebi, Cirano',
'github' : 'https://github.com/magodopado',
'photo' : 'images/portraits/cirano_eusebi.jpg'
},
{
'name' : 'Sottile, Cristian',
'github' : 'https://github.com/cristian-s',
'photo' : 'images/portraits/cristian_sottile.jpg'
},
{
'name' : 'Aparicio, Natalia',
'github' : 'https://github.com/natiidc',
'photo' : 'images/portraits/natalia_aparicio.jpg'
},
{
'name' : 'Cascio, Bruno',
'github' : 'https://github.com/brunocascio',
'photo' : 'images/portraits/bruno_cascio.jpg'
}
];
$scope.devteam = $filter('shuffle')(devTeam);
})
/*
| ---------------------------------------------------------------------------
| Data input
| ---------------------------------------------------------------------------
*/
.controller('RequirementsController', function($scope, $state, SamsService, SchedulerService){
console.info('In Requirements Controller');
$scope.modes = SchedulerService.getModes();
$scope.inputProcesses = [];
$scope.processes = [];
$scope.pages = {};
$scope.secuences = [];
$scope.requirements = SchedulerService.getRequirements();
$scope.loadDefault = function(){
$scope.inputProcesses = ['a','b','c'];
$scope.processes = ['a','b','c'];
$scope.pages = {
a:'1,2,3,4',
b:'5,6,7,8',
c:'9,10,11'
};
$scope.secuences = [
{'process': $scope.processes[0], 'cantPages': 1, 'mode': 'read'},
{'process': $scope.processes[1], 'cantPages': 2, 'mode': 'read'},
{'process': $scope.processes[2], 'cantPages': 1, 'mode': 'write'},
{'process': $scope.processes[1], 'cantPages': 1, 'mode': 'read'}
];
}
$scope.hasPages = function(){
return ($scope.pages && Object.keys($scope.pages).length);
}
$scope.next = function() {
$scope.processRequirements();
$state.go('step.policies');
}
$scope.__needClean = function(){
var isEmptyPages = true;
var isEmptyProcesses = (!$scope.processes || $scope.processes.length == 0);
angular.forEach($scope.pages, function(p,i){
if ( p || p !== '' ) {
isEmptyPages = false;
}
});
if( isEmptyProcesses ){
$scope.pages = {};
$scope.secuences = [];
$scope.processes = [];
}
if ( isEmptyPages ) {
$scope.pages = {};
$scope.secuences = [];
}
}
// parsing comma separated string
$scope.$watch('inputProcesses', function(newVal, oldVal){
// TODO: Validate unique processes
// TODO: multiple commas
$scope.processes = SamsService.stringToArray($scope.processes, newVal, ',');
$scope.__needClean();
});
// parsing comma separated string
$scope.$watch('pages', function(newVal, oldVal){
// TODO: multiple commas
if ( newVal !== undefined ){
$scope.pages = newVal;
}
$scope.__needClean();
}, true);
// add a new box for future requirements
$scope.add = function() {
var req = SamsService.createEmptyRequirement();
$scope.secuences.push(req);
}
// parsing user data input and send to scheduler.
$scope.processRequirements = function(){
//clean old requirements
$scope.requirements = [];
// clone pages
var pages = angular.copy($scope.pages);
// create requeriments
$scope.requirements = SamsService.createRequirements(pages, $scope.secuences);
SchedulerService.addRequirements($scope.requirements);
}
})
/*
| ---------------------------------------------------------------------------
| Policies
| ---------------------------------------------------------------------------
*/
.controller('PoliciesController', function($scope, SamsService, SchedulerService){
console.info('In Policies Controller');
/*
| ---------------------------------------------------------------------------
| Algorithm Selection
| ---------------------------------------------------------------------------
*/
$scope.algorithms = SchedulerService.getAlgorithms();
$scope.algorithmSelected = SchedulerService.getAlgorithm();
$scope.changeAlgorithm = function(){
SchedulerService.setAlgorithm( $scope.algorithmSelected );
}
/*
| ---------------------------------------------------------------------------
| Helper, validate assign with replace policy
| ---------------------------------------------------------------------------
*/
$scope.isAvailable = function(replaceOption) {
var assignOption = $scope.selectedAssignmentOption;
return SamsService.areCompatiblePolicies(replaceOption, assignOption);
}
/*
| ---------------------------------------------------------------------------
| Memory
| ---------------------------------------------------------------------------
*/
$scope.memorySize = SchedulerService.getMemorySize() || 4; // input
$scope.changeMemorySize = function(){
if ( typeof $scope.memorySize == 'number'){
SchedulerService.setMemorySize( $scope.memorySize );
}
}
// run when load (UX: prevent memory 0)
$scope.changeMemorySize();
/*
| ---------------------------------------------------------------------------
| isFixedEvenAssignmentPolicy
| ---------------------------------------------------------------------------
*/
$scope.setAssignmentOption = function(a){
$scope.selectedReplacementOption = null;
$scope.selectedAssignmentOption = a;
var isFixedEven = ($scope.selectedAssignmentOption === 'fixed');
SchedulerService.setFixedEvenAssignmentPolicy( isFixedEven );
SchedulerService.setLocalReplacementPolicy(isFixedEven);
}
$scope.assignmentOptions = SchedulerService.getAssigmentPolicies();
if ( SchedulerService.isFixedEvenAssignmentPolicy() ) {
$scope.selectedAssignmentOption = 'fixed';
SchedulerService.setLocalReplacementPolicy(true);
} else {
$scope.selectedAssignmentOption = 'dynamic';
// update if is not setted
$scope.setAssignmentOption($scope.selectedAssignmentOption);
SchedulerService.setLocalReplacementPolicy(false);
}
/*
| ---------------------------------------------------------------------------
| isAsyncFlushReplacementPolicy
| ---------------------------------------------------------------------------
*/
$scope.queueOptions = SchedulerService.getQueuePolicies();
$scope.hasAlgorithm = function () {
return $scope.algorithmSelected;
}
$scope.changeOptions = function(){
// TODO: check if algorithm is FIFO
SchedulerService.setAsyncFlushReplacementPolicy($scope.queueOptions['async-flush']);
}
})
/*
| ---------------------------------------------------------------------------
| Show results
| ---------------------------------------------------------------------------
*/
.controller('ResolutionController', function($scope, $state, SchedulerService, checkData){
console.info('In Resolution Controller');
if (!checkData)
return $state.go('step.requirements');
try {
$scope.framesTotal = SchedulerService.getMemorySize() - 1;
$scope.results = SchedulerService.run();
$scope.instants = $scope.results.length - 1;
} catch (err) {
console.log(err);
alert(err);
return $state.go('step.requirements');
}
})
},{"angular":9}],3:[function(require,module,exports){
'use strict'
var angular = require('angular');
angular.module('sams.filters', [])
.filter('inArray', function(){
return function(array, value){
return (array.indexOf(value) !== -1);
}
})
.filter('isBoolean', function(){
return function(value){
return (typeof value === 'boolean');
}
})
.filter('capitalize', function(){
return function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
})
.filter('makeRange', function() {
return function(input) {
var lowBound, highBound;
switch (input.length) {
case 1:
lowBound = 0;
highBound = parseInt(input[0]) - 1;
break;
case 2:
lowBound = parseInt(input[0]);
highBound = parseInt(input[1]);
break;
default:
return input;
}
var result = [];
for (var i = lowBound; i <= highBound; i++)
result.push(i);
return result;
};
})
.filter('shuffle', function() {
return function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
});
},{"angular":9}],4:[function(require,module,exports){
'use strict'
var angular = require('angular');
var translator = require('angular-translate');
var app = angular.module('sams.locales', ['pascalprecht.translate']);
app.config(function($translateProvider){
/*
| ---------------------------------------------------------------------------
| Translates
| ---------------------------------------------------------------------------
*/
$translateProvider.useSanitizeValueStrategy('escaped');
$translateProvider.translations('en', {
ABOUT_TITLE: 'Devteam',
ABOUT_ABOUTSAMS_TITLE: 'About SAMS', //<small style="color:#488FE7">and it\'s roots</small>',
ABOUT_TUTORIAL_TITLE: 'Tutorial', //<small style="color:#488FE7"></small>',
ABOUT_GITHUB_TITLE: 'Project\'s Github Information', //<small style="color:#488FE7">Fork it!</small>',
ABOUT_SAMS: 'About SAMS',
TUTORIAL: 'Tutorial',
GITHUB: 'GitHub',
HOME_START: 'START',
HOME_DOWNLOAD: 'DOWNLOAD',
HOME_ABOUT: 'ABOUT',
BREADCRUMB_REQUIREMENTS: 'Requirements',
BREADCRUMB_POLICIES: 'Policies',
BREADCRUMB_RESOLUTION: 'Resolution',
});
$translateProvider.translations('es', {
ABOUT_TITLE: 'Desarrolladores',
ABOUT_ABOUTSAMS_TITLE: 'Acerca de SAMS', // <small style="color:#488FE7">y sus comienzos</small>',
ABOUT_TUTORIAL_TITLE: 'Tutorial', //<small style="color:#488FE7"></small>',
ABOUT_GITHUB_TITLE: 'Información del Github del proyecto', // <small style="color:#488FE7">¡Forkealo!</small>',
ABOUT_SAMS: 'Acerca de SAMS',
TUTORIAL: 'Tutorial',
GITHUB: 'GitHub',
HOME_START: 'EMPEZAR',
HOME_DOWNLOAD: 'DESCARGAR',
HOME_ABOUT: 'ACERCA DE',
BREADCRUMB_REQUIREMENTS: 'Requerimientos',
BREADCRUMB_POLICIES: 'Políticas',
BREADCRUMB_RESOLUTION: 'Resolución',
});
$translateProvider.preferredLanguage( 'es' );
});
},{"angular":9,"angular-translate":6}],5:[function(require,module,exports){
'use strict'
var angular = require('angular')
, Scheduler = require('sams');
angular.module('sams.services', [])
/*
| -----------------------------------------------------------------------------
| Validation Service
| -----------------------------------------------------------------------------
|
*/
.factory('ValidationService', function($filter){
return {
checkBooleanType: function(value) {
return $filter('isBoolean')(value);
},
checkIntType: function(value) {
return angular.isNumber(value);
},
checkObjectType: function(obj) {
return angular.isObject(obj);
},
inArray: function(arr, value) {
return $filter('inArray')(arr, value);
}
}
})
/*
| -----------------------------------------------------------------------------
| Sams Service (Helpers)
| -----------------------------------------------------------------------------
|
*/
.factory('SamsService', function(){
return {
getLocales: function(){
return ['es', 'en'];
},
getDefaultLocale: function() {
var locale = window.localStorage.getItem('locale');
return (!locale || locale === '') ? 'es' : locale;
},
setDefaultLocale: function(val) {
window.localStorage.setItem('locale', val);
},
areCompatiblePolicies: function(replacement, assigment){
// Dynamic should be only global
if ( assigment === 'dynamic'){
if ( replacement === 'global' ) {
return false;
}
return true;
// Fixed should be only local
} else if ( assigment === 'fixed' ) {
if ( replacement === 'local' ) {
return false;
}
return true;
}
},
createRequirements: function(pages, secuences){
var reqs = []
angular.forEach(pages, function(pagesString, p){
pages[p] = pagesString.split(',');
});
// create requirements
secuences.forEach(function(obj, index){
for (var i = 0; i < obj.cantPages; i++) {
var req = {};
req['process'] = obj.process;
req['pageNumber'] = pages[obj.process].shift();
req['mode'] = obj.mode;
reqs.push(req);
}
});
return reqs;
},
createEmptyRequirement: function() {
return {
process: null,
cantPages: null,
mode: 'read'
};
},
stringToArray: function(array, stringValue, delimiter) {
delimiter = delimiter || ','
if (typeof stringValue === 'string'){
array = stringValue.split(delimiter);
if (array[array.length-1] == ""){
array.pop()
}
}
return array;
}
}
})
/*
| -----------------------------------------------------------------------------
| Scheduler Service
| -----------------------------------------------------------------------------
|
*/
.factory('SchedulerService', function(ValidationService){
var algorithms = ['fifo', 'fifo2', 'lru', 'nru', 'optimal'];
var modes = ['read', 'write', 'finish'];
var assigmentPolicies = ['fixed', 'dynamic'];
var queuePolicies = {'async-flush': false};
var scheduler = new Scheduler();
return {
/*
| ---------------------------------------
| set algorithm
| ---------------------------------------
*/
setAlgorithm: function(algorithm) {
if ( ! ValidationService.inArray(this.getAlgorithms(), algorithm) )
throw new Error("Algorithm doesn't exists");
if (algorithm === 'fifo2') {
scheduler.setAlgorithm('fifo');
this.setSecondChanceReplacementPolicy(true);
} else {
scheduler.setAlgorithm(algorithm);
}
return this;
},
/*
| ---------------------------------------
| get algorithm
| ---------------------------------------
*/
getAlgorithm: function() {
return scheduler.getAlgorithm();
},
/*
| ---------------------------------------
| get memory size
| ---------------------------------------
*/
getMemorySize: function() {
return scheduler.getMemorySize() || 0;
},
/*
| ---------------------------------------
| is fixed Assigment
| ---------------------------------------
*/
isFixedEvenAssignmentPolicy: function() {
return scheduler.isFixedEvenAssignmentPolicy();
},
/*
| ---------------------------------------
| is local Replacement
| ---------------------------------------
*/
isLocalReplacementPolicy: function() {
return scheduler.isLocalReplacementPolicy();
},
/*
| ---------------------------------------
| set if is fixed or dynamic
| ---------------------------------------
*/
setFixedEvenAssignmentPolicy: function(enabled) {
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setFixedEvenAssignmentPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is local or global
| ---------------------------------------
*/
setLocalReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setLocalReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is async flush
| ---------------------------------------
*/
setAsyncFlushReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setAsyncFlushReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is second chance
| ---------------------------------------
*/
setSecondChanceReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setSecondChanceReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set size of memory
| ---------------------------------------
*/
setMemorySize: function(size){
if ( ! ValidationService.checkIntType(size) )
throw new Error("value should be a integer value");
scheduler.setMemorySize( parseInt(size) );
return this;
},
/*
| ---------------------------------------
| set parsed requirements
| ---------------------------------------
*/
addRequirements: function(reqs){
if ( !ValidationService.checkObjectType(reqs) )
throw new Error("obj should be an object");
scheduler.addRequirements(reqs);
return this;
},
/*
| ---------------------------------------
| get requirements
| ---------------------------------------
*/
getRequirements: function(){
return scheduler.getRequirements() || [];
},
/*
| ---------------------------------------
| verify if all data is completed
| ---------------------------------------
*/
isValidData: function(){
var memSize = scheduler.getMemorySize();
var algorithm = scheduler.getAlgorithm();
var reqs = scheduler.getRequirements();
return memSize && algorithm && (reqs && reqs.length);
},
/*
| ---------------------------------------
| Helpers
| ---------------------------------------
*/
getAlgorithms: function() {
return algorithms;
},
getAssigmentPolicies: function() {
return assigmentPolicies;
},
getQueuePolicies: function() {
return queuePolicies;
},
getModes: function() {
return modes;
},
/*
| ---------------------------------------
| RUN :D
| ---------------------------------------
*/
run: function(){
return scheduler.run();
}
}
})
},{"angular":9,"sams":11}],6:[function(require,module,exports){
/*!
* angular-translate - v2.7.2 - 2015-06-01
* http://github.com/angular-translate/angular-translate
* Copyright (c) 2015 ; Licensed MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define([], function () {
return (factory());
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
factory();
}
}(this, function () {
/**
* @ngdoc overview
* @name pascalprecht.translate
*
* @description
* The main module which holds everything together.
*/
angular.module('pascalprecht.translate', ['ng'])
.run(runTranslate);
function runTranslate($translate) {
'use strict';
var key = $translate.storageKey(),
storage = $translate.storage();
var fallbackFromIncorrectStorageValue = function () {
var preferred = $translate.preferredLanguage();
if (angular.isString(preferred)) {
$translate.use(preferred);
// $translate.use() will also remember the language.
// So, we don't need to call storage.put() here.
} else {
storage.put(key, $translate.use());
}
};
fallbackFromIncorrectStorageValue.displayName = 'fallbackFromIncorrectStorageValue';
if (storage) {
if (!storage.get(key)) {
fallbackFromIncorrectStorageValue();
} else {
$translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue);
}
} else if (angular.isString($translate.preferredLanguage())) {
$translate.use($translate.preferredLanguage());
}
}
runTranslate.$inject = ['$translate'];
runTranslate.displayName = 'runTranslate';
/**
* @ngdoc object
* @name pascalprecht.translate.$translateSanitizationProvider
*
* @description
*
* Configurations for $translateSanitization
*/
angular.module('pascalprecht.translate').provider('$translateSanitization', $translateSanitizationProvider);
function $translateSanitizationProvider () {
'use strict';
var $sanitize,
currentStrategy = null, // TODO change to either 'sanitize', 'escape' or ['sanitize', 'escapeParameters'] in 3.0.
hasConfiguredStrategy = false,
hasShownNoStrategyConfiguredWarning = false,
strategies;
/**
* Definition of a sanitization strategy function
* @callback StrategyFunction
* @param {string|object} value - value to be sanitized (either a string or an interpolated value map)
* @param {string} mode - either 'text' for a string (translation) or 'params' for the interpolated params
* @return {string|object}
*/
/**
* @ngdoc property
* @name strategies
* @propertyOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Following strategies are built-in:
* <dl>
* <dt>sanitize</dt>
* <dd>Sanitizes HTML in the translation text using $sanitize</dd>
* <dt>escape</dt>
* <dd>Escapes HTML in the translation</dd>
* <dt>sanitizeParameters</dt>
* <dd>Sanitizes HTML in the values of the interpolation parameters using $sanitize</dd>
* <dt>escapeParameters</dt>
* <dd>Escapes HTML in the values of the interpolation parameters</dd>
* <dt>escaped</dt>
* <dd>Support legacy strategy name 'escaped' for backwards compatibility (will be removed in 3.0)</dd>
* </dl>
*
*/
strategies = {
sanitize: function (value, mode) {
if (mode === 'text') {
value = htmlSanitizeValue(value);
}
return value;
},
escape: function (value, mode) {
if (mode === 'text') {
value = htmlEscapeValue(value);
}
return value;
},
sanitizeParameters: function (value, mode) {
if (mode === 'params') {
value = mapInterpolationParameters(value, htmlSanitizeValue);
}
return value;
},
escapeParameters: function (value, mode) {
if (mode === 'params') {
value = mapInterpolationParameters(value, htmlEscapeValue);
}
return value;
}
};
// Support legacy strategy name 'escaped' for backwards compatibility.
// TODO should be removed in 3.0
strategies.escaped = strategies.escapeParameters;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#addStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Adds a sanitization strategy to the list of known strategies.
*
* @param {string} strategyName - unique key for a strategy
* @param {StrategyFunction} strategyFunction - strategy function
* @returns {object} this
*/
this.addStrategy = function (strategyName, strategyFunction) {
strategies[strategyName] = strategyFunction;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#removeStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Removes a sanitization strategy from the list of known strategies.
*
* @param {string} strategyName - unique key for a strategy
* @returns {object} this
*/
this.removeStrategy = function (strategyName) {
delete strategies[strategyName];
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#useStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
*
* @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
* @returns {object} this
*/
this.useStrategy = function (strategy) {
hasConfiguredStrategy = true;
currentStrategy = strategy;
return this;
};
/**
* @ngdoc object
* @name pascalprecht.translate.$translateSanitization
* @requires $injector
* @requires $log
*
* @description
* Sanitizes interpolation parameters and translated texts.
*
*/
this.$get = ['$injector', '$log', function ($injector, $log) {
var applyStrategies = function (value, mode, selectedStrategies) {
angular.forEach(selectedStrategies, function (selectedStrategy) {
if (angular.isFunction(selectedStrategy)) {
value = selectedStrategy(value, mode);
} else if (angular.isFunction(strategies[selectedStrategy])) {
value = strategies[selectedStrategy](value, mode);
} else {
throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \'' + selectedStrategy + '\'');
}
});
return value;
};
// TODO: should be removed in 3.0
var showNoStrategyConfiguredWarning = function () {
if (!hasConfiguredStrategy && !hasShownNoStrategyConfiguredWarning) {
$log.warn('pascalprecht.translate.$translateSanitization: No sanitization strategy has been configured. This can have serious security implications. See http://angular-translate.github.io/docs/#/guide/19_security for details.');
hasShownNoStrategyConfiguredWarning = true;
}
};
if ($injector.has('$sanitize')) {
$sanitize = $injector.get('$sanitize');
}
return {
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitization#useStrategy
* @methodOf pascalprecht.translate.$translateSanitization
*
* @description
* Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
*
* @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
*/
useStrategy: (function (self) {
return function (strategy) {
self.useStrategy(strategy);
};
})(this),
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitization#sanitize
* @methodOf pascalprecht.translate.$translateSanitization
*
* @description
* Sanitizes a value.
*
* @param {string|object} value The value which should be sanitized.
* @param {string} mode The current sanitization mode, either 'params' or 'text'.
* @param {string|StrategyFunction|array} [strategy] Optional custom strategy which should be used instead of the currently selected strategy.
* @returns {string|object} sanitized value
*/
sanitize: function (value, mode, strategy) {
if (!currentStrategy) {
showNoStrategyConfiguredWarning();
}
if (arguments.length < 3) {
strategy = currentStrategy;
}
if (!strategy) {
return value;
}
var selectedStrategies = angular.isArray(strategy) ? strategy : [strategy];
return applyStrategies(value, mode, selectedStrategies);
}
};
}];
var htmlEscapeValue = function (value) {
var element = angular.element('<div></div>');
element.text(value); // not chainable, see #1044
return element.html();
};
var htmlSanitizeValue = function (value) {
if (!$sanitize) {
throw new Error('pascalprecht.translate.$translateSanitization: Error cannot find $sanitize service. Either include the ngSanitize module (https://docs.angularjs.org/api/ngSanitize) or use a sanitization strategy which does not depend on $sanitize, such as \'escape\'.');
}
return $sanitize(value);
};
var mapInterpolationParameters = function (value, iteratee) {
if (angular.isObject(value)) {
var result = angular.isArray(value) ? [] : {};
angular.forEach(value, function (propertyValue, propertyKey) {
result[propertyKey] = mapInterpolationParameters(propertyValue, iteratee);
});
return result;
} else if (angular.isNumber(value)) {
return value;
} else {
return iteratee(value);
}
};
}
/**
* @ngdoc object
* @name pascalprecht.translate.$translateProvider
* @description
*
* $translateProvider allows developers to register translation-tables, asynchronous loaders
* and similar to configure translation behavior directly inside of a module.
*
*/
angular.module('pascalprecht.translate')
.constant('pascalprechtTranslateOverrider', {})
.provider('$translate', $translate);
function $translate($STORAGE_KEY, $windowProvider, $translateSanitizationProvider, pascalprechtTranslateOverrider) {
'use strict';
var $translationTable = {},
$preferredLanguage,
$availableLanguageKeys = [],
$languageKeyAliases,
$fallbackLanguage,
$fallbackWasString,
$uses,
$nextLang,
$storageFactory,
$storageKey = $STORAGE_KEY,
$storagePrefix,
$missingTranslationHandlerFactory,
$interpolationFactory,
$interpolatorFactories = [],
$loaderFactory,
$cloakClassName = 'translate-cloak',
$loaderOptions,
$notFoundIndicatorLeft,
$notFoundIndicatorRight,
$postCompilingEnabled = false,
$forceAsyncReloadEnabled = false,
NESTED_OBJECT_DELIMITER = '.',
loaderCache,
directivePriority = 0,
statefulFilter = true,
uniformLanguageTagResolver = 'default',
languageTagResolver = {
'default': function (tag) {
return (tag || '').split('-').join('_');
},
java: function (tag) {
var temp = (tag || '').split('-').join('_');
var parts = temp.split('_');
return parts.length > 1 ? (parts[0].toLowerCase() + '_' + parts[1].toUpperCase()) : temp;
},
bcp47: function (tag) {
var temp = (tag || '').split('_').join('-');
var parts = temp.split('-');
return parts.length > 1 ? (parts[0].toLowerCase() + '-' + parts[1].toUpperCase()) : temp;
}
};
var version = '2.7.2';
// tries to determine the browsers language
var getFirstBrowserLanguage = function () {
// internal purpose only
if (angular.isFunction(pascalprechtTranslateOverrider.getLocale)) {
return pascalprechtTranslateOverrider.getLocale();
}
var nav = $windowProvider.$get().navigator,
browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
i,
language;
// support for HTML 5.1 "navigator.languages"
if (angular.isArray(nav.languages)) {
for (i = 0; i < nav.languages.length; i++) {
language = nav.languages[i];
if (language && language.length) {
return language;
}
}
}
// support for other well known properties in browsers
for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
language = nav[browserLanguagePropertyKeys[i]];
if (language && language.length) {
return language;
}
}
return null;
};
getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage';
// tries to determine the browsers locale
var getLocale = function () {
var locale = getFirstBrowserLanguage() || '';
if (languageTagResolver[uniformLanguageTagResolver]) {
locale = languageTagResolver[uniformLanguageTagResolver](locale);
}
return locale;
};
getLocale.displayName = 'angular-translate/service: getLocale';
/**
* @name indexOf
* @private
*
* @description
* indexOf polyfill. Kinda sorta.
*
* @param {array} array Array to search in.
* @param {string} searchElement Element to search for.
*
* @returns {int} Index of search element.
*/
var indexOf = function(array, searchElement) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === searchElement) {
return i;
}
}
return -1;
};
/**
* @name trim
* @private
*
* @description
* trim polyfill
*
* @returns {string} The string stripped of whitespace from both ends
*/
var trim = function() {
return this.toString().replace(/^\s+|\s+$/g, '');
};
var negotiateLocale = function (preferred) {
var avail = [],
locale = angular.lowercase(preferred),
i = 0,
n = $availableLanguageKeys.length;
for (; i < n; i++) {
avail.push(angular.lowercase($availableLanguageKeys[i]));
}
if (indexOf(avail, locale) > -1) {
return preferred;
}
if ($languageKeyAliases) {
var alias;
for (var langKeyAlias in $languageKeyAliases) {
var hasWildcardKey = false;
var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) &&
angular.lowercase(langKeyAlias) === angular.lowercase(preferred);
if (langKeyAlias.slice(-1) === '*') {
hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length-1);
}
if (hasExactKey || hasWildcardKey) {
alias = $languageKeyAliases[langKeyAlias];
if (indexOf(avail, angular.lowercase(alias)) > -1) {
return alias;
}
}
}
}
if (preferred) {
var parts = preferred.split('_');
if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) {
return parts[0];
}
}
// If everything fails, just return the preferred, unchanged.
return preferred;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#translations
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a new translation table for specific language key.
*
* To register a translation table for specific language, pass a defined language
* key as first parameter.
*
* <pre>
* // register translation table for language: 'de_DE'
* $translateProvider.translations('de_DE', {
* 'GREETING': 'Hallo Welt!'
* });
*
* // register another one
* $translateProvider.translations('en_US', {
* 'GREETING': 'Hello world!'
* });
* </pre>
*
* When registering multiple translation tables for for the same language key,
* the actual translation table gets extended. This allows you to define module
* specific translation which only get added, once a specific module is loaded in
* your app.
*
* Invoking this method with no arguments returns the translation table which was
* registered with no language key. Invoking it with a language key returns the
* related translation table.
*
* @param {string} key A language key.
* @param {object} translationTable A plain old JavaScript object that represents a translation table.
*
*/
var translations = function (langKey, translationTable) {
if (!langKey && !translationTable) {
return $translationTable;
}
if (langKey && !translationTable) {
if (angular.isString(langKey)) {
return $translationTable[langKey];
}
} else {
if (!angular.isObject($translationTable[langKey])) {
$translationTable[langKey] = {};
}
angular.extend($translationTable[langKey], flatObject(translationTable));
}
return this;
};
this.translations = translations;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#cloakClassName
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
*
* Let's you change the class name for `translate-cloak` directive.
* Default class name is `translate-cloak`.
*
* @param {string} name translate-cloak class name
*/
this.cloakClassName = function (name) {
if (!name) {
return $cloakClassName;
}
$cloakClassName = name;
return this;
};
/**
* @name flatObject
* @private
*
* @description
* Flats an object. This function is used to flatten given translation data with
* namespaces, so they are later accessible via dot notation.
*/
var flatObject = function (data, path, result, prevKey) {
var key, keyWithPath, keyWithShortPath, val;
if (!path) {
path = [];
}
if (!result) {
result = {};
}
for (key in data) {
if (!Object.prototype.hasOwnProperty.call(data, key)) {
continue;
}
val = data[key];
if (angular.isObject(val)) {
flatObject(val, path.concat(key), result, key);
} else {
keyWithPath = path.length ? ('' + path.join(NESTED_OBJECT_DELIMITER) + NESTED_OBJECT_DELIMITER + key) : key;
if(path.length && key === prevKey){
// Create shortcut path (foo.bar == foo.bar.bar)
keyWithShortPath = '' + path.join(NESTED_OBJECT_DELIMITER);
// Link it to original path
result[keyWithShortPath] = '@:' + keyWithPath;
}
result[keyWithPath] = val;
}
}
return result;
};
flatObject.displayName = 'flatObject';
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#addInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Adds interpolation services to angular-translate, so it can manage them.
*
* @param {object} factory Interpolation service factory
*/
this.addInterpolation = function (factory) {
$interpolatorFactories.push(factory);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use interpolation functionality of messageformat.js.
* This is useful when having high level pluralization and gender selection.
*/
this.useMessageFormatInterpolation = function () {
return this.useInterpolation('$translateMessageFormatInterpolation');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate which interpolation style to use as default, application-wide.
* Simply pass a factory/service name. The interpolation service has to implement
* the correct interface.
*
* @param {string} factory Interpolation service name.
*/
this.useInterpolation = function (factory) {
$interpolationFactory = factory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useSanitizeStrategy
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Simply sets a sanitation strategy type.
*
* @param {string} value Strategy type.
*/
this.useSanitizeValueStrategy = function (value) {
$translateSanitizationProvider.useStrategy(value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#preferredLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which of the registered translation tables to use for translation
* at initial startup by passing a language key. Similar to `$translateProvider#use`
* only that it says which language to **prefer**.
*
* @param {string} langKey A language key.
*
*/
this.preferredLanguage = function(langKey) {
setupPreferredLanguage(langKey);
return this;
};
var setupPreferredLanguage = function (langKey) {
if (langKey) {
$preferredLanguage = langKey;
}
return $preferredLanguage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found. E.g. when
* setting the indicator as 'X' and one tries to translate a translation id
* called `NOT_FOUND`, this will result in `X NOT_FOUND X`.
*
* Internally this methods sets a left indicator and a right indicator using
* `$translateProvider.translationNotFoundIndicatorLeft()` and
* `$translateProvider.translationNotFoundIndicatorRight()`.
*
* **Note**: These methods automatically add a whitespace between the indicators
* and the translation id.
*
* @param {string} indicator An indicator, could be any string.
*/
this.translationNotFoundIndicator = function (indicator) {
this.translationNotFoundIndicatorLeft(indicator);
this.translationNotFoundIndicatorRight(indicator);
return this;
};
/**
* ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found left to the
* translation id.
*
* @param {string} indicator An indicator.
*/
this.translationNotFoundIndicatorLeft = function (indicator) {
if (!indicator) {
return $notFoundIndicatorLeft;
}
$notFoundIndicatorLeft = indicator;
return this;
};
/**
* ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found right to the
* translation id.
*
* @param {string} indicator An indicator.
*/
this.translationNotFoundIndicatorRight = function (indicator) {
if (!indicator) {
return $notFoundIndicatorRight;
}
$notFoundIndicatorRight = indicator;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#fallbackLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which of the registered translation tables to use when missing translations
* at initial startup by passing a language key. Similar to `$translateProvider#use`
* only that it says which language to **fallback**.
*
* @param {string||array} langKey A language key.
*
*/
this.fallbackLanguage = function (langKey) {
fallbackStack(langKey);
return this;
};
var fallbackStack = function (langKey) {
if (langKey) {
if (angular.isString(langKey)) {
$fallbackWasString = true;
$fallbackLanguage = [ langKey ];
} else if (angular.isArray(langKey)) {
$fallbackWasString = false;
$fallbackLanguage = langKey;
}
if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) {
$fallbackLanguage.push($preferredLanguage);
}
return this;
} else {
if ($fallbackWasString) {
return $fallbackLanguage[0];
} else {
return $fallbackLanguage;
}
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#use
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Set which translation table to use for translation by given language key. When
* trying to 'use' a language which isn't provided, it'll throw an error.
*
* You actually don't have to use this method since `$translateProvider#preferredLanguage`
* does the job too.
*
* @param {string} langKey A language key.
*/
this.use = function (langKey) {
if (langKey) {
if (!$translationTable[langKey] && (!$loaderFactory)) {
// only throw an error, when not loading translation data asynchronously
throw new Error('$translateProvider couldn\'t find translationTable for langKey: \'' + langKey + '\'');
}
$uses = langKey;
return this;
}
return $uses;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#storageKey
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which key must represent the choosed language by a user in the storage.
*
* @param {string} key A key for the storage.
*/
var storageKey = function(key) {
if (!key) {
if ($storagePrefix) {
return $storagePrefix + $storageKey;
}
return $storageKey;
}
$storageKey = key;
return this;
};
this.storageKey = storageKey;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useUrlLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateUrlLoader` extension service as loader.
*
* @param {string} url Url
* @param {Object=} options Optional configuration object
*/
this.useUrlLoader = function (url, options) {
return this.useLoader('$translateUrlLoader', angular.extend({ url: url }, options));
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useStaticFilesLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader.
*
* @param {Object=} options Optional configuration object
*/
this.useStaticFilesLoader = function (options) {
return this.useLoader('$translateStaticFilesLoader', options);
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use any other service as loader.
*
* @param {string} loaderFactory Factory name to use
* @param {Object=} options Optional configuration object
*/
this.useLoader = function (loaderFactory, options) {
$loaderFactory = loaderFactory;
$loaderOptions = options || {};
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLocalStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateLocalStorage` service as storage layer.
*
*/
this.useLocalStorage = function () {
return this.useStorage('$translateLocalStorage');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useCookieStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateCookieStorage` service as storage layer.
*/
this.useCookieStorage = function () {
return this.useStorage('$translateCookieStorage');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use custom service as storage layer.
*/
this.useStorage = function (storageFactory) {
$storageFactory = storageFactory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#storagePrefix
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets prefix for storage key.
*
* @param {string} prefix Storage key prefix
*/
this.storagePrefix = function (prefix) {
if (!prefix) {
return prefix;
}
$storagePrefix = prefix;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use built-in log handler when trying to translate
* a translation Id which doesn't exist.
*
* This is actually a shortcut method for `useMissingTranslationHandler()`.
*
*/
this.useMissingTranslationHandlerLog = function () {
return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Expects a factory name which later gets instantiated with `$injector`.
* This method can be used to tell angular-translate to use a custom
* missingTranslationHandler. Just build a factory which returns a function
* and expects a translation id as argument.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.useMissingTranslationHandler('customHandler');
* });
*
* app.factory('customHandler', function (dep1, dep2) {
* return function (translationId) {
* // something with translationId and dep1 and dep2
* };
* });
* </pre>
*
* @param {string} factory Factory name
*/
this.useMissingTranslationHandler = function (factory) {
$missingTranslationHandlerFactory = factory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#usePostCompiling
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* If post compiling is enabled, all translated values will be processed
* again with AngularJS' $compile.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.usePostCompiling(true);
* });
* </pre>
*
* @param {string} factory Factory name
*/
this.usePostCompiling = function (value) {
$postCompilingEnabled = !(!value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#forceAsyncReload
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* If force async reload is enabled, async loader will always be called
* even if $translationTable already contains the language key, adding
* possible new entries to the $translationTable.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.forceAsyncReload(true);
* });
* </pre>
*
* @param {boolean} value - valid values are true or false
*/
this.forceAsyncReload = function (value) {
$forceAsyncReloadEnabled = !(!value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#uniformLanguageTag
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate which language tag should be used as a result when determining
* the current browser language.
*
* This setting must be set before invoking {@link pascalprecht.translate.$translateProvider#methods_determinePreferredLanguage determinePreferredLanguage()}.
*
* <pre>
* $translateProvider
* .uniformLanguageTag('bcp47')
* .determinePreferredLanguage()
* </pre>
*
* The resolver currently supports:
* * default
* (traditionally: hyphens will be converted into underscores, i.e. en-US => en_US)
* en-US => en_US
* en_US => en_US
* en-us => en_us
* * java
* like default, but the second part will be always in uppercase
* en-US => en_US
* en_US => en_US
* en-us => en_US
* * BCP 47 (RFC 4646 & 4647)
* en-US => en-US
* en_US => en-US
* en-us => en-US
*
* See also:
* * http://en.wikipedia.org/wiki/IETF_language_tag
* * http://www.w3.org/International/core/langtags/
* * http://tools.ietf.org/html/bcp47
*
* @param {string|object} options - options (or standard)
* @param {string} options.standard - valid values are 'default', 'bcp47', 'java'
*/
this.uniformLanguageTag = function (options) {
if (!options) {
options = {};
} else if (angular.isString(options)) {
options = {
standard: options
};
}
uniformLanguageTagResolver = options.standard;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#determinePreferredLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to try to determine on its own which language key
* to set as preferred language. When `fn` is given, angular-translate uses it
* to determine a language key, otherwise it uses the built-in `getLocale()`
* method.
*
* The `getLocale()` returns a language key in the format `[lang]_[country]` or
* `[lang]` depending on what the browser provides.
*
* Use this method at your own risk, since not all browsers return a valid
* locale (see {@link pascalprecht.translate.$translateProvider#methods_uniformLanguageTag uniformLanguageTag()}).
*
* @param {Function=} fn Function to determine a browser's locale
*/
this.determinePreferredLanguage = function (fn) {
var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale();
if (!$availableLanguageKeys.length) {
$preferredLanguage = locale;
} else {
$preferredLanguage = negotiateLocale(locale);
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a set of language keys the app will work with. Use this method in
* combination with
* {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.
* When available languages keys are registered, angular-translate
* tries to find the best fitting language key depending on the browsers locale,
* considering your language key convention.
*
* @param {object} languageKeys Array of language keys the your app will use
* @param {object=} aliases Alias map.
*/
this.registerAvailableLanguageKeys = function (languageKeys, aliases) {
if (languageKeys) {
$availableLanguageKeys = languageKeys;
if (aliases) {
$languageKeyAliases = aliases;
}
return this;
}
return $availableLanguageKeys;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLoaderCache
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a cache for internal $http based loaders.
* {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.
* When false the cache will be disabled (default). When true or undefined
* the cache will be a default (see $cacheFactory). When an object it will
* be treat as a cache object itself: the usage is $http({cache: cache})
*
* @param {object} cache boolean, string or cache-object
*/
this.useLoaderCache = function (cache) {
if (cache === false) {
// disable cache
loaderCache = undefined;
} else if (cache === true) {
// enable cache using AJS defaults
loaderCache = true;
} else if (typeof(cache) === 'undefined') {
// enable cache using default
loaderCache = '$translationCache';
} else if (cache) {
// enable cache using given one (see $cacheFactory)
loaderCache = cache;
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#directivePriority
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets the default priority of the translate directive. The standard value is `0`.
* Calling this function without an argument will return the current value.
*
* @param {number} priority for the translate-directive
*/
this.directivePriority = function (priority) {
if (priority === undefined) {
// getter
return directivePriority;
} else {
// setter with chaining
directivePriority = priority;
return this;
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#statefulFilter
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Since AngularJS 1.3, filters which are not stateless (depending at the scope)
* have to explicit define this behavior.
* Sets whether the translate filter should be stateful or stateless. The standard value is `true`
* meaning being stateful.
* Calling this function without an argument will return the current value.
*
* @param {boolean} state - defines the state of the filter
*/
this.statefulFilter = function (state) {
if (state === undefined) {
// getter
return statefulFilter;
} else {
// setter with chaining
statefulFilter = state;
return this;
}
};
/**
* @ngdoc object
* @name pascalprecht.translate.$translate
* @requires $interpolate
* @requires $log
* @requires $rootScope
* @requires $q
*
* @description
* The `$translate` service is the actual core of angular-translate. It expects a translation id
* and optional interpolate parameters to translate contents.
*
* <pre>
* $translate('HEADLINE_TEXT').then(function (translation) {
* $scope.translatedText = translation;
* });
* </pre>
*
* @param {string|array} translationId A token which represents a translation id
* This can be optionally an array of translation ids which
* results that the function returns an object where each key
* is the translation id and the value the translation.
* @param {object=} interpolateParams An object hash for dynamic values
* @param {string} interpolationId The id of the interpolation to use
* @returns {object} promise
*/
this.$get = [
'$log',
'$injector',
'$rootScope',
'$q',
function ($log, $injector, $rootScope, $q) {
var Storage,
defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'),
pendingLoader = false,
interpolatorHashMap = {},
langPromises = {},
fallbackIndex,
startFallbackIteration;
var $translate = function (translationId, interpolateParams, interpolationId, defaultTranslationText) {
// Duck detection: If the first argument is an array, a bunch of translations was requested.
// The result is an object.
if (angular.isArray(translationId)) {
// Inspired by Q.allSettled by Kris Kowal
// https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563
// This transforms all promises regardless resolved or rejected
var translateAll = function (translationIds) {
var results = {}; // storing the actual results
var promises = []; // promises to wait for
// Wraps the promise a) being always resolved and b) storing the link id->value
var translate = function (translationId) {
var deferred = $q.defer();
var regardless = function (value) {
results[translationId] = value;
deferred.resolve([translationId, value]);
};
// we don't care whether the promise was resolved or rejected; just store the values
$translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless);
return deferred.promise;
};
for (var i = 0, c = translationIds.length; i < c; i++) {
promises.push(translate(translationIds[i]));
}
// wait for all (including storing to results)
return $q.all(promises).then(function () {
// return the results
return results;
});
};
return translateAll(translationId);
}
var deferred = $q.defer();
// trim off any whitespace
if (translationId) {
translationId = trim.apply(translationId);
}
var promiseToWaitFor = (function () {
var promise = $preferredLanguage ?
langPromises[$preferredLanguage] :
langPromises[$uses];
fallbackIndex = 0;
if ($storageFactory && !promise) {
// looks like there's no pending promise for $preferredLanguage or
// $uses. Maybe there's one pending for a language that comes from
// storage.
var langKey = Storage.get($storageKey);
promise = langPromises[langKey];
if ($fallbackLanguage && $fallbackLanguage.length) {
var index = indexOf($fallbackLanguage, langKey);
// maybe the language from storage is also defined as fallback language
// we increase the fallback language index to not search in that language
// as fallback, since it's probably the first used language
// in that case the index starts after the first element
fallbackIndex = (index === 0) ? 1 : 0;
// but we can make sure to ALWAYS fallback to preferred language at least
if (indexOf($fallbackLanguage, $preferredLanguage) < 0) {
$fallbackLanguage.push($preferredLanguage);
}
}
}
return promise;
}());
if (!promiseToWaitFor) {
// no promise to wait for? okay. Then there's no loader registered
// nor is a one pending for language that comes from storage.
// We can just translate.
determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText).then(deferred.resolve, deferred.reject);
} else {
var promiseResolved = function () {
determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText).then(deferred.resolve, deferred.reject);
};
promiseResolved.displayName = 'promiseResolved';
promiseToWaitFor['finally'](promiseResolved, deferred.reject);
}
return deferred.promise;
};
/**
* @name applyNotFoundIndicators
* @private
*
* @description
* Applies not fount indicators to given translation id, if needed.
* This function gets only executed, if a translation id doesn't exist,
* which is why a translation id is expected as argument.
*
* @param {string} translationId Translation id.
* @returns {string} Same as given translation id but applied with not found
* indicators.
*/
var applyNotFoundIndicators = function (translationId) {
// applying notFoundIndicators
if ($notFoundIndicatorLeft) {
translationId = [$notFoundIndicatorLeft, translationId].join(' ');
}
if ($notFoundIndicatorRight) {
translationId = [translationId, $notFoundIndicatorRight].join(' ');
}
return translationId;
};
/**
* @name useLanguage
* @private
*
* @description
* Makes actual use of a language by setting a given language key as used
* language and informs registered interpolators to also use the given
* key as locale.
*
* @param {key} Locale key.
*/
var useLanguage = function (key) {
$uses = key;
$rootScope.$emit('$translateChangeSuccess', {language: key});
if ($storageFactory) {
Storage.put($translate.storageKey(), $uses);
}
// inform default interpolator
defaultInterpolator.setLocale($uses);
var eachInterpolator = function (interpolator, id) {
interpolatorHashMap[id].setLocale($uses);
};
eachInterpolator.displayName = 'eachInterpolatorLocaleSetter';
// inform all others too!
angular.forEach(interpolatorHashMap, eachInterpolator);
$rootScope.$emit('$translateChangeEnd', {language: key});
};
/**
* @name loadAsync
* @private
*
* @description
* Kicks of registered async loader using `$injector` and applies existing
* loader options. When resolved, it updates translation tables accordingly
* or rejects with given language key.
*
* @param {string} key Language key.
* @return {Promise} A promise.
*/
var loadAsync = function (key) {
if (!key) {
throw 'No language key specified for loading.';
}
var deferred = $q.defer();
$rootScope.$emit('$translateLoadingStart', {language: key});
pendingLoader = true;
var cache = loaderCache;
if (typeof(cache) === 'string') {
// getting on-demand instance of loader
cache = $injector.get(cache);
}
var loaderOptions = angular.extend({}, $loaderOptions, {
key: key,
$http: angular.extend({}, {
cache: cache
}, $loaderOptions.$http)
});
var onLoaderSuccess = function (data) {
var translationTable = {};
$rootScope.$emit('$translateLoadingSuccess', {language: key});
if (angular.isArray(data)) {
angular.forEach(data, function (table) {
angular.extend(translationTable, flatObject(table));
});
} else {
angular.extend(translationTable, flatObject(data));
}
pendingLoader = false;
deferred.resolve({
key: key,
table: translationTable
});
$rootScope.$emit('$translateLoadingEnd', {language: key});
};
onLoaderSuccess.displayName = 'onLoaderSuccess';
var onLoaderError = function (key) {
$rootScope.$emit('$translateLoadingError', {language: key});
deferred.reject(key);
$rootScope.$emit('$translateLoadingEnd', {language: key});
};
onLoaderError.displayName = 'onLoaderError';
$injector.get($loaderFactory)(loaderOptions)
.then(onLoaderSuccess, onLoaderError);
return deferred.promise;
};
if ($storageFactory) {
Storage = $injector.get($storageFactory);
if (!Storage.get || !Storage.put) {
throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or put() method!');
}
}
// if we have additional interpolations that were added via
// $translateProvider.addInterpolation(), we have to map'em
if ($interpolatorFactories.length) {
var eachInterpolationFactory = function (interpolatorFactory) {
var interpolator = $injector.get(interpolatorFactory);
// setting initial locale for each interpolation service
interpolator.setLocale($preferredLanguage || $uses);
// make'em recognizable through id
interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator;
};
eachInterpolationFactory.displayName = 'interpolationFactoryAdder';
angular.forEach($interpolatorFactories, eachInterpolationFactory);
}
/**
* @name getTranslationTable
* @private
*
* @description
* Returns a promise that resolves to the translation table
* or is rejected if an error occurred.
*
* @param langKey
* @returns {Q.promise}
*/
var getTranslationTable = function (langKey) {
var deferred = $q.defer();
if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) {
deferred.resolve($translationTable[langKey]);
} else if (langPromises[langKey]) {
var onResolve = function (data) {
translations(data.key, data.table);
deferred.resolve(data.table);
};
onResolve.displayName = 'translationTableResolver';
langPromises[langKey].then(onResolve, deferred.reject);
} else {
deferred.reject();
}
return deferred.promise;
};
/**
* @name getFallbackTranslation
* @private
*
* @description
* Returns a promise that will resolve to the translation
* or be rejected if no translation was found for the language.
* This function is currently only used for fallback language translation.
*
* @param langKey The language to translate to.
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise}
*/
var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) {
var deferred = $q.defer();
var onResolve = function (translationTable) {
if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
Interpolator.setLocale(langKey);
var translation = translationTable[translationId];
if (translation.substr(0, 2) === '@:') {
getFallbackTranslation(langKey, translation.substr(2), interpolateParams, Interpolator)
.then(deferred.resolve, deferred.reject);
} else {
deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams));
}
Interpolator.setLocale($uses);
} else {
deferred.reject();
}
};
onResolve.displayName = 'fallbackTranslationResolver';
getTranslationTable(langKey).then(onResolve, deferred.reject);
return deferred.promise;
};
/**
* @name getFallbackTranslationInstant
* @private
*
* @description
* Returns a translation
* This function is currently only used for fallback language translation.
*
* @param langKey The language to translate to.
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {string} translation
*/
var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) {
var result, translationTable = $translationTable[langKey];
if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
Interpolator.setLocale(langKey);
result = Interpolator.interpolate(translationTable[translationId], interpolateParams);
if (result.substr(0, 2) === '@:') {
return getFallbackTranslationInstant(langKey, result.substr(2), interpolateParams, Interpolator);
}
Interpolator.setLocale($uses);
}
return result;
};
/**
* @name translateByHandler
* @private
*
* Translate by missing translation handler.
*
* @param translationId
* @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is
* absent
*/
var translateByHandler = function (translationId, interpolateParams) {
// If we have a handler factory - we might also call it here to determine if it provides
// a default text for a translationid that can't be found anywhere in our tables
if ($missingTranslationHandlerFactory) {
var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses, interpolateParams);
if (resultString !== undefined) {
return resultString;
} else {
return translationId;
}
} else {
return translationId;
}
};
/**
* @name resolveForFallbackLanguage
* @private
*
* Recursive helper function for fallbackTranslation that will sequentially look
* for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
*
* @param fallbackLanguageIndex
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise} Promise that will resolve to the translation.
*/
var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator, defaultTranslationText) {
var deferred = $q.defer();
if (fallbackLanguageIndex < $fallbackLanguage.length) {
var langKey = $fallbackLanguage[fallbackLanguageIndex];
getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then(
deferred.resolve,
function () {
// Look in the next fallback language for a translation.
// It delays the resolving by passing another promise to resolve.
resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator, defaultTranslationText).then(deferred.resolve);
}
);
} else {
// No translation found in any fallback language
// if a default translation text is set in the directive, then return this as a result
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
// if no default translation is set and an error handler is defined, send it to the handler
// and then return the result
deferred.resolve(translateByHandler(translationId, interpolateParams));
}
}
return deferred.promise;
};
/**
* @name resolveForFallbackLanguageInstant
* @private
*
* Recursive helper function for fallbackTranslation that will sequentially look
* for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
*
* @param fallbackLanguageIndex
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {string} translation
*/
var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) {
var result;
if (fallbackLanguageIndex < $fallbackLanguage.length) {
var langKey = $fallbackLanguage[fallbackLanguageIndex];
result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator);
if (!result) {
result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator);
}
}
return result;
};
/**
* Translates with the usage of the fallback languages.
*
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise} Promise, that resolves to the translation.
*/
var fallbackTranslation = function (translationId, interpolateParams, Interpolator, defaultTranslationText) {
// Start with the fallbackLanguage with index 0
return resolveForFallbackLanguage((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator, defaultTranslationText);
};
/**
* Translates with the usage of the fallback languages.
*
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {String} translation
*/
var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) {
// Start with the fallbackLanguage with index 0
return resolveForFallbackLanguageInstant((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator);
};
var determineTranslation = function (translationId, interpolateParams, interpolationId, defaultTranslationText) {
var deferred = $q.defer();
var table = $uses ? $translationTable[$uses] : $translationTable,
Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator;
// if the translation id exists, we can just interpolate it
if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
var translation = table[translationId];
// If using link, rerun $translate with linked translationId and return it
if (translation.substr(0, 2) === '@:') {
$translate(translation.substr(2), interpolateParams, interpolationId, defaultTranslationText)
.then(deferred.resolve, deferred.reject);
} else {
deferred.resolve(Interpolator.interpolate(translation, interpolateParams));
}
} else {
var missingTranslationHandlerTranslation;
// for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
if ($missingTranslationHandlerFactory && !pendingLoader) {
missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
}
// since we couldn't translate the inital requested translation id,
// we try it now with one or more fallback languages, if fallback language(s) is
// configured.
if ($uses && $fallbackLanguage && $fallbackLanguage.length) {
fallbackTranslation(translationId, interpolateParams, Interpolator, defaultTranslationText)
.then(function (translation) {
deferred.resolve(translation);
}, function (_translationId) {
deferred.reject(applyNotFoundIndicators(_translationId));
});
} else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
// looks like the requested translation id doesn't exists.
// Now, if there is a registered handler for missing translations and no
// asyncLoader is pending, we execute the handler
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
deferred.resolve(missingTranslationHandlerTranslation);
}
} else {
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
deferred.reject(applyNotFoundIndicators(translationId));
}
}
}
return deferred.promise;
};
var determineTranslationInstant = function (translationId, interpolateParams, interpolationId) {
var result, table = $uses ? $translationTable[$uses] : $translationTable,
Interpolator = defaultInterpolator;
// if the interpolation id exists use custom interpolator
if (interpolatorHashMap && Object.prototype.hasOwnProperty.call(interpolatorHashMap, interpolationId)) {
Interpolator = interpolatorHashMap[interpolationId];
}
// if the translation id exists, we can just interpolate it
if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
var translation = table[translationId];
// If using link, rerun $translate with linked translationId and return it
if (translation.substr(0, 2) === '@:') {
result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId);
} else {
result = Interpolator.interpolate(translation, interpolateParams);
}
} else {
var missingTranslationHandlerTranslation;
// for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
if ($missingTranslationHandlerFactory && !pendingLoader) {
missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
}
// since we couldn't translate the inital requested translation id,
// we try it now with one or more fallback languages, if fallback language(s) is
// configured.
if ($uses && $fallbackLanguage && $fallbackLanguage.length) {
fallbackIndex = 0;
result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator);
} else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
// looks like the requested translation id doesn't exists.
// Now, if there is a registered handler for missing translations and no
// asyncLoader is pending, we execute the handler
result = missingTranslationHandlerTranslation;
} else {
result = applyNotFoundIndicators(translationId);
}
}
return result;
};
var clearNextLangAndPromise = function(key) {
if ($nextLang === key) {
$nextLang = undefined;
}
langPromises[key] = undefined;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#preferredLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key for the preferred language.
*
* @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime)
*
* @return {string} preferred language key
*/
$translate.preferredLanguage = function (langKey) {
if(langKey) {
setupPreferredLanguage(langKey);
}
return $preferredLanguage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#cloakClassName
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the configured class name for `translate-cloak` directive.
*
* @return {string} cloakClassName
*/
$translate.cloakClassName = function () {
return $cloakClassName;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#fallbackLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key for the fallback languages or sets a new fallback stack.
*
* @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime)
*
* @return {string||array} fallback language key
*/
$translate.fallbackLanguage = function (langKey) {
if (langKey !== undefined && langKey !== null) {
fallbackStack(langKey);
// as we might have an async loader initiated and a new translation language might have been defined
// we need to add the promise to the stack also. So - iterate.
if ($loaderFactory) {
if ($fallbackLanguage && $fallbackLanguage.length) {
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
if (!langPromises[$fallbackLanguage[i]]) {
langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]);
}
}
}
}
$translate.use($translate.use());
}
if ($fallbackWasString) {
return $fallbackLanguage[0];
} else {
return $fallbackLanguage;
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#useFallbackLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Sets the first key of the fallback language stack to be used for translation.
* Therefore all languages in the fallback array BEFORE this key will be skipped!
*
* @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to
* get back to the whole stack
*/
$translate.useFallbackLanguage = function (langKey) {
if (langKey !== undefined && langKey !== null) {
if (!langKey) {
startFallbackIteration = 0;
} else {
var langKeyPosition = indexOf($fallbackLanguage, langKey);
if (langKeyPosition > -1) {
startFallbackIteration = langKeyPosition;
}
}
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#proposedLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key of language that is currently loaded asynchronously.
*
* @return {string} language key
*/
$translate.proposedLanguage = function () {
return $nextLang;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#storage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns registered storage.
*
* @return {object} Storage
*/
$translate.storage = function () {
return Storage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#use
* @methodOf pascalprecht.translate.$translate
*
* @description
* Tells angular-translate which language to use by given language key. This method is
* used to change language at runtime. It also takes care of storing the language
* key in a configured store to let your app remember the choosed language.
*
* When trying to 'use' a language which isn't available it tries to load it
* asynchronously with registered loaders.
*
* Returns promise object with loaded language file data
* @example
* $translate.use("en_US").then(function(data){
* $scope.text = $translate("HELLO");
* });
*
* @param {string} key Language key
* @return {string} Language key
*/
$translate.use = function (key) {
if (!key) {
return $uses;
}
var deferred = $q.defer();
$rootScope.$emit('$translateChangeStart', {language: key});
// Try to get the aliased language key
var aliasedKey = negotiateLocale(key);
if (aliasedKey) {
key = aliasedKey;
}
// if there isn't a translation table for the language we've requested,
// we load it asynchronously
if (($forceAsyncReloadEnabled || !$translationTable[key]) && $loaderFactory && !langPromises[key]) {
$nextLang = key;
langPromises[key] = loadAsync(key).then(function (translation) {
translations(translation.key, translation.table);
deferred.resolve(translation.key);
useLanguage(translation.key);
return translation;
}, function (key) {
$rootScope.$emit('$translateChangeError', {language: key});
deferred.reject(key);
$rootScope.$emit('$translateChangeEnd', {language: key});
return $q.reject(key);
});
langPromises[key]['finally'](function () {
clearNextLangAndPromise(key);
});
} else if ($nextLang === key && langPromises[key]) {
// we are already loading this asynchronously
// resolve our new deferred when the old langPromise is resolved
langPromises[key].then(function (translation) {
deferred.resolve(translation.key);
return translation;
}, function (key) {
deferred.reject(key);
return $q.reject(key);
});
} else {
deferred.resolve(key);
useLanguage(key);
}
return deferred.promise;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#storageKey
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the key for the storage.
*
* @return {string} storage key
*/
$translate.storageKey = function () {
return storageKey();
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#isPostCompilingEnabled
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns whether post compiling is enabled or not
*
* @return {bool} storage key
*/
$translate.isPostCompilingEnabled = function () {
return $postCompilingEnabled;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#isForceAsyncReloadEnabled
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns whether force async reload is enabled or not
*
* @return {boolean} forceAsyncReload value
*/
$translate.isForceAsyncReloadEnabled = function () {
return $forceAsyncReloadEnabled;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#refresh
* @methodOf pascalprecht.translate.$translate
*
* @description
* Refreshes a translation table pointed by the given langKey. If langKey is not specified,
* the module will drop all existent translation tables and load new version of those which
* are currently in use.
*
* Refresh means that the module will drop target translation table and try to load it again.
*
* In case there are no loaders registered the refresh() method will throw an Error.
*
* If the module is able to refresh translation tables refresh() method will broadcast
* $translateRefreshStart and $translateRefreshEnd events.
*
* @example
* // this will drop all currently existent translation tables and reload those which are
* // currently in use
* $translate.refresh();
* // this will refresh a translation table for the en_US language
* $translate.refresh('en_US');
*
* @param {string} langKey A language key of the table, which has to be refreshed
*
* @return {promise} Promise, which will be resolved in case a translation tables refreshing
* process is finished successfully, and reject if not.
*/
$translate.refresh = function (langKey) {
if (!$loaderFactory) {
throw new Error('Couldn\'t refresh translation table, no loader registered!');
}
var deferred = $q.defer();
function resolve() {
deferred.resolve();
$rootScope.$emit('$translateRefreshEnd', {language: langKey});
}
function reject() {
deferred.reject();
$rootScope.$emit('$translateRefreshEnd', {language: langKey});
}
$rootScope.$emit('$translateRefreshStart', {language: langKey});
if (!langKey) {
// if there's no language key specified we refresh ALL THE THINGS!
var tables = [], loadingKeys = {};
// reload registered fallback languages
if ($fallbackLanguage && $fallbackLanguage.length) {
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
tables.push(loadAsync($fallbackLanguage[i]));
loadingKeys[$fallbackLanguage[i]] = true;
}
}
// reload currently used language
if ($uses && !loadingKeys[$uses]) {
tables.push(loadAsync($uses));
}
var allTranslationsLoaded = function (tableData) {
$translationTable = {};
angular.forEach(tableData, function (data) {
translations(data.key, data.table);
});
if ($uses) {
useLanguage($uses);
}
resolve();
};
allTranslationsLoaded.displayName = 'refreshPostProcessor';
$q.all(tables).then(allTranslationsLoaded, reject);
} else if ($translationTable[langKey]) {
var oneTranslationsLoaded = function (data) {
translations(data.key, data.table);
if (langKey === $uses) {
useLanguage($uses);
}
resolve();
};
oneTranslationsLoaded.displayName = 'refreshPostProcessor';
loadAsync(langKey).then(oneTranslationsLoaded, reject);
} else {
reject();
}
return deferred.promise;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#instant
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns a translation instantly from the internal state of loaded translation. All rules
* regarding the current language, the preferred language of even fallback languages will be
* used except any promise handling. If a language was not found, an asynchronous loading
* will be invoked in the background.
*
* @param {string|array} translationId A token which represents a translation id
* This can be optionally an array of translation ids which
* results that the function's promise returns an object where
* each key is the translation id and the value the translation.
* @param {object} interpolateParams Params
* @param {string} interpolationId The id of the interpolation to use
*
* @return {string|object} translation
*/
$translate.instant = function (translationId, interpolateParams, interpolationId) {
// Detect undefined and null values to shorten the execution and prevent exceptions
if (translationId === null || angular.isUndefined(translationId)) {
return translationId;
}
// Duck detection: If the first argument is an array, a bunch of translations was requested.
// The result is an object.
if (angular.isArray(translationId)) {
var results = {};
for (var i = 0, c = translationId.length; i < c; i++) {
results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId);
}
return results;
}
// We discarded unacceptable values. So we just need to verify if translationId is empty String
if (angular.isString(translationId) && translationId.length < 1) {
return translationId;
}
// trim off any whitespace
if (translationId) {
translationId = trim.apply(translationId);
}
var result, possibleLangKeys = [];
if ($preferredLanguage) {
possibleLangKeys.push($preferredLanguage);
}
if ($uses) {
possibleLangKeys.push($uses);
}
if ($fallbackLanguage && $fallbackLanguage.length) {
possibleLangKeys = possibleLangKeys.concat($fallbackLanguage);
}
for (var j = 0, d = possibleLangKeys.length; j < d; j++) {
var possibleLangKey = possibleLangKeys[j];
if ($translationTable[possibleLangKey]) {
if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') {
result = determineTranslationInstant(translationId, interpolateParams, interpolationId);
} else if ($notFoundIndicatorLeft || $notFoundIndicatorRight) {
result = applyNotFoundIndicators(translationId);
}
}
if (typeof result !== 'undefined') {
break;
}
}
if (!result && result !== '') {
// Return translation of default interpolator if not found anything.
result = defaultInterpolator.interpolate(translationId, interpolateParams);
if ($missingTranslationHandlerFactory && !pendingLoader) {
result = translateByHandler(translationId, interpolateParams);
}
}
return result;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#versionInfo
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the current version information for the angular-translate library
*
* @return {string} angular-translate version
*/
$translate.versionInfo = function () {
return version;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#loaderCache
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the defined loaderCache.
*
* @return {boolean|string|object} current value of loaderCache
*/
$translate.loaderCache = function () {
return loaderCache;
};
// internal purpose only
$translate.directivePriority = function () {
return directivePriority;
};
// internal purpose only
$translate.statefulFilter = function () {
return statefulFilter;
};
if ($loaderFactory) {
// If at least one async loader is defined and there are no
// (default) translations available we should try to load them.
if (angular.equals($translationTable, {})) {
$translate.use($translate.use());
}
// Also, if there are any fallback language registered, we start
// loading them asynchronously as soon as we can.
if ($fallbackLanguage && $fallbackLanguage.length) {
var processAsyncResult = function (translation) {
translations(translation.key, translation.table);
$rootScope.$emit('$translateChangeEnd', { language: translation.key });
return translation;
};
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
var fallbackLanguageId = $fallbackLanguage[i];
if ($forceAsyncReloadEnabled || !$translationTable[fallbackLanguageId]) {
langPromises[fallbackLanguageId] = loadAsync(fallbackLanguageId).then(processAsyncResult);
}
}
}
}
return $translate;
}
];
}
$translate.$inject = ['$STORAGE_KEY', '$windowProvider', '$translateSanitizationProvider', 'pascalprechtTranslateOverrider'];
$translate.displayName = 'displayName';
/**
* @ngdoc object
* @name pascalprecht.translate.$translateDefaultInterpolation
* @requires $interpolate
*
* @description
* Uses angular's `$interpolate` services to interpolate strings against some values.
*
* Be aware to configure a proper sanitization strategy.
*
* See also:
* * {@link pascalprecht.translate.$translateSanitization}
*
* @return {object} $translateDefaultInterpolation Interpolator service
*/
angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);
function $translateDefaultInterpolation ($interpolate, $translateSanitization) {
'use strict';
var $translateInterpolator = {},
$locale,
$identifier = 'default';
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#setLocale
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Sets current locale (this is currently not use in this interpolation).
*
* @param {string} locale Language key or locale.
*/
$translateInterpolator.setLocale = function (locale) {
$locale = locale;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Returns an identifier for this interpolation service.
*
* @returns {string} $identifier
*/
$translateInterpolator.getInterpolationIdentifier = function () {
return $identifier;
};
/**
* @deprecated will be removed in 3.0
* @see {@link pascalprecht.translate.$translateSanitization}
*/
$translateInterpolator.useSanitizeValueStrategy = function (value) {
$translateSanitization.useStrategy(value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#interpolate
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Interpolates given string agains given interpolate params using angulars
* `$interpolate` service.
*
* @returns {string} interpolated string.
*/
$translateInterpolator.interpolate = function (string, interpolationParams) {
interpolationParams = interpolationParams || {};
interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params');
var interpolatedText = $interpolate(string)(interpolationParams);
interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text');
return interpolatedText;
};
return $translateInterpolator;
}
$translateDefaultInterpolation.$inject = ['$interpolate', '$translateSanitization'];
$translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';
angular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY');
angular.module('pascalprecht.translate')
/**
* @ngdoc directive
* @name pascalprecht.translate.directive:translate
* @requires $compile
* @requires $filter
* @requires $interpolate
* @restrict A
*
* @description
* Translates given translation id either through attribute or DOM content.
* Internally it uses `translate` filter to translate translation id. It possible to
* pass an optional `translate-values` object literal as string into translation id.
*
* @param {string=} translate Translation id which could be either string or interpolated string.
* @param {string=} translate-values Values to pass into translation id. Can be passed as object literal string or interpolated object.
* @param {string=} translate-attr-ATTR translate Translation id and put it into ATTR attribute.
* @param {string=} translate-default will be used unless translation was successful
* @param {boolean=} translate-compile (default true if present) defines locally activation of {@link pascalprecht.translate.$translateProvider#methods_usePostCompiling}
*
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="TranslateCtrl">
<pre translate="TRANSLATION_ID"></pre>
<pre translate>TRANSLATION_ID</pre>
<pre translate translate-attr-title="TRANSLATION_ID"></pre>
<pre translate="{{translationId}}"></pre>
<pre translate>{{translationId}}</pre>
<pre translate="WITH_VALUES" translate-values="{value: 5}"></pre>
<pre translate translate-values="{value: 5}">WITH_VALUES</pre>
<pre translate="WITH_VALUES" translate-values="{{values}}"></pre>
<pre translate translate-values="{{values}}">WITH_VALUES</pre>
<pre translate translate-attr-title="WITH_VALUES" translate-values="{{values}}"></pre>
</div>
</file>
<file name="script.js">
angular.module('ngView', ['pascalprecht.translate'])
.config(function ($translateProvider) {
$translateProvider.translations('en',{
'TRANSLATION_ID': 'Hello there!',
'WITH_VALUES': 'The following value is dynamic: {{value}}'
}).preferredLanguage('en');
});
angular.module('ngView').controller('TranslateCtrl', function ($scope) {
$scope.translationId = 'TRANSLATION_ID';
$scope.values = {
value: 78
};
});
</file>
<file name="scenario.js">
it('should translate', function () {
inject(function ($rootScope, $compile) {
$rootScope.translationId = 'TRANSLATION_ID';
element = $compile('<p translate="TRANSLATION_ID"></p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate="{{translationId}}"></p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate>TRANSLATION_ID</p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate>{{translationId}}</p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate translate-attr-title="TRANSLATION_ID"></p>')($rootScope);
$rootScope.$digest();
expect(element.attr('title')).toBe('Hello there!');
});
});
</file>
</example>
*/
.directive('translate', translateDirective);
function translateDirective($translate, $q, $interpolate, $compile, $parse, $rootScope) {
'use strict';
/**
* @name trim
* @private
*
* @description
* trim polyfill
*
* @returns {string} The string stripped of whitespace from both ends
*/
var trim = function() {
return this.toString().replace(/^\s+|\s+$/g, '');
};
return {
restrict: 'AE',
scope: true,
priority: $translate.directivePriority(),
compile: function (tElement, tAttr) {
var translateValuesExist = (tAttr.translateValues) ?
tAttr.translateValues : undefined;
var translateInterpolation = (tAttr.translateInterpolation) ?
tAttr.translateInterpolation : undefined;
var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i);
var interpolateRegExp = '^(.*)(' + $interpolate.startSymbol() + '.*' + $interpolate.endSymbol() + ')(.*)',
watcherRegExp = '^(.*)' + $interpolate.startSymbol() + '(.*)' + $interpolate.endSymbol() + '(.*)';
return function linkFn(scope, iElement, iAttr) {
scope.interpolateParams = {};
scope.preText = '';
scope.postText = '';
var translationIds = {};
var initInterpolationParams = function (interpolateParams, iAttr, tAttr) {
// initial setup
if (iAttr.translateValues) {
angular.extend(interpolateParams, $parse(iAttr.translateValues)(scope.$parent));
}
// initially fetch all attributes if existing and fill the params
if (translateValueExist) {
for (var attr in tAttr) {
if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
var attributeName = angular.lowercase(attr.substr(14, 1)) + attr.substr(15);
interpolateParams[attributeName] = tAttr[attr];
}
}
}
};
// Ensures any change of the attribute "translate" containing the id will
// be re-stored to the scope's "translationId".
// If the attribute has no content, the element's text value (white spaces trimmed off) will be used.
var observeElementTranslation = function (translationId) {
// Remove any old watcher
if (angular.isFunction(observeElementTranslation._unwatchOld)) {
observeElementTranslation._unwatchOld();
observeElementTranslation._unwatchOld = undefined;
}
if (angular.equals(translationId , '') || !angular.isDefined(translationId)) {
// Resolve translation id by inner html if required
var interpolateMatches = trim.apply(iElement.text()).match(interpolateRegExp);
// Interpolate translation id if required
if (angular.isArray(interpolateMatches)) {
scope.preText = interpolateMatches[1];
scope.postText = interpolateMatches[3];
translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent);
var watcherMatches = iElement.text().match(watcherRegExp);
if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) {
observeElementTranslation._unwatchOld = scope.$watch(watcherMatches[2], function (newValue) {
translationIds.translate = newValue;
updateTranslations();
});
}
} else {
translationIds.translate = iElement.text().replace(/^\s+|\s+$/g,'');
}
} else {
translationIds.translate = translationId;
}
updateTranslations();
};
var observeAttributeTranslation = function (translateAttr) {
iAttr.$observe(translateAttr, function (translationId) {
translationIds[translateAttr] = translationId;
updateTranslations();
});
};
// initial setup with values
initInterpolationParams(scope.interpolateParams, iAttr, tAttr);
var firstAttributeChangedEvent = true;
iAttr.$observe('translate', function (translationId) {
if (typeof translationId === 'undefined') {
// case of element "<translate>xyz</translate>"
observeElementTranslation('');
} else {
// case of regular attribute
if (translationId !== '' || !firstAttributeChangedEvent) {
translationIds.translate = translationId;
updateTranslations();
}
}
firstAttributeChangedEvent = false;
});
for (var translateAttr in iAttr) {
if (iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') {
observeAttributeTranslation(translateAttr);
}
}
iAttr.$observe('translateDefault', function (value) {
scope.defaultText = value;
});
if (translateValuesExist) {
iAttr.$observe('translateValues', function (interpolateParams) {
if (interpolateParams) {
scope.$parent.$watch(function () {
angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent));
});
}
});
}
if (translateValueExist) {
var observeValueAttribute = function (attrName) {
iAttr.$observe(attrName, function (value) {
var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15);
scope.interpolateParams[attributeName] = value;
});
};
for (var attr in iAttr) {
if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
observeValueAttribute(attr);
}
}
}
// Master update function
var updateTranslations = function () {
for (var key in translationIds) {
if (translationIds.hasOwnProperty(key) && translationIds[key] !== undefined) {
updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText);
}
}
};
// Put translation processing function outside loop
var updateTranslation = function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText) {
if (translationId) {
$translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText)
.then(function (translation) {
applyTranslation(translation, scope, true, translateAttr);
}, function (translationId) {
applyTranslation(translationId, scope, false, translateAttr);
});
} else {
// as an empty string cannot be translated, we can solve this using successful=false
applyTranslation(translationId, scope, false, translateAttr);
}
};
var applyTranslation = function (value, scope, successful, translateAttr) {
if (translateAttr === 'translate') {
// default translate into innerHTML
if (!successful && typeof scope.defaultText !== 'undefined') {
value = scope.defaultText;
}
iElement.html(scope.preText + value + scope.postText);
var globallyEnabled = $translate.isPostCompilingEnabled();
var locallyDefined = typeof tAttr.translateCompile !== 'undefined';
var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false';
if ((globallyEnabled && !locallyDefined) || locallyEnabled) {
$compile(iElement.contents())(scope);
}
} else {
// translate attribute
if (!successful && typeof scope.defaultText !== 'undefined') {
value = scope.defaultText;
}
var attributeName = iAttr.$attr[translateAttr];
if (attributeName.substr(0, 5) === 'data-') {
// ensure html5 data prefix is stripped
attributeName = attributeName.substr(5);
}
attributeName = attributeName.substr(15);
iElement.attr(attributeName, value);
}
};
if (translateValuesExist || translateValueExist || iAttr.translateDefault) {
scope.$watch('interpolateParams', updateTranslations, true);
}
// Ensures the text will be refreshed after the current language was changed
// w/ $translate.use(...)
var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations);
// ensure translation will be looked up at least one
if (iElement.text().length) {
if (iAttr.translate) {
observeElementTranslation(iAttr.translate);
} else {
observeElementTranslation('');
}
} else if (iAttr.translate) {
// ensure attribute will be not skipped
observeElementTranslation(iAttr.translate);
}
updateTranslations();
scope.$on('$destroy', unbind);
};
}
};
}
translateDirective.$inject = ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope'];
translateDirective.displayName = 'translateDirective';
angular.module('pascalprecht.translate')
/**
* @ngdoc directive
* @name pascalprecht.translate.directive:translateCloak
* @requires $rootScope
* @requires $translate
* @restrict A
*
* $description
* Adds a `translate-cloak` class name to the given element where this directive
* is applied initially and removes it, once a loader has finished loading.
*
* This directive can be used to prevent initial flickering when loading translation
* data asynchronously.
*
* The class name is defined in
* {@link pascalprecht.translate.$translateProvider#cloakClassName $translate.cloakClassName()}.
*
* @param {string=} translate-cloak If a translationId is provided, it will be used for showing
* or hiding the cloak. Basically it relies on the translation
* resolve.
*/
.directive('translateCloak', translateCloakDirective);
function translateCloakDirective($rootScope, $translate) {
'use strict';
return {
compile: function (tElement) {
var applyCloak = function () {
tElement.addClass($translate.cloakClassName());
},
removeCloak = function () {
tElement.removeClass($translate.cloakClassName());
},
removeListener = $rootScope.$on('$translateChangeEnd', function () {
removeCloak();
removeListener();
removeListener = null;
});
applyCloak();
return function linkFn(scope, iElement, iAttr) {
// Register a watcher for the defined translation allowing a fine tuned cloak
if (iAttr.translateCloak && iAttr.translateCloak.length) {
iAttr.$observe('translateCloak', function (translationId) {
$translate(translationId).then(removeCloak, applyCloak);
});
}
};
}
};
}
translateCloakDirective.$inject = ['$rootScope', '$translate'];
translateCloakDirective.displayName = 'translateCloakDirective';
angular.module('pascalprecht.translate')
/**
* @ngdoc filter
* @name pascalprecht.translate.filter:translate
* @requires $parse
* @requires pascalprecht.translate.$translate
* @function
*
* @description
* Uses `$translate` service to translate contents. Accepts interpolate parameters
* to pass dynamized values though translation.
*
* @param {string} translationId A translation id to be translated.
* @param {*=} interpolateParams Optional object literal (as hash or string) to pass values into translation.
*
* @returns {string} Translated text.
*
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="TranslateCtrl">
<pre>{{ 'TRANSLATION_ID' | translate }}</pre>
<pre>{{ translationId | translate }}</pre>
<pre>{{ 'WITH_VALUES' | translate:'{value: 5}' }}</pre>
<pre>{{ 'WITH_VALUES' | translate:values }}</pre>
</div>
</file>
<file name="script.js">
angular.module('ngView', ['pascalprecht.translate'])
.config(function ($translateProvider) {
$translateProvider.translations('en', {
'TRANSLATION_ID': 'Hello there!',
'WITH_VALUES': 'The following value is dynamic: {{value}}'
});
$translateProvider.preferredLanguage('en');
});
angular.module('ngView').controller('TranslateCtrl', function ($scope) {
$scope.translationId = 'TRANSLATION_ID';
$scope.values = {
value: 78
};
});
</file>
</example>
*/
.filter('translate', translateFilterFactory);
function translateFilterFactory($parse, $translate) {
'use strict';
var translateFilter = function (translationId, interpolateParams, interpolation) {
if (!angular.isObject(interpolateParams)) {
interpolateParams = $parse(interpolateParams)(this);
}
return $translate.instant(translationId, interpolateParams, interpolation);
};
if ($translate.statefulFilter()) {
translateFilter.$stateful = true;
}
return translateFilter;
}
translateFilterFactory.$inject = ['$parse', '$translate'];
translateFilterFactory.displayName = 'translateFilterFactory';
angular.module('pascalprecht.translate')
/**
* @ngdoc object
* @name pascalprecht.translate.$translationCache
* @requires $cacheFactory
*
* @description
* The first time a translation table is used, it is loaded in the translation cache for quick retrieval. You
* can load translation tables directly into the cache by consuming the
* `$translationCache` service directly.
*
* @return {object} $cacheFactory object.
*/
.factory('$translationCache', $translationCache);
function $translationCache($cacheFactory) {
'use strict';
return $cacheFactory('translations');
}
$translationCache.$inject = ['$cacheFactory'];
$translationCache.displayName = '$translationCache';
return 'pascalprecht.translate';
}));
},{}],7:[function(require,module,exports){
/**
* State-based routing for AngularJS
* @version v0.2.15
* @link http://angular-ui.github.com/
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = 'ui.router';
}
(function (window, angular, undefined) {
/*jshint globalstrict:true*/
/*global angular:false*/
'use strict';
var isDefined = angular.isDefined,
isFunction = angular.isFunction,
isString = angular.isString,
isObject = angular.isObject,
isArray = angular.isArray,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy;
function inherit(parent, extra) {
return extend(new (extend(function() {}, { prototype: parent }))(), extra);
}
function merge(dst) {
forEach(arguments, function(obj) {
if (obj !== dst) {
forEach(obj, function(value, key) {
if (!dst.hasOwnProperty(key)) dst[key] = value;
});
}
});
return dst;
}
/**
* Finds the common ancestor path between two states.
*
* @param {Object} first The first state.
* @param {Object} second The second state.
* @return {Array} Returns an array of state names in descending order, not including the root.
*/
function ancestors(first, second) {
var path = [];
for (var n in first.path) {
if (first.path[n] !== second.path[n]) break;
path.push(first.path[n]);
}
return path;
}
/**
* IE8-safe wrapper for `Object.keys()`.
*
* @param {Object} object A JavaScript object.
* @return {Array} Returns the keys of the object as an array.
*/
function objectKeys(object) {
if (Object.keys) {
return Object.keys(object);
}
var result = [];
forEach(object, function(val, key) {
result.push(key);
});
return result;
}
/**
* IE8-safe wrapper for `Array.prototype.indexOf()`.
*
* @param {Array} array A JavaScript array.
* @param {*} value A value to search the array for.
* @return {Number} Returns the array index value of `value`, or `-1` if not present.
*/
function indexOf(array, value) {
if (Array.prototype.indexOf) {
return array.indexOf(value, Number(arguments[2]) || 0);
}
var len = array.length >>> 0, from = Number(arguments[2]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
for (; from < len; from++) {
if (from in array && array[from] === value) return from;
}
return -1;
}
/**
* Merges a set of parameters with all parameters inherited between the common parents of the
* current state and a given destination state.
*
* @param {Object} currentParams The value of the current state parameters ($stateParams).
* @param {Object} newParams The set of parameters which will be composited with inherited params.
* @param {Object} $current Internal definition of object representing the current state.
* @param {Object} $to Internal definition of object representing state to transition to.
*/
function inheritParams(currentParams, newParams, $current, $to) {
var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
for (var i in parents) {
if (!parents[i].params) continue;
parentParams = objectKeys(parents[i].params);
if (!parentParams.length) continue;
for (var j in parentParams) {
if (indexOf(inheritList, parentParams[j]) >= 0) continue;
inheritList.push(parentParams[j]);
inherited[parentParams[j]] = currentParams[parentParams[j]];
}
}
return extend({}, inherited, newParams);
}
/**
* Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
*
* @param {Object} a The first object.
* @param {Object} b The second object.
* @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
* it defaults to the list of keys in `a`.
* @return {Boolean} Returns `true` if the keys match, otherwise `false`.
*/
function equalForKeys(a, b, keys) {
if (!keys) {
keys = [];
for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
}
for (var i=0; i<keys.length; i++) {
var k = keys[i];
if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
}
return true;
}
/**
* Returns the subset of an object, based on a list of keys.
*
* @param {Array} keys
* @param {Object} values
* @return {Boolean} Returns a subset of `values`.
*/
function filterByKeys(keys, values) {
var filtered = {};
forEach(keys, function (name) {
filtered[name] = values[name];
});
return filtered;
}
// like _.indexBy
// when you know that your index values will be unique, or you want last-one-in to win
function indexBy(array, propName) {
var result = {};
forEach(array, function(item) {
result[item[propName]] = item;
});
return result;
}
// extracted from underscore.js
// Return a copy of the object only containing the whitelisted properties.
function pick(obj) {
var copy = {};
var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
forEach(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
}
// extracted from underscore.js
// Return a copy of the object omitting the blacklisted properties.
function omit(obj) {
var copy = {};
var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
for (var key in obj) {
if (indexOf(keys, key) == -1) copy[key] = obj[key];
}
return copy;
}
function pluck(collection, key) {
var result = isArray(collection) ? [] : {};
forEach(collection, function(val, i) {
result[i] = isFunction(key) ? key(val) : val[key];
});
return result;
}
function filter(collection, callback) {
var array = isArray(collection);
var result = array ? [] : {};
forEach(collection, function(val, i) {
if (callback(val, i)) {
result[array ? result.length : i] = val;
}
});
return result;
}
function map(collection, callback) {
var result = isArray(collection) ? [] : {};
forEach(collection, function(val, i) {
result[i] = callback(val, i);
});
return result;
}
/**
* @ngdoc overview
* @name ui.router.util
*
* @description
* # ui.router.util sub-module
*
* This module is a dependency of other sub-modules. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*
*/
angular.module('ui.router.util', ['ng']);
/**
* @ngdoc overview
* @name ui.router.router
*
* @requires ui.router.util
*
* @description
* # ui.router.router sub-module
*
* This module is a dependency of other sub-modules. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*/
angular.module('ui.router.router', ['ui.router.util']);
/**
* @ngdoc overview
* @name ui.router.state
*
* @requires ui.router.router
* @requires ui.router.util
*
* @description
* # ui.router.state sub-module
*
* This module is a dependency of the main ui.router module. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*
*/
angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
/**
* @ngdoc overview
* @name ui.router
*
* @requires ui.router.state
*
* @description
* # ui.router
*
* ## The main module for ui.router
* There are several sub-modules included with the ui.router module, however only this module is needed
* as a dependency within your angular app. The other modules are for organization purposes.
*
* The modules are:
* * ui.router - the main "umbrella" module
* * ui.router.router -
*
* *You'll need to include **only** this module as the dependency within your angular app.*
*
* <pre>
* <!doctype html>
* <html ng-app="myApp">
* <head>
* <script src="js/angular.js"></script>
* <!-- Include the ui-router script -->
* <script src="js/angular-ui-router.min.js"></script>
* <script>
* // ...and add 'ui.router' as a dependency
* var myApp = angular.module('myApp', ['ui.router']);
* </script>
* </head>
* <body>
* </body>
* </html>
* </pre>
*/
angular.module('ui.router', ['ui.router.state']);
angular.module('ui.router.compat', ['ui.router']);
/**
* @ngdoc object
* @name ui.router.util.$resolve
*
* @requires $q
* @requires $injector
*
* @description
* Manages resolution of (acyclic) graphs of promises.
*/
$Resolve.$inject = ['$q', '$injector'];
function $Resolve( $q, $injector) {
var VISIT_IN_PROGRESS = 1,
VISIT_DONE = 2,
NOTHING = {},
NO_DEPENDENCIES = [],
NO_LOCALS = NOTHING,
NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
/**
* @ngdoc function
* @name ui.router.util.$resolve#study
* @methodOf ui.router.util.$resolve
*
* @description
* Studies a set of invocables that are likely to be used multiple times.
* <pre>
* $resolve.study(invocables)(locals, parent, self)
* </pre>
* is equivalent to
* <pre>
* $resolve.resolve(invocables, locals, parent, self)
* </pre>
* but the former is more efficient (in fact `resolve` just calls `study`
* internally).
*
* @param {object} invocables Invocable objects
* @return {function} a function to pass in locals, parent and self
*/
this.study = function (invocables) {
if (!isObject(invocables)) throw new Error("'invocables' must be an object");
var invocableKeys = objectKeys(invocables || {});
// Perform a topological sort of invocables to build an ordered plan
var plan = [], cycle = [], visited = {};
function visit(value, key) {
if (visited[key] === VISIT_DONE) return;
cycle.push(key);
if (visited[key] === VISIT_IN_PROGRESS) {
cycle.splice(0, indexOf(cycle, key));
throw new Error("Cyclic dependency: " + cycle.join(" -> "));
}
visited[key] = VISIT_IN_PROGRESS;
if (isString(value)) {
plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
} else {
var params = $injector.annotate(value);
forEach(params, function (param) {
if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
});
plan.push(key, value, params);
}
cycle.pop();
visited[key] = VISIT_DONE;
}
forEach(invocables, visit);
invocables = cycle = visited = null; // plan is all that's required
function isResolve(value) {
return isObject(value) && value.then && value.$$promises;
}
return function (locals, parent, self) {
if (isResolve(locals) && self === undefined) {
self = parent; parent = locals; locals = null;
}
if (!locals) locals = NO_LOCALS;
else if (!isObject(locals)) {
throw new Error("'locals' must be an object");
}
if (!parent) parent = NO_PARENT;
else if (!isResolve(parent)) {
throw new Error("'parent' must be a promise returned by $resolve.resolve()");
}
// To complete the overall resolution, we have to wait for the parent
// promise and for the promise for each invokable in our plan.
var resolution = $q.defer(),
result = resolution.promise,
promises = result.$$promises = {},
values = extend({}, locals),
wait = 1 + plan.length/3,
merged = false;
function done() {
// Merge parent values we haven't got yet and publish our own $$values
if (!--wait) {
if (!merged) merge(values, parent.$$values);
result.$$values = values;
result.$$promises = result.$$promises || true; // keep for isResolve()
delete result.$$inheritedValues;
resolution.resolve(values);
}
}
function fail(reason) {
result.$$failure = reason;
resolution.reject(reason);
}
// Short-circuit if parent has already failed
if (isDefined(parent.$$failure)) {
fail(parent.$$failure);
return result;
}
if (parent.$$inheritedValues) {
merge(values, omit(parent.$$inheritedValues, invocableKeys));
}
// Merge parent values if the parent has already resolved, or merge
// parent promises and wait if the parent resolve is still in progress.
extend(promises, parent.$$promises);
if (parent.$$values) {
merged = merge(values, omit(parent.$$values, invocableKeys));
result.$$inheritedValues = omit(parent.$$values, invocableKeys);
done();
} else {
if (parent.$$inheritedValues) {
result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
}
parent.then(done, fail);
}
// Process each invocable in the plan, but ignore any where a local of the same name exists.
for (var i=0, ii=plan.length; i<ii; i+=3) {
if (locals.hasOwnProperty(plan[i])) done();
else invoke(plan[i], plan[i+1], plan[i+2]);
}
function invoke(key, invocable, params) {
// Create a deferred for this invocation. Failures will propagate to the resolution as well.
var invocation = $q.defer(), waitParams = 0;
function onfailure(reason) {
invocation.reject(reason);
fail(reason);
}
// Wait for any parameter that we have a promise for (either from parent or from this
// resolve; in that case study() will have made sure it's ordered before us in the plan).
forEach(params, function (dep) {
if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
waitParams++;
promises[dep].then(function (result) {
values[dep] = result;
if (!(--waitParams)) proceed();
}, onfailure);
}
});
if (!waitParams) proceed();
function proceed() {
if (isDefined(result.$$failure)) return;
try {
invocation.resolve($injector.invoke(invocable, self, values));
invocation.promise.then(function (result) {
values[key] = result;
done();
}, onfailure);
} catch (e) {
onfailure(e);
}
}
// Publish promise synchronously; invocations further down in the plan may depend on it.
promises[key] = invocation.promise;
}
return result;
};
};
/**
* @ngdoc function
* @name ui.router.util.$resolve#resolve
* @methodOf ui.router.util.$resolve
*
* @description
* Resolves a set of invocables. An invocable is a function to be invoked via
* `$injector.invoke()`, and can have an arbitrary number of dependencies.
* An invocable can either return a value directly,
* or a `$q` promise. If a promise is returned it will be resolved and the
* resulting value will be used instead. Dependencies of invocables are resolved
* (in this order of precedence)
*
* - from the specified `locals`
* - from another invocable that is part of this `$resolve` call
* - from an invocable that is inherited from a `parent` call to `$resolve`
* (or recursively
* - from any ancestor `$resolve` of that parent).
*
* The return value of `$resolve` is a promise for an object that contains
* (in this order of precedence)
*
* - any `locals` (if specified)
* - the resolved return values of all injectables
* - any values inherited from a `parent` call to `$resolve` (if specified)
*
* The promise will resolve after the `parent` promise (if any) and all promises
* returned by injectables have been resolved. If any invocable
* (or `$injector.invoke`) throws an exception, or if a promise returned by an
* invocable is rejected, the `$resolve` promise is immediately rejected with the
* same error. A rejection of a `parent` promise (if specified) will likewise be
* propagated immediately. Once the `$resolve` promise has been rejected, no
* further invocables will be called.
*
* Cyclic dependencies between invocables are not permitted and will caues `$resolve`
* to throw an error. As a special case, an injectable can depend on a parameter
* with the same name as the injectable, which will be fulfilled from the `parent`
* injectable of the same name. This allows inherited values to be decorated.
* Note that in this case any other injectable in the same `$resolve` with the same
* dependency would see the decorated value, not the inherited value.
*
* Note that missing dependencies -- unlike cyclic dependencies -- will cause an
* (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
* exception.
*
* Invocables are invoked eagerly as soon as all dependencies are available.
* This is true even for dependencies inherited from a `parent` call to `$resolve`.
*
* As a special case, an invocable can be a string, in which case it is taken to
* be a service name to be passed to `$injector.get()`. This is supported primarily
* for backwards-compatibility with the `resolve` property of `$routeProvider`
* routes.
*
* @param {object} invocables functions to invoke or
* `$injector` services to fetch.
* @param {object} locals values to make available to the injectables
* @param {object} parent a promise returned by another call to `$resolve`.
* @param {object} self the `this` for the invoked methods
* @return {object} Promise for an object that contains the resolved return value
* of all invocables, as well as any inherited and local values.
*/
this.resolve = function (invocables, locals, parent, self) {
return this.study(invocables)(locals, parent, self);
};
}
angular.module('ui.router.util').service('$resolve', $Resolve);
/**
* @ngdoc object
* @name ui.router.util.$templateFactory
*
* @requires $http
* @requires $templateCache
* @requires $injector
*
* @description
* Service. Manages loading of templates.
*/
$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
function $TemplateFactory( $http, $templateCache, $injector) {
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromConfig
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template from a configuration object.
*
* @param {object} config Configuration object for which to load a template.
* The following properties are search in the specified order, and the first one
* that is defined is used to create the template:
*
* @param {string|object} config.template html string template or function to
* load via {@link ui.router.util.$templateFactory#fromString fromString}.
* @param {string|object} config.templateUrl url to load or a function returning
* the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
* @param {Function} config.templateProvider function to invoke via
* {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
* @param {object} params Parameters to pass to the template function.
* @param {object} locals Locals to pass to `invoke` if the template is loaded
* via a `templateProvider`. Defaults to `{ params: params }`.
*
* @return {string|object} The template html as a string, or a promise for
* that string,or `null` if no template is configured.
*/
this.fromConfig = function (config, params, locals) {
return (
isDefined(config.template) ? this.fromString(config.template, params) :
isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
null
);
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromString
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template from a string or a function returning a string.
*
* @param {string|object} template html template as a string or function that
* returns an html template as a string.
* @param {object} params Parameters to pass to the template function.
*
* @return {string|object} The template html as a string, or a promise for that
* string.
*/
this.fromString = function (template, params) {
return isFunction(template) ? template(params) : template;
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromUrl
* @methodOf ui.router.util.$templateFactory
*
* @description
* Loads a template from the a URL via `$http` and `$templateCache`.
*
* @param {string|Function} url url of the template to load, or a function
* that returns a url.
* @param {Object} params Parameters to pass to the url function.
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
this.fromUrl = function (url, params) {
if (isFunction(url)) url = url(params);
if (url == null) return null;
else return $http
.get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
.then(function(response) { return response.data; });
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromProvider
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template by invoking an injectable provider function.
*
* @param {Function} provider Function to invoke via `$injector.invoke`
* @param {Object} params Parameters for the template.
* @param {Object} locals Locals to pass to `invoke`. Defaults to
* `{ params: params }`.
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
this.fromProvider = function (provider, params, locals) {
return $injector.invoke(provider, null, locals || { params: params });
};
}
angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
var $$UMFP; // reference to $UrlMatcherFactoryProvider
/**
* @ngdoc object
* @name ui.router.util.type:UrlMatcher
*
* @description
* Matches URLs against patterns and extracts named parameters from the path or the search
* part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
* of search parameters. Multiple search parameter names are separated by '&'. Search parameters
* do not influence whether or not a URL is matched, but their values are passed through into
* the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
*
* Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
* syntax, which optionally allows a regular expression for the parameter to be specified:
*
* * `':'` name - colon placeholder
* * `'*'` name - catch-all placeholder
* * `'{' name '}'` - curly placeholder
* * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
* regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
*
* Parameter names may contain only word characters (latin letters, digits, and underscore) and
* must be unique within the pattern (across both path and search parameters). For colon
* placeholders or curly placeholders without an explicit regexp, a path parameter matches any
* number of characters other than '/'. For catch-all placeholders the path parameter matches
* any number of characters.
*
* Examples:
*
* * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
* trailing slashes, and patterns have to match the entire path, not just a prefix.
* * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
* '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
* * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
* * `'/user/{id:[^/]*}'` - Same as the previous example.
* * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
* parameter consists of 1 to 8 hex digits.
* * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
* path into the parameter 'path'.
* * `'/files/*path'` - ditto.
* * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
* in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
*
* @param {string} pattern The pattern to compile into a matcher.
* @param {Object} config A configuration object hash:
* @param {Object=} parentMatcher Used to concatenate the pattern/config onto
* an existing UrlMatcher
*
* * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
* * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
*
* @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
* URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
* non-null) will start with this prefix.
*
* @property {string} source The pattern that was passed into the constructor
*
* @property {string} sourcePath The path portion of the source property
*
* @property {string} sourceSearch The search portion of the source property
*
* @property {string} regex The constructed regex that will be used to match against the url when
* it is time to determine which url will match.
*
* @returns {Object} New `UrlMatcher` object
*/
function UrlMatcher(pattern, config, parentMatcher) {
config = extend({ params: {} }, isObject(config) ? config : {});
// Find all placeholders and create a compiled pattern, using either classic or curly syntax:
// '*' name
// ':' name
// '{' name '}'
// '{' name ':' regexp '}'
// The regular expression is somewhat complicated due to the need to allow curly braces
// inside the regular expression. The placeholder regexp breaks down as follows:
// ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
// \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
// (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
// [^{}\\]+ - anything other than curly braces or backslash
// \\. - a backslash escape
// \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
compiled = '^', last = 0, m,
segments = this.segments = [],
parentParams = parentMatcher ? parentMatcher.params : {},
params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
paramNames = [];
function addParameter(id, type, config, location) {
paramNames.push(id);
if (parentParams[id]) return parentParams[id];
if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
params[id] = new $$UMFP.Param(id, type, config, location);
return params[id];
}
function quoteRegExp(string, pattern, squash, optional) {
var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
if (!pattern) return result;
switch(squash) {
case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
case true: surroundPattern = ['?(', ')?']; break;
default: surroundPattern = ['(' + squash + "|", ')?']; break;
}
return result + surroundPattern[0] + pattern + surroundPattern[1];
}
this.source = pattern;
// Split into static segments separated by path parameter placeholders.
// The number of segments is always 1 more than the number of parameters.
function matchDetails(m, isSearch) {
var id, regexp, segment, type, cfg, arrayMode;
id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
cfg = config.params[id];
segment = pattern.substring(last, m.index);
regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
return {
id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
};
}
var p, param, segment;
while ((m = placeholder.exec(pattern))) {
p = matchDetails(m, false);
if (p.segment.indexOf('?') >= 0) break; // we're into the search part
param = addParameter(p.id, p.type, p.cfg, "path");
compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
segments.push(p.segment);
last = placeholder.lastIndex;
}
segment = pattern.substring(last);
// Find any search parameter names and remove them from the last segment
var i = segment.indexOf('?');
if (i >= 0) {
var search = this.sourceSearch = segment.substring(i);
segment = segment.substring(0, i);
this.sourcePath = pattern.substring(0, last + i);
if (search.length > 0) {
last = 0;
while ((m = searchPlaceholder.exec(search))) {
p = matchDetails(m, true);
param = addParameter(p.id, p.type, p.cfg, "search");
last = placeholder.lastIndex;
// check if ?&
}
}
} else {
this.sourcePath = pattern;
this.sourceSearch = '';
}
compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
segments.push(segment);
this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
this.prefix = segments[0];
this.$$paramNames = paramNames;
}
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#concat
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Returns a new matcher for a pattern constructed by appending the path part and adding the
* search parameters of the specified pattern to this pattern. The current pattern is not
* modified. This can be understood as creating a pattern for URLs that are relative to (or
* suffixes of) the current pattern.
*
* @example
* The following two matchers are equivalent:
* <pre>
* new UrlMatcher('/user/{id}?q').concat('/details?date');
* new UrlMatcher('/user/{id}/details?q&date');
* </pre>
*
* @param {string} pattern The pattern to append.
* @param {Object} config An object hash of the configuration for the matcher.
* @returns {UrlMatcher} A matcher for the concatenated pattern.
*/
UrlMatcher.prototype.concat = function (pattern, config) {
// Because order of search parameters is irrelevant, we can add our own search
// parameters to the end of the new pattern. Parse the new pattern by itself
// and then join the bits together, but it's much easier to do this on a string level.
var defaultConfig = {
caseInsensitive: $$UMFP.caseInsensitive(),
strict: $$UMFP.strictMode(),
squash: $$UMFP.defaultSquashPolicy()
};
return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
};
UrlMatcher.prototype.toString = function () {
return this.source;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#exec
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Tests the specified path against this matcher, and returns an object containing the captured
* parameter values, or null if the path does not match. The returned object contains the values
* of any search parameters that are mentioned in the pattern, but their value may be null if
* they are not present in `searchParams`. This means that search parameters are always treated
* as optional.
*
* @example
* <pre>
* new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
* x: '1', q: 'hello'
* });
* // returns { id: 'bob', q: 'hello', r: null }
* </pre>
*
* @param {string} path The URL path to match, e.g. `$location.path()`.
* @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
* @returns {Object} The captured parameter values.
*/
UrlMatcher.prototype.exec = function (path, searchParams) {
var m = this.regexp.exec(path);
if (!m) return null;
searchParams = searchParams || {};
var paramNames = this.parameters(), nTotal = paramNames.length,
nPath = this.segments.length - 1,
values = {}, i, j, cfg, paramName;
if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
function decodePathArray(string) {
function reverseString(str) { return str.split("").reverse().join(""); }
function unquoteDashes(str) { return str.replace(/\\-/g, "-"); }
var split = reverseString(string).split(/-(?!\\)/);
var allReversed = map(split, reverseString);
return map(allReversed, unquoteDashes).reverse();
}
for (i = 0; i < nPath; i++) {
paramName = paramNames[i];
var param = this.params[paramName];
var paramVal = m[i+1];
// if the param value matches a pre-replace pair, replace the value before decoding.
for (j = 0; j < param.replace; j++) {
if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
}
if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
values[paramName] = param.value(paramVal);
}
for (/**/; i < nTotal; i++) {
paramName = paramNames[i];
values[paramName] = this.params[paramName].value(searchParams[paramName]);
}
return values;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#parameters
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Returns the names of all path and search parameters of this pattern in an unspecified order.
*
* @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
* pattern has no parameters, an empty array is returned.
*/
UrlMatcher.prototype.parameters = function (param) {
if (!isDefined(param)) return this.$$paramNames;
return this.params[param] || null;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#validate
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Checks an object hash of parameters to validate their correctness according to the parameter
* types of this `UrlMatcher`.
*
* @param {Object} params The object hash of parameters to validate.
* @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
*/
UrlMatcher.prototype.validates = function (params) {
return this.params.$$validates(params);
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#format
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Creates a URL that matches this pattern by substituting the specified values
* for the path and search parameters. Null values for path parameters are
* treated as empty strings.
*
* @example
* <pre>
* new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
* // returns '/user/bob?q=yes'
* </pre>
*
* @param {Object} values the values to substitute for the parameters in this pattern.
* @returns {string} the formatted URL (path and optionally search part).
*/
UrlMatcher.prototype.format = function (values) {
values = values || {};
var segments = this.segments, params = this.parameters(), paramset = this.params;
if (!this.validates(values)) return null;
var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
function encodeDashes(str) { // Replace dashes with encoded "\-"
return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
}
for (i = 0; i < nTotal; i++) {
var isPathParam = i < nPath;
var name = params[i], param = paramset[name], value = param.value(values[name]);
var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
var squash = isDefaultValue ? param.squash : false;
var encoded = param.type.encode(value);
if (isPathParam) {
var nextSegment = segments[i + 1];
if (squash === false) {
if (encoded != null) {
if (isArray(encoded)) {
result += map(encoded, encodeDashes).join("-");
} else {
result += encodeURIComponent(encoded);
}
}
result += nextSegment;
} else if (squash === true) {
var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
result += nextSegment.match(capture)[1];
} else if (isString(squash)) {
result += squash + nextSegment;
}
} else {
if (encoded == null || (isDefaultValue && squash !== false)) continue;
if (!isArray(encoded)) encoded = [ encoded ];
encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
result += (search ? '&' : '?') + (name + '=' + encoded);
search = true;
}
}
return result;
};
/**
* @ngdoc object
* @name ui.router.util.type:Type
*
* @description
* Implements an interface to define custom parameter types that can be decoded from and encoded to
* string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
* objects when matching or formatting URLs, or comparing or validating parameter values.
*
* See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
* information on registering custom types.
*
* @param {Object} config A configuration object which contains the custom type definition. The object's
* properties will override the default methods and/or pattern in `Type`'s public interface.
* @example
* <pre>
* {
* decode: function(val) { return parseInt(val, 10); },
* encode: function(val) { return val && val.toString(); },
* equals: function(a, b) { return this.is(a) && a === b; },
* is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
* pattern: /\d+/
* }
* </pre>
*
* @property {RegExp} pattern The regular expression pattern used to match values of this type when
* coming from a substring of a URL.
*
* @returns {Object} Returns a new `Type` object.
*/
function Type(config) {
extend(this, config);
}
/**
* @ngdoc function
* @name ui.router.util.type:Type#is
* @methodOf ui.router.util.type:Type
*
* @description
* Detects whether a value is of a particular type. Accepts a native (decoded) value
* and determines whether it matches the current `Type` object.
*
* @param {*} val The value to check.
* @param {string} key Optional. If the type check is happening in the context of a specific
* {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
* parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
* @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
*/
Type.prototype.is = function(val, key) {
return true;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#encode
* @methodOf ui.router.util.type:Type
*
* @description
* Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
* return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
* only needs to be a representation of `val` that has been coerced to a string.
*
* @param {*} val The value to encode.
* @param {string} key The name of the parameter in which `val` is stored. Can be used for
* meta-programming of `Type` objects.
* @returns {string} Returns a string representation of `val` that can be encoded in a URL.
*/
Type.prototype.encode = function(val, key) {
return val;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#decode
* @methodOf ui.router.util.type:Type
*
* @description
* Converts a parameter value (from URL string or transition param) to a custom/native value.
*
* @param {string} val The URL parameter value to decode.
* @param {string} key The name of the parameter in which `val` is stored. Can be used for
* meta-programming of `Type` objects.
* @returns {*} Returns a custom representation of the URL parameter value.
*/
Type.prototype.decode = function(val, key) {
return val;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#equals
* @methodOf ui.router.util.type:Type
*
* @description
* Determines whether two decoded values are equivalent.
*
* @param {*} a A value to compare against.
* @param {*} b A value to compare against.
* @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
*/
Type.prototype.equals = function(a, b) {
return a == b;
};
Type.prototype.$subPattern = function() {
var sub = this.pattern.toString();
return sub.substr(1, sub.length - 2);
};
Type.prototype.pattern = /.*/;
Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
/** Given an encoded string, or a decoded object, returns a decoded object */
Type.prototype.$normalize = function(val) {
return this.is(val) ? val : this.decode(val);
};
/*
* Wraps an existing custom Type as an array of Type, depending on 'mode'.
* e.g.:
* - urlmatcher pattern "/path?{queryParam[]:int}"
* - url: "/path?queryParam=1&queryParam=2
* - $stateParams.queryParam will be [1, 2]
* if `mode` is "auto", then
* - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
* - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
*/
Type.prototype.$asArray = function(mode, isSearch) {
if (!mode) return this;
if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
function ArrayType(type, mode) {
function bindTo(type, callbackName) {
return function() {
return type[callbackName].apply(type, arguments);
};
}
// Wrap non-array value as array
function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
// Unwrap array value for "auto" mode. Return undefined for empty array.
function arrayUnwrap(val) {
switch(val.length) {
case 0: return undefined;
case 1: return mode === "auto" ? val[0] : val;
default: return val;
}
}
function falsey(val) { return !val; }
// Wraps type (.is/.encode/.decode) functions to operate on each value of an array
function arrayHandler(callback, allTruthyMode) {
return function handleArray(val) {
val = arrayWrap(val);
var result = map(val, callback);
if (allTruthyMode === true)
return filter(result, falsey).length === 0;
return arrayUnwrap(result);
};
}
// Wraps type (.equals) functions to operate on each value of an array
function arrayEqualsHandler(callback) {
return function handleArray(val1, val2) {
var left = arrayWrap(val1), right = arrayWrap(val2);
if (left.length !== right.length) return false;
for (var i = 0; i < left.length; i++) {
if (!callback(left[i], right[i])) return false;
}
return true;
};
}
this.encode = arrayHandler(bindTo(type, 'encode'));
this.decode = arrayHandler(bindTo(type, 'decode'));
this.is = arrayHandler(bindTo(type, 'is'), true);
this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
this.pattern = type.pattern;
this.$normalize = arrayHandler(bindTo(type, '$normalize'));
this.name = type.name;
this.$arrayMode = mode;
}
return new ArrayType(this, mode);
};
/**
* @ngdoc object
* @name ui.router.util.$urlMatcherFactory
*
* @description
* Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
* is also available to providers under the name `$urlMatcherFactoryProvider`.
*/
function $UrlMatcherFactory() {
$$UMFP = this;
var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
string: {
encode: valToString,
decode: valFromString,
// TODO: in 1.0, make string .is() return false if value is undefined/null by default.
// In 0.2.x, string params are optional by default for backwards compat
is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; },
pattern: /[^/]*/
},
int: {
encode: valToString,
decode: function(val) { return parseInt(val, 10); },
is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
pattern: /\d+/
},
bool: {
encode: function(val) { return val ? 1 : 0; },
decode: function(val) { return parseInt(val, 10) !== 0; },
is: function(val) { return val === true || val === false; },
pattern: /0|1/
},
date: {
encode: function (val) {
if (!this.is(val))
return undefined;
return [ val.getFullYear(),
('0' + (val.getMonth() + 1)).slice(-2),
('0' + val.getDate()).slice(-2)
].join("-");
},
decode: function (val) {
if (this.is(val)) return val;
var match = this.capture.exec(val);
return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
},
is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
},
json: {
encode: angular.toJson,
decode: angular.fromJson,
is: angular.isObject,
equals: angular.equals,
pattern: /[^/]*/
},
any: { // does not encode/decode
encode: angular.identity,
decode: angular.identity,
equals: angular.equals,
pattern: /.*/
}
};
function getDefaultConfig() {
return {
strict: isStrictMode,
caseInsensitive: isCaseInsensitive
};
}
function isInjectable(value) {
return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
}
/**
* [Internal] Get the default value of a parameter, which may be an injectable function.
*/
$UrlMatcherFactory.$$getDefaultValue = function(config) {
if (!isInjectable(config.value)) return config.value;
if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
return injector.invoke(config.value);
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#caseInsensitive
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Defines whether URL matching should be case sensitive (the default behavior), or not.
*
* @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
* @returns {boolean} the current value of caseInsensitive
*/
this.caseInsensitive = function(value) {
if (isDefined(value))
isCaseInsensitive = value;
return isCaseInsensitive;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#strictMode
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Defines whether URLs should match trailing slashes, or not (the default behavior).
*
* @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
* @returns {boolean} the current value of strictMode
*/
this.strictMode = function(value) {
if (isDefined(value))
isStrictMode = value;
return isStrictMode;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Sets the default behavior when generating or matching URLs with default parameter values.
*
* @param {string} value A string that defines the default parameter URL squashing behavior.
* `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
* `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
* parameter is surrounded by slashes, squash (remove) one slash from the URL
* any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
* the parameter value from the URL and replace it with this string.
*/
this.defaultSquashPolicy = function(value) {
if (!isDefined(value)) return defaultSquashPolicy;
if (value !== true && value !== false && !isString(value))
throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
defaultSquashPolicy = value;
return value;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#compile
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
*
* @param {string} pattern The URL pattern.
* @param {Object} config The config object hash.
* @returns {UrlMatcher} The UrlMatcher.
*/
this.compile = function (pattern, config) {
return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#isMatcher
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Returns true if the specified object is a `UrlMatcher`, or false otherwise.
*
* @param {Object} object The object to perform the type check against.
* @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
* implementing all the same methods.
*/
this.isMatcher = function (o) {
if (!isObject(o)) return false;
var result = true;
forEach(UrlMatcher.prototype, function(val, name) {
if (isFunction(val)) {
result = result && (isDefined(o[name]) && isFunction(o[name]));
}
});
return result;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#type
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
* generate URLs with typed parameters.
*
* @param {string} name The type name.
* @param {Object|Function} definition The type definition. See
* {@link ui.router.util.type:Type `Type`} for information on the values accepted.
* @param {Object|Function} definitionFn (optional) A function that is injected before the app
* runtime starts. The result of this function is merged into the existing `definition`.
* See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
*
* @returns {Object} Returns `$urlMatcherFactoryProvider`.
*
* @example
* This is a simple example of a custom type that encodes and decodes items from an
* array, using the array index as the URL-encoded value:
*
* <pre>
* var list = ['John', 'Paul', 'George', 'Ringo'];
*
* $urlMatcherFactoryProvider.type('listItem', {
* encode: function(item) {
* // Represent the list item in the URL using its corresponding index
* return list.indexOf(item);
* },
* decode: function(item) {
* // Look up the list item by index
* return list[parseInt(item, 10)];
* },
* is: function(item) {
* // Ensure the item is valid by checking to see that it appears
* // in the list
* return list.indexOf(item) > -1;
* }
* });
*
* $stateProvider.state('list', {
* url: "/list/{item:listItem}",
* controller: function($scope, $stateParams) {
* console.log($stateParams.item);
* }
* });
*
* // ...
*
* // Changes URL to '/list/3', logs "Ringo" to the console
* $state.go('list', { item: "Ringo" });
* </pre>
*
* This is a more complex example of a type that relies on dependency injection to
* interact with services, and uses the parameter name from the URL to infer how to
* handle encoding and decoding parameter values:
*
* <pre>
* // Defines a custom type that gets a value from a service,
* // where each service gets different types of values from
* // a backend API:
* $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
*
* // Matches up services to URL parameter names
* var services = {
* user: Users,
* post: Posts
* };
*
* return {
* encode: function(object) {
* // Represent the object in the URL using its unique ID
* return object.id;
* },
* decode: function(value, key) {
* // Look up the object by ID, using the parameter
* // name (key) to call the correct service
* return services[key].findById(value);
* },
* is: function(object, key) {
* // Check that object is a valid dbObject
* return angular.isObject(object) && object.id && services[key];
* }
* equals: function(a, b) {
* // Check the equality of decoded objects by comparing
* // their unique IDs
* return a.id === b.id;
* }
* };
* });
*
* // In a config() block, you can then attach URLs with
* // type-annotated parameters:
* $stateProvider.state('users', {
* url: "/users",
* // ...
* }).state('users.item', {
* url: "/{user:dbObject}",
* controller: function($scope, $stateParams) {
* // $stateParams.user will now be an object returned from
* // the Users service
* },
* // ...
* });
* </pre>
*/
this.type = function (name, definition, definitionFn) {
if (!isDefined(definition)) return $types[name];
if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
$types[name] = new Type(extend({ name: name }, definition));
if (definitionFn) {
typeQueue.push({ name: name, def: definitionFn });
if (!enqueue) flushTypeQueue();
}
return this;
};
// `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
function flushTypeQueue() {
while(typeQueue.length) {
var type = typeQueue.shift();
if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
angular.extend($types[type.name], injector.invoke(type.def));
}
}
// Register default types. Store them in the prototype of $types.
forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
$types = inherit($types, {});
/* No need to document $get, since it returns this */
this.$get = ['$injector', function ($injector) {
injector = $injector;
enqueue = false;
flushTypeQueue();
forEach(defaultTypes, function(type, name) {
if (!$types[name]) $types[name] = new Type(type);
});
return this;
}];
this.Param = function Param(id, type, config, location) {
var self = this;
config = unwrapShorthand(config);
type = getType(config, type, location);
var arrayMode = getArrayMode();
type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
var isOptional = config.value !== undefined;
var squash = getSquashPolicy(config, isOptional);
var replace = getReplace(config, arrayMode, isOptional, squash);
function unwrapShorthand(config) {
var keys = isObject(config) ? objectKeys(config) : [];
var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
if (isShorthand) config = { value: config };
config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
return config;
}
function getType(config, urlType, location) {
if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
if (urlType) return urlType;
if (!config.type) return (location === "config" ? $types.any : $types.string);
return config.type instanceof Type ? config.type : new Type(config.type);
}
// array config: param name (param[]) overrides default settings. explicit config overrides param name.
function getArrayMode() {
var arrayDefaults = { array: (location === "search" ? "auto" : false) };
var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
return extend(arrayDefaults, arrayParamNomenclature, config).array;
}
/**
* returns false, true, or the squash value to indicate the "default parameter url squash policy".
*/
function getSquashPolicy(config, isOptional) {
var squash = config.squash;
if (!isOptional || squash === false) return false;
if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
if (squash === true || isString(squash)) return squash;
throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
}
function getReplace(config, arrayMode, isOptional, squash) {
var replace, configuredKeys, defaultPolicy = [
{ from: "", to: (isOptional || arrayMode ? undefined : "") },
{ from: null, to: (isOptional || arrayMode ? undefined : "") }
];
replace = isArray(config.replace) ? config.replace : [];
if (isString(squash))
replace.push({ from: squash, to: undefined });
configuredKeys = map(replace, function(item) { return item.from; } );
return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
}
/**
* [Internal] Get the default value of a parameter, which may be an injectable function.
*/
function $$getDefaultValue() {
if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
var defaultValue = injector.invoke(config.$$fn);
if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
return defaultValue;
}
/**
* [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
* default value, which may be the result of an injectable function.
*/
function $value(value) {
function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
function $replace(value) {
var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
return replacement.length ? replacement[0] : value;
}
value = $replace(value);
return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
}
function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
extend(this, {
id: id,
type: type,
location: location,
array: arrayMode,
squash: squash,
replace: replace,
isOptional: isOptional,
value: $value,
dynamic: undefined,
config: config,
toString: toString
});
};
function ParamSet(params) {
extend(this, params || {});
}
ParamSet.prototype = {
$$new: function() {
return inherit(this, extend(new ParamSet(), { $$parent: this}));
},
$$keys: function () {
var keys = [], chain = [], parent = this,
ignore = objectKeys(ParamSet.prototype);
while (parent) { chain.push(parent); parent = parent.$$parent; }
chain.reverse();
forEach(chain, function(paramset) {
forEach(objectKeys(paramset), function(key) {
if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
});
});
return keys;
},
$$values: function(paramValues) {
var values = {}, self = this;
forEach(self.$$keys(), function(key) {
values[key] = self[key].value(paramValues && paramValues[key]);
});
return values;
},
$$equals: function(paramValues1, paramValues2) {
var equal = true, self = this;
forEach(self.$$keys(), function(key) {
var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
if (!self[key].type.equals(left, right)) equal = false;
});
return equal;
},
$$validates: function $$validate(paramValues) {
var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
for (i = 0; i < keys.length; i++) {
param = this[keys[i]];
rawVal = paramValues[keys[i]];
if ((rawVal === undefined || rawVal === null) && param.isOptional)
break; // There was no parameter value, but the param is optional
normalized = param.type.$normalize(rawVal);
if (!param.type.is(normalized))
return false; // The value was not of the correct Type, and could not be decoded to the correct Type
encoded = param.type.encode(normalized);
if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
}
return true;
},
$$parent: undefined
};
this.ParamSet = ParamSet;
}
// Register as a provider so it's available to other providers
angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
/**
* @ngdoc object
* @name ui.router.router.$urlRouterProvider
*
* @requires ui.router.util.$urlMatcherFactoryProvider
* @requires $locationProvider
*
* @description
* `$urlRouterProvider` has the responsibility of watching `$location`.
* When `$location` changes it runs through a list of rules one by one until a
* match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
* a url in a state configuration. All urls are compiled into a UrlMatcher object.
*
* There are several methods on `$urlRouterProvider` that make it useful to use directly
* in your module config.
*/
$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
var rules = [], otherwise = null, interceptDeferred = false, listener;
// Returns a string that is a prefix of all strings matching the RegExp
function regExpPrefix(re) {
var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
}
// Interpolates matched values into a String.replace()-style pattern
function interpolate(pattern, match) {
return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
return match[what === '$' ? 0 : Number(what)];
});
}
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#rule
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Defines rules that are used by `$urlRouterProvider` to find matches for
* specific URLs.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* // Here's an example of how you might allow case insensitive urls
* $urlRouterProvider.rule(function ($injector, $location) {
* var path = $location.path(),
* normalized = path.toLowerCase();
*
* if (path !== normalized) {
* return normalized;
* }
* });
* });
* </pre>
*
* @param {object} rule Handler function that takes `$injector` and `$location`
* services as arguments. You can use them to return a valid path as a string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
this.rule = function (rule) {
if (!isFunction(rule)) throw new Error("'rule' must be a function");
rules.push(rule);
return this;
};
/**
* @ngdoc object
* @name ui.router.router.$urlRouterProvider#otherwise
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Defines a path that is used when an invalid route is requested.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* // if the path doesn't match any of the urls you configured
* // otherwise will take care of routing the user to the
* // specified url
* $urlRouterProvider.otherwise('/index');
*
* // Example of using function rule as param
* $urlRouterProvider.otherwise(function ($injector, $location) {
* return '/a/valid/url';
* });
* });
* </pre>
*
* @param {string|object} rule The url path you want to redirect to or a function
* rule that returns the url path. The function version is passed two params:
* `$injector` and `$location` services, and must return a url string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
this.otherwise = function (rule) {
if (isString(rule)) {
var redirect = rule;
rule = function () { return redirect; };
}
else if (!isFunction(rule)) throw new Error("'rule' must be a function");
otherwise = rule;
return this;
};
function handleIfMatch($injector, handler, match) {
if (!match) return false;
var result = $injector.invoke(handler, handler, { $match: match });
return isDefined(result) ? result : true;
}
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#when
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Registers a handler for a given url matching. if handle is a string, it is
* treated as a redirect, and is interpolated according to the syntax of match
* (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
*
* If the handler is a function, it is injectable. It gets invoked if `$location`
* matches. You have the option of inject the match object as `$match`.
*
* The handler can return
*
* - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
* will continue trying to find another one that matches.
* - **string** which is treated as a redirect and passed to `$location.url()`
* - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* $urlRouterProvider.when($state.url, function ($match, $stateParams) {
* if ($state.$current.navigable !== state ||
* !equalForKeys($match, $stateParams) {
* $state.transitionTo(state, $match, false);
* }
* });
* });
* </pre>
*
* @param {string|object} what The incoming path that you want to redirect.
* @param {string|object} handler The path you want to redirect your user to.
*/
this.when = function (what, handler) {
var redirect, handlerIsString = isString(handler);
if (isString(what)) what = $urlMatcherFactory.compile(what);
if (!handlerIsString && !isFunction(handler) && !isArray(handler))
throw new Error("invalid 'handler' in when()");
var strategies = {
matcher: function (what, handler) {
if (handlerIsString) {
redirect = $urlMatcherFactory.compile(handler);
handler = ['$match', function ($match) { return redirect.format($match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
}, {
prefix: isString(what.prefix) ? what.prefix : ''
});
},
regex: function (what, handler) {
if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
if (handlerIsString) {
redirect = handler;
handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path()));
}, {
prefix: regExpPrefix(what)
});
}
};
var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
for (var n in check) {
if (check[n]) return this.rule(strategies[n](what, handler));
}
throw new Error("invalid 'what' in when()");
};
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#deferIntercept
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Disables (or enables) deferring location change interception.
*
* If you wish to customize the behavior of syncing the URL (for example, if you wish to
* defer a transition but maintain the current URL), call this method at configuration time.
* Then, at run time, call `$urlRouter.listen()` after you have configured your own
* `$locationChangeSuccess` event handler.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
*
* // Prevent $urlRouter from automatically intercepting URL changes;
* // this allows you to configure custom behavior in between
* // location changes and route synchronization:
* $urlRouterProvider.deferIntercept();
*
* }).run(function ($rootScope, $urlRouter, UserService) {
*
* $rootScope.$on('$locationChangeSuccess', function(e) {
* // UserService is an example service for managing user state
* if (UserService.isLoggedIn()) return;
*
* // Prevent $urlRouter's default handler from firing
* e.preventDefault();
*
* UserService.handleLogin().then(function() {
* // Once the user has logged in, sync the current URL
* // to the router:
* $urlRouter.sync();
* });
* });
*
* // Configures $urlRouter's listener *after* your custom listener
* $urlRouter.listen();
* });
* </pre>
*
* @param {boolean} defer Indicates whether to defer location change interception. Passing
no parameter is equivalent to `true`.
*/
this.deferIntercept = function (defer) {
if (defer === undefined) defer = true;
interceptDeferred = defer;
};
/**
* @ngdoc object
* @name ui.router.router.$urlRouter
*
* @requires $location
* @requires $rootScope
* @requires $injector
* @requires $browser
*
* @description
*
*/
this.$get = $get;
$get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
function $get( $location, $rootScope, $injector, $browser) {
var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
function appendBasePath(url, isHtml5, absolute) {
if (baseHref === '/') return url;
if (isHtml5) return baseHref.slice(0, -1) + url;
if (absolute) return baseHref.slice(1) + url;
return url;
}
// TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
function update(evt) {
if (evt && evt.defaultPrevented) return;
var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
lastPushedUrl = undefined;
// TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
//if (ignoreUpdate) return true;
function check(rule) {
var handled = rule($injector, $location);
if (!handled) return false;
if (isString(handled)) $location.replace().url(handled);
return true;
}
var n = rules.length, i;
for (i = 0; i < n; i++) {
if (check(rules[i])) return;
}
// always check otherwise last to allow dynamic updates to the set of rules
if (otherwise) check(otherwise);
}
function listen() {
listener = listener || $rootScope.$on('$locationChangeSuccess', update);
return listener;
}
if (!interceptDeferred) listen();
return {
/**
* @ngdoc function
* @name ui.router.router.$urlRouter#sync
* @methodOf ui.router.router.$urlRouter
*
* @description
* Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
* This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
* perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
* with the transition by calling `$urlRouter.sync()`.
*
* @example
* <pre>
* angular.module('app', ['ui.router'])
* .run(function($rootScope, $urlRouter) {
* $rootScope.$on('$locationChangeSuccess', function(evt) {
* // Halt state change from even starting
* evt.preventDefault();
* // Perform custom logic
* var meetsRequirement = ...
* // Continue with the update and state transition if logic allows
* if (meetsRequirement) $urlRouter.sync();
* });
* });
* </pre>
*/
sync: function() {
update();
},
listen: function() {
return listen();
},
update: function(read) {
if (read) {
location = $location.url();
return;
}
if ($location.url() === location) return;
$location.url(location);
$location.replace();
},
push: function(urlMatcher, params, options) {
var url = urlMatcher.format(params || {});
// Handle the special hash param, if needed
if (url !== null && params && params['#']) {
url += '#' + params['#'];
}
$location.url(url);
lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
if (options && options.replace) $location.replace();
},
/**
* @ngdoc function
* @name ui.router.router.$urlRouter#href
* @methodOf ui.router.router.$urlRouter
*
* @description
* A URL generation method that returns the compiled URL for a given
* {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
*
* @example
* <pre>
* $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
* person: "bob"
* });
* // $bob == "/about/bob";
* </pre>
*
* @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
* @param {object=} params An object of parameter values to fill the matcher's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
*/
href: function(urlMatcher, params, options) {
if (!urlMatcher.validates(params)) return null;
var isHtml5 = $locationProvider.html5Mode();
if (angular.isObject(isHtml5)) {
isHtml5 = isHtml5.enabled;
}
var url = urlMatcher.format(params);
options = options || {};
if (!isHtml5 && url !== null) {
url = "#" + $locationProvider.hashPrefix() + url;
}
// Handle special hash param, if needed
if (url !== null && params && params['#']) {
url += '#' + params['#'];
}
url = appendBasePath(url, isHtml5, options.absolute);
if (!options.absolute || !url) {
return url;
}
var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
port = (port === 80 || port === 443 ? '' : ':' + port);
return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
}
};
}
}
angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
/**
* @ngdoc object
* @name ui.router.state.$stateProvider
*
* @requires ui.router.router.$urlRouterProvider
* @requires ui.router.util.$urlMatcherFactoryProvider
*
* @description
* The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
* on state.
*
* A state corresponds to a "place" in the application in terms of the overall UI and
* navigation. A state describes (via the controller / template / view properties) what
* the UI looks like and does at that place.
*
* States often have things in common, and the primary way of factoring out these
* commonalities in this model is via the state hierarchy, i.e. parent/child states aka
* nested states.
*
* The `$stateProvider` provides interfaces to declare these states for your app.
*/
$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
// Builds state properties from definition passed to registerState()
var stateBuilder = {
// Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
// state.children = [];
// if (parent) parent.children.push(state);
parent: function(state) {
if (isDefined(state.parent) && state.parent) return findState(state.parent);
// regex matches any valid composite state name
// would match "contact.list" but not "contacts"
var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
return compositeName ? findState(compositeName[1]) : root;
},
// inherit 'data' from parent and override by own values (if any)
data: function(state) {
if (state.parent && state.parent.data) {
state.data = state.self.data = extend({}, state.parent.data, state.data);
}
return state.data;
},
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: function(state) {
var url = state.url, config = { params: state.params || {} };
if (isString(url)) {
if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
return (state.parent.navigable || root).url.concat(url, config);
}
if (!url || $urlMatcherFactory.isMatcher(url)) return url;
throw new Error("Invalid url '" + url + "' in state '" + state + "'");
},
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: function(state) {
return state.url ? state : (state.parent ? state.parent.navigable : null);
},
// Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
ownParams: function(state) {
var params = state.url && state.url.params || new $$UMFP.ParamSet();
forEach(state.params || {}, function(config, id) {
if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
});
return params;
},
// Derive parameters for this state and ensure they're a super-set of parent's parameters
params: function(state) {
return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
},
// If there is no explicit multi-view configuration, make one up so we don't have
// to handle both cases in the view directive later. Note that having an explicit
// 'views' property will mean the default unnamed view properties are ignored. This
// is also a good time to resolve view names to absolute names, so everything is a
// straight lookup at link time.
views: function(state) {
var views = {};
forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
if (name.indexOf('@') < 0) name += '@' + state.parent.name;
views[name] = view;
});
return views;
},
// Keep a full path from the root down to this state as this is needed for state activation.
path: function(state) {
return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
},
// Speed up $state.contains() as it's used a lot
includes: function(state) {
var includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
},
$delegates: {}
};
function isRelative(stateName) {
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
}
function findState(stateOrName, base) {
if (!stateOrName) return undefined;
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
base = findState(base);
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function queueState(parentName, state) {
if (!queue[parentName]) {
queue[parentName] = [];
}
queue[parentName].push(state);
}
function flushQueuedChildren(parentName) {
var queued = queue[parentName] || [];
while(queued.length) {
registerState(queued.shift());
}
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
// Get parent name
var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
: (isString(state.parent)) ? state.parent
: (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
: '';
// If parent is not registered yet, add state to queue and register later
if (parentName && !states[parentName]) {
return queueState(parentName, state.self);
}
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, { inherit: true, location: false });
}
}]);
}
// Register any queued children
flushQueuedChildren(name);
return state;
}
// Checks text to see if it looks like a glob.
function isGlob (text) {
return text.indexOf('*') > -1;
}
// Returns true if glob matches current $state name.
function doesStateMatchGlob (glob) {
var globSegments = glob.split('.'),
segments = $state.$current.name.split('.');
//match single stars
for (var i = 0, l = globSegments.length; i < l; i++) {
if (globSegments[i] === '*') {
segments[i] = '*';
}
}
//match greedy starts
if (globSegments[0] === '**') {
segments = segments.slice(indexOf(segments, globSegments[1]));
segments.unshift('**');
}
//match greedy ends
if (globSegments[globSegments.length - 1] === '**') {
segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
segments.push('**');
}
if (globSegments.length != segments.length) {
return false;
}
return segments.join('') === globSegments.join('');
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#decorator
* @methodOf ui.router.state.$stateProvider
*
* @description
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by `$stateProvider`. This can be used
* to add custom functionality to ui-router, for example inferring templateUrl
* based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* @example
* <pre>
* // Override the internal 'views' builder with a function that takes the state
* // definition, and a reference to the internal function being overridden:
* $stateProvider.decorator('views', function (state, parent) {
* var result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* var autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
*
* // ...
*
* $state.go('home');
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* </pre>
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
this.decorator = decorator;
function decorator(name, func) {
/*jshint validthis: true */
if (isString(name) && !isDefined(func)) {
return stateBuilder[name];
}
if (!isFunction(func) || !isString(name)) {
return this;
}
if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
stateBuilder.$delegates[name] = stateBuilder[name];
}
stateBuilder[name] = func;
return this;
}
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#state
* @methodOf ui.router.state.$stateProvider
*
* @description
* Registers a state configuration under a given state name. The stateConfig object
* has the following acceptable properties.
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} stateConfig State configuration object.
* @param {string|function=} stateConfig.template
* <a id='template'></a>
* html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <pre>template:
* "<h1>inline template definition</h1>" +
* "<div ui-view></div>"</pre>
* <pre>template: function(params) {
* return "<h1>generated template</h1>"; }</pre>
* </div>
*
* @param {string|function=} stateConfig.templateUrl
* <a id='templateUrl'></a>
*
* path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <pre>templateUrl: "home.html"</pre>
* <pre>templateUrl: function(params) {
* return myTemplates[params.pageId]; }</pre>
*
* @param {function=} stateConfig.templateProvider
* <a id='templateProvider'></a>
* Provider function that returns HTML content string.
* <pre> templateProvider:
* function(MyTemplateService, params) {
* return MyTemplateService.getTemplate(params.pageId);
* }</pre>
*
* @param {string|function=} stateConfig.controller
* <a id='controller'></a>
*
* Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
* Optionally, the ControllerAs may be declared here.
* <pre>controller: "MyRegisteredController"</pre>
* <pre>controller:
* "MyRegisteredController as fooCtrl"}</pre>
* <pre>controller: function($scope, MyService) {
* $scope.data = MyService.getData(); }</pre>
*
* @param {function=} stateConfig.controllerProvider
* <a id='controllerProvider'></a>
*
* Injectable provider function that returns the actual controller or string.
* <pre>controllerProvider:
* function(MyResolveData) {
* if (MyResolveData.foo)
* return "FooCtrl"
* else if (MyResolveData.bar)
* return "BarCtrl";
* else return function($scope) {
* $scope.baz = "Qux";
* }
* }</pre>
*
* @param {string=} stateConfig.controllerAs
* <a id='controllerAs'></a>
*
* A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
* <pre>controllerAs: "myCtrl"</pre>
*
* @param {string|object=} stateConfig.parent
* <a id='parent'></a>
* Optionally specifies the parent state of this state.
*
* <pre>parent: 'parentState'</pre>
* <pre>parent: parentState // JS variable</pre>
*
* @param {object=} stateConfig.resolve
* <a id='resolve'></a>
*
* An optional map<string, function> of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved before the controller is instantiated.
* If all the promises are resolved successfully, the $stateChangeSuccess event is fired
* and the values of the resolved promises are injected into any controllers that reference them.
* If any of the promises are rejected the $stateChangeError event is fired.
*
* The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <pre>resolve: {
* myResolve1:
* function($http, $stateParams) {
* return $http.get("/api/foos/"+stateParams.fooID);
* }
* }</pre>
*
* @param {string=} stateConfig.url
* <a id='url'></a>
*
* A url fragment with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
* more details on acceptable patterns )
*
* examples:
* <pre>url: "/home"
* url: "/users/:userid"
* url: "/books/{bookid:[a-zA-Z_-]}"
* url: "/books/{categoryid:int}"
* url: "/books/{publishername:string}/{categoryid:int}"
* url: "/messages?before&after"
* url: "/messages?{before:date}&{after:date}"
* url: "/messages/:mailboxid?{before:date}&{after:date}"
* </pre>
*
* @param {object=} stateConfig.views
* <a id='views'></a>
* an optional map<string, object> which defined multiple views, or targets views
* manually/explicitly.
*
* Examples:
*
* Targets three named `ui-view`s in the parent state's template
* <pre>views: {
* header: {
* controller: "headerCtrl",
* templateUrl: "header.html"
* }, body: {
* controller: "bodyCtrl",
* templateUrl: "body.html"
* }, footer: {
* controller: "footCtrl",
* templateUrl: "footer.html"
* }
* }</pre>
*
* Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
* <pre>views: {
* 'header@top': {
* controller: "msgHeaderCtrl",
* templateUrl: "msgHeader.html"
* }, 'body': {
* controller: "messagesCtrl",
* templateUrl: "messages.html"
* }
* }</pre>
*
* @param {boolean=} [stateConfig.abstract=false]
* <a id='abstract'></a>
* An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
* <pre>abstract: true</pre>
*
* @param {function=} stateConfig.onEnter
* <a id='onEnter'></a>
*
* Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function,
* because it won't be automatically annotated by your build tools.
*
* <pre>onEnter: function(MyService, $stateParams) {
* MyService.foo($stateParams.myParam);
* }</pre>
*
* @param {function=} stateConfig.onExit
* <a id='onExit'></a>
*
* Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function,
* because it won't be automatically annotated by your build tools.
*
* <pre>onExit: function(MyService, $stateParams) {
* MyService.cleanup($stateParams.myParam);
* }</pre>
*
* @param {boolean=} [stateConfig.reloadOnSearch=true]
* <a id='reloadOnSearch'></a>
*
* If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
* <pre>reloadOnSearch: false</pre>
*
* @param {object=} stateConfig.data
* <a id='data'></a>
*
* Arbitrary data object, useful for custom configuration. The parent state's `data` is
* prototypally inherited. In other words, adding a data property to a state adds it to
* the entire subtree via prototypal inheritance.
*
* <pre>data: {
* requiredRole: 'foo'
* } </pre>
*
* @param {object=} stateConfig.params
* <a id='params'></a>
*
* A map which optionally configures parameters declared in the `url`, or
* defines additional non-url parameters. For each parameter being
* configured, add a configuration object keyed to the name of the parameter.
*
* Each parameter configuration object may contain the following properties:
*
* - ** value ** - {object|function=}: specifies the default value for this
* parameter. This implicitly sets this parameter as optional.
*
* When UI-Router routes to a state and no value is
* specified for this parameter in the URL or transition, the
* default value will be used instead. If `value` is a function,
* it will be injected and invoked, and the return value used.
*
* *Note*: `undefined` is treated as "no default value" while `null`
* is treated as "the default value is `null`".
*
* *Shorthand*: If you only need to configure the default value of the
* parameter, you may use a shorthand syntax. In the **`params`**
* map, instead mapping the param name to a full parameter configuration
* object, simply set map it to the default parameter value, e.g.:
*
* <pre>// define a parameter's default value
* params: {
* param1: { value: "defaultValue" }
* }
* // shorthand default values
* params: {
* param1: "defaultValue",
* param2: "param2Default"
* }</pre>
*
* - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
* treated as an array of values. If you specified a Type, the value will be
* treated as an array of the specified Type. Note: query parameter values
* default to a special `"auto"` mode.
*
* For query parameters in `"auto"` mode, if multiple values for a single parameter
* are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
* are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
* only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
* value (e.g.: `{ foo: '1' }`).
*
* <pre>params: {
* param1: { array: true }
* }</pre>
*
* - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
* the current parameter value is the same as the default value. If `squash` is not set, it uses the
* configured default squash policy.
* (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
*
* There are three squash settings:
*
* - false: The parameter's default value is not squashed. It is encoded and included in the URL
* - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
* by slashes in the state's `url` declaration, then one of those slashes are omitted.
* This can allow for cleaner looking URLs.
* - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
*
* <pre>params: {
* param1: {
* value: "defaultId",
* squash: true
* } }
* // squash "defaultValue" to "~"
* params: {
* param1: {
* value: "defaultValue",
* squash: "~"
* } }
* </pre>
*
*
* @example
* <pre>
* // Some state name examples
*
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* </pre>
*
*/
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
/**
* @ngdoc object
* @name ui.router.state.$state
*
* @requires $rootScope
* @requires $q
* @requires ui.router.state.$view
* @requires $injector
* @requires ui.router.util.$resolve
* @requires ui.router.state.$stateParams
* @requires ui.router.router.$urlRouter
*
* @property {object} params A param object, e.g. {sectionId: section.id)}, that
* you'd like to test against the current active state.
* @property {object} current A reference to the state's config object. However
* you passed it in. Useful for accessing custom data.
* @property {object} transition Currently pending transition. A promise that'll
* resolve or reject.
*
* @description
* `$state` service is responsible for representing states as well as transitioning
* between them. It also provides interfaces to ask for current state or even states
* you're coming from.
*/
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
var TransitionSuperseded = $q.reject(new Error('transition superseded'));
var TransitionPrevented = $q.reject(new Error('transition prevented'));
var TransitionAborted = $q.reject(new Error('transition aborted'));
var TransitionFailed = $q.reject(new Error('transition failed'));
// Handles the case where a state which is the target of a transition is not found, and the user
// can optionally retry or defer the transition
function handleRedirect(redirect, state, params, options) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateNotFound
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when a requested state **cannot be found** using the provided state name during transition.
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
* you can see its three properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
*
* @param {Object} event Event object.
* @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
* @param {State} fromState Current state object.
* @param {Object} fromParams Current state params.
*
* @example
*
* <pre>
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", {a:1, b:2}, {inherit:false});
*
* // somewhere else
* $scope.$on('$stateNotFound',
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* })
* </pre>
*/
var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
if (evt.defaultPrevented) {
$urlRouter.update();
return TransitionAborted;
}
if (!evt.retry) {
return null;
}
// Allow the handler to return a promise to defer state lookup retry
if (options.$retry) {
$urlRouter.update();
return TransitionFailed;
}
var retryTransition = $state.transition = $q.when(evt.retry);
retryTransition.then(function() {
if (retryTransition !== $state.transition) return TransitionSuperseded;
redirect.options.$retry = true;
return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
}, function() {
return TransitionAborted;
});
$urlRouter.update();
return retryTransition;
}
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* A method that force reloads the current state. All resolves are re-resolved,
* controllers reinstantiated, and events re-fired.
*
* @example
* <pre>
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* $state.reload();
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: true
* });
* </pre>
*
* @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
* @example
* <pre>
* //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
* //and current state is 'contacts.detail.item'
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* //will reload 'contact.detail' and 'contact.detail.item' states
* $state.reload('contact.detail');
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: true
* });
* </pre>
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.reload = function reload(state) {
return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
};
/**
* @ngdoc function
* @name ui.router.state.$state#go
* @methodOf ui.router.state.$state
*
* @description
* Convenience method for transitioning to a new state. `$state.go` calls
* `$state.transitionTo` internally but automatically sets options to
* `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
* This allows you to easily use an absolute or relative to path and specify
* only the parameters you'd like to update (while letting unspecified parameters
* inherit from the currently active ancestor states).
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
* <img src='../ngdoc_assets/StateGoExamples.png'/>
*
* @param {string} to Absolute state name or relative state path. Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
* transitioning to a sibling will get you the parameters for all parents, transitioning to a child
* will get you all current parameters, etc.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition.
*
* Possible success values:
*
* - $state.current
*
* <br/>Possible rejection values:
*
* - 'transition superseded' - when a newer transition has been started after this one
* - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
* - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
* when a `$stateNotFound` `event.retry` promise errors.
* - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
* - *resolve error* - when an error has occurred with a `resolve`
*
*/
$state.go = function go(to, params, options) {
return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string} to State name.
* @param {object=} toParams A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
* if String, then will reload the state with the name given in reload, and any children.
* if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.transitionTo = function transitionTo(to, toParams, options) {
toParams = toParams || {};
options = extend({
location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
}, options || {});
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var evt, toState = findState(to, options.relative);
// Store the hash param for later (since it will be stripped out by various methods)
var hash = toParams['#'];
if (!isDefined(toState)) {
var redirect = { to: to, toParams: toParams, options: options };
var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
if (redirectResult) {
return redirectResult;
}
// Always retry once if the $stateNotFound was not prevented
// (handles either redirect changed or state lazy-definition)
to = redirect.to;
toParams = redirect.toParams;
options = redirect.options;
toState = findState(to, options.relative);
if (!isDefined(toState)) {
if (!options.relative) throw new Error("No such state '" + to + "'");
throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
}
}
if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
if (!toState.params.$$validates(toParams)) return TransitionFailed;
toParams = toState.params.$$values(toParams);
to = toState;
var toPath = to.path;
// Starting from the root of the path, keep all levels that haven't changed
var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
if (!options.reload) {
while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
} else if (isString(options.reload) || isObject(options.reload)) {
if (isObject(options.reload) && !options.reload.name) {
throw new Error('Invalid reload state object');
}
var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
if (options.reload && !reloadState) {
throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
}
while (state && state === fromPath[keep] && state !== reloadState) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
}
// If we're going to the same state and all locals are kept, we've got nothing to do.
// But clear 'transition', as we still want to cancel any other pending transitions.
// TODO: We may not want to bump 'transition' if we're called from a location change
// that we've initiated ourselves, because we might accidentally abort a legitimate
// transition initiated from code?
if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
if (hash) toParams['#'] = hash;
$state.params = toParams;
copy($state.params, $stateParams);
if (options.location && to.navigable && to.navigable.url) {
$urlRouter.push(to.navigable.url, toParams, {
$$avoidResync: true, replace: options.location === 'replace'
});
$urlRouter.update(true);
}
$state.transition = null;
return $q.when($state.current);
}
// Filter parameters before we pass them to event handlers etc.
toParams = filterByKeys(to.params.$$keys(), toParams || {});
// Broadcast start event and cancel the transition if requested
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeStart
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when the state transition **begins**. You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*
* @example
*
* <pre>
* $rootScope.$on('$stateChangeStart',
* function(event, toState, toParams, fromState, fromParams){
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* </pre>
*/
if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
$rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
$urlRouter.update();
return TransitionPrevented;
}
}
// Resolve locals for the remaining states, but don't update any global state just
// yet -- if anything fails to resolve the current state needs to remain untouched.
// We also set up an inheritance chain for the locals here. This allows the view directive
// to quickly look up the correct definition for each view in the current state. Even
// though we create the locals object itself outside resolveState(), it is initially
// empty and gets filled asynchronously. We need to keep track of the promise for the
// (fully resolved) current locals, and pass this down the chain.
var resolved = $q.when(locals);
for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
locals = toLocals[l] = inherit(locals);
resolved = resolveState(state, toParams, state === to, resolved, locals, options);
}
// Once everything is resolved, we are ready to perform the actual transition
// and return a promise for the new state. We also keep track of what the
// current promise is, so that we can detect overlapping transitions and
// keep only the outcome of the last transition.
var transition = $state.transition = resolved.then(function () {
var l, entering, exiting;
if ($state.transition !== transition) return TransitionSuperseded;
// Exit 'from' states not kept
for (l = fromPath.length - 1; l >= keep; l--) {
exiting = fromPath[l];
if (exiting.self.onExit) {
$injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
}
exiting.locals = null;
}
// Enter 'to' states not kept
for (l = keep; l < toPath.length; l++) {
entering = toPath[l];
entering.locals = toLocals[l];
if (entering.self.onEnter) {
$injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
}
}
// Re-add the saved hash before we start returning things
if (hash) toParams['#'] = hash;
// Run it again, to catch any transitions in callbacks
if ($state.transition !== transition) return TransitionSuperseded;
// Update globals in $state
$state.$current = to;
$state.current = to.self;
$state.params = toParams;
copy($state.params, $stateParams);
$state.transition = null;
if (options.location && to.navigable) {
$urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
$$avoidResync: true, replace: options.location === 'replace'
});
}
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeSuccess
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired once the state transition is **complete**.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*/
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
}
$urlRouter.update(true);
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeError
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when an **error occurs** during transition. It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
* @param {Error} error The resolve error object.
*/
evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
return $q.reject(error);
});
return transition;
};
/**
* @ngdoc function
* @name ui.router.state.$state#is
* @methodOf ui.router.state.$state
*
* @description
* Similar to {@link ui.router.state.$state#methods_includes $state.includes},
* but only checks for the full state name. If params is supplied then it will be
* tested for strict equality against the current active params object, so all params
* must match with none missing and no extras.
*
* @example
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // absolute name
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // relative name (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.is('.item')}">Item</div>
* </pre>
*
* @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
* test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it is the state.
*/
$state.is = function is(stateOrName, params, options) {
options = extend({ relative: $state.$current }, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) { return undefined; }
if ($state.$current !== state) { return false; }
return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#includes
* @methodOf ui.router.state.$state
*
* @description
* A method to determine if the current active state is equal to or is the child of the
* state stateName. If any params are passed then they will be tested for a match as well.
* Not all the parameters need to be passed, just the ones you'd like to test for equality.
*
* @example
* Partial and relative names
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // Using partial names
* $state.includes("contacts"); // returns true
* $state.includes("contacts.details"); // returns true
* $state.includes("contacts.details.item"); // returns true
* $state.includes("contacts.list"); // returns false
* $state.includes("about"); // returns false
*
* // Using relative names (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
* </pre>
*
* Basic globbing patterns
* <pre>
* $state.$current.name = 'contacts.details.item.url';
*
* $state.includes("*.details.*.*"); // returns true
* $state.includes("*.details.**"); // returns true
* $state.includes("**.item.**"); // returns true
* $state.includes("*.details.item.url"); // returns true
* $state.includes("*.details.*.url"); // returns true
* $state.includes("*.details.*"); // returns false
* $state.includes("item.**"); // returns false
* </pre>
*
* @param {string} stateOrName A partial name, relative name, or glob pattern
* to be searched for within the current state name.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`,
* that you'd like to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
* .includes will test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it does include the state
*/
$state.includes = function includes(stateOrName, params, options) {
options = extend({ relative: $state.$current }, options || {});
if (isString(stateOrName) && isGlob(stateOrName)) {
if (!doesStateMatchGlob(stateOrName)) {
return false;
}
stateOrName = $state.$current.name;
}
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) { return undefined; }
if (!isDefined($state.$current.includes[state.name])) { return false; }
return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#href
* @methodOf ui.router.state.$state
*
* @description
* A url generation method that returns the compiled url for the given state populated with the given params.
*
* @example
* <pre>
* expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
* </pre>
*
* @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
* @param {object=} params An object of parameter values to fill the state's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
* first parameter, then the constructed href url will be built from the first navigable ancestor (aka
* ancestor with a valid url).
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} compiled state url
*/
$state.href = function href(stateOrName, params, options) {
options = extend({
lossy: true,
inherit: true,
absolute: false,
relative: $state.$current
}, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) return null;
if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
var nav = (state && options.lossy) ? state.navigable : state;
if (!nav || nav.url === undefined || nav.url === null) {
return null;
}
return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
absolute: options.absolute
});
};
/**
* @ngdoc function
* @name ui.router.state.$state#get
* @methodOf ui.router.state.$state
*
* @description
* Returns the state configuration object for any specific state or all states.
*
* @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
* the requested state. If not provided, returns an array of ALL state configs.
* @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
* @returns {Object|Array} State configuration object or array of all objects.
*/
$state.get = function (stateOrName, context) {
if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
var state = findState(stateOrName, context || $state.$current);
return (state && state.self) ? state.self : null;
};
function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
// Make a restricted $stateParams with only the parameters that apply to this state if
// necessary. In addition to being available to the controller and onEnter/onExit callbacks,
// we also need $stateParams to be available for any $injector calls we make during the
// dependency resolution process.
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [dst.resolve.then(function (globals) {
dst.globals = globals;
})];
if (inherited) promises.push(inherited);
function resolveViews() {
var viewsPromises = [];
// Resolve template and dependencies for all views.
forEach(state.views, function (view, name) {
var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
injectables.$template = [ function () {
return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
}];
viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
// References to the controller (only instantiated at link time)
if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
var injectLocals = angular.extend({}, injectables, dst.globals);
result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
} else {
result.$$controller = view.controller;
}
// Provide access to the state itself for internal use
result.$$state = state;
result.$$controllerAs = view.controllerAs;
dst[name] = result;
}));
});
return $q.all(viewsPromises).then(function(){
return dst.globals;
});
}
// Wait for all the promises and then return the activation object
return $q.all(promises).then(resolveViews).then(function (values) {
return dst;
});
}
return $state;
}
function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
// Return true if there are no differences in non-search (path/object) params, false if there are differences
function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
// Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
function notSearchParam(key) {
return fromAndToState.params[key].location != "search";
}
var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
return nonQueryParamSet.$$equals(fromParams, toParams);
}
// If reload was not explicitly requested
// and we're transitioning to the same state we're already in
// and the locals didn't change
// or they changed in a way that doesn't merit reloading
// (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
// Then return true.
if (!options.reload && to === from &&
(locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
return true;
}
}
}
angular.module('ui.router.state')
.value('$stateParams', {})
.provider('$state', $StateProvider);
$ViewProvider.$inject = [];
function $ViewProvider() {
this.$get = $get;
/**
* @ngdoc object
* @name ui.router.state.$view
*
* @requires ui.router.util.$templateFactory
* @requires $rootScope
*
* @description
*
*/
$get.$inject = ['$rootScope', '$templateFactory'];
function $get( $rootScope, $templateFactory) {
return {
// $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
/**
* @ngdoc function
* @name ui.router.state.$view#load
* @methodOf ui.router.state.$view
*
* @description
*
* @param {string} name name
* @param {object} options option object.
*/
load: function load(name, options) {
var result, defaults = {
template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
};
options = extend(defaults, options);
if (options.view) {
result = $templateFactory.fromConfig(options.view, options.params, options.locals);
}
if (result && options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$viewContentLoading
* @eventOf ui.router.state.$view
* @eventType broadcast on root scope
* @description
*
* Fired once the view **begins loading**, *before* the DOM is rendered.
*
* @param {Object} event Event object.
* @param {Object} viewConfig The view config properties (template, controller, etc).
*
* @example
*
* <pre>
* $scope.$on('$viewContentLoading',
* function(event, viewConfig){
* // Access to all the view config properties.
* // and one special property 'targetView'
* // viewConfig.targetView
* });
* </pre>
*/
$rootScope.$broadcast('$viewContentLoading', options);
}
return result;
}
};
}
}
angular.module('ui.router.state').provider('$view', $ViewProvider);
/**
* @ngdoc object
* @name ui.router.state.$uiViewScrollProvider
*
* @description
* Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
*/
function $ViewScrollProvider() {
var useAnchorScroll = false;
/**
* @ngdoc function
* @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
* @methodOf ui.router.state.$uiViewScrollProvider
*
* @description
* Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
* scrolling based on the url anchor.
*/
this.useAnchorScroll = function () {
useAnchorScroll = true;
};
/**
* @ngdoc object
* @name ui.router.state.$uiViewScroll
*
* @requires $anchorScroll
* @requires $timeout
*
* @description
* When called with a jqLite element, it scrolls the element into view (after a
* `$timeout` so the DOM has time to refresh).
*
* If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
* this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
*/
this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
if (useAnchorScroll) {
return $anchorScroll;
}
return function ($element) {
return $timeout(function () {
$element[0].scrollIntoView();
}, 0, false);
};
}];
}
angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-view
*
* @requires ui.router.state.$state
* @requires $compile
* @requires $controller
* @requires $injector
* @requires ui.router.state.$uiViewScroll
* @requires $document
*
* @restrict ECA
*
* @description
* The ui-view directive tells $state where to place your templates.
*
* @param {string=} name A view name. The name should be unique amongst the other views in the
* same state. You can have views of the same name that live in different states.
*
* @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
* when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
* service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
* scroll ui-view elements into view when they are populated during a state activation.
*
* *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
* functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
*
* @param {string=} onload Expression to evaluate whenever the view updates.
*
* @example
* A view can be unnamed or named.
* <pre>
* <!-- Unnamed -->
* <div ui-view></div>
*
* <!-- Named -->
* <div ui-view="viewName"></div>
* </pre>
*
* You can only have one unnamed view within any template (or root html). If you are only using a
* single view and it is unnamed then you can populate it like so:
* <pre>
* <div ui-view></div>
* $stateProvider.state("home", {
* template: "<h1>HELLO!</h1>"
* })
* </pre>
*
* The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
* config property, by name, in this case an empty name:
* <pre>
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* </pre>
*
* But typically you'll only use the views property if you name your view or have more than one view
* in the same template. There's not really a compelling reason to name a view if its the only one,
* but you could if you wanted, like so:
* <pre>
* <div ui-view="main"></div>
* </pre>
* <pre>
* $stateProvider.state("home", {
* views: {
* "main": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* </pre>
*
* Really though, you'll use views to set up multiple views:
* <pre>
* <div ui-view></div>
* <div ui-view="chart"></div>
* <div ui-view="data"></div>
* </pre>
*
* <pre>
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* },
* "chart": {
* template: "<chart_thing/>"
* },
* "data": {
* template: "<data_thing/>"
* }
* }
* })
* </pre>
*
* Examples for `autoscroll`:
*
* <pre>
* <!-- If autoscroll present with no expression,
* then scroll ui-view into view -->
* <ui-view autoscroll/>
*
* <!-- If autoscroll present with valid expression,
* then scroll ui-view into view if expression evaluates to true -->
* <ui-view autoscroll='true'/>
* <ui-view autoscroll='false'/>
* <ui-view autoscroll='scopeVariable'/>
* </pre>
*/
$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
function getService() {
return ($injector.has) ? function(service) {
return $injector.has(service) ? $injector.get(service) : null;
} : function(service) {
try {
return $injector.get(service);
} catch (e) {
return null;
}
};
}
var service = getService(),
$animator = service('$animator'),
$animate = service('$animate');
// Returns a set of DOM manipulation functions based on which Angular version
// it should use
function getRenderer(attrs, scope) {
var statics = function() {
return {
enter: function (element, target, cb) { target.after(element); cb(); },
leave: function (element, cb) { element.remove(); cb(); }
};
};
if ($animate) {
return {
enter: function(element, target, cb) {
var promise = $animate.enter(element, null, target, cb);
if (promise && promise.then) promise.then(cb);
},
leave: function(element, cb) {
var promise = $animate.leave(element, cb);
if (promise && promise.then) promise.then(cb);
}
};
}
if ($animator) {
var animate = $animator && $animator(scope, attrs);
return {
enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
leave: function(element, cb) { animate.leave(element); cb(); }
};
}
return statics();
}
var directive = {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
compile: function (tElement, tAttrs, $transclude) {
return function (scope, $element, attrs) {
var previousEl, currentEl, currentScope, latestLocals,
onloadExp = attrs.onload || '',
autoScrollExp = attrs.autoscroll,
renderer = getRenderer(attrs, scope);
scope.$on('$stateChangeSuccess', function() {
updateView(false);
});
scope.$on('$viewContentLoading', function() {
updateView(false);
});
updateView(true);
function cleanupLastView() {
if (previousEl) {
previousEl.remove();
previousEl = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentEl) {
renderer.leave(currentEl, function() {
previousEl = null;
});
previousEl = currentEl;
currentEl = null;
}
}
function updateView(firstTime) {
var newScope,
name = getUiViewName(scope, attrs, $element, $interpolate),
previousLocals = name && $state.$current && $state.$current.locals[name];
if (!firstTime && previousLocals === latestLocals) return; // nothing to do
newScope = scope.$new();
latestLocals = $state.$current.locals[name];
var clone = $transclude(newScope, function(clone) {
renderer.enter(clone, $element, function onUiViewEnter() {
if(currentScope) {
currentScope.$emit('$viewContentAnimationEnded');
}
if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
$uiViewScroll(clone);
}
});
cleanupLastView();
});
currentEl = clone;
currentScope = newScope;
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoaded
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description *
* Fired once the view is **loaded**, *after* the DOM is rendered.
*
* @param {Object} event Event object.
*/
currentScope.$emit('$viewContentLoaded');
currentScope.$eval(onloadExp);
}
};
}
};
return directive;
}
$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
return {
restrict: 'ECA',
priority: -400,
compile: function (tElement) {
var initial = tElement.html();
return function (scope, $element, attrs) {
var current = $state.$current,
name = getUiViewName(scope, attrs, $element, $interpolate),
locals = current && current.locals[name];
if (! locals) {
return;
}
$element.data('$uiView', { name: name, state: locals.$$state });
$element.html(locals.$template ? locals.$template : initial);
var link = $compile($element.contents());
if (locals.$$controller) {
locals.$scope = scope;
locals.$element = $element;
var controller = $controller(locals.$$controller, locals);
if (locals.$$controllerAs) {
scope[locals.$$controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
link(scope);
};
}
};
}
/**
* Shared ui-view code for both directives:
* Given scope, element, and its attributes, return the view's name
*/
function getUiViewName(scope, attrs, element, $interpolate) {
var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
var inherited = element.inheritedData('$uiView');
return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
}
angular.module('ui.router.state').directive('uiView', $ViewDirective);
angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
function parseStateRef(ref, current) {
var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
if (preparsed) ref = current + '(' + preparsed[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1], paramExpr: parsed[3] || null };
}
function stateContext(el) {
var stateData = el.parent().inheritedData('$uiView');
if (stateData && stateData.state && stateData.state.name) {
return stateData.state;
}
}
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref
*
* @requires ui.router.state.$state
* @requires $timeout
*
* @restrict A
*
* @description
* A directive that binds a link (`<a>` tag) to a state. If the state has an associated
* URL, the directive will automatically generate & update the `href` attribute via
* the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
* the link will trigger a state transition with optional parameters.
*
* Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
* handled natively by the browser.
*
* You can also use relative state paths within ui-sref, just like the relative
* paths passed to `$state.go()`. You just need to be aware that the path is relative
* to the state that the link lives in, in other words the state that loaded the
* template containing the link.
*
* You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
* using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
* and `reload`.
*
* @example
* Here's an example of how you'd use ui-sref and how it would compile. If you have the
* following template:
* <pre>
* <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
* </li>
* </ul>
* </pre>
*
* Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
* <pre>
* <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
* </li>
* </ul>
*
* <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
* </pre>
*
* @param {string} ui-sref 'stateName' can be any valid absolute or relative state
* @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
*/
$StateRefDirective.$inject = ['$state', '$timeout'];
function $StateRefDirective($state, $timeout) {
var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function(scope, element, attrs, uiSrefActive) {
var ref = parseStateRef(attrs.uiSref, $state.current.name);
var params = null, url = null, base = stateContext(element) || $state.$current;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
var newHref = null, isAnchor = element.prop("tagName").toUpperCase() === "A";
var isForm = element[0].nodeName === "FORM";
var attr = isForm ? "action" : hrefKind, nav = true;
var options = { relative: base, inherit: true };
var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
angular.forEach(allowedOptions, function(option) {
if (option in optionsOverride) {
options[option] = optionsOverride[option];
}
});
var update = function(newVal) {
if (newVal) params = angular.copy(newVal);
if (!nav) return;
newHref = $state.href(ref.state, params, options);
var activeDirective = uiSrefActive[1] || uiSrefActive[0];
if (activeDirective) {
activeDirective.$$addStateInfo(ref.state, params);
}
if (newHref === null) {
nav = false;
return false;
}
attrs.$set(attr, newHref);
};
if (ref.paramExpr) {
scope.$watch(ref.paramExpr, function(newVal, oldVal) {
if (newVal !== params) update(newVal);
}, true);
params = angular.copy(scope.$eval(ref.paramExpr));
}
update();
if (isForm) return;
element.bind("click", function(e) {
var button = e.which || e.button;
if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
var transition = $timeout(function() {
$state.go(ref.state, params, options);
});
e.preventDefault();
// if the state has no URL, ignore one preventDefault from the <a> directive.
var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
e.preventDefault = function() {
if (ignorePreventDefaultCount-- <= 0)
$timeout.cancel(transition);
};
}
});
}
};
}
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref-active
*
* @requires ui.router.state.$state
* @requires ui.router.state.$stateParams
* @requires $interpolate
*
* @restrict A
*
* @description
* A directive working alongside ui-sref to add classes to an element when the
* related ui-sref directive's state is active, and removing them when it is inactive.
* The primary use-case is to simplify the special appearance of navigation menus
* relying on `ui-sref`, by having the "active" state's menu button appear different,
* distinguishing it from the inactive menu items.
*
* ui-sref-active can live on the same element as ui-sref or on a parent element. The first
* ui-sref-active found at the same level or above the ui-sref will be used.
*
* Will activate when the ui-sref's target state or any child state is active. If you
* need to activate only when the ui-sref target state is active and *not* any of
* it's children, then you will use
* {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
*
* @example
* Given the following template:
* <pre>
* <ul>
* <li ui-sref-active="active" class="item">
* <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
* </li>
* </ul>
* </pre>
*
*
* When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
* the resulting HTML will appear as (note the 'active' class):
* <pre>
* <ul>
* <li ui-sref-active="active" class="item active">
* <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
* </li>
* </ul>
* </pre>
*
* The class name is interpolated **once** during the directives link time (any further changes to the
* interpolated value are ignored).
*
* Multiple classes may be specified in a space-separated format:
* <pre>
* <ul>
* <li ui-sref-active='class1 class2 class3'>
* <a ui-sref="app.user">link</a>
* </li>
* </ul>
* </pre>
*/
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref-active-eq
*
* @requires ui.router.state.$state
* @requires ui.router.state.$stateParams
* @requires $interpolate
*
* @restrict A
*
* @description
* The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
* when the exact target state used in the `ui-sref` is active; no child states.
*
*/
$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
function $StateRefActiveDirective($state, $stateParams, $interpolate) {
return {
restrict: "A",
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
var states = [], activeClass;
// There probably isn't much point in $observing this
// uiSrefActive and uiSrefActiveEq share the same directive object with some
// slight difference in logic routing
activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
// Allow uiSref to communicate with uiSrefActive[Equals]
this.$$addStateInfo = function (newState, newParams) {
var state = $state.get(newState, stateContext($element));
states.push({
state: state || { name: newState },
params: newParams
});
update();
};
$scope.$on('$stateChangeSuccess', update);
// Update route state
function update() {
if (anyMatch()) {
$element.addClass(activeClass);
} else {
$element.removeClass(activeClass);
}
}
function anyMatch() {
for (var i = 0; i < states.length; i++) {
if (isMatch(states[i].state, states[i].params)) {
return true;
}
}
return false;
}
function isMatch(state, params) {
if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
return $state.is(state.name, params);
} else {
return $state.includes(state.name, params);
}
}
}]
};
}
angular.module('ui.router.state')
.directive('uiSref', $StateRefDirective)
.directive('uiSrefActive', $StateRefActiveDirective)
.directive('uiSrefActiveEq', $StateRefActiveDirective);
/**
* @ngdoc filter
* @name ui.router.state.filter:isState
*
* @requires ui.router.state.$state
*
* @description
* Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
*/
$IsStateFilter.$inject = ['$state'];
function $IsStateFilter($state) {
var isFilter = function (state) {
return $state.is(state);
};
isFilter.$stateful = true;
return isFilter;
}
/**
* @ngdoc filter
* @name ui.router.state.filter:includedByState
*
* @requires ui.router.state.$state
*
* @description
* Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
*/
$IncludedByStateFilter.$inject = ['$state'];
function $IncludedByStateFilter($state) {
var includesFilter = function (state) {
return $state.includes(state);
};
includesFilter.$stateful = true;
return includesFilter;
}
angular.module('ui.router.state')
.filter('isState', $IsStateFilter)
.filter('includedByState', $IncludedByStateFilter);
})(window, window.angular);
},{}],8:[function(require,module,exports){
/**
* @license AngularJS v1.4.4
* (c) 2010-2015 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {'use strict';
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var SKIP_INDEXES = 2;
var templateArgs = arguments,
code = templateArgs[0],
message = '[' + (module ? module + ':' : '') + code + '] ',
template = templateArgs[1],
paramPrefix, i;
message += template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1),
shiftedIndex = index + SKIP_INDEXES;
if (shiftedIndex < templateArgs.length) {
return toDebugString(templateArgs[shiftedIndex]);
}
return match;
});
message += '\nhttp://errors.angularjs.org/1.4.4/' +
(module ? module + '/' : '') + code;
for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
encodeURIComponent(toDebugString(templateArgs[i]));
}
return new ErrorConstructor(message);
};
}
/* We need to tell jshint what variables are being exported */
/* global angular: true,
msie: true,
jqLite: true,
jQuery: true,
slice: true,
splice: true,
push: true,
toString: true,
ngMinErr: true,
angularModule: true,
uid: true,
REGEX_STRING_REGEXP: true,
VALIDITY_STATE_PROPERTY: true,
lowercase: true,
uppercase: true,
manualLowercase: true,
manualUppercase: true,
nodeName_: true,
isArrayLike: true,
forEach: true,
forEachSorted: true,
reverseParams: true,
nextUid: true,
setHashKey: true,
extend: true,
toInt: true,
inherit: true,
merge: true,
noop: true,
identity: true,
valueFn: true,
isUndefined: true,
isDefined: true,
isObject: true,
isBlankObject: true,
isString: true,
isNumber: true,
isDate: true,
isArray: true,
isFunction: true,
isRegExp: true,
isWindow: true,
isScope: true,
isFile: true,
isFormData: true,
isBlob: true,
isBoolean: true,
isPromiseLike: true,
trim: true,
escapeForRegexp: true,
isElement: true,
makeMap: true,
includes: true,
arrayRemove: true,
copy: true,
shallowCopy: true,
equals: true,
csp: true,
jq: true,
concat: true,
sliceArgs: true,
bind: true,
toJsonReplacer: true,
toJson: true,
fromJson: true,
convertTimezoneToLocal: true,
timezoneToOffset: true,
startingTag: true,
tryDecodeURIComponent: true,
parseKeyValue: true,
toKeyValue: true,
encodeUriSegment: true,
encodeUriQuery: true,
angularInit: true,
bootstrap: true,
getTestability: true,
snake_case: true,
bindJQuery: true,
assertArg: true,
assertArgFn: true,
assertNotHasOwnProperty: true,
getter: true,
getBlockNodes: true,
hasOwnProperty: true,
createMap: true,
NODE_TYPE_ELEMENT: true,
NODE_TYPE_ATTRIBUTE: true,
NODE_TYPE_TEXT: true,
NODE_TYPE_COMMENT: true,
NODE_TYPE_DOCUMENT: true,
NODE_TYPE_DOCUMENT_FRAGMENT: true,
*/
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @description
*
* # ng (core module)
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
* <div doc-module-components="ng"></div>
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
/**
* @ngdoc function
* @name angular.lowercase
* @module ng
* @kind function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @ngdoc function
* @name angular.uppercase
* @module ng
* @kind function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
// Support: iOS 8.2 (not reproducible in simulator)
// "length" in obj used to prevent JIT error (gh-11508)
var length = "length" in Object(obj) && obj.length;
if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
}
return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
// Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
// Slow path for objects which do not have a method `hasOwnProperty`
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function forEachSorted(obj, iterator, context) {
var keys = Object.keys(obj).sort();
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value); };
}
/**
* A consistent way of creating unique IDs in angular.
*
* Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
* we hit number precision issues in JavaScript.
*
* Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
*
* @returns {number} an unique alpha-numeric string
*/
function nextUid() {
return ++uid;
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
} else {
delete obj.$$hashKey;
}
}
function baseExtend(dst, objs, deep) {
var h = dst.$$hashKey;
for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i];
if (!isObject(obj) && !isFunction(obj)) continue;
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
var src = obj[key];
if (deep && isObject(src)) {
if (isDate(src)) {
dst[key] = new Date(src.valueOf());
} else if (isRegExp(src)) {
dst[key] = new RegExp(src);
} else {
if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
baseExtend(dst[key], [src], true);
}
} else {
dst[key] = src;
}
}
}
setHashKey(dst, h);
return dst;
}
/**
* @ngdoc function
* @name angular.extend
* @module ng
* @kind function
*
* @description
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
*
* **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
* {@link angular.merge} for this.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
return baseExtend(dst, slice.call(arguments, 1), false);
}
/**
* @ngdoc function
* @name angular.merge
* @module ng
* @kind function
*
* @description
* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
*
* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
* objects, performing a deep copy.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function merge(dst) {
return baseExtend(dst, slice.call(arguments, 1), true);
}
function toInt(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(Object.create(parent), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @module ng
* @kind function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
```js
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
```
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @module ng
* @kind function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
```js
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
```
* @param {*} value to be returned.
* @returns {*} the value passed in.
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
function hasCustomToString(obj) {
return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
var isArray = Array.isArray;
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
function isTypedArray(value) {
return TYPED_ARRAY_REGEXP.test(toString.call(value));
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08');
};
/**
* @ngdoc function
* @name angular.isElement
* @module ng
* @kind function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str) {
var obj = {}, items = str.split(","), i;
for (i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function nodeName_(element) {
return lowercase(element.nodeName || (element[0] && element[0].nodeName));
}
function includes(array, obj) {
return Array.prototype.indexOf.call(array, obj) != -1;
}
function arrayRemove(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
<example module="copyExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}]);
</script>
</file>
</example>
*/
function copy(source, destination, stackSource, stackDest) {
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
"Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (isTypedArray(destination)) {
throw ngMinErr('cpta',
"Can't copy! TypedArray destination cannot be mutated.");
}
if (!destination) {
destination = source;
if (isObject(source)) {
var index;
if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
return stackDest[index];
}
// TypedArray, Date and RegExp have specific copy functionality and must be
// pushed onto the stack before returning.
// Array and other objects create the base object and recurse to copy child
// objects. The array/object will be pushed onto the stack when recursed.
if (isArray(source)) {
return copy(source, [], stackSource, stackDest);
} else if (isTypedArray(source)) {
destination = new source.constructor(source);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else {
var emptyObject = Object.create(getPrototypeOf(source));
return copy(source, emptyObject, stackSource, stackDest);
}
if (stackDest) {
stackSource.push(source);
stackDest.push(destination);
}
}
} else {
if (source === destination) throw ngMinErr('cpi',
"Can't copy! Source and destination are identical.");
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
stackSource.push(source);
stackDest.push(destination);
}
var result, key;
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
destination.push(copy(source[i], null, stackSource, stackDest));
}
} else {
var h = destination.$$hashKey;
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
delete destination[key];
});
}
if (isBlankObject(source)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in source) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
} else if (source && typeof source.hasOwnProperty === 'function') {
// Slow path, which must rely on hasOwnProperty
for (key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
} else {
// Slowest path --- hasOwnProperty can't be called as a method
for (key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return equals(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
return isRegExp(o2) ? o1.toString() == o2.toString() : false;
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
var csp = function() {
if (!isDefined(csp.rules)) {
var ngCspElement = (document.querySelector('[ng-csp]') ||
document.querySelector('[data-ng-csp]'));
if (ngCspElement) {
var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
ngCspElement.getAttribute('data-ng-csp');
csp.rules = {
noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
};
} else {
csp.rules = {
noUnsafeEval: noUnsafeEval(),
noInlineStyle: false
};
}
}
return csp.rules;
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
};
/**
* @ngdoc directive
* @module ng
* @name ngJq
*
* @element ANY
* @param {string=} ngJq the name of the library available under `window`
* to be used for angular.element
* @description
* Use this directive to force the angular.element library. This should be
* used to force either jqLite by leaving ng-jq blank or setting the name of
* the jquery variable under window (eg. jQuery).
*
* Since angular looks for this directive when it is loaded (doesn't wait for the
* DOMContentLoaded event), it must be placed on an element that comes before the script
* which loads angular. Also, only the first instance of `ng-jq` will be used and all
* others ignored.
*
* @example
* This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-jq>
...
...
</html>
```
* @example
* This example shows how to use a jQuery based library of a different name.
* The library name must be available at the top most 'window'.
```html
<!doctype html>
<html ng-app ng-jq="jQueryLib">
...
...
</html>
```
*/
var jq = function() {
if (isDefined(jq.name_)) return jq.name_;
var el;
var i, ii = ngAttrPrefixes.length, prefix, name;
for (i = 0; i < ii; ++i) {
prefix = ngAttrPrefixes[i];
if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
name = el.getAttribute(prefix + 'jq');
break;
}
}
return (jq.name_ = name);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/* jshint -W101 */
/**
* @ngdoc function
* @name angular.bind
* @module ng
* @kind function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
/* jshint +W101 */
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, concat(curryArgs, arguments, 0))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @module ng
* @kind function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
* stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
* If set to an integer, the JSON output will contain that many spaces per indentation.
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
/**
* @ngdoc function
* @name angular.fromJson
* @module ng
* @kind function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|string|number} Deserialized JSON string.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function timezoneToOffset(timezone, fallback) {
var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
reverse = reverse ? -1 : 1;
var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.empty();
} catch (e) {}
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns {Object.<string,boolean|Array>}
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {};
forEach((keyValue || "").split('&'), function(keyValue) {
var splitPoint, key, val;
if (keyValue) {
key = keyValue = keyValue.replace(/\+/g,'%20');
splitPoint = keyValue.indexOf('=');
if (splitPoint !== -1) {
key = keyValue.substring(0, splitPoint);
val = keyValue.substring(splitPoint + 1);
}
key = tryDecodeURIComponent(key);
if (isDefined(key)) {
val = isDefined(val) ? tryDecodeURIComponent(val) : true;
if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if (isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%3B/gi, ';').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
function getNgAttribute(element, ngAttr) {
var attr, i, ii = ngAttrPrefixes.length;
for (i = 0; i < ii; ++i) {
attr = ngAttrPrefixes[i] + ngAttr;
if (isString(attr = element.getAttribute(attr))) {
return attr;
}
}
return null;
}
/**
* @ngdoc directive
* @name ngApp
* @module ng
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
* @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
* created in "strict-di" mode. This means that the application will fail to invoke functions which
* do not use explicit function annotation (and are thus unsuitable for minification), as described
* in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
* tracking down the root of these bugs.
*
* @description
*
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
* designates the **root element** of the application and is typically placed near the root element
* of the page - e.g. on the `<body>` or `<html>` tags.
*
* Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
* found in the document will be used to define the root element to auto-bootstrap as an
* application. To run multiple applications in an HTML document you must manually bootstrap them using
* {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
*
* You can specify an **AngularJS module** to be used as the root module for the application. This
* module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
* should contain the application code needed or have dependencies on other modules that will
* contain the code. See {@link angular.module} for more information.
*
* In the example below if the `ngApp` directive were not placed on the `html` element then the
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
* would not be resolved to `3`.
*
* `ngApp` is the easiest, and most common way to bootstrap an application.
*
<example module="ngAppDemo">
<file name="index.html">
<div ng-controller="ngAppDemoController">
I can add: {{a}} + {{b}} = {{ a+b }}
</div>
</file>
<file name="script.js">
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
$scope.a = 1;
$scope.b = 2;
});
</file>
</example>
*
* Using `ngStrictDi`, you would see something like this:
*
<example ng-app-included="true">
<file name="index.html">
<div ng-app="ngAppStrictDemo" ng-strict-di>
<div ng-controller="GoodController1">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
</p>
</div>
<div ng-controller="GoodController2">
Name: <input ng-model="name"><br />
Hello, {{name}}!
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
</p>
</div>
<div ng-controller="BadController">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
</p>
</div>
</div>
</file>
<file name="script.js">
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = "World";
}
GoodController2.$inject = ['$scope'];
</file>
<file name="style.css">
div[ng-controller] {
margin-bottom: 1em;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;
}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;
}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;
}
</file>
</example>
*/
function angularInit(element, bootstrap) {
var appElement,
module,
config = {};
// The element `element` has priority over any other element
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
appElement = element;
module = element.getAttribute(name);
}
});
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
var candidate;
if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
appElement = candidate;
module = candidate.getAttribute(name);
}
});
if (appElement) {
config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
bootstrap(appElement, module ? [module] : [], config);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @module ng
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link ng.directive:ngApp ngApp}.
*
* Angular will detect if it has been loaded into the browser more than once and only allow the
* first loaded script to be bootstrapped and will report a warning to the browser console for
* each of the subsequent scripts. This prevents strange results in applications, where otherwise
* multiple instances of Angular try to work on the DOM.
*
* ```html
* <!doctype html>
* <html>
* <body>
* <div ng-controller="WelcomeController">
* {{greeting}}
* </div>
*
* <script src="angular.js"></script>
* <script>
* var app = angular.module('demo', [])
* .controller('WelcomeController', function($scope) {
* $scope.greeting = 'Welcome!';
* });
* angular.bootstrap(document, ['demo']);
* </script>
* </body>
* </html>
* ```
*
* @param {DOMElement} element DOM element which is the root of angular application.
* @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
* @param {Object=} config an object for defining configuration options for the application. The
* following keys are supported:
*
* * `strictDi` - disable automatic function annotation for the application. This is meant to
* assist in finding bugs which break minified code. Defaults to `false`.
*
* @returns {auto.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules, config) {
if (!isObject(config)) config = {};
var defaultConfig = {
strictDi: false
};
config = extend(defaultConfig, config);
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === document) ? 'document' : startingTag(element);
//Encode angle brackets to prevent input from being sanitized to empty string #8683
throw ngMinErr(
'btstrpd',
"App Already Bootstrapped with this Element '{0}'",
tag.replace(/</,'<').replace(/>/,'>'));
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
// Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
modules.push(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
config.debugInfoEnabled = true;
window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
}
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
return doBootstrap();
};
if (isFunction(angular.resumeDeferredBootstrap)) {
angular.resumeDeferredBootstrap();
}
}
/**
* @ngdoc function
* @name angular.reloadWithDebugInfo
* @module ng
* @description
* Use this function to reload the current application with debug information turned on.
* This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
*
* See {@link ng.$compileProvider#debugInfoEnabled} for more.
*/
function reloadWithDebugInfo() {
window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
window.location.reload();
}
/**
* @name angular.getTestability
* @module ng
* @description
* Get the testability service for the instance of Angular on the given
* element.
* @param {DOMElement} element DOM element which is the root of angular application.
*/
function getTestability(rootElement) {
var injector = angular.element(rootElement).injector();
if (!injector) {
throw ngMinErr('test',
'no injector found for element argument to getTestability');
}
return injector.get('$$testability');
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
var bindJQueryFired = false;
var skipDestroyOnNextJQueryCleanData;
function bindJQuery() {
var originalCleanData;
if (bindJQueryFired) {
return;
}
// bind to jQuery if present;
var jqName = jq();
jQuery = window.jQuery; // use default jQuery.
if (isDefined(jqName)) { // `ngJq` present
jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
}
// Use jQuery if it exists with proper functionality, otherwise default to us.
// Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
// Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
// versions. It will not work for sure with jQuery <1.7, though.
if (jQuery && jQuery.fn.on) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
// All nodes removed from the DOM via various jQuery APIs like .remove()
// are passed through jQuery.cleanData. Monkey-patch this method to fire
// the $destroy event on all removed nodes.
originalCleanData = jQuery.cleanData;
jQuery.cleanData = function(elems) {
var events;
if (!skipDestroyOnNextJQueryCleanData) {
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
events = jQuery._data(elem, "events");
if (events && events.$destroy) {
jQuery(elem).triggerHandler('$destroy');
}
}
} else {
skipDestroyOnNextJQueryCleanData = false;
}
originalCleanData(elems);
};
} else {
jqLite = JQLite;
}
angular.element = jqLite;
// Prevent double-proxying.
bindJQueryFired = true;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {String} path path to traverse
* @param {boolean} [bindFnToScope=true]
* @returns {Object} value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {jqLite} jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
// collection, otherwise update the original collection.
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes = [node];
do {
node = node.nextSibling;
if (!node) break;
blockNodes.push(node);
} while (node !== endNode);
return jqLite(blockNodes);
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc type
* @name angular.Module
* @module ng
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
var ngMinErr = minErr('ng');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
var angular = ensure(window, 'angular', Object);
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @module ng
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving Angular
* modules.
* All modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* Passing one argument retrieves an existing {@link angular.Module},
* whereas passing more than one argument creates a new {@link angular.Module}
*
*
* # Module
*
* A module is a collection of services, directives, controllers, filters, and configuration information.
* `angular.module` is used to configure the {@link auto.$injector $injector}.
*
* ```js
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(['$locationProvider', function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* }]);
* ```
*
* Then you can create an injector and load your modules like this:
*
* ```js
* var injector = angular.injector(['ng', 'myModule'])
* ```
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {!Array.<string>=} requires If specified then new module is being created. If
* unspecified then the module is being retrieved for further configuration.
* @param {Function=} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
var assertNotHasOwnProperty = function(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
};
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var configBlocks = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @module ng
*
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @module ng
*
* @description
* Name of the module.
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @module ng
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link auto.$provide#provider $provide.provider()}.
*/
provider: invokeLaterAndSetModuleName('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @module ng
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link auto.$provide#factory $provide.factory()}.
*/
factory: invokeLaterAndSetModuleName('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @module ng
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link auto.$provide#service $provide.service()}.
*/
service: invokeLaterAndSetModuleName('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @module ng
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link auto.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @module ng
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link auto.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#decorator
* @module ng
* @param {string} The name of the service to decorate.
* @param {Function} This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance.
* @description
* See {@link auto.$provide#decorator $provide.decorator()}.
*/
decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid angular expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global: toDebugString: true */
function serializeObject(obj) {
var seen = [];
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '<<already seen>>';
seen.push(val);
}
return val;
});
}
function toDebugString(obj) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (typeof obj === 'undefined') {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj);
}
return obj;
}
/* global angularModule: true,
version: true,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
inputDirective,
formDirective,
scriptDirective,
selectDirective,
styleDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngIncludeFillContentDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
patternDirective,
patternDirective,
requiredDirective,
requiredDirective,
minlengthDirective,
minlengthDirective,
maxlengthDirective,
maxlengthDirective,
ngValueDirective,
ngModelOptionsDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$CoreAnimateCssProvider,
$$CoreAnimateQueueProvider,
$$CoreAnimateRunnerProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DocumentProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$$ForceReflowProvider,
$InterpolateProvider,
$IntervalProvider,
$$HashMapProvider,
$HttpProvider,
$HttpParamSerializerProvider,
$HttpParamSerializerJQLikeProvider,
$HttpBackendProvider,
$LocationProvider,
$LogProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$$QProvider,
$$SanitizeUriProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$TemplateCacheProvider,
$TemplateRequestProvider,
$$TestabilityProvider,
$TimeoutProvider,
$$RAFProvider,
$WindowProvider,
$$jqLiteProvider,
$$CookieReaderProvider
*/
/**
* @ngdoc object
* @name angular.version
* @module ng
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.4.4', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 4,
dot: 4,
codeName: 'pylon-requirement'
};
function publishExternalAPI(angular) {
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'merge': merge,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0},
'getTestability': getTestability,
'$$minErr': minErr,
'$$csp': csp,
'reloadWithDebugInfo': reloadWithDebugInfo
});
angularModule = setupModuleLoader(window);
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
$provide.provider({
$$sanitizeUri: $$SanitizeUriProvider
});
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
pattern: patternDirective,
ngPattern: patternDirective,
required: requiredDirective,
ngRequired: requiredDirective,
minlength: minlengthDirective,
ngMinlength: minlengthDirective,
maxlength: maxlengthDirective,
ngMaxlength: maxlengthDirective,
ngValue: ngValueDirective,
ngModelOptions: ngModelOptionsDirective
}).
directive({
ngInclude: ngIncludeFillContentDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$animateCss: $CoreAnimateCssProvider,
$$animateQueue: $$CoreAnimateQueueProvider,
$$AnimateRunner: $$CoreAnimateRunnerProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$$forceReflow: $$ForceReflowProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$http: $HttpProvider,
$httpParamSerializer: $HttpParamSerializerProvider,
$httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$$q: $$QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$templateRequest: $TemplateRequestProvider,
$$testability: $$TestabilityProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider,
$$jqLite: $$jqLiteProvider,
$$HashMap: $$HashMapProvider,
$$cookieReader: $$CookieReaderProvider
});
}
]);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* global JQLitePrototype: true,
addEventListenerFn: true,
removeEventListenerFn: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true,
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1,
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
},
removeEventListenerFn = function(element, type, fn) {
element.removeEventListener(type, fn, false);
};
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteHasData(node) {
for (var key in jqCache[node.ng339]) {
return true;
}
return false;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = tmp || fragment.appendChild(context.createElement("div"));
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = "";
}
// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants) jqLiteRemoveData(element);
if (element.querySelectorAll) {
var descendants = element.querySelectorAll('*');
for (var i = 0, l = descendants.length; i < l; i++) {
jqLiteRemoveData(descendants[i]);
}
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
removeEventListenerFn(element, type, handle);
}
delete events[type];
}
} else {
forEach(type.split(' '), function(type) {
if (isDefined(fn)) {
var listenerFns = events[type];
arrayRemove(listenerFns || [], fn);
if (listenerFns && listenerFns.length > 0) {
return;
}
}
removeEventListenerFn(element, type, handle);
delete events[type];
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
return;
}
if (expandoStore.handle) {
if (expandoStore.events.$destroy) {
expandoStore.handle({}, '$destroy');
}
jqLiteOff(element);
}
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[key] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[key];
} else { // mass-setter: data({key1: val1, key2: val2})
extend(data, key);
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf(" " + selector + " ") > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType == NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if ((value = jqLite.data(element, names[i])) !== undefined) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behaviour
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document is already loaded
if (document.readyState === 'complete') {
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(element, name) {
var nodeName = element.nodeName;
return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData,
hasData: jqLiteHasData
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var nodeType = element.nodeType;
if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
return;
}
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name) || noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
eventFns[i].call(element, event);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
while (i--) {
type = types[i];
var eventFns = events[type];
if (!eventFns) {
events[type] = [];
if (type === 'mouseenter' || type === 'mouseleave') {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
var target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !target.contains(related))) {
handle(event, type);
}
});
} else {
if (type !== '$destroy') {
addEventListenerFn(element, type, handle);
}
}
eventFns = events[type];
}
eventFns.push(fn);
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
children.push(element);
}
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode).eq(0).clone()[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
// Provider for private $$jqLite service
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType == 'function' || (objType == 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array, isolatedUid) {
if (isolatedUid) {
var uid = 0;
this.nextUid = function() {
return ++uid;
};
}
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key, this.nextUid)] = value;
},
/**
* @param key
* @returns {Object} the value for the key
*/
get: function(key) {
return this[hashKey(key, this.nextUid)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key, this.nextUid)];
delete this[key];
return value;
}
};
var $$HashMapProvider = [function() {
this.$get = [function() {
return HashMap;
}];
}];
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector object that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
* disallows argument name annotation inference.
* @returns {injector} Injector object. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document) {
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running Angular app
* from outside Angular. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
args = fnText.match(FN_ARGS);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector) {
* return $injector;
* })).toBe($injector);
* ```
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. This method of discovering
* annotations is disallowed when the injector is in strict mode.
* *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
* argument names.
*
* ## `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @param {string=} caller An optional string to provide the origin of the function call for error messages.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
* injected according to the {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} name Name of the service to query.
* @returns {boolean} `true` if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* You can disallow this method by using strict injection mode.
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An Angular **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
* Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is the service
* constructor function that will be used to instantiate the service instance.
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
* that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an Angular
* {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service**, such as a string, a number, an array, an object or a function,
* with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an Angular {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
* intercepts the creation of a service, allowing it to override or modify the behaviour of the
* service. The object returned by the decorator may be the original service, or a new service
* object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
}));
forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function enforceReturnValue(name, factory) {
return function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
}
return result;
};
}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val), false); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
var runBlocks = [], moduleFn;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
function runInvokeQueue(queue) {
var i, ii;
for (i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
/* jshint -W022 */
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName, caller);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals, serviceName) {
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = [],
$inject = createInjector.$$annotate(fn, strictDi, serviceName),
length, i,
key;
for (i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, serviceName)
);
}
if (isArray(fn)) {
fn = fn[length];
}
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
}
function instantiate(Type, locals, serviceName) {
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
// Object creation: http://jsperf.com/create-constructor/2
var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
var returnedValue = invoke(Type, instance, locals, serviceName);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: createInjector.$$annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
/**
* @ngdoc provider
* @name $anchorScrollProvider
*
* @description
* Use `$anchorScrollProvider` to disable automatic scrolling whenever
* {@link ng.$location#hash $location.hash()} changes.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
/**
* @ngdoc method
* @name $anchorScrollProvider#disableAutoScrolling
*
* @description
* By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
* {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
* Use this method to disable automatic scrolling.
*
* If automatic scrolling is disabled, one must explicitly call
* {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
* current hash.
*/
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
/**
* @ngdoc service
* @name $anchorScroll
* @kind function
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
* current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
* in the
* [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
*
* It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
* match any anchor whenever it changes. This can be disabled by calling
* {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
*
* Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
* vertical scroll-offset (either fixed or dynamic).
*
* @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
* {@link ng.$location#hash $location.hash()} will be used.
*
* @property {(number|function|jqLite)} yOffset
* If set, specifies a vertical scroll-offset. This is often useful when there are fixed
* positioned elements at the top of the page, such as navbars, headers etc.
*
* `yOffset` can be specified in various ways:
* - **number**: A fixed number of pixels to be used as offset.<br /><br />
* - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
* a number representing the offset (in pixels).<br /><br />
* - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
* the top of the page to the element's bottom will be used as offset.<br />
* **Note**: The element will be taken into account only as long as its `position` is set to
* `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
* their height and/or positioning according to the viewport's size.
*
* <br />
* <div class="alert alert-warning">
* In order for `yOffset` to work properly, scrolling should take place on the document's root and
* not some child element.
* </div>
*
* @example
<example module="anchorScrollExample">
<file name="index.html">
<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
</file>
<file name="script.js">
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function ($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
</file>
<file name="style.css">
#scrollArea {
height: 280px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
</file>
</example>
*
* <hr />
* The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
* See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
*
* @example
<example module="anchorScrollOffsetExample">
<file name="index.html">
<div class="fixed-header" ng-controller="headerCtrl">
<a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
Go to anchor {{x}}
</a>
</div>
<div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
Anchor {{x}} of 5
</div>
</file>
<file name="script.js">
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function ($anchorScroll, $location, $scope) {
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
}
]);
</file>
<file name="style.css">
body {
padding-top: 50px;
}
.anchor {
border: 2px dashed DarkOrchid;
padding: 10px 10px 200px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 50px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
</file>
</example>
*/
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// Helper function to get first anchor from a NodeList
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
// and working in all supported browsers.)
function getFirstAnchor(list) {
var result = null;
Array.prototype.some.call(list, function(element) {
if (nodeName_(element) === 'a') {
result = element;
return true;
}
});
return result;
}
function getYOffset() {
var offset = scroll.yOffset;
if (isFunction(offset)) {
offset = offset();
} else if (isElement(offset)) {
var elem = offset[0];
var style = $window.getComputedStyle(elem);
if (style.position !== 'fixed') {
offset = 0;
} else {
offset = elem.getBoundingClientRect().bottom;
}
} else if (!isNumber(offset)) {
offset = 0;
}
return offset;
}
function scrollTo(elem) {
if (elem) {
elem.scrollIntoView();
var offset = getYOffset();
if (offset) {
// `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
// This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
// top of the viewport.
//
// IF the number of pixels from the top of `elem` to the end of the page's content is less
// than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
// way down the page.
//
// This is often the case for elements near the bottom of the page.
//
// In such cases we do not need to scroll the whole `offset` up, just the difference between
// the top of the element and the offset, which is enough to align the top of `elem` at the
// desired position.
var elemTop = elem.getBoundingClientRect().top;
$window.scrollBy(0, elemTop - offset);
}
} else {
$window.scrollTo(0, 0);
}
}
function scroll(hash) {
hash = isString(hash) ? hash : $location.hash();
var elm;
// empty hash, scroll to the top of the page
if (!hash) scrollTo(null);
// element with given id
else if ((elm = document.getElementById(hash))) scrollTo(elm);
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') scrollTo(null);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction(newVal, oldVal) {
// skip the initial scroll if $location.hash is empty
if (newVal === oldVal && newVal === '') return;
jqLiteDocumentLoaded(function() {
$rootScope.$evalAsync(scroll);
});
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
var ELEMENT_NODE = 1;
var NG_ANIMATE_CLASSNAME = 'ng-animate';
function mergeClasses(a,b) {
if (!a && !b) return '';
if (!a) return b;
if (!b) return a;
if (isArray(a)) a = a.join(' ');
if (isArray(b)) b = b.join(' ');
return a + ' ' + b;
}
function extractElementNode(element) {
for (var i = 0; i < element.length; i++) {
var elm = element[i];
if (elm.nodeType === ELEMENT_NODE) {
return elm;
}
}
}
function splitClasses(classes) {
if (isString(classes)) {
classes = classes.split(' ');
}
// Use createMap() to prevent class assumptions involving property names in
// Object.prototype
var obj = createMap();
forEach(classes, function(klass) {
// sometimes the split leaves empty string values
// incase extra spaces were applied to the options
if (klass.length) {
obj[klass] = true;
}
});
return obj;
}
// if any other type of options value besides an Object value is
// passed into the $animate.method() animation then this helper code
// will be run which will ignore it. While this patch is not the
// greatest solution to this, a lot of existing plugins depend on
// $animate to either call the callback (< 1.2) or return a promise
// that can be changed. This helper function ensures that the options
// are wiped clean incase a callback function is provided.
function prepareAnimateOptions(options) {
return isObject(options)
? options
: {};
}
var $$CoreAnimateRunnerProvider = function() {
this.$get = ['$q', '$$rAF', function($q, $$rAF) {
function AnimateRunner() {}
AnimateRunner.all = noop;
AnimateRunner.chain = noop;
AnimateRunner.prototype = {
end: noop,
cancel: noop,
resume: noop,
pause: noop,
complete: noop,
then: function(pass, fail) {
return $q(function(resolve) {
$$rAF(function() {
resolve();
});
}).then(pass, fail);
}
};
return AnimateRunner;
}];
};
// this is prefixed with Core since it conflicts with
// the animateQueueProvider defined in ngAnimate/animateQueue.js
var $$CoreAnimateQueueProvider = function() {
var postDigestQueue = new HashMap();
var postDigestElements = [];
this.$get = ['$$AnimateRunner', '$rootScope',
function($$AnimateRunner, $rootScope) {
return {
enabled: noop,
on: noop,
off: noop,
pin: noop,
push: function(element, event, options, domOperation) {
domOperation && domOperation();
options = options || {};
options.from && element.css(options.from);
options.to && element.css(options.to);
if (options.addClass || options.removeClass) {
addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
}
return new $$AnimateRunner(); // jshint ignore:line
}
};
function addRemoveClassesPostDigest(element, add, remove) {
var classVal, data = postDigestQueue.get(element);
if (!data) {
postDigestQueue.put(element, data = {});
postDigestElements.push(element);
}
var updateData = function(classes, value) {
var changed = false;
if (classes) {
classes = isString(classes) ? classes.split(' ') :
isArray(classes) ? classes : [];
forEach(classes, function(className) {
if (className) {
changed = true;
data[className] = value;
}
});
}
return changed;
};
var classesAdded = updateData(add, true);
var classesRemoved = updateData(remove, false);
if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;
$rootScope.$$postDigest(function() {
forEach(postDigestElements, function(element) {
var data = postDigestQueue.get(element);
if (data) {
var existing = splitClasses(element.attr('class'));
var toAdd = '';
var toRemove = '';
forEach(data, function(status, className) {
var hasClass = !!existing[className];
if (status !== hasClass) {
if (status) {
toAdd += (toAdd.length ? ' ' : '') + className;
} else {
toRemove += (toRemove.length ? ' ' : '') + className;
}
}
});
forEach(element, function(elm) {
toAdd && jqLiteAddClass(elm, toAdd);
toRemove && jqLiteRemoveClass(elm, toRemove);
});
postDigestQueue.remove(element);
}
});
postDigestElements.length = 0;
});
}
}];
};
/**
* @ngdoc provider
* @name $animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM updates and resolves the returned runner promise.
*
* In order to enable animations the `ngAnimate` module has to be loaded.
*
* To see the functional implementation check out `src/ngAnimate/animate.js`.
*/
var $AnimateProvider = ['$provide', function($provide) {
var provider = this;
this.$$registeredAnimations = Object.create(null);
/**
* @ngdoc method
* @name $animateProvider#register
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(element, ... , doneFunction, options)`
* The element to animate, the `doneFunction` and the options fed into the animation. Depending
* on the type of animation additional arguments will be injected into the animation function. The
* list below explains the function signatures for the different animation methods:
*
* - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
* - addClass: function(element, addedClasses, doneFunction, options)
* - removeClass: function(element, removedClasses, doneFunction, options)
* - enter, leave, move: function(element, doneFunction, options)
* - animate: function(element, fromStyles, toStyles, doneFunction, options)
*
* Make sure to trigger the `doneFunction` once the animation is fully complete.
*
* ```js
* return {
* //enter, leave, move signature
* eventFn : function(element, done, options) {
* //code to run the animation
* //once complete, then run done()
* return function endFunction(wasCancelled) {
* //code to cancel the animation
* }
* }
* }
* ```
*
* @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
* @param {Function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
if (name && name.charAt(0) !== '.') {
throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
}
var key = name + '-animation';
provider.$$registeredAnimations[name.substr(1)] = key;
$provide.factory(key, factory);
};
/**
* @ngdoc method
* @name $animateProvider#classNameFilter
*
* @description
* Sets and/or returns the CSS class regular expression that is checked when performing
* an animation. Upon bootstrap the classNameFilter value is not set at all and will
* therefore enable $animate to attempt to perform an animation on any element that is triggered.
* When setting the `classNameFilter` value, animations will only be performed on elements
* that successfully match the filter expression. This in turn can boost performance
* for low-powered devices as well as applications containing a lot of structural operations.
* @param {RegExp=} expression The className expression which will be checked against all animations
* @return {RegExp} The current CSS className expression value. If null then there is no expression value
*/
this.classNameFilter = function(expression) {
if (arguments.length === 1) {
this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
if (this.$$classNameFilter) {
var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
if (reservedRegex.test(this.$$classNameFilter.toString())) {
throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
}
}
}
return this.$$classNameFilter;
};
this.$get = ['$$animateQueue', function($$animateQueue) {
function domInsert(element, parentElement, afterElement) {
// if for some reason the previous element was removed
// from the dom sometime before this code runs then let's
// just stick to using the parent element as the anchor
if (afterElement) {
var afterNode = extractElementNode(afterElement);
if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
afterElement = null;
}
}
afterElement ? afterElement.after(element) : parentElement.prepend(element);
}
/**
* @ngdoc service
* @name $animate
* @description The $animate service exposes a series of DOM utility methods that provide support
* for animation hooks. The default behavior is the application of DOM operations, however,
* when an animation is detected (and animations are enabled), $animate will do the heavy lifting
* to ensure that animation runs with the triggered DOM operation.
*
* By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
* included and only when it is active then the animation hooks that `$animate` triggers will be
* functional. Once active then all structural `ng-` directives will trigger animations as they perform
* their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
* `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
*
* It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
*
* To learn more about enabling animation support, click here to visit the
* {@link ngAnimate ngAnimate module page}.
*/
return {
// we don't call it directly since non-existant arguments may
// be interpreted as null within the sub enabled function
/**
*
* @ngdoc method
* @name $animate#on
* @kind function
* @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
* has fired on the given element or among any of its children. Once the listener is fired, the provided callback
* is fired with the following params:
*
* ```js
* $animate.on('enter', container,
* function callback(element, phase) {
* // cool we detected an enter animation within the container
* }
* );
* ```
*
* @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
* as well as among its children
* @param {Function} callback the callback function that will be fired when the listener is triggered
*
* The arguments present in the callback function are:
* * `element` - The captured DOM element that the animation was fired on.
* * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
*/
on: $$animateQueue.on,
/**
*
* @ngdoc method
* @name $animate#off
* @kind function
* @description Deregisters an event listener based on the event which has been associated with the provided element. This method
* can be used in three different ways depending on the arguments:
*
* ```js
* // remove all the animation event listeners listening for `enter`
* $animate.off('enter');
*
* // remove all the animation event listeners listening for `enter` on the given element and its children
* $animate.off('enter', container);
*
* // remove the event listener function provided by `listenerFn` that is set
* // to listen for `enter` on the given `element` as well as its children
* $animate.off('enter', container, callback);
* ```
*
* @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement=} container the container element the event listener was placed on
* @param {Function=} callback the callback function that was registered as the listener
*/
off: $$animateQueue.off,
/**
* @ngdoc method
* @name $animate#pin
* @kind function
* @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
* outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
* element despite being outside the realm of the application or within another application. Say for example if the application
* was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
* as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
* that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
*
* Note that this feature is only active when the `ngAnimate` module is used.
*
* @param {DOMElement} element the external element that will be pinned
* @param {DOMElement} parentElement the host parent element that will be associated with the external element
*/
pin: $$animateQueue.pin,
/**
*
* @ngdoc method
* @name $animate#enabled
* @kind function
* @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
* function can be called in four ways:
*
* ```js
* // returns true or false
* $animate.enabled();
*
* // changes the enabled state for all animations
* $animate.enabled(false);
* $animate.enabled(true);
*
* // returns true or false if animations are enabled for an element
* $animate.enabled(element);
*
* // changes the enabled state for an element and its children
* $animate.enabled(element, true);
* $animate.enabled(element, false);
* ```
*
* @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
* @param {boolean=} enabled whether or not the animations will be enabled for the element
*
* @return {boolean} whether or not animations are enabled
*/
enabled: $$animateQueue.enabled,
/**
* @ngdoc method
* @name $animate#cancel
* @kind function
* @description Cancels the provided animation.
*
* @param {Promise} animationPromise The animation promise that is returned when an animation is started.
*/
cancel: function(runner) {
runner.end && runner.end();
},
/**
*
* @ngdoc method
* @name $animate#enter
* @kind function
* @description Inserts the element into the DOM either after the `after` element (if provided) or
* as the first child within the `parent` element and then triggers an animation.
* A promise is returned that will be resolved during the next digest once the animation
* has completed.
*
* @param {DOMElement} element the element which will be inserted into the DOM
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
enter: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
},
/**
*
* @ngdoc method
* @name $animate#move
* @kind function
* @description Inserts (moves) the element into its new position in the DOM either after
* the `after` element (if provided) or as the first child within the `parent` element
* and then triggers an animation. A promise is returned that will be resolved
* during the next digest once the animation has completed.
*
* @param {DOMElement} element the element which will be moved into the new DOM position
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
move: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
},
/**
* @ngdoc method
* @name $animate#leave
* @kind function
* @description Triggers an animation and then removes the element from the DOM.
* When the function is called a promise is returned that will be resolved during the next
* digest once the animation has completed.
*
* @param {DOMElement} element the element which will be removed from the DOM
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
leave: function(element, options) {
return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
element.remove();
});
},
/**
* @ngdoc method
* @name $animate#addClass
* @kind function
*
* @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
* execution, the addClass operation will only be handled after the next digest and it will not trigger an
* animation if element already contains the CSS class or if the class is removed at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
addClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addclass, className);
return $$animateQueue.push(element, 'addClass', options);
},
/**
* @ngdoc method
* @name $animate#removeClass
* @kind function
*
* @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
* execution, the removeClass operation will only be handled after the next digest and it will not trigger an
* animation if element does not contain the CSS class or if the class is added at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
removeClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.removeClass = mergeClasses(options.removeClass, className);
return $$animateQueue.push(element, 'removeClass', options);
},
/**
* @ngdoc method
* @name $animate#setClass
* @kind function
*
* @description Performs both the addition and removal of a CSS classes on an element and (during the process)
* triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
* `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
* passed. Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
setClass: function(element, add, remove, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addClass, add);
options.removeClass = mergeClasses(options.removeClass, remove);
return $$animateQueue.push(element, 'setClass', options);
},
/**
* @ngdoc method
* @name $animate#animate
* @kind function
*
* @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
* If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
* on the provided styles. For example, if a transition animation is set for the given className then the provided from and
* to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
* will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
*
* @param {DOMElement} element the element which the CSS styles will be applied to
* @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
* @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
* @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
* this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
* (Note that if no animation is detected then this value will not be appplied to the element.)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
animate: function(element, from, to, className, options) {
options = prepareAnimateOptions(options);
options.from = options.from ? extend(options.from, from) : from;
options.to = options.to ? extend(options.to, to) : to;
className = className || 'ng-inline-animate';
options.tempClasses = mergeClasses(options.tempClasses, className);
return $$animateQueue.push(element, 'animate', options);
}
};
}];
}];
/**
* @ngdoc service
* @name $animateCss
* @kind object
*
* @description
* This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
* then the `$animateCss` service will actually perform animations.
*
* Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
*/
var $CoreAnimateCssProvider = function() {
this.$get = ['$$rAF', '$q', function($$rAF, $q) {
var RAFPromise = function() {};
RAFPromise.prototype = {
done: function(cancel) {
this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
},
end: function() {
this.done();
},
cancel: function() {
this.done(true);
},
getPromise: function() {
if (!this.defer) {
this.defer = $q.defer();
}
return this.defer.promise;
},
then: function(f1,f2) {
return this.getPromise().then(f1,f2);
},
'catch': function(f1) {
return this.getPromise().catch(f1);
},
'finally': function(f1) {
return this.getPromise().finally(f1);
}
};
return function(element, options) {
if (options.from) {
element.css(options.from);
options.from = null;
}
var closed, runner = new RAFPromise();
return {
start: run,
end: run
};
function run() {
$$rAF(function() {
close();
if (!closed) {
runner.done();
}
closed = true;
});
return runner;
}
function close() {
if (options.addClass) {
element.addClass(options.addClass);
options.addClass = null;
}
if (options.removeClass) {
element.removeClass(options.removeClass);
options.removeClass = null;
}
if (options.to) {
element.css(options.to);
options.to = null;
}
}
};
}];
};
/* global stripHash: true */
/**
* ! This is a private undocumented service !
*
* @name $browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} $log window.console or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while (outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
function getHash(url) {
var index = url.indexOf('#');
return index === -1 ? '' : url.substr(index);
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var cachedState, lastHistoryState,
lastBrowserUrl = location.href,
baseElement = document.find('base'),
reloadLocation = null;
cacheState();
lastHistoryState = cachedState;
/**
* @name $browser#url
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record?
* @param {object=} state object to use with pushState/replaceState
*/
self.url = function(url, replace, state) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (isUndefined(state)) {
state = null;
}
// Android Browser BFCache causes location, history reference to become stale.
if (location !== window.location) location = window.location;
if (history !== window.history) history = window.history;
// setter
if (url) {
var sameState = lastHistoryState === state;
// Don't change anything if previous and current URLs and states match. This also prevents
// IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
// See https://github.com/angular/angular.js/commit/ffb2701
if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
return self;
}
var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
lastBrowserUrl = url;
lastHistoryState = state;
// Don't use history API if only the hash changed
// due to a bug in IE10/IE11 which leads
// to not firing a `hashchange` nor `popstate` event
// in some cases (see #9143).
if ($sniffer.history && (!sameBase || !sameState)) {
history[replace ? 'replaceState' : 'pushState'](state, '', url);
cacheState();
// Do the assignment again so that those two variables are referentially identical.
lastHistoryState = cachedState;
} else {
if (!sameBase || reloadLocation) {
reloadLocation = url;
}
if (replace) {
location.replace(url);
} else if (!sameBase) {
location.href = url;
} else {
location.hash = getHash(url);
}
}
return self;
// getter
} else {
// - reloadLocation is needed as browsers don't allow to read out
// the new location.href if a reload happened.
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return reloadLocation || location.href.replace(/%27/g,"'");
}
};
/**
* @name $browser#state
*
* @description
* This method is a getter.
*
* Return history.state or null if history.state is undefined.
*
* @returns {object} state
*/
self.state = function() {
return cachedState;
};
var urlChangeListeners = [],
urlChangeInit = false;
function cacheStateAndFireUrlChange() {
cacheState();
fireUrlChange();
}
function getCurrentState() {
try {
return history.state;
} catch (e) {
// MSIE can reportedly throw when there is no state (UNCONFIRMED).
}
}
// This variable should be used *only* inside the cacheState function.
var lastCachedState = null;
function cacheState() {
// This should be the only place in $browser where `history.state` is read.
cachedState = getCurrentState();
cachedState = isUndefined(cachedState) ? null : cachedState;
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (equals(cachedState, lastCachedState)) {
cachedState = lastCachedState;
}
lastCachedState = cachedState;
}
function fireUrlChange() {
if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
return;
}
lastBrowserUrl = self.url();
lastHistoryState = cachedState;
forEach(urlChangeListeners, function(listener) {
listener(self.url(), cachedState);
});
}
/**
* @name $browser#onUrlChange
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed from outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
// TODO(vojta): refactor to use node's syntax for events
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
// hashchange event
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
/**
* @private
* Remove popstate and hashchange handler from window.
*
* NOTE: this api is intended for use only by $rootScope.
*/
self.$$applicationDestroyed = function() {
jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
};
/**
* Checks whether the url has changed outside of Angular.
* Needs to be exported to be able to check for changes that have been done in sync,
* as hashchange/popstate events fire in async.
*/
self.$$checkUrlChange = fireUrlChange;
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name $browser#baseHref
*
* @description
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string} The current base href
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
};
/**
* @name $browser#defer
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name $browser#defer.cancel
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document',
function($window, $log, $sniffer, $document) {
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc service
* @name $cacheFactory
*
* @description
* Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
* them.
*
* ```js
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* ```
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
* @example
<example module="cacheExampleApp">
<file name="index.html">
<div ng-controller="CacheController">
<input ng-model="newCacheKey" placeholder="Key">
<input ng-model="newCacheValue" placeholder="Value">
<button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
<p ng-if="keys.length">Cached Values</p>
<div ng-repeat="key in keys">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="cache.get(key)"></b>
</div>
<p>Cache Info</p>
<div ng-repeat="(key, value) in cache.info()">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="value"></b>
</div>
</div>
</file>
<file name="script.js">
angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
$scope.keys = [];
$scope.cache = $cacheFactory('cacheId');
$scope.put = function(key, value) {
if ($scope.cache.get(key) === undefined) {
$scope.keys.push(key);
}
$scope.cache.put(key, value === undefined ? null : value);
};
}]);
</file>
<file name="style.css">
p {
margin: 10px 0 3px;
}
</file>
</example>
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
/**
* @ngdoc type
* @name $cacheFactory.Cache
*
* @description
* A cache object used to store and retrieve data, primarily used by
* {@link $http $http} and the {@link ng.directive:script script} directive to cache
* templates and other data.
*
* ```js
* angular.module('superCache')
* .factory('superCache', ['$cacheFactory', function($cacheFactory) {
* return $cacheFactory('super-cache');
* }]);
* ```
*
* Example test:
*
* ```js
* it('should behave like a cache', inject(function(superCache) {
* superCache.put('key', 'value');
* superCache.put('another key', 'another value');
*
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 2
* });
*
* superCache.remove('another key');
* expect(superCache.get('another key')).toBeUndefined();
*
* superCache.removeAll();
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 0
* });
* }));
* ```
*/
return caches[cacheId] = {
/**
* @ngdoc method
* @name $cacheFactory.Cache#put
* @kind function
*
* @description
* Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
* retrieved later, and incrementing the size of the cache if the key was not already
* present in the cache. If behaving like an LRU cache, it will also remove stale
* entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param {string} key the key under which the cached data is stored.
* @param {*} value the value to store alongside the key. If it is undefined, the key
* will not be stored.
* @returns {*} the value stored.
*/
put: function(key, value) {
if (isUndefined(value)) return;
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
}
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#get
* @kind function
*
* @description
* Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the data to be retrieved
* @returns {*} the value stored.
*/
get: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
}
return data[key];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#remove
* @kind function
*
* @description
* Removes an entry from the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the entry to be removed
*/
remove: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
}
delete data[key];
size--;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#removeAll
* @kind function
*
* @description
* Clears the cache object of any entries.
*/
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#destroy
* @kind function
*
* @description
* Destroys the {@link $cacheFactory.Cache Cache} object entirely,
* removing it from the {@link $cacheFactory $cacheFactory} set.
*/
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#info
* @kind function
*
* @description
* Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
*
* @returns {object} an object with the following properties:
* <ul>
* <li>**id**: the id of the cache instance</li>
* <li>**size**: the number of entries kept in the cache instance</li>
* <li>**...**: any additional properties from the options object when creating the
* cache.</li>
* </ul>
*/
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name $cacheFactory#info
*
* @description
* Get information about all the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name $cacheFactory#get
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc service
* @name $templateCache
*
* @description
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, or by consuming the
* `$templateCache` service directly.
*
* Adding via the `script` tag:
*
* ```html
* <script type="text/ng-template" id="templateId.html">
* <p>This is the content of the template</p>
* </script>
* ```
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
* element with ng-app attribute), otherwise the template will be ignored.
*
* Adding via the `$templateCache` service:
*
* ```js
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* ```
*
* To retrieve the template later, simply use it in your HTML:
* ```html
* <div ng-include=" 'templateId.html' "></div>
* ```
*
* or get it via Javascript:
* ```js
* $templateCache.get('templateId.html')
* ```
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc service
* @name $compile
* @kind function
*
* @description
* Compiles an HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#directive directives}.
*
* <div class="alert alert-warning">
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
* </div>
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a "Directive Definition Object" (see below) that defines the directive properties,
* or just the `postLink` function (all other properties will have the default values).
*
* <div class="alert alert-success">
* **Best Practice:** It's recommended to use the "directive definition object" form.
* </div>
*
* Here's an example directive declared with a Directive Definition Object:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* priority: 0,
* template: '<div></div>', // or // function(tElement, tAttrs) { ... },
* // or
* // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
* transclude: false,
* restrict: 'A',
* templateNamespace: 'html',
* scope: false,
* controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
* controllerAs: 'stringIdentifier',
* bindToController: false,
* require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
* compile: function compile(tElement, tAttrs, transclude) {
* return {
* pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* post: function postLink(scope, iElement, iAttrs, controller) { ... }
* }
* // or
* // return function postLink( ... ) { ... }
* },
* // or
* // link: {
* // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* // post: function postLink(scope, iElement, iAttrs, controller) { ... }
* // }
* // or
* // link: function postLink( ... ) { ... }
* };
* return directiveDefinitionObject;
* });
* ```
*
* <div class="alert alert-warning">
* **Note:** Any unspecified options will use the default value. You can see the default values below.
* </div>
*
* Therefore the above can be simplified as:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* ```
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `multiElement`
* When this property is set to true, the HTML compiler will collect DOM nodes between
* nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
* together as the directive elements. It is recommended that this feature be used on directives
* which are not strictly behavioural (such as {@link ngClick}), and which
* do not manipulate or replace child nodes (such as {@link ngInclude}).
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions
* are also run in priority order, but post-link functions are run in reverse order. The order
* of directives with the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined). Note that expressions
* and other directives used in the directive's template will also be excluded from execution.
*
* #### `scope`
* **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
* same element request a new scope, only one new scope is created. The new scope rule does not
* apply for the root of the template since the root of the template always gets a new scope.
*
* **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
* normal scope in that it does not prototypically inherit from the parent scope. This is useful
* when creating reusable components, which should not accidentally read or modify data in the
* parent scope.
*
* The 'isolate' scope takes an object hash which defines a set of local scope properties
* derived from the parent scope. These local properties are useful for aliasing values for
* templates. Locals definition is a hash of local scope property to its source:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="hello {{name}}">` and widget definition
* of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
* the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
* `localName` property on the widget scope. The `name` is read from the parent scope (not
* component scope).
*
* * `=` or `=attr` - set up bi-directional binding between a local scope property and the
* parent scope property of name defined via the value of the `attr` attribute. If no `attr`
* name is specified then the attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="parentModel">` and widget definition of
* `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
* value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
* in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
* scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
* can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
* you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
* `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
*
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the
* local name. Given `<widget my-attr="count = count + value">` and widget definition of
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
* a function wrapper for the `count = count + value` expression. Often it's desirable to
* pass data from the isolated scope via an expression to the parent scope, this can be
* done by passing a map of local variable names and values into the expression wrapper fn.
* For example, if the expression is `increment(amount)` then we can specify the amount value
* by calling the `localFn` as `localFn({amount: 22})`.
*
*
* #### `bindToController`
* When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
* allow a component to have its properties bound to the controller, rather than to scope. When the controller
* is instantiated, the initial values of the isolate scope bindings are already available.
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and it is shared with other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function([scope], cloneLinkingFn, futureParentElement)`.
* * `scope`: optional argument to override the scope.
* * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
* * `futureParentElement`:
* * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
* * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
* * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
* and when the `cloneLinkinFn` is passed,
* as those elements need to created and cloned in a special way when they are defined outside their
* usual containers (e.g. like `<svg>`).
* * See also the `directive.templateNamespace` property.
*
*
* #### `require`
* Require another directive and inject its controller as the fourth argument to the linking function. The
* `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
* injected argument will be an array in corresponding order. If no such directive can be
* found, or if the directive does not have a controller, then an error is raised (unless no link function
* is specified, in which case error checking is skipped). The name can be prefixed with:
*
* * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
* * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
* * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
* * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
* * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
* `null` to the `link` fn if not found.
* * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
* `null` to the `link` fn if not found.
*
*
* #### `controllerAs`
* Identifier name for a reference to the controller in the directive's scope.
* This allows the controller to be referenced from the directive template. The directive
* needs to define a scope for this configuration to be used. Useful in the case when
* directive is used as component.
*
*
* #### `restrict`
* String of subset of `EACM` which restricts the directive to a specific directive
* declaration style. If omitted, the defaults (elements and attributes) are used.
*
* * `E` - Element name (default): `<my-directive></my-directive>`
* * `A` - Attribute (default): `<div my-directive="exp"></div>`
* * `C` - Class: `<div class="my-directive: exp;"></div>`
* * `M` - Comment: `<!-- directive: my-directive exp -->`
*
*
* #### `templateNamespace`
* String representing the document type used by the markup in the template.
* AngularJS needs this information as those elements need to be created and cloned
* in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
*
* * `html` - All root nodes in the template are HTML. Root nodes may also be
* top-level elements such as `<svg>` or `<math>`.
* * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
* * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
*
* If no `templateNamespace` is specified, then the namespace is considered to be `html`.
*
* #### `template`
* HTML markup that may:
* * Replace the contents of the directive's element (default).
* * Replace the directive's element itself (if `replace` is true - DEPRECATED).
* * Wrap the contents of the directive's element (if `transclude` is true).
*
* Value may be:
*
* * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
* * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
* function api below) and returns a string value.
*
*
* #### `templateUrl`
* This is similar to `template` but the template is loaded from the specified URL, asynchronously.
*
* Because template loading is asynchronous the compiler will suspend compilation of directives on that element
* for later when the template has been resolved. In the meantime it will continue to compile and link
* sibling and parent elements as though this element had not contained any directives.
*
* The compiler does not suspend the entire compilation to wait for templates to be loaded because this
* would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
* case when only one deeply nested directive has `templateUrl`.
*
* Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
*
* You can specify `templateUrl` as a string representing the URL or as a function which takes two
* arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
* a string value representing the url. In either case, the template URL is passed through {@link
* $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
*
*
* #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
* specify what the template should replace. Defaults to `false`.
*
* * `true` - the template will replace the directive's element.
* * `false` - the template will replace the contents of the directive's element.
*
* The replacement process migrates all of the attributes / classes from the old element to the new
* one. See the {@link guide/directive#template-expanding-directive
* Directives Guide} for an example.
*
* There are very few scenarios where element replacement is required for the application function,
* the main one being reusable custom components that are used within SVG contexts
* (because SVG doesn't work with custom elements in the DOM tree).
*
* #### `transclude`
* Extract the contents of the element where the directive appears and make it available to the directive.
* The contents are compiled and provided to the directive as a **transclusion function**. See the
* {@link $compile#transclusion Transclusion} section below.
*
* There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
* directive's element or the entire element:
*
* * `true` - transclude the content (i.e. the child nodes) of the directive's element.
* * `'element'` - transclude the whole of the directive's element including any directives on this
* element that defined at a lower priority than this directive. When used, the `template`
* property is ignored.
*
*
* #### `compile`
*
* ```js
* function compile(tElement, tAttrs, transclude) { ... }
* ```
*
* The compile function deals with transforming the template DOM. Since most directives do not do
* template transformation, it is not used often. The compile function takes the following arguments:
*
* * `tElement` - template element - The element where the directive has been declared. It is
* safe to do template transformation on the element and child elements only.
*
* * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
* between all directive compile functions.
*
* * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
*
* <div class="alert alert-warning">
* **Note:** The template instance and the link instance may be different objects if the template has
* been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
* apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
* should be done in a linking function rather than in a compile function.
* </div>
* <div class="alert alert-warning">
* **Note:** The compile function cannot handle directives that recursively use themselves in their
* own templates or compile functions. Compiling these directives results in an infinite loop and a
* stack overflow errors.
*
* This can be avoided by manually using $compile in the postLink function to imperatively compile
* a directive's template instead of relying on automatic template compilation via `template` or
* `templateUrl` declaration or manual compilation inside the compile function.
* </div>
*
* <div class="alert alert-danger">
* **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
* e.g. does not know about the right outer scope. Please use the transclude function that is passed
* to the link function instead.
* </div>
* A compile function can have a return value which can be either a function or an object.
*
* * returning a (post-link) function - is equivalent to registering the linking function via the
* `link` property of the config object when the compile function is empty.
*
* * returning an object with function(s) registered via `pre` and `post` properties - allows you to
* control when a linking function should be called during the linking phase. See info about
* pre-linking and post-linking functions below.
*
*
* #### `link`
* This property is used only if the `compile` property is not defined.
*
* ```js
* function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
* ```
*
* The link function is responsible for registering DOM listeners as well as updating the DOM. It is
* executed after the template has been cloned. This is where most of the directive logic will be
* put.
*
* * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
* directive for registering {@link ng.$rootScope.Scope#$watch watches}.
*
* * `iElement` - instance element - The element where the directive is to be used. It is safe to
* manipulate the children of the element only in `postLink` function since the children have
* already been linked.
*
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
* between all directive linking functions.
*
* * `controller` - the directive's required controller instance(s) - Instances are shared
* among all directives, which allows the directives to use the controllers as a communication
* channel. The exact value depends on the directive's `require` property:
* * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
* * `string`: the controller instance
* * `array`: array of controller instances
*
* If a required controller cannot be found, and it is optional, the instance is `null`,
* otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
*
* Note that you can also require the directive's own controller - it will be made available like
* any other controller.
*
* * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
* This is the same as the `$transclude`
* parameter of directive controllers, see there for details.
* `function([scope], cloneLinkingFn, futureParentElement)`.
*
* #### Pre-linking function
*
* Executed before the child elements are linked. Not safe to do DOM transformation since the
* compiler linking function will fail to locate the correct elements for linking.
*
* #### Post-linking function
*
* Executed after the child elements are linked.
*
* Note that child elements that contain `templateUrl` directives will not have been compiled
* and linked since they are waiting for their template to load asynchronously and their own
* compilation and linking has been suspended until that occurs.
*
* It is safe to do DOM transformation in the post-linking function on elements that are not waiting
* for their async templates to be resolved.
*
*
* ### Transclusion
*
* Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
* copying them to another part of the DOM, while maintaining their connection to the original AngularJS
* scope from where they were taken.
*
* Transclusion is used (often with {@link ngTransclude}) to insert the
* original contents of a directive's element into a specified place in the template of the directive.
* The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
* content has access to the properties on the scope from which it was taken, even if the directive
* has isolated scope.
* See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
*
* This makes it possible for the widget to have private state for its template, while the transcluded
* content has access to its originating scope.
*
* <div class="alert alert-warning">
* **Note:** When testing an element transclude directive you must not place the directive at the root of the
* DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
* Testing Transclusion Directives}.
* </div>
*
* #### Transclusion Functions
*
* When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
* function** to the directive's `link` function and `controller`. This transclusion function is a special
* **linking function** that will return the compiled contents linked to a new transclusion scope.
*
* <div class="alert alert-info">
* If you are just using {@link ngTransclude} then you don't need to worry about this function, since
* ngTransclude will deal with it for us.
* </div>
*
* If you want to manually control the insertion and removal of the transcluded content in your directive
* then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
* object that contains the compiled DOM, which is linked to the correct transclusion scope.
*
* When you call a transclusion function you can pass in a **clone attach function**. This function accepts
* two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
* content and the `scope` is the newly created transclusion scope, to which the clone is bound.
*
* <div class="alert alert-info">
* **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
* since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
* </div>
*
* It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
* attach function**:
*
* ```js
* var transcludedContent, transclusionScope;
*
* $transclude(function(clone, scope) {
* element.append(clone);
* transcludedContent = clone;
* transclusionScope = scope;
* });
* ```
*
* Later, if you want to remove the transcluded content from your DOM then you should also destroy the
* associated transclusion scope:
*
* ```js
* transcludedContent.remove();
* transclusionScope.$destroy();
* ```
*
* <div class="alert alert-info">
* **Best Practice**: if you intend to add and remove transcluded content manually in your directive
* (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
* then you are also responsible for calling `$destroy` on the transclusion scope.
* </div>
*
* The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
* automatically destroy their transluded clones as necessary so you do not need to worry about this if
* you are simply using {@link ngTransclude} to inject the transclusion into your directive.
*
*
* #### Transclusion Scopes
*
* When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
* scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
* when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
* was taken.
*
* For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
* like this:
*
* ```html
* <div ng-app>
* <div isolate>
* <div transclusion>
* </div>
* </div>
* </div>
* ```
*
* The `$parent` scope hierarchy will look like this:
*
* ```
* - $rootScope
* - isolate
* - transclusion
* ```
*
* but the scopes will inherit prototypically from different scopes to their `$parent`.
*
* ```
* - $rootScope
* - transclusion
* - isolate
* ```
*
*
* ### Attributes
*
* The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
* `link()` or `compile()` functions. It has a variety of uses.
*
* accessing *Normalized attribute names:*
* Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
* the attributes object allows for normalized access to
* the attributes.
*
* * *Directive inter-communication:* All directives share the same instance of the attributes
* object which allows the directives to use the attributes object as inter directive
* communication.
*
* * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
* allowing other directives to read the interpolated value.
*
* * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
* that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
* the only way to easily get the actual value because during the linking phase the interpolation
* hasn't been evaluated yet and so the value is at this time set to `undefined`.
*
* ```js
* function linkingFn(scope, elm, attrs, ctrl) {
* // get the attribute value
* console.log(attrs.ngModel);
*
* // change the attribute
* attrs.$set('ngModel', 'new value');
*
* // observe changes to interpolated attribute
* attrs.$observe('ngModel', function(value) {
* console.log('ngModel has changed value to ' + value);
* });
* }
* ```
*
* ## Example
*
* <div class="alert alert-warning">
* **Note**: Typically directives are registered with `module.directive`. The example below is
* to illustrate how `$compile` works.
* </div>
*
<example module="compileExample">
<file name="index.html">
<script>
angular.module('compileExample', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
})
.controller('GreeterController', ['$scope', function($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}]);
</script>
<div ng-controller="GreeterController">
<input ng-model="name"> <br/>
<textarea ng-model="html"></textarea> <br/>
<div compile="html"></div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should auto compile', function() {
var textarea = $('textarea');
var output = $('div[compile]');
// The initial state reads 'Hello Angular'.
expect(output.getText()).toBe('Hello Angular');
textarea.clear();
textarea.sendKeys('{{name}}!');
expect(output.getText()).toBe('Angular!');
});
</file>
</example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
*
* <div class="alert alert-danger">
* **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
* e.g. will not use the right outer scope. Please pass the transclude function as a
* `parentBoundTranscludeFn` to the link function instead.
* </div>
*
* @param {number} maxPriority only apply directives lower than given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* * `options` - An optional object hash with linking options. If `options` is provided, then the following
* keys may be used to control linking behavior:
*
* * `parentBoundTranscludeFn` - the transclude function made available to
* directives; if given, it will be passed through to the link functions of
* directives found in `element` during compilation.
* * `transcludeControllers` - an object hash with keys that map controller names
* to controller instances; if given, it will make the controllers
* available to directives.
* * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
* the cloned elements; only needed for transcludes that are allowed to contain non html
* elements (e.g. SVG elements). See also the directive.controller property.
*
* Calling the linking function returns the element of the template. It is either the original
* element passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* ```js
* var element = $compile('<p>{{total}}</p>')(scope);
* ```
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* ```js
* var templateElement = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clonedElement`
* ```
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
var $compileMinErr = minErr('$compile');
/**
* @ngdoc provider
* @name $compileProvider
*
* @description
*/
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
function $CompileProvider($provide, $$sanitizeUriProvider) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
// The assumption is that future DOM event attribute names will begin with
// 'on' and be composed of only English letters.
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
function parseIsolateBindings(scope, directiveName, isController) {
var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
var bindings = {};
forEach(scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP);
if (!match) {
throw $compileMinErr('iscp',
"Invalid {3} for directive '{0}'." +
" Definition: {... {1}: '{2}' ...}",
directiveName, scopeName, definition,
(isController ? "controller bindings definition" :
"isolate scope definition"));
}
bindings[scopeName] = {
mode: match[1][0],
collection: match[2] === '*',
optional: match[3] === '?',
attrName: match[4] || scopeName
};
});
return bindings;
}
function parseDirectiveBindings(directive, directiveName) {
var bindings = {
isolateScope: null,
bindToController: null
};
if (isObject(directive.scope)) {
if (directive.bindToController === true) {
bindings.bindToController = parseIsolateBindings(directive.scope,
directiveName, true);
bindings.isolateScope = {};
} else {
bindings.isolateScope = parseIsolateBindings(directive.scope,
directiveName, false);
}
}
if (isObject(directive.bindToController)) {
bindings.bindToController =
parseIsolateBindings(directive.bindToController, directiveName, true);
}
if (isObject(bindings.bindToController)) {
var controller = directive.controller;
var controllerAs = directive.controllerAs;
if (!controller) {
// There is no controller, there may or may not be a controllerAs property
throw $compileMinErr('noctrl',
"Cannot bind to controller without directive '{0}'s controller.",
directiveName);
} else if (!identifierForController(controller, controllerAs)) {
// There is a controller, but no identifier or controllerAs property
throw $compileMinErr('noident',
"Cannot bind to controller without identifier for directive '{0}'.",
directiveName);
}
}
return bindings;
}
function assertValidDirectiveName(name) {
var letter = name.charAt(0);
if (!letter || letter !== lowercase(letter)) {
throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
}
if (name !== name.trim()) {
throw $compileMinErr('baddir',
"Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
name);
}
}
/**
* @ngdoc method
* @name $compileProvider#directive
* @kind function
*
* @description
* Register a new directive with the compiler.
*
* @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
* will match as <code>ng-bind</code>), or an object map of directives where the keys are the
* names and the values are the factories.
* @param {Function|Array} directiveFactory An injectable directive factory function. See
* {@link guide/directive} for more info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
assertNotHasOwnProperty(name, 'directive');
if (isString(name)) {
assertValidDirectiveName(name);
assertArg(directiveFactory, 'directiveFactory');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory, index) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.index = index;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'EA';
var bindings = directive.$$bindings =
parseDirectiveBindings(directive, directive.name);
if (isObject(bindings.isolateScope)) {
directive.$$isolateBindings = bindings.isolateScope;
}
directive.$$moduleName = directiveFactory.$$moduleName;
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc method
* @name $compileProvider#aHrefSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at preventing XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#imgSrcSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#debugInfoEnabled
*
* @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
* current debugInfoEnabled state
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*
* @kind function
*
* @description
* Call this method to enable/disable various debug runtime information in the compiler such as adding
* binding information and a reference to the current scope on to DOM elements.
* If enabled, the compiler will add the following to DOM elements that have been bound to the scope
* * `ng-binding` CSS class
* * `$binding` data property containing an array of the binding expressions
*
* You may want to disable this in production for a significant performance boost. See
* {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
*
* The default value is true.
*/
var debugInfoEnabled = true;
this.debugInfoEnabled = function(enabled) {
if (isDefined(enabled)) {
debugInfoEnabled = enabled;
return this;
}
return debugInfoEnabled;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
'$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
$controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
var Attributes = function(element, attributesToCopy) {
if (attributesToCopy) {
var keys = Object.keys(attributesToCopy);
var i, l, key;
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
this[key] = attributesToCopy[key];
}
} else {
this.$attr = {};
}
this.$$element = element;
};
Attributes.prototype = {
/**
* @ngdoc method
* @name $compile.directive.Attributes#$normalize
* @kind function
*
* @description
* Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
* `data-`) to its normalized, camelCase form.
*
* Also there is special case for Moz prefix starting with upper case letter.
*
* For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
*
* @param {string} name Name to normalize
*/
$normalize: directiveNormalize,
/**
* @ngdoc method
* @name $compile.directive.Attributes#$addClass
* @kind function
*
* @description
* Adds the CSS class value specified by the classVal parameter to the element. If animations
* are enabled then an animation will be triggered for the class addition.
*
* @param {string} classVal The className value that will be added to the element
*/
$addClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.addClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$removeClass
* @kind function
*
* @description
* Removes the CSS class value specified by the classVal parameter from the element. If
* animations are enabled then an animation will be triggered for the class removal.
*
* @param {string} classVal The className value that will be removed from the element
*/
$removeClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.removeClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$updateClass
* @kind function
*
* @description
* Adds and removes the appropriate CSS class values to the element based on the difference
* between the new and old CSS class values (specified as newClasses and oldClasses).
*
* @param {string} newClasses The current CSS className value
* @param {string} oldClasses The former CSS className value
*/
$updateClass: function(newClasses, oldClasses) {
var toAdd = tokenDifference(newClasses, oldClasses);
if (toAdd && toAdd.length) {
$animate.addClass(this.$$element, toAdd);
}
var toRemove = tokenDifference(oldClasses, newClasses);
if (toRemove && toRemove.length) {
$animate.removeClass(this.$$element, toRemove);
}
},
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
// TODO: decide whether or not to throw an error if "class"
//is set through this function since it may cause $updateClass to
//become unstable.
var node = this.$$element[0],
booleanKey = getBooleanAttrName(node, key),
aliasedKey = getAliasedAttrName(node, key),
observer = key,
nodeName;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
} else if (aliasedKey) {
this[aliasedKey] = value;
observer = aliasedKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
nodeName = nodeName_(this.$$element);
if ((nodeName === 'a' && key === 'href') ||
(nodeName === 'img' && key === 'src')) {
// sanitize a[href] and img[src] values
this[key] = value = $$sanitizeUri(value, key === 'src');
} else if (nodeName === 'img' && key === 'srcset') {
// sanitize img[srcset] values
var result = "";
// first check if there are spaces because it's not the same pattern
var trimmedSrcset = trim(value);
// ( 999x ,| 999w ,| ,|, )
var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
// split srcset into tuple of uri and descriptor except for the last item
var rawUris = trimmedSrcset.split(pattern);
// for each tuples
var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
for (var i = 0; i < nbrUrisWith2parts; i++) {
var innerIdx = i * 2;
// sanitize the uri
result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
// add the descriptor
result += (" " + trim(rawUris[innerIdx + 1]));
}
// split the last item into uri and descriptor
var lastTuple = trim(rawUris[i * 2]).split(/\s/);
// sanitize the last uri
result += $$sanitizeUri(trim(lastTuple[0]), true);
// and add the last descriptor if any
if (lastTuple.length === 2) {
result += (" " + trim(lastTuple[1]));
}
this[key] = value = result;
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
var $$observers = this.$$observers;
$$observers && forEach($$observers[observer], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$observe
* @kind function
*
* @description
* Observes an interpolated attribute.
*
* The observer function will be invoked once during the next `$digest` following
* compilation. The observer is then invoked whenever the interpolated value
* changes.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(interpolatedValue)} fn Function that will be called whenever
the interpolated value of the attribute changes.
* See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
* @returns {function()} Returns a deregistration function for this observer.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return function() {
arrayRemove(listeners, fn);
};
}
};
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch (e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
},
NG_ATTR_BINDING = /^ngAttr[A-Z]/;
compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
var bindings = $element.data('$binding') || [];
if (isArray(binding)) {
bindings = bindings.concat(binding);
} else {
bindings.push(binding);
}
$element.data('$binding', bindings);
} : noop;
compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
safeAddClass($element, 'ng-binding');
} : noop;
compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
$element.data(dataName, scope);
} : noop;
compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
} : noop;
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
previousCompileContext) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can
// modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index) {
if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn =
compileNodes($compileNodes, transcludeFn, $compileNodes,
maxPriority, ignoreDirective, previousCompileContext);
compile.$$addScopeClass($compileNodes);
var namespace = null;
return function publicLinkFn(scope, cloneConnectFn, options) {
assertArg(scope, 'scope');
options = options || {};
var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
transcludeControllers = options.transcludeControllers,
futureParentElement = options.futureParentElement;
// When `parentBoundTranscludeFn` is passed, it is a
// `controllersBoundTransclude` function (it was previously passed
// as `transclude` to directive.link) so we must unwrap it to get
// its `boundTranscludeFn`
if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
}
if (!namespace) {
namespace = detectNamespaceForChildElements(futureParentElement);
}
var $linkNode;
if (namespace !== 'html') {
// When using a directive with replace:true and templateUrl the $compileNodes
// (or a child element inside of them)
// might change, so we need to recreate the namespace adapted compileNodes
// for call to the link function.
// Note: This will already clone the nodes...
$linkNode = jqLite(
wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
);
} else if (cloneConnectFn) {
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
$linkNode = JQLitePrototype.clone.call($compileNodes);
} else {
$linkNode = $compileNodes;
}
if (transcludeControllers) {
for (var controllerName in transcludeControllers) {
$linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
}
}
compile.$$addScopeInfo($linkNode, scope);
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
return $linkNode;
};
}
function detectNamespaceForChildElements(parentElement) {
// TODO: Make this detect MathML as well...
var node = parentElement && parentElement[0];
if (!node) {
return 'html';
} else {
return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
* the rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} maxPriority Max directive priority.
* @returns {Function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
previousCompileContext) {
var linkFns = [],
attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
for (var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
null, [], [], previousCompileContext)
: null;
if (nodeLinkFn && nodeLinkFn.scope) {
compile.$$addScopeClass(attrs.$$element);
}
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
!(childNodes = nodeList[i].childNodes) ||
!childNodes.length)
? null
: compileNodes(childNodes,
nodeLinkFn ? (
(nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
&& nodeLinkFn.transclude) : transcludeFn);
if (nodeLinkFn || childLinkFn) {
linkFns.push(i, nodeLinkFn, childLinkFn);
linkFnFound = true;
nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
}
//use the previous context only for the first element in the virtual group
previousCompileContext = null;
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
var stableNodeList;
if (nodeLinkFnFound) {
// copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
// offsets don't get screwed up
var nodeListLength = nodeList.length;
stableNodeList = new Array(nodeListLength);
// create a sparse array by only copying the elements which have a linkFn
for (i = 0; i < linkFns.length; i+=3) {
idx = linkFns[i];
stableNodeList[idx] = nodeList[idx];
}
} else {
stableNodeList = nodeList;
}
for (i = 0, ii = linkFns.length; i < ii;) {
node = stableNodeList[linkFns[i++]];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new();
compile.$$addScopeInfo(jqLite(node), childScope);
var destroyBindings = nodeLinkFn.$$destroyBindings;
if (destroyBindings) {
nodeLinkFn.$$destroyBindings = null;
childScope.$on('$destroyed', destroyBindings);
}
} else {
childScope = scope;
}
if (nodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(
scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
} else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
childBoundTranscludeFn = parentBoundTranscludeFn;
} else if (!parentBoundTranscludeFn && transcludeFn) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
} else {
childBoundTranscludeFn = null;
}
nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
nodeLinkFn);
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
}
}
}
}
function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
if (!transcludedScope) {
transcludedScope = scope.$new(false, containingScope);
transcludedScope.$$transcluded = true;
}
return transcludeFn(transcludedScope, cloneFn, {
parentBoundTranscludeFn: previousBoundTranscludeFn,
transcludeControllers: controllers,
futureParentElement: futureParentElement
});
};
return boundTranscludeFn;
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch (nodeType) {
case NODE_TYPE_ELEMENT: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName = false;
var attrEndName = false;
attr = nAttrs[j];
name = attr.name;
value = trim(attr.value);
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
name = name.replace(PREFIX_REGEXP, '')
.substr(8).replace(/_(.)/g, function(match, letter) {
return letter.toUpperCase();
});
}
var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
if (directiveIsMultiElement(directiveNName)) {
if (ngAttrName === directiveNName + 'Start') {
attrStartName = name;
attrEndName = name.substr(0, name.length - 5) + 'end';
name = name.substr(0, name.length - 6);
}
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
if (isNgAttr || !attrs.hasOwnProperty(nName)) {
attrs[nName] = value;
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
}
addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
attrEndName);
}
// use class as directive
className = node.className;
if (isObject(className)) {
// Maybe SVGAnimatedString
className = className.animVal;
}
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case NODE_TYPE_TEXT: /* Text Node */
if (msie === 11) {
// Workaround for #11781
while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
node.parentNode.removeChild(node.nextSibling);
}
}
addTextInterpolateDirective(directives, node.nodeValue);
break;
case NODE_TYPE_COMMENT: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read
// comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Given a node with an directive-start it collects all of the siblings until it finds
* directive-end.
* @param node
* @param attrStart
* @param attrEnd
* @returns {*}
*/
function groupScan(node, attrStart, attrEnd) {
var nodes = [];
var depth = 0;
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
do {
if (!node) {
throw $compileMinErr('uterdir',
"Unterminated attribute, found '{0}' but no matching '{1}' found.",
attrStart, attrEnd);
}
if (node.nodeType == NODE_TYPE_ELEMENT) {
if (node.hasAttribute(attrStart)) depth++;
if (node.hasAttribute(attrEnd)) depth--;
}
nodes.push(node);
node = node.nextSibling;
} while (depth > 0);
} else {
nodes.push(node);
}
return jqLite(nodes);
}
/**
* Wrapper for linking function which converts normal linking function into a grouped
* linking function.
* @param linkFn
* @param attrStart
* @param attrEnd
* @returns {Function}
*/
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
return function(scope, element, attrs, controllers, transcludeFn) {
element = groupScan(element[0], attrStart, attrEnd);
return linkFn(scope, element, attrs, controllers, transcludeFn);
};
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new
* child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes
* on it.
* @param {Object=} originalReplaceDirective An optional directive that will be ignored when
* compiling the transclusion.
* @param {Array.<Function>} preLinkFns
* @param {Array.<Function>} postLinkFns
* @param {Object} previousCompileContext Context used for previous compilation of the current
* node
* @returns {Function} linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
previousCompileContext) {
previousCompileContext = previousCompileContext || {};
var terminalPriority = -Number.MAX_VALUE,
newScopeDirective = previousCompileContext.newScopeDirective,
controllerDirectives = previousCompileContext.controllerDirectives,
newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
templateDirective = previousCompileContext.templateDirective,
nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
hasTranscludeDirective = false,
hasTemplate = false,
hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
replaceDirective = originalReplaceDirective,
childTranscludeFn = transcludeFn,
linkFn,
directiveValue;
// executes all directives on the current element
for (var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
var attrStart = directive.$$start;
var attrEnd = directive.$$end;
// collect multiblock sections
if (attrStart) {
$compileNode = groupScan(compileNode, attrStart, attrEnd);
}
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
// skip the check for directives with async templates, we'll check the derived sync
// directive when the template arrives
if (!directive.templateUrl) {
if (isObject(directiveValue)) {
// This directive is trying to add an isolated scope.
// Check that there is no scope of any kind already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
directive, $compileNode);
newIsolateScopeDirective = directive;
} else {
// This directive is trying to add a child scope.
// Check that there is no isolated scope already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
$compileNode);
}
}
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (!directive.templateUrl && directive.controller) {
directiveValue = directive.controller;
controllerDirectives = controllerDirectives || createMap();
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
hasTranscludeDirective = true;
// Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
// This option should only be used by directives that know how to safely handle element transclusion,
// where the transcluded nodes are added or replaced after linking.
if (!directive.$$tlb) {
assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
nonTlbTranscludeDirective = directive;
}
if (directiveValue == 'element') {
hasElementTranscludeDirective = true;
terminalPriority = directive.priority;
$template = $compileNode;
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' +
templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, sliceArgs($template), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name, {
// Don't pass in:
// - controllerDirectives - otherwise we'll create duplicates controllers
// - newIsolateScopeDirective or templateDirective - combining templates with
// element transclusion doesn't make sense.
//
// We need only nonTlbTranscludeDirective so that we prevent putting transclusion
// on the same element more than once.
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
} else {
$template = jqLite(jqLiteClone(compileNode)).contents();
$compileNode.empty(); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directive.template) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = (isFunction(directive.template))
? directive.template($compileNode, templateAttrs)
: directive.template;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
replaceDirective = directive;
if (jqLiteIsTextNode(directiveValue)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
// - collect directives from the template and sort them by priority
// - combine directives as: processed + template + unprocessed
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
if (newIsolateScopeDirective) {
markDirectivesAsIsolate(templateDirectives);
}
directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
controllerDirectives: controllerDirectives,
newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
newIsolateScopeDirective: newIsolateScopeDirective,
templateDirective: templateDirective,
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn, attrStart, attrEnd);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
nodeLinkFn.templateOnThisElement = hasTemplate;
nodeLinkFn.transclude = childTranscludeFn;
previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post, attrStart, attrEnd) {
if (pre) {
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
pre.require = directive.require;
pre.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
pre = cloneAndAnnotateFn(pre, {isolateScope: true});
}
preLinkFns.push(pre);
}
if (post) {
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
post.require = directive.require;
post.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
post = cloneAndAnnotateFn(post, {isolateScope: true});
}
postLinkFns.push(post);
}
}
function getControllers(directiveName, require, $element, elementControllers) {
var value;
if (isString(require)) {
var match = require.match(REQUIRE_PREFIX_REGEXP);
var name = require.substring(match[0].length);
var inheritType = match[1] || match[3];
var optional = match[2] === '?';
//If only parents then start at the parent element
if (inheritType === '^^') {
$element = $element.parent();
//Otherwise attempt getting the controller from elementControllers in case
//the element is transcluded (and has no data) and to avoid .data if possible
} else {
value = elementControllers && elementControllers[name];
value = value && value.instance;
}
if (!value) {
var dataName = '$' + name + 'Controller';
value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
}
if (!value && !optional) {
throw $compileMinErr('ctreq',
"Controller '{0}', required by directive '{1}', can't be found!",
name, directiveName);
}
} else if (isArray(require)) {
value = [];
for (var i = 0, ii = require.length; i < ii; i++) {
value[i] = getControllers(directiveName, require[i], $element, elementControllers);
}
}
return value || null;
}
function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
var elementControllers = createMap();
for (var controllerKey in controllerDirectives) {
var directive = controllerDirectives[controllerKey];
var locals = {
$scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
$element: $element,
$attrs: attrs,
$transclude: transcludeFn
};
var controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
// For directives with element transclusion the element is a comment,
// but jQuery .data doesn't support attaching data to comment nodes as it's hard to
// clean up (http://bugs.jquery.com/ticket/8335).
// Instead, we save the controllers for the element in a local hash and attach to .data
// later, once we have the actual element.
elementControllers[directive.name] = controllerInstance;
if (!hasElementTranscludeDirective) {
$element.data('$' + directive.name + 'Controller', controllerInstance.instance);
}
}
return elementControllers;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
thisLinkFn) {
var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
attrs;
if (compileNode === linkNode) {
attrs = templateAttrs;
$element = templateAttrs.$$element;
} else {
$element = jqLite(linkNode);
attrs = new Attributes($element, templateAttrs);
}
if (newIsolateScopeDirective) {
isolateScope = scope.$new(true);
}
if (boundTranscludeFn) {
// track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
// is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
transcludeFn = controllersBoundTransclude;
transcludeFn.$$boundTransclude = boundTranscludeFn;
}
if (controllerDirectives) {
elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
}
if (newIsolateScopeDirective) {
// Initialize isolate scope bindings for new isolate scope directive.
compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
templateDirective === newIsolateScopeDirective.$$originalDirective)));
compile.$$addScopeClass($element, true);
isolateScope.$$isolateBindings =
newIsolateScopeDirective.$$isolateBindings;
initializeDirectiveBindings(scope, attrs, isolateScope,
isolateScope.$$isolateBindings,
newIsolateScopeDirective, isolateScope);
}
if (elementControllers) {
// Initialize bindToController bindings for new/isolate scopes
var scopeDirective = newIsolateScopeDirective || newScopeDirective;
var bindings;
var controllerForBindings;
if (scopeDirective && elementControllers[scopeDirective.name]) {
bindings = scopeDirective.$$bindings.bindToController;
controller = elementControllers[scopeDirective.name];
if (controller && controller.identifier && bindings) {
controllerForBindings = controller;
thisLinkFn.$$destroyBindings =
initializeDirectiveBindings(scope, attrs, controller.instance,
bindings, scopeDirective);
}
}
for (i in elementControllers) {
controller = elementControllers[i];
var controllerResult = controller();
if (controllerResult !== controller.instance) {
// If the controller constructor has a return value, overwrite the instance
// from setupControllers and update the element data
controller.instance = controllerResult;
$element.data('$' + i + 'Controller', controllerResult);
if (controller === controllerForBindings) {
// Remove and re-install bindToController bindings
thisLinkFn.$$destroyBindings();
thisLinkFn.$$destroyBindings =
initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
}
}
}
}
// PRELINKING
for (i = 0, ii = preLinkFns.length; i < ii; i++) {
linkFn = preLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// RECURSION
// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.
var scopeToChild = scope;
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
scopeToChild = isolateScope;
}
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for (i = postLinkFns.length - 1; i >= 0; i--) {
linkFn = postLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// This is the function that is injected as `$transclude`.
// Note: all arguments are optional!
function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
var transcludeControllers;
// No scope passed in:
if (!isScope(scope)) {
futureParentElement = cloneAttachFn;
cloneAttachFn = scope;
scope = undefined;
}
if (hasElementTranscludeDirective) {
transcludeControllers = elementControllers;
}
if (!futureParentElement) {
futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
}
return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
}
}
}
function markDirectivesAsIsolate(directives) {
// mark all directives as needing isolate scope.
for (var j = 0, jj = directives.length; j < jj; j++) {
directives[j] = inherit(directives[j], {$$isolateScope: true});
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns {boolean} true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
endAttrName) {
if (name === ignoreDirective) return null;
var match = null;
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
try {
directive = directives[i];
if ((maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
if (startAttrName) {
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
}
tDirectives.push(directive);
match = directive;
}
} catch (e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* looks up the directive and returns true if it is a multi-element directive,
* and therefore requires DOM nodes between -start and -end markers to be grouped
* together.
*
* @param {string} name name of the directive to look up.
* @returns true if directive was registered as multi-element.
*/
function directiveIsMultiElement(name) {
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
if (directive.multiElement) {
return true;
}
}
}
return false;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key] && src[key] !== value) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
// `dst` will never contain hasOwnProperty as DOM parser won't let it.
// You will get an "InvalidCharacterError: DOM Exception 5" error if you
// have an attribute like "has-own-property" or "data-has-own-property", etc.
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, $compileNode, tAttrs,
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
derivedSyncDirective = inherit(origAsyncDirective, {
templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
}),
templateUrl = (isFunction(origAsyncDirective.templateUrl))
? origAsyncDirective.templateUrl($compileNode, tAttrs)
: origAsyncDirective.templateUrl,
templateNamespace = origAsyncDirective.templateNamespace;
$compileNode.empty();
$templateRequest(templateUrl)
.then(function(content) {
var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
content = denormalizeTemplate(content);
if (origAsyncDirective.replace) {
if (jqLiteIsTextNode(content)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(templateNamespace, trim(content)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
origAsyncDirective.name, templateUrl);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
if (isObject(origAsyncDirective.scope)) {
markDirectivesAsIsolate(templateDirectives);
}
directives = templateDirectives.concat(directives);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
previousCompileContext);
forEach($rootElement, function(node, i) {
if (node == compileNode) {
$rootElement[i] = $compileNode[0];
}
});
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while (linkQueue.length) {
var scope = linkQueue.shift(),
beforeTemplateLinkNode = linkQueue.shift(),
linkRootElement = linkQueue.shift(),
boundTranscludeFn = linkQueue.shift(),
linkNode = $compileNode[0];
if (scope.$$destroyed) continue;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
var oldClasses = beforeTemplateLinkNode.className;
if (!(previousCompileContext.hasElementTranscludeDirective &&
origAsyncDirective.replace)) {
// it was cloned therefore we have to clone as well.
linkNode = jqLiteClone(compileNode);
}
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
// Copy in CSS classes from original node
safeAddClass(jqLite(linkNode), oldClasses);
}
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
} else {
childBoundTranscludeFn = boundTranscludeFn;
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
childBoundTranscludeFn, afterTemplateNodeLinkFn);
}
linkQueue = null;
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
var childBoundTranscludeFn = boundTranscludeFn;
if (scope.$$destroyed) return;
if (linkQueue) {
linkQueue.push(scope,
node,
rootElement,
childBoundTranscludeFn);
} else {
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
afterTemplateNodeLinkFn);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
var diff = b.priority - a.priority;
if (diff !== 0) return diff;
if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
return a.index - b.index;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
function wrapModuleNameIfDefined(moduleName) {
return moduleName ?
(' (module: ' + moduleName + ')') :
'';
}
if (previousDirective) {
throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: function textInterpolateCompileFn(templateNode) {
var templateNodeParent = templateNode.parent(),
hasCompileParent = !!templateNodeParent.length;
// When transcluding a template that has bindings in the root
// we don't have a parent and thus need to add the class during linking fn.
if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
return function textInterpolateLinkFn(scope, node) {
var parent = node.parent();
if (!hasCompileParent) compile.$$addBindingClass(parent);
compile.$$addBindingInfo(parent, interpolateFn.expressions);
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
};
}
});
}
}
function wrapTemplate(type, template) {
type = lowercase(type || 'html');
switch (type) {
case 'svg':
case 'math':
var wrapper = document.createElement('div');
wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
return wrapper.childNodes[0].childNodes;
default:
return template;
}
}
function getTrustedContext(node, attrNormalizedName) {
if (attrNormalizedName == "srcdoc") {
return $sce.HTML;
}
var tag = nodeName_(node);
// maction[xlink:href] can source SVG. It's not limited to <maction>.
if (attrNormalizedName == "xlinkHref" ||
(tag == "form" && attrNormalizedName == "action") ||
(tag != "img" && (attrNormalizedName == "src" ||
attrNormalizedName == "ngSrc"))) {
return $sce.RESOURCE_URL;
}
}
function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
var trustedContext = getTrustedContext(node, name);
allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
// no interpolation found -> ignore
if (!interpolateFn) return;
if (name === "multiple" && nodeName_(node) === "select") {
throw $compileMinErr("selmulti",
"Binding to the 'multiple' attribute is not supported. Element: {0}",
startingTag(node));
}
directives.push({
priority: 100,
compile: function() {
return {
pre: function attrInterpolatePreLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
throw $compileMinErr('nodomevents',
"Interpolations for HTML DOM event attributes are disallowed. Please use the " +
"ng- versions (such as ng-click instead of onclick) instead.");
}
// If the attribute has changed since last $interpolate()ed
var newValue = attr[name];
if (newValue !== value) {
// we need to interpolate again since the attribute value has been updated
// (e.g. by another directive's compile function)
// ensure unset/empty values make interpolateFn falsy
interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
value = newValue;
}
// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
if (!interpolateFn) return;
// initialize attr object so that it's ready in case we need the value for isolate
// scope initialization, otherwise the value would not be available from isolate
// directive's linking fn during linking phase
attr[name] = interpolateFn(scope);
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
//special case for class attribute addition + removal
//so that class changes can tap into the animation
//hooks provided by the $animate service. Be sure to
//skip animations when the first digest occurs (when
//both the new and the old values are the same) since
//the CSS classes are the non-interpolated values
if (name === 'class' && newValue != oldValue) {
attr.$updateClass(newValue, oldValue);
} else {
attr.$set(name, newValue);
}
});
}
};
}
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
* the shell, but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, elementsToRemove, newNode) {
var firstElementToRemove = elementsToRemove[0],
removeCount = elementsToRemove.length,
parent = firstElementToRemove.parentNode,
i, ii;
if ($rootElement) {
for (i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == firstElementToRemove) {
$rootElement[i++] = newNode;
for (var j = i, j2 = j + removeCount - 1,
jj = $rootElement.length;
j < jj; j++, j2++) {
if (j2 < jj) {
$rootElement[j] = $rootElement[j2];
} else {
delete $rootElement[j];
}
}
$rootElement.length -= removeCount - 1;
// If the replaced element is also the jQuery .context then replace it
// .context is a deprecated jQuery api, so we should set it only when jQuery set it
// http://api.jquery.com/context/
if ($rootElement.context === firstElementToRemove) {
$rootElement.context = newNode;
}
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, firstElementToRemove);
}
// TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
var fragment = document.createDocumentFragment();
fragment.appendChild(firstElementToRemove);
if (jqLite.hasData(firstElementToRemove)) {
// Copy over user data (that includes Angular's $scope etc.). Don't copy private
// data here because there's no public interface in jQuery to do that and copying over
// event listeners (which is the main use of private data) wouldn't work anyway.
jqLite(newNode).data(jqLite(firstElementToRemove).data());
// Remove data of the replaced element. We cannot just call .remove()
// on the element it since that would deallocate scope that is needed
// for the new node. Instead, remove the data "manually".
if (!jQuery) {
delete jqLite.cache[firstElementToRemove[jqLite.expando]];
} else {
// jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
// the replaced element. The cleanData version monkey-patched by Angular would cause
// the scope to be trashed and we do need the very same scope to work with the new
// element. However, we cannot just cache the non-patched version and use it here as
// that would break if another library patches the method after Angular does (one
// example is jQuery UI). Instead, set a flag indicating scope destroying should be
// skipped this one time.
skipDestroyOnNextJQueryCleanData = true;
jQuery.cleanData([firstElementToRemove]);
}
}
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
var element = elementsToRemove[k];
jqLite(element).remove(); // must do this way to clean up expando
fragment.appendChild(element);
delete elementsToRemove[k];
}
elementsToRemove[0] = newNode;
elementsToRemove.length = 1;
}
function cloneAndAnnotateFn(fn, annotation) {
return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
}
function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
try {
linkFn(scope, $element, attrs, controllers, transcludeFn);
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// Set up $watches for isolate scope and controller bindings. This process
// only occurs for isolate scopes and new scopes with controllerAs.
function initializeDirectiveBindings(scope, attrs, destination, bindings,
directive, newScope) {
var onNewScopeDestroyed;
forEach(bindings, function(definition, scopeName) {
var attrName = definition.attrName,
optional = definition.optional,
mode = definition.mode, // @, =, or &
lastValue,
parentGet, parentSet, compare;
switch (mode) {
case '@':
if (!optional && !hasOwnProperty.call(attrs, attrName)) {
destination[scopeName] = attrs[attrName] = void 0;
}
attrs.$observe(attrName, function(value) {
if (isString(value)) {
destination[scopeName] = value;
}
});
attrs.$$observers[attrName].$$scope = scope;
if (isString(attrs[attrName])) {
// If the attribute has been provided then we trigger an interpolation to ensure
// the value is there for use in the link fn
destination[scopeName] = $interpolate(attrs[attrName])(scope);
}
break;
case '=':
if (!hasOwnProperty.call(attrs, attrName)) {
if (optional) break;
attrs[attrName] = void 0;
}
if (optional && !attrs[attrName]) break;
parentGet = $parse(attrs[attrName]);
if (parentGet.literal) {
compare = equals;
} else {
compare = function(a, b) { return a === b || (a !== a && b !== b); };
}
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = destination[scopeName] = parentGet(scope);
throw $compileMinErr('nonassign',
"Expression '{0}' used with directive '{1}' is non-assignable!",
attrs[attrName], directive.name);
};
lastValue = destination[scopeName] = parentGet(scope);
var parentValueWatch = function parentValueWatch(parentValue) {
if (!compare(parentValue, destination[scopeName])) {
// we are out of sync and need to copy
if (!compare(parentValue, lastValue)) {
// parent changed and it has precedence
destination[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(scope, parentValue = destination[scopeName]);
}
}
return lastValue = parentValue;
};
parentValueWatch.$stateful = true;
var unwatch;
if (definition.collection) {
unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
} else {
unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
}
onNewScopeDestroyed = (onNewScopeDestroyed || []);
onNewScopeDestroyed.push(unwatch);
break;
case '&':
// Don't assign Object.prototype method to scope
parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
// Don't assign noop to destination if expression is not valid
if (parentGet === noop && optional) break;
destination[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
}
});
var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
onNewScopeDestroyed[i]();
}
} : noop;
if (newScope && destroyBindings !== noop) {
newScope.$on('$destroy', destroyBindings);
return noop;
}
return destroyBindings;
}
}];
}
var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc type
* @name $compile.directive.Attributes
*
* @description
* A shared object between directive compile / linking functions which contains normalized DOM
* element attributes. The values reflect current binding state `{{ }}`. The normalization is
* needed since all of these are treated as equivalent in Angular:
*
* ```
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
* ```
*/
/**
* @ngdoc property
* @name $compile.directive.Attributes#$attr
*
* @description
* A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc method
* @name $compile.directive.Attributes#$set
* @kind function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to. The value can be an interpolated string.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function tokenDifference(str1, str2) {
var values = '',
tokens1 = str1.split(/\s+/),
tokens2 = str2.split(/\s+/);
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values += (values.length > 0 ? ' ' : '') + token;
}
return values;
}
function removeComments(jqNodes) {
jqNodes = jqLite(jqNodes);
var i = jqNodes.length;
if (i <= 1) {
return jqNodes;
}
while (i--) {
var node = jqNodes[i];
if (node.nodeType === NODE_TYPE_COMMENT) {
splice.call(jqNodes, i, 1);
}
}
return jqNodes;
}
var $controllerMinErr = minErr('$controller');
var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
function identifierForController(controller, ident) {
if (ident && isString(ident)) return ident;
if (isString(controller)) {
var match = CNTRL_REG.exec(controller);
if (match) return match[3];
}
}
/**
* @ngdoc provider
* @name $controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {},
globals = false;
/**
* @ngdoc method
* @name $controllerProvider#register
* @param {string|Object} name Controller name, or an object map of controllers where the keys are
* the names and the values are the constructors.
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
assertNotHasOwnProperty(name, 'controller');
if (isObject(name)) {
extend(controllers, name);
} else {
controllers[name] = constructor;
}
};
/**
* @ngdoc method
* @name $controllerProvider#allowGlobals
* @description If called, allows `$controller` to find controller constructors on `window`
*/
this.allowGlobals = function() {
globals = true;
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc service
* @name $controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
* `window` object (not recommended)
*
* The string can use the `controller as property` syntax, where the controller instance is published
* as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
* to work correctly.
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link auto.$injector $injector}, but extracted into
* a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
*/
return function(expression, locals, later, ident) {
// PRIVATE API:
// param `later` --- indicates that the controller's constructor is invoked at a later time.
// If true, $controller will allocate the object with the correct
// prototype chain, but will not invoke the controller until a returned
// callback is invoked.
// param `ident` --- An optional label which overrides the label parsed from the controller
// expression, if any.
var instance, match, constructor, identifier;
later = later === true;
if (ident && isString(ident)) {
identifier = ident;
}
if (isString(expression)) {
match = expression.match(CNTRL_REG);
if (!match) {
throw $controllerMinErr('ctrlfmt',
"Badly formed controller string '{0}'. " +
"Must match `__name__ as __id__` or `__name__`.", expression);
}
constructor = match[1],
identifier = identifier || match[3];
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
assertArgFn(expression, constructor, true);
}
if (later) {
// Instantiate controller later:
// This machinery is used to create an instance of the object before calling the
// controller's constructor itself.
//
// This allows properties to be added to the controller before the constructor is
// invoked. Primarily, this is used for isolate scope bindings in $compile.
//
// This feature is not intended for use by applications, and is thus not documented
// publicly.
// Object creation: http://jsperf.com/create-constructor/2
var controllerPrototype = (isArray(expression) ?
expression[expression.length - 1] : expression).prototype;
instance = Object.create(controllerPrototype || null);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
var instantiate;
return instantiate = extend(function() {
var result = $injector.invoke(expression, instance, locals, constructor);
if (result !== instance && (isObject(result) || isFunction(result))) {
instance = result;
if (identifier) {
// If result changed, re-assign controllerAs value to scope.
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
}
return instance;
}, {
instance: instance,
identifier: identifier
});
}
instance = $injector.instantiate(expression, locals, constructor);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
return instance;
};
function addIdentifier(locals, identifier, instance, name) {
if (!(locals && isObject(locals.$scope))) {
throw minErr('$controller')('noscp',
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
name, identifier);
}
locals.$scope[identifier] = instance;
}
}];
}
/**
* @ngdoc service
* @name $document
* @requires $window
*
* @description
* A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
*
* @example
<example module="documentExample">
<file name="index.html">
<div ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>
</file>
<file name="script.js">
angular.module('documentExample', [])
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
$scope.title = $document[0].title;
$scope.windowTitle = angular.element(window.document)[0].title;
}]);
</file>
</example>
*/
function $DocumentProvider() {
this.$get = ['$window', function(window) {
return jqLite(window.document);
}];
}
/**
* @ngdoc service
* @name $exceptionHandler
* @requires ng.$log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* ## Example:
*
* ```js
* angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
* return function(exception, cause) {
* exception.message += ' (caused by "' + cause + '")';
* throw exception;
* };
* });
* ```
*
* This example will override the normal action of `$exceptionHandler`, to make angular
* exceptions fail hard when they happen, instead of just logging to the console.
*
* <hr />
* Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
* methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
* (unless executed during a digest).
*
* If you wish, you can manually delegate exceptions, e.g.
* `try { ... } catch(e) { $exceptionHandler(e); }`
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
var $$ForceReflowProvider = function() {
this.$get = ['$document', function($document) {
return function(domNode) {
//the line below will force the browser to perform a repaint so
//that all the animated elements within the animation frame will
//be properly updated and drawn on screen. This is required to
//ensure that the preparation animation is properly flushed so that
//the active state picks up from there. DO NOT REMOVE THIS LINE.
//DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
//WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
//WILL TAKE YEARS AWAY FROM YOUR LIFE.
if (domNode) {
if (!domNode.nodeType && domNode instanceof jqLite) {
domNode = domNode[0];
}
} else {
domNode = $document[0].body;
}
return domNode.offsetWidth + 1;
};
}];
};
var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
'[': /]$/,
'{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $httpMinErr = minErr('$http');
var $httpMinErrLegacyFn = function(method) {
return function() {
throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
};
};
function serializeValue(v) {
if (isObject(v)) {
return isDate(v) ? v.toISOString() : toJson(v);
}
return v;
}
function $HttpParamSerializerProvider() {
/**
* @ngdoc service
* @name $httpParamSerializer
* @description
*
* Default {@link $http `$http`} params serializer that converts objects to strings
* according to the following rules:
*
* * `{'foo': 'bar'}` results in `foo=bar`
* * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
* * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
*
* Note that serializer will sort the request parameters alphabetically.
* */
this.$get = function() {
return function ngParamSerializer(params) {
if (!params) return '';
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (isArray(value)) {
forEach(value, function(v, k) {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
});
} else {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
}
});
return parts.join('&');
};
};
}
function $HttpParamSerializerJQLikeProvider() {
/**
* @ngdoc service
* @name $httpParamSerializerJQLike
* @description
*
* Alternative {@link $http `$http`} params serializer that follows
* jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
* The serializer will also sort the params alphabetically.
*
* To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
*
* ```js
* $http({
* url: myUrl,
* method: 'GET',
* params: myParams,
* paramSerializer: '$httpParamSerializerJQLike'
* });
* ```
*
* It is also possible to set it as the default `paramSerializer` in the
* {@link $httpProvider#defaults `$httpProvider`}.
*
* Additionally, you can inject the serializer and use it explicitly, for example to serialize
* form data for submission:
*
* ```js
* .controller(function($http, $httpParamSerializerJQLike) {
* //...
*
* $http({
* url: myUrl,
* method: 'POST',
* data: $httpParamSerializerJQLike(myData),
* headers: {
* 'Content-Type': 'application/x-www-form-urlencoded'
* }
* });
*
* });
* ```
*
* */
this.$get = function() {
return function jQueryLikeParamSerializer(params) {
if (!params) return '';
var parts = [];
serialize(params, '', true);
return parts.join('&');
function serialize(toSerialize, prefix, topLevel) {
if (toSerialize === null || isUndefined(toSerialize)) return;
if (isArray(toSerialize)) {
forEach(toSerialize, function(value, index) {
serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
});
} else if (isObject(toSerialize) && !isDate(toSerialize)) {
forEachSorted(toSerialize, function(value, key) {
serialize(value, prefix +
(topLevel ? '' : '[') +
key +
(topLevel ? '' : ']'));
});
} else {
parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
}
}
};
};
}
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
function isJsonLike(str) {
var jsonStart = str.match(JSON_START);
return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = createMap(), i;
function fillInParsed(key, val) {
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
if (isString(headers)) {
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
});
} else if (isObject(headers)) {
forEach(headers, function(headerVal, headerKey) {
fillInParsed(lowercase(headerKey), trim(headerVal));
});
}
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers HTTP headers getter fn.
* @param {number} status HTTP status code of the response.
* @param {(Function|Array.<Function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, status, fns) {
if (isFunction(fns)) {
return fns(data, headers, status);
}
forEach(fns, function(fn) {
data = fn(data, headers, status);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
/**
* @ngdoc provider
* @name $httpProvider
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
function $HttpProvider() {
/**
* @ngdoc property
* @name $httpProvider#defaults
* @description
*
* Object containing default values for all {@link ng.$http $http} requests.
*
* - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
* that will provide the cache for all requests who set their `cache` property to `true`.
* If you set the `defaults.cache = false` then only requests that specify their own custom
* cache object will be cached. See {@link $http#caching $http Caching} for more information.
*
* - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
* Defaults value is `'XSRF-TOKEN'`.
*
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
* - **`defaults.headers`** - {Object} - Default headers for all $http requests.
* Refer to {@link ng.$http#setting-http-headers $http} for documentation on
* setting default headers.
* - **`defaults.headers.common`**
* - **`defaults.headers.post`**
* - **`defaults.headers.put`**
* - **`defaults.headers.patch`**
*
*
* - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
* used to the prepare string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
* Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
*
**/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
paramSerializer: '$httpParamSerializer'
};
var useApplyAsync = false;
/**
* @ngdoc method
* @name $httpProvider#useApplyAsync
* @description
*
* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests
* concurrently (common during application bootstrap).
*
* Defaults to false. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
* "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
* to load and share the same digest cycle.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
return this;
}
return useApplyAsync;
};
var useLegacyPromise = true;
/**
* @ngdoc method
* @name $httpProvider#useLegacyPromiseExtensions
* @description
*
* Configure `$http` service to return promises without the shorthand methods `success` and `error`.
* This should be used to make sure that applications work without these methods.
*
* Defaults to false. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useLegacyPromiseExtensions = function(value) {
if (isDefined(value)) {
useLegacyPromise = !!value;
return this;
}
return useLegacyPromise;
};
/**
* @ngdoc property
* @name $httpProvider#interceptors
* @description
*
* Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
* pre-processing of request or postprocessing of responses.
*
* These service factories are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
var interceptorFactories = this.interceptors = [];
this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Make sure that default param serializer is exposed as a function
*/
defaults.paramSerializer = isString(defaults.paramSerializer) ?
$injector.get(defaults.paramSerializer) : defaults.paramSerializer;
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
/**
* @ngdoc service
* @kind function
* @name $http
* @requires ng.$httpBackend
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
* object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* ## General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}.
*
* ```js
* // Simple GET request example :
* $http.get('/someUrl').
* then(function(response) {
* // this callback will be called asynchronously
* // when the response is available
* }, function(response) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* ```js
* // Simple POST request example (passing data) :
* $http.post('/someUrl', {msg:'hello word!'}).
* then(function(response) {
* // this callback will be called asynchronously
* // when the response is available
* }, function(response) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
* - **statusText** – `{string}` – HTTP status text of the response.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* ## Writing Unit Tests that use $http
* When unit testing (using {@link ngMock ngMock}), it is necessary to call
* {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
* request using trained responses.
*
* ```
* $httpBackend.expectGET(...);
* $http.get(...);
* $httpBackend.flush();
* ```
*
* ## Shortcut methods
*
* Shortcut methods are also available. All shortcut methods require passing in the URL, and
* request data must be passed in for POST/PUT requests.
*
* ```js
* $http.get('/someUrl').then(successCallback);
* $http.post('/someUrl', data).then(successCallback);
* ```
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
* - {@link ng.$http#patch $http.patch}
*
*
* ## Deprecation Notice
* <div class="alert alert-danger">
* The `$http` legacy promise methods `success` and `error` have been deprecated.
* Use the standard `then` method instead.
* If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
* `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
* </div>
*
* ## Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. For example:
*
* ```
* module.run(function($http) {
* $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
* });
* ```
*
* In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
* To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
* Use the `headers` property, setting the desired header to `undefined`. For example:
*
* ```js
* var req = {
* method: 'POST',
* url: 'http://example.com',
* headers: {
* 'Content-Type': undefined
* },
* data: { test: 'test' }
* }
*
* $http(req).then(function(){...}, function(){...});
* ```
*
* ## Transforming Requests and Responses
*
* Both requests and responses can be transformed using transformation functions: `transformRequest`
* and `transformResponse`. These properties can be a single function that returns
* the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
* which allows you to `push` or `unshift` a new transformation function into the transformation chain.
*
* ### Default Transformations
*
* The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
* `defaults.transformResponse` properties. If a request does not provide its own transformations
* then these will be applied.
*
* You can augment or replace the default transformations by modifying these properties by adding to or
* replacing the array.
*
* Angular provides the following default transformations:
*
* Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
*
* ### Overriding the Default Transformations Per Request
*
* If you wish override the request/response transformations only for a single request then provide
* `transformRequest` and/or `transformResponse` properties on the configuration object passed
* into `$http`.
*
* Note that if you provide these properties on the config object the default transformations will be
* overwritten. If you wish to augment the default transformations then you must include them in your
* local transformation array.
*
* The following code demonstrates adding a new response transformation to be run after the default response
* transformations have been run.
*
* ```js
* function appendTransform(defaults, transform) {
*
* // We can't guarantee that the default transformation is an array
* defaults = angular.isArray(defaults) ? defaults : [defaults];
*
* // Append the new transformation to the defaults
* return defaults.concat(transform);
* }
*
* $http({
* url: '...',
* method: 'GET',
* transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
* return doTransform(value);
* })
* });
* ```
*
*
* ## Caching
*
* To enable caching, set the request configuration `cache` property to `true` (to use default
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
* When the cache is enabled, `$http` stores the response from the server in the specified
* cache. The next time the same request is made, the response is served from the cache without
* sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* You can change the default cache to a new object (built with
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the
* {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
* their `cache` property to `true` will now use this cache object.
*
* If you set the default cache to `false` then only requests that specify their own custom
* cache object will be cached.
*
* ## Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with a http `config` object. The function is free to
* modify the `config` object or create a new one. The function needs to return the `config`
* object directly, or a promise containing the `config` or a new `config` object.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` object or create a new one. The function needs to return the `response`
* object directly, or as a promise containing the `response` or a new `response` object.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* ```js
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config;
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response;
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* }
* };
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // alternatively, register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
*
* 'response': function(response) {
* // same as above
* }
* };
* });
* ```
*
* ## Security Considerations
*
* When designing web applications, consider security threats from:
*
* - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ### JSON Vulnerability Protection
*
* A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* allows third party website to turn your JSON resource URL into
* [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* ```js
* ['one','two']
* ```
*
* which is vulnerable to attack, your server can return:
* ```js
* )]}',
* ['one','two']
* ```
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ### Cross Site Request Forgery (XSRF) Protection
*
* [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
*
* In order to prevent collisions in environments where multiple Angular apps share the
* same domain or subdomain, we recommend that each application uses unique cookie name.
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
* with the `paramSerializer` and appended as GET parameters.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent. Functions accept a config object as an argument.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **transformResponse** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default TransformationjqLiks}
* - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
* prepare the string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as function registered with the
* {@link $injector $injector}, which means you can create your own serializer
* by registering it as a {@link auto.$provide#service service}.
* The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
* alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
* for more information.
* - **responseType** - `{string}` - see
* [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
*
* @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
* when the request succeeds or fails.
*
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example module="httpExample">
<file name="index.html">
<div ng-controller="FetchController">
<select ng-model="method" aria-label="Request method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80" aria-label="URL" />
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
if (!angular.isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
}
var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse,
paramSerializer: defaults.paramSerializer
}, requestConfig);
config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
config.paramSerializer = isString(config.paramSerializer) ?
$injector.get(config.paramSerializer) : config.paramSerializer;
var serverRequest = function(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while (chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
if (useLegacyPromise) {
promise.success = function(fn) {
assertArgFn(fn, 'fn');
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
assertArgFn(fn, 'fn');
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
} else {
promise.success = $httpMinErrLegacyFn('success');
promise.error = $httpMinErrLegacyFn('error');
}
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
if (!response.data) {
resp.data = response.data;
} else {
resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
}
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function executeHeaderFns(headers, config) {
var headerContent, processedHeaders = {};
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn(config);
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
});
return processedHeaders;
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
// execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders, shallowCopy(config));
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name $http#get
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#delete
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#head
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#jsonp
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name $http#post
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#put
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#patch
*
* @description
* Shortcut method to perform `PATCH` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put', 'patch');
/**
* @ngdoc property
* @name $http#defaults
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend({}, config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend({}, config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
reqHeaders = config.headers,
url = buildUrl(config.url, config.paramSerializer(config.params));
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
} else {
resolvePromise(cachedResp, 200, {}, 'OK');
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
function resolveHttpPromise() {
resolvePromise(response, status, headersString, statusText);
}
if (useApplyAsync) {
$rootScope.$applyAsync(resolveHttpPromise);
} else {
resolveHttpPromise();
if (!$rootScope.$$phase) $rootScope.$apply();
}
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers, statusText) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config,
statusText: statusText
});
}
function resolvePromiseWithResult(result) {
resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
}
function removePendingReq() {
var idx = $http.pendingRequests.indexOf(config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, serializedParams) {
if (serializedParams.length > 0) {
url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
}
return url;
}
}];
}
function createXhr() {
return new window.XMLHttpRequest();
}
/**
* @ngdoc service
* @name $httpBackend
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
}];
}
function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
callbacks[callbackId].called = true;
};
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
callbackId, function(status, text) {
completeRequest(callback, status, callbacks[callbackId].data, "", text);
callbacks[callbackId] = noop;
});
} else {
var xhr = createXhr();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
xhr.onload = function requestLoaded() {
var statusText = xhr.statusText || '';
// responseText is the old-school way of retrieving response (supported by IE9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
var response = ('response' in xhr) ? xhr.response : xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
completeRequest(callback,
status,
response,
xhr.getAllResponseHeaders(),
statusText);
};
var requestError = function() {
// The response is always empty
// See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
completeRequest(callback, -1, null, null, '');
};
xhr.onerror = requestError;
xhr.onabort = requestError;
if (withCredentials) {
xhr.withCredentials = true;
}
if (responseType) {
try {
xhr.responseType = responseType;
} catch (e) {
// WebKit added support for the json responseType value on 09/03/2013
// https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
// known to throw when setting the value "json" as the response type. Other older
// browsers implementing the responseType
//
// The json response type can be ignored if not supported, because JSON payloads are
// parsed on the client-side regardless.
if (responseType !== 'json') {
throw e;
}
}
}
xhr.send(post);
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (isPromiseLike(timeout)) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
if (timeoutId !== undefined) {
$browserDefer.cancel(timeoutId);
}
jsonpDone = xhr = null;
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, callbackId, done) {
// we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'), callback = null;
script.type = "text/javascript";
script.src = url;
script.async = true;
callback = function(event) {
removeEventListenerFn(script, "load", callback);
removeEventListenerFn(script, "error", callback);
rawDocument.body.removeChild(script);
script = null;
var status = -1;
var text = "unknown";
if (event) {
if (event.type === "load" && !callbacks[callbackId].called) {
event = { type: "error" };
}
text = event.type;
status = event.type === "error" ? 404 : 200;
}
if (done) {
done(status, text);
}
};
addEventListenerFn(script, "load", callback);
addEventListenerFn(script, "error", callback);
rawDocument.body.appendChild(script);
return callback;
}
}
var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
$interpolateMinErr.throwNoconcat = function(text) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
};
$interpolateMinErr.interr = function(text, err) {
return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
};
/**
* @ngdoc provider
* @name $interpolateProvider
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<example module="customInterpolationApp">
<file name="index.html">
<script>
var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
customInterpolationApp.controller('DemoController', function() {
this.label = "This binding is brought you by // interpolation symbols.";
});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
//demo.label//
</div>
</file>
<file name="protractor.js" type="protractor">
it('should interpolate binding with custom symbols', function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
});
</file>
</example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name $interpolateProvider#startSymbol
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value) {
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name $interpolateProvider#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value) {
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length,
escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
function escape(ch) {
return '\\\\\\' + ch;
}
function unescapeText(text) {
return text.replace(escapedStartRegexp, startSymbol).
replace(escapedEndRegexp, endSymbol);
}
function stringify(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
value = toJson(value);
}
return value;
}
/**
* @ngdoc service
* @name $interpolate
* @kind function
*
* @requires $parse
* @requires $sce
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
* ```js
* var $interpolate = ...; // injected
* var exp = $interpolate('Hello {{name | uppercase}}!');
* expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
* ```
*
* `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
* `true`, the interpolation function will return `undefined` unless all embedded expressions
* evaluate to a value other than `undefined`.
*
* ```js
* var $interpolate = ...; // injected
* var context = {greeting: 'Hello', name: undefined };
*
* // default "forgiving" mode
* var exp = $interpolate('{{greeting}} {{name}}!');
* expect(exp(context)).toEqual('Hello !');
*
* // "allOrNothing" mode
* exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
* expect(exp(context)).toBeUndefined();
* context.name = 'Angular';
* expect(exp(context)).toEqual('Hello Angular!');
* ```
*
* `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
*
* ####Escaped Interpolation
* $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
* can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
* It will be rendered as a regular start/end marker, and will not be interpreted as an expression
* or binding.
*
* This enables web-servers to prevent script injection attacks and defacing attacks, to some
* degree, while also enabling code examples to work without relying on the
* {@link ng.directive:ngNonBindable ngNonBindable} directive.
*
* **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
* replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
* interpolation start/end markers with their escaped counterparts.**
*
* Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
* output when the $interpolate service processes the text. So, for HTML elements interpolated
* by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
* set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
* this is typically useful only when user-data is used in rendering a template from the server, or
* when otherwise untrusted data is used by a directive.
*
* <example>
* <file name="index.html">
* <div ng-init="username='A user'">
* <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
* </p>
* <p><strong>{{username}}</strong> attempts to inject code which will deface the
* application, but fails to accomplish their task, because the server has correctly
* escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
* characters.</p>
* <p>Instead, the result of the attempted script injection is visible, and can be removed
* from the database by an administrator.</p>
* </div>
* </file>
* </example>
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @param {string=} trustedContext when provided, the returned function passes the interpolated
* result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
* provides Strict Contextual Escaping for details.
* @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
* unless all embedded expressions evaluate to a value other than `undefined`.
* @returns {function(context)} an interpolation function which is used to compute the
* interpolated string. The function has these parameters:
*
* - `context`: evaluation context for all expressions embedded in the interpolated text
*/
function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
allOrNothing = !!allOrNothing;
var startIndex,
endIndex,
index = 0,
expressions = [],
parseFns = [],
textLength = text.length,
exp,
concat = [],
expressionPositions = [];
while (index < textLength) {
if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
if (index !== startIndex) {
concat.push(unescapeText(text.substring(index, startIndex)));
}
exp = text.substring(startIndex + startSymbolLength, endIndex);
expressions.push(exp);
parseFns.push($parse(exp, parseStringifyInterceptor));
index = endIndex + endSymbolLength;
expressionPositions.push(concat.length);
concat.push('');
} else {
// we did not find an interpolation, so we have to add the remainder to the separators array
if (index !== textLength) {
concat.push(unescapeText(text.substring(index)));
}
break;
}
}
// Concatenating expressions makes it hard to reason about whether some combination of
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
// single expression be used for iframe[src], object[src], etc., we ensure that the value
// that's used is assigned or constructed by some JS code somewhere that is more testable or
// make it obvious that you bound the value to some user controlled value. This helps reduce
// the load when auditing for XSS issues.
if (trustedContext && concat.length > 1) {
$interpolateMinErr.throwNoconcat(text);
}
if (!mustHaveExpression || expressions.length) {
var compute = function(values) {
for (var i = 0, ii = expressions.length; i < ii; i++) {
if (allOrNothing && isUndefined(values[i])) return;
concat[expressionPositions[i]] = values[i];
}
return concat.join('');
};
var getValue = function(value) {
return trustedContext ?
$sce.getTrusted(trustedContext, value) :
$sce.valueOf(value);
};
return extend(function interpolationFn(context) {
var i = 0;
var ii = expressions.length;
var values = new Array(ii);
try {
for (; i < ii; i++) {
values[i] = parseFns[i](context);
}
return compute(values);
} catch (err) {
$exceptionHandler($interpolateMinErr.interr(text, err));
}
}, {
// all of these properties are undocumented for now
exp: text, //just for compatibility with regular watchers created via $watch
expressions: expressions,
$$watchDelegate: function(scope, listener) {
var lastValue;
return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
var currValue = compute(values);
if (isFunction(listener)) {
listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
}
lastValue = currValue;
});
}
});
}
function parseStringifyInterceptor(value) {
try {
value = getValue(value);
return allOrNothing && !isDefined(value) ? value : stringify(value);
} catch (err) {
$exceptionHandler($interpolateMinErr.interr(text, err));
}
}
}
/**
* @ngdoc method
* @name $interpolate#startSymbol
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
};
/**
* @ngdoc method
* @name $interpolate#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
* the symbol.
*
* @returns {string} end symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
};
return $interpolate;
}];
}
function $IntervalProvider() {
this.$get = ['$rootScope', '$window', '$q', '$$q',
function($rootScope, $window, $q, $$q) {
var intervals = {};
/**
* @ngdoc service
* @name $interval
*
* @description
* Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
* milliseconds.
*
* The return value of registering an interval function is a promise. This promise will be
* notified upon each tick of the interval, and will be resolved after `count` iterations, or
* run indefinitely if `count` is not defined. The value of the notification will be the
* number of iterations that have run.
* To cancel an interval, call `$interval.cancel(promise)`.
*
* In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* <div class="alert alert-warning">
* **Note**: Intervals created by this service must be explicitly destroyed when you are finished
* with them. In particular they are not automatically destroyed when a controller's scope or a
* directive's element are destroyed.
* You should take this into consideration and make sure to always cancel the interval at the
* appropriate moment. See the example below for more details on how and when to do this.
* </div>
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @param {...*=} Pass additional parameters to the executed function.
* @returns {promise} A promise which will be notified on each iteration.
*
* @example
* <example module="intervalExample">
* <file name="index.html">
* <script>
* angular.module('intervalExample', [])
* .controller('ExampleController', ['$scope', '$interval',
* function($scope, $interval) {
* $scope.format = 'M/d/yy h:mm:ss a';
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
*
* var stop;
* $scope.fight = function() {
* // Don't start a new fight if we are already fighting
* if ( angular.isDefined(stop) ) return;
*
* stop = $interval(function() {
* if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
* $scope.blood_1 = $scope.blood_1 - 3;
* $scope.blood_2 = $scope.blood_2 - 4;
* } else {
* $scope.stopFight();
* }
* }, 100);
* };
*
* $scope.stopFight = function() {
* if (angular.isDefined(stop)) {
* $interval.cancel(stop);
* stop = undefined;
* }
* };
*
* $scope.resetFight = function() {
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
* };
*
* $scope.$on('$destroy', function() {
* // Make sure that the interval is destroyed too
* $scope.stopFight();
* });
* }])
* // Register the 'myCurrentTime' directive factory method.
* // We inject $interval and dateFilter service since the factory method is DI.
* .directive('myCurrentTime', ['$interval', 'dateFilter',
* function($interval, dateFilter) {
* // return the directive link function. (compile function not needed)
* return function(scope, element, attrs) {
* var format, // date format
* stopTime; // so that we can cancel the time updates
*
* // used to update the UI
* function updateTime() {
* element.text(dateFilter(new Date(), format));
* }
*
* // watch the expression, and update the UI on change.
* scope.$watch(attrs.myCurrentTime, function(value) {
* format = value;
* updateTime();
* });
*
* stopTime = $interval(updateTime, 1000);
*
* // listen on DOM destroy (removal) event, and cancel the next UI update
* // to prevent updating time after the DOM element was removed.
* element.on('$destroy', function() {
* $interval.cancel(stopTime);
* });
* }
* }]);
* </script>
*
* <div>
* <div ng-controller="ExampleController">
* <label>Date format: <input ng-model="format"></label> <hr/>
* Current time is: <span my-current-time="format"></span>
* <hr/>
* Blood 1 : <font color='red'>{{blood_1}}</font>
* Blood 2 : <font color='red'>{{blood_2}}</font>
* <button type="button" data-ng-click="fight()">Fight</button>
* <button type="button" data-ng-click="stopFight()">StopFight</button>
* <button type="button" data-ng-click="resetFight()">resetFight</button>
* </div>
* </div>
*
* </file>
* </example>
*/
function interval(fn, delay, count, invokeApply) {
var hasParams = arguments.length > 4,
args = hasParams ? sliceArgs(arguments, 4) : [],
setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
iteration = 0,
skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise;
count = isDefined(count) ? count : 0;
promise.then(null, null, (!hasParams) ? fn : function() {
fn.apply(null, args);
});
promise.$$intervalId = setInterval(function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
intervals[promise.$$intervalId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $interval#cancel
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {Promise=} promise returned by the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully canceled.
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
intervals[promise.$$intervalId].reject('canceled');
$window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
return true;
}
return false;
};
return interval;
}];
}
/**
* @ngdoc service
* @name $locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function parseAbsoluteUrl(absoluteUrl, locationObj) {
var parsedUrl = urlResolve(absoluteUrl);
locationObj.$$protocol = parsedUrl.protocol;
locationObj.$$host = parsedUrl.hostname;
locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
function parseAppUrl(relativeUrl, locationObj) {
var prefixed = (relativeUrl.charAt(0) !== '/');
if (prefixed) {
relativeUrl = '/' + relativeUrl;
}
var match = urlResolve(relativeUrl);
locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
match.pathname.substring(1) : match.pathname);
locationObj.$$search = parseKeyValue(match.search);
locationObj.$$hash = decodeURIComponent(match.hash);
// make sure path starts with '/';
if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
locationObj.$$path = '/' + locationObj.$$path;
}
}
/**
*
* @param {string} begin
* @param {string} whole
* @returns {string} returns text from whole after begin or undefined if it does not begin with
* expected string.
*/
function beginsWith(begin, whole) {
if (whole.indexOf(begin) === 0) {
return whole.substr(begin.length);
}
}
function stripHash(url) {
var index = url.indexOf('#');
return index == -1 ? url : url.substr(0, index);
}
function trimEmptyHash(url) {
return url.replace(/(#.+)|#$/, '$1');
}
function stripFile(url) {
return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}
/* return the server only (scheme://host:port) */
function serverBase(url) {
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}
/**
* LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} basePrefix url path prefix
*/
function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
this.$$html5 = true;
basePrefix = basePrefix || '';
parseAbsoluteUrl(appBase, this);
/**
* Parse given html5 (regular) url string into properties
* @param {string} url HTML5 url
* @private
*/
this.$$parse = function(url) {
var pathUrl = beginsWith(appBaseNoFile, url);
if (!isString(pathUrl)) {
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
appBaseNoFile);
}
parseAppUrl(pathUrl, this);
if (!this.$$path) {
this.$$path = '/';
}
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var appUrl, prevAppUrl;
var rewrittenUrl;
if ((appUrl = beginsWith(appBase, url)) !== undefined) {
prevAppUrl = appUrl;
if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
rewrittenUrl = appBase + prevAppUrl;
}
} else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
rewrittenUrl = appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when developer doesn't opt into html5 mode.
* It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
parseAbsoluteUrl(appBase, this);
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
var withoutHashUrl;
if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
// The rest of the url starts with a hash so we have
// got either a hashbang path or a plain hash fragment
withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
if (isUndefined(withoutHashUrl)) {
// There was no hashbang prefix so we just have a hash fragment
withoutHashUrl = withoutBaseUrl;
}
} else {
// There was no hashbang path nor hash fragment:
// If we are in HTML5 mode we use what is left as the path;
// Otherwise we ignore what is left
if (this.$$html5) {
withoutHashUrl = withoutBaseUrl;
} else {
withoutHashUrl = '';
if (isUndefined(withoutBaseUrl)) {
appBase = url;
this.replace();
}
}
}
parseAppUrl(withoutHashUrl, this);
this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
this.$$compose();
/*
* In Windows, on an anchor node on documents loaded from
* the filesystem, the browser will return a pathname
* prefixed with the drive name ('/C:/path') when a
* pathname without a drive is set:
* * a.setAttribute('href', '/foo')
* * a.pathname === '/C:/foo' //true
*
* Inside of Angular, we're always using pathnames that
* do not include drive names for routing.
*/
function removeWindowsDriveName(path, url, base) {
/*
Matches paths for file protocol on windows,
such as /C:/foo/bar, and captures only /foo/bar.
*/
var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
var firstPathSegmentMatch;
//Get the relative path from the input URL.
if (url.indexOf(base) === 0) {
url = url.replace(base, '');
}
// The input URL intentionally contains a first path segment that ends with a colon.
if (windowsFilePathExp.exec(url)) {
return path;
}
firstPathSegmentMatch = windowsFilePathExp.exec(path);
return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
}
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
this.$$parseLinkUrl = function(url, relHref) {
if (stripHash(appBase) == stripHash(url)) {
this.$$parse(url);
return true;
}
return false;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is enabled but the browser
* does not support it.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
this.$$html5 = true;
LocationHashbangUrl.apply(this, arguments);
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var rewrittenUrl;
var appUrl;
if (appBase == stripHash(url)) {
rewrittenUrl = url;
} else if ((appUrl = beginsWith(appBaseNoFile, url))) {
rewrittenUrl = appBase + hashPrefix + appUrl;
} else if (appBaseNoFile === url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
// include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
this.$$absUrl = appBase + hashPrefix + this.$$url;
};
}
var locationPrototype = {
/**
* Are we in html5 mode?
* @private
*/
$$html5: false,
/**
* Has any change been replacing?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name $location#absUrl
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var absUrl = $location.absUrl();
* // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
* ```
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name $location#url
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var url = $location.url();
* // => "/some/path?foo=bar&baz=xoxo"
* ```
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url) {
if (isUndefined(url)) {
return this.$$url;
}
var match = PATH_MATCH.exec(url);
if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
if (match[2] || match[1] || url === '') this.search(match[3] || '');
this.hash(match[5] || '');
return this;
},
/**
* @ngdoc method
* @name $location#protocol
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var protocol = $location.protocol();
* // => "http"
* ```
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name $location#host
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var host = $location.host();
* // => "example.com"
*
* // given url http://user:[email protected]:8080/#/some/path?foo=bar&baz=xoxo
* host = $location.host();
* // => "example.com"
* host = location.host;
* // => "example.com:8080"
* ```
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name $location#port
*
* @description
* This method is getter only.
*
* Return port of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var port = $location.port();
* // => 80
* ```
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name $location#path
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var path = $location.path();
* // => "/some/path"
* ```
*
* @param {(string|number)=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
path = path !== null ? path.toString() : '';
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name $location#search
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var searchObject = $location.search();
* // => {foo: 'bar', baz: 'xoxo'}
*
* // set foo to 'yipee'
* $location.search('foo', 'yipee');
* // $location.search() => {foo: 'yipee', baz: 'xoxo'}
* ```
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
* hash object.
*
* When called with a single argument the method acts as a setter, setting the `search` component
* of `$location` to the specified value.
*
* If the argument is a hash object containing an array of values, these values will be encoded
* as duplicate search parameters in the url.
*
* @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
* will override only a single search property.
*
* If `paramValue` is an array, it will override the property of the `search` component of
* `$location` specified via the first argument.
*
* If `paramValue` is `null`, the property specified via the first argument will be deleted.
*
* If `paramValue` is `true`, the property specified via the first argument will be added with no
* value nor trailing equal sign.
*
* @return {Object} If called with no arguments returns the parsed `search` object. If called with
* one or more arguments returns `$location` object itself.
*/
search: function(search, paramValue) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (isString(search) || isNumber(search)) {
search = search.toString();
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
search = copy(search, {});
// remove object undefined or null properties
forEach(search, function(value, key) {
if (value == null) delete search[key];
});
this.$$search = search;
} else {
throw $locationMinErr('isrcharg',
'The first argument of the `$location#search()` call must be a string or an object.');
}
break;
default:
if (isUndefined(paramValue) || paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name $location#hash
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
* var hash = $location.hash();
* // => "hashValue"
* ```
*
* @param {(string|number)=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', function(hash) {
return hash !== null ? hash.toString() : '';
}),
/**
* @ngdoc method
* @name $location#replace
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
Location.prototype = Object.create(locationPrototype);
/**
* @ngdoc method
* @name $location#state
*
* @description
* This method is getter / setter.
*
* Return the history state object when called without any parameter.
*
* Change the history state object when called with one parameter and return `$location`.
* The state object is later passed to `pushState` or `replaceState`.
*
* NOTE: This method is supported only in HTML5 mode and only in browsers supporting
* the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
* older browsers (like IE9 or Android < 4.0), don't use this method.
*
* @param {object=} state State object for pushState or replaceState
* @return {object} state
*/
Location.prototype.state = function(state) {
if (!arguments.length) {
return this.$$state;
}
if (Location !== LocationHtml5Url || !this.$$html5) {
throw $locationMinErr('nostate', 'History API state support is available only ' +
'in HTML5 mode and only in browsers supporting HTML5 History API');
}
// The user might modify `stateObject` after invoking `$location.state(stateObject)`
// but we're changing the $$state reference to $browser.state() during the $digest
// so the modification window is narrow.
this.$$state = isUndefined(state) ? null : state;
return this;
};
});
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value)) {
return this[property];
}
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc service
* @name $location
*
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/$location Developer Guide: Using $location}
*/
/**
* @ngdoc provider
* @name $locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider() {
var hashPrefix = '',
html5Mode = {
enabled: false,
requireBase: true,
rewriteLinks: true
};
/**
* @ngdoc method
* @name $locationProvider#hashPrefix
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc method
* @name $locationProvider#html5Mode
* @description
* @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
* If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
* properties:
* - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
* change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
* support `pushState`.
* - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
* whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
* true, and a base tag is not present, an error will be thrown when `$location` is injected.
* See the {@link guide/$location $location guide for more information}
* - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
* enables/disables url rewriting for relative links.
*
* @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isBoolean(mode)) {
html5Mode.enabled = mode;
return this;
} else if (isObject(mode)) {
if (isBoolean(mode.enabled)) {
html5Mode.enabled = mode.enabled;
}
if (isBoolean(mode.requireBase)) {
html5Mode.requireBase = mode.requireBase;
}
if (isBoolean(mode.rewriteLinks)) {
html5Mode.rewriteLinks = mode.rewriteLinks;
}
return this;
} else {
return html5Mode;
}
};
/**
* @ngdoc event
* @name $location#$locationChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a URL will change.
*
* This change can be prevented by calling
* `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
* details about event object. Upon successful change
* {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
/**
* @ngdoc event
* @name $location#$locationChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a URL was changed.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
function($rootScope, $browser, $sniffer, $rootElement, $window) {
var $location,
LocationMode,
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
initialUrl = $browser.url(),
appBase;
if (html5Mode.enabled) {
if (!baseHref && html5Mode.requireBase) {
throw $locationMinErr('nobase',
"$location in HTML5 mode requires a <base> tag to be present!");
}
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
var appBaseNoFile = stripFile(appBase);
$location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
$location.$$parseLinkUrl(initialUrl, initialUrl);
$location.$$state = $browser.state();
var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
function setBrowserUrlWithFallback(url, replace, state) {
var oldUrl = $location.url();
var oldState = $location.$$state;
try {
$browser.url(url, replace, state);
// Make sure $location.state() returns referentially identical (not just deeply equal)
// state object; this makes possible quick checking if the state changed in the digest
// loop. Checking deep equality would be too expensive.
$location.$$state = $browser.state();
} catch (e) {
// Restore old values if pushState fails
$location.url(oldUrl);
$location.$$state = oldState;
throw e;
}
}
$rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (nodeName_(elm[0]) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href');
// get the actual href attribute - see
// http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
var relHref = elm.attr('href') || elm.attr('xlink:href');
if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
// SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
// an animation.
absHref = urlResolve(absHref.animVal).href;
}
// Ignore when url is started with javascript: or mailto:
if (IGNORE_URI_REGEXP.test(absHref)) return;
if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
if ($location.$$parseLinkUrl(absHref, relHref)) {
// We do a preventDefault for all urls that are part of the angular application,
// in html5mode and also without, so that we are able to abort navigation without
// getting double entries in the location history.
event.preventDefault();
// update location manually
if ($location.absUrl() != $browser.url()) {
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
$window.angular['ff-684208-preventDefault'] = true;
}
}
}
});
// rewrite hashbang url <> html5 url
if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
$browser.url($location.absUrl(), true);
}
var initializing = true;
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl, newState) {
if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
// If we are navigating outside of the app then force a reload
$window.location.href = newUrl;
return;
}
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
var oldState = $location.$$state;
var defaultPrevented;
$location.$$parse(newUrl);
$location.$$state = newState;
defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
newState, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
setBrowserUrlWithFallback(oldUrl, false, oldState);
} else {
initializing = false;
afterLocationChange(oldUrl, oldState);
}
});
if (!$rootScope.$$phase) $rootScope.$digest();
});
// update browser
$rootScope.$watch(function $locationWatch() {
var oldUrl = trimEmptyHash($browser.url());
var newUrl = trimEmptyHash($location.absUrl());
var oldState = $browser.state();
var currentReplace = $location.$$replace;
var urlOrStateChanged = oldUrl !== newUrl ||
($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
if (initializing || urlOrStateChanged) {
initializing = false;
$rootScope.$evalAsync(function() {
var newUrl = $location.absUrl();
var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
$location.$$state, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
} else {
if (urlOrStateChanged) {
setBrowserUrlWithFallback(newUrl, currentReplace,
oldState === $location.$$state ? null : $location.$$state);
}
afterLocationChange(oldUrl, oldState);
}
});
}
$location.$$replace = false;
// we don't need to return anything because $evalAsync will make the digest loop dirty when
// there is a change
});
return $location;
function afterLocationChange(oldUrl, oldState) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
$location.$$state, oldState);
}
}];
}
/**
* @ngdoc service
* @name $log
* @requires $window
*
* @description
* Simple service for logging. Default implementation safely writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* The default is to log `debug` messages. You can use
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
*
* @example
<example module="logExample">
<file name="script.js">
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}]);
</file>
<file name="index.html">
<div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
<label>Message:
<input type="text" ng-model="message" /></label>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
<button ng-click="$log.debug(message)">debug</button>
</div>
</file>
</example>
*/
/**
* @ngdoc provider
* @name $logProvider
* @description
* Use the `$logProvider` to configure how the application logs messages
*/
function $LogProvider() {
var debug = true,
self = this;
/**
* @ngdoc method
* @name $logProvider#debugEnabled
* @description
* @param {boolean=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
if (isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = ['$window', function($window) {
return {
/**
* @ngdoc method
* @name $log#log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name $log#info
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name $log#warn
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name $log#error
*
* @description
* Write an error message
*/
error: consoleLog('error'),
/**
* @ngdoc method
* @name $log#debug
*
* @description
* Write a debug message
*/
debug: (function() {
var fn = consoleLog('debug');
return function() {
if (debug) {
fn.apply(self, arguments);
}
};
}())
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2 == null ? '' : arg2);
};
}
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security
function ensureSafeMemberName(name, fullExpression) {
if (name === "__defineGetter__" || name === "__defineSetter__"
|| name === "__lookupGetter__" || name === "__lookupSetter__"
|| name === "__proto__") {
throw $parseMinErr('isecfld',
'Attempting to access a disallowed field in Angular expressions! '
+ 'Expression: {0}', fullExpression);
}
return name;
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj.window === obj) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// block Object so that we can't get hold of dangerous Object.* methods
obj === Object) {
throw $parseMinErr('isecobj',
'Referencing Object in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
return obj;
}
var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;
function ensureSafeFunction(obj, fullExpression) {
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (obj === CALL || obj === APPLY || obj === BIND) {
throw $parseMinErr('isecff',
'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
}
var OPERATORS = createMap();
forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function(options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function(text) {
this.text = text;
this.index = 0;
this.tokens = [];
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (ch === '"' || ch === "'") {
this.readString(ch);
} else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdent(ch)) {
this.readIdent();
} else if (this.is(ch, '(){}[].,;:?')) {
this.tokens.push({index: this.index, text: ch});
this.index++;
} else if (this.isWhitespace(ch)) {
this.index++;
} else {
var ch2 = ch + this.peek();
var ch3 = ch2 + this.peek(2);
var op1 = OPERATORS[ch];
var op2 = OPERATORS[ch2];
var op3 = OPERATORS[ch3];
if (op1 || op2 || op3) {
var token = op3 ? ch3 : (op2 ? ch2 : ch);
this.tokens.push({index: this.index, text: token, operator: true});
this.index += token.length;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
}
return this.tokens;
},
is: function(ch, chars) {
return chars.indexOf(ch) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9') && typeof ch === "string";
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdent: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
this.tokens.push({
index: start,
text: number,
constant: true,
value: Number(number)
});
},
readIdent: function() {
var start = this.index;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (!(this.isIdent(ch) || this.isNumber(ch))) {
break;
}
this.index++;
}
this.tokens.push({
index: start,
text: this.text.slice(start, this.index),
identifier: true
});
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i)) {
this.throwError('Invalid unicode escape [\\u' + hex + ']');
}
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
constant: true,
value: string
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
var AST = function(lexer, options) {
this.lexer = lexer;
this.options = options;
};
AST.Program = 'Program';
AST.ExpressionStatement = 'ExpressionStatement';
AST.AssignmentExpression = 'AssignmentExpression';
AST.ConditionalExpression = 'ConditionalExpression';
AST.LogicalExpression = 'LogicalExpression';
AST.BinaryExpression = 'BinaryExpression';
AST.UnaryExpression = 'UnaryExpression';
AST.CallExpression = 'CallExpression';
AST.MemberExpression = 'MemberExpression';
AST.Identifier = 'Identifier';
AST.Literal = 'Literal';
AST.ArrayExpression = 'ArrayExpression';
AST.Property = 'Property';
AST.ObjectExpression = 'ObjectExpression';
AST.ThisExpression = 'ThisExpression';
// Internal use only
AST.NGValueParameter = 'NGValueParameter';
AST.prototype = {
ast: function(text) {
this.text = text;
this.tokens = this.lexer.lex(text);
var value = this.program();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
return value;
},
program: function() {
var body = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
body.push(this.expressionStatement());
if (!this.expect(';')) {
return { type: AST.Program, body: body};
}
}
},
expressionStatement: function() {
return { type: AST.ExpressionStatement, expression: this.filterChain() };
},
filterChain: function() {
var left = this.expression();
var token;
while ((token = this.expect('|'))) {
left = this.filter(left);
}
return left;
},
expression: function() {
return this.assignment();
},
assignment: function() {
var result = this.ternary();
if (this.expect('=')) {
result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
}
return result;
},
ternary: function() {
var test = this.logicalOR();
var alternate;
var consequent;
if (this.expect('?')) {
alternate = this.expression();
if (this.consume(':')) {
consequent = this.expression();
return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
}
}
return test;
},
logicalOR: function() {
var left = this.logicalAND();
while (this.expect('||')) {
left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
}
return left;
},
logicalAND: function() {
var left = this.equality();
while (this.expect('&&')) {
left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
}
return left;
},
equality: function() {
var left = this.relational();
var token;
while ((token = this.expect('==','!=','===','!=='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
}
return left;
},
relational: function() {
var left = this.additive();
var token;
while ((token = this.expect('<', '>', '<=', '>='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
}
return left;
},
unary: function() {
var token;
if ((token = this.expect('+', '-', '!'))) {
return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
} else {
return this.primary();
}
},
primary: function() {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else if (this.constants.hasOwnProperty(this.peek().text)) {
primary = copy(this.constants[this.consume().text]);
} else if (this.peek().identifier) {
primary = this.identifier();
} else if (this.peek().constant) {
primary = this.constant();
} else {
this.throwError('not a primary expression', this.peek());
}
var next;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
this.consume(')');
} else if (next.text === '[') {
primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
this.consume(']');
} else if (next.text === '.') {
primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
filter: function(baseExpression) {
var args = [baseExpression];
var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
while (this.expect(':')) {
args.push(this.expression());
}
return result;
},
parseArguments: function() {
var args = [];
if (this.peekToken().text !== ')') {
do {
args.push(this.expression());
} while (this.expect(','));
}
return args;
},
identifier: function() {
var token = this.consume();
if (!token.identifier) {
this.throwError('is not a valid identifier', token);
}
return { type: AST.Identifier, name: token.text };
},
constant: function() {
// TODO check that it is a constant
return { type: AST.Literal, value: this.consume().value };
},
arrayDeclaration: function() {
var elements = [];
if (this.peekToken().text !== ']') {
do {
if (this.peek(']')) {
// Support trailing commas per ES5.1.
break;
}
elements.push(this.expression());
} while (this.expect(','));
}
this.consume(']');
return { type: AST.ArrayExpression, elements: elements };
},
object: function() {
var properties = [], property;
if (this.peekToken().text !== '}') {
do {
if (this.peek('}')) {
// Support trailing commas per ES5.1.
break;
}
property = {type: AST.Property, kind: 'init'};
if (this.peek().constant) {
property.key = this.constant();
} else if (this.peek().identifier) {
property.key = this.identifier();
} else {
this.throwError("invalid key", this.peek());
}
this.consume(':');
property.value = this.expression();
properties.push(property);
} while (this.expect(','));
}
this.consume('}');
return {type: AST.ObjectExpression, properties: properties };
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
consume: function(e1) {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
var token = this.expect(e1);
if (!token) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
return token;
},
peekToken: function() {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
return this.peekAhead(0, e1, e2, e3, e4);
},
peekAhead: function(i, e1, e2, e3, e4) {
if (this.tokens.length > i) {
var token = this.tokens[i];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4) {
var token = this.peek(e1, e2, e3, e4);
if (token) {
this.tokens.shift();
return token;
}
return false;
},
/* `undefined` is not a constant, it is an identifier,
* but using it as an identifier is not supported
*/
constants: {
'true': { type: AST.Literal, value: true },
'false': { type: AST.Literal, value: false },
'null': { type: AST.Literal, value: null },
'undefined': {type: AST.Literal, value: undefined },
'this': {type: AST.ThisExpression }
}
};
function ifDefined(v, d) {
return typeof v !== 'undefined' ? v : d;
}
function plusFn(l, r) {
if (typeof l === 'undefined') return r;
if (typeof r === 'undefined') return l;
return l + r;
}
function isStateless($filter, filterName) {
var fn = $filter(filterName);
return !fn.$stateful;
}
function findConstantAndWatchExpressions(ast, $filter) {
var allConstants;
var argsToWatch;
switch (ast.type) {
case AST.Program:
allConstants = true;
forEach(ast.body, function(expr) {
findConstantAndWatchExpressions(expr.expression, $filter);
allConstants = allConstants && expr.expression.constant;
});
ast.constant = allConstants;
break;
case AST.Literal:
ast.constant = true;
ast.toWatch = [];
break;
case AST.UnaryExpression:
findConstantAndWatchExpressions(ast.argument, $filter);
ast.constant = ast.argument.constant;
ast.toWatch = ast.argument.toWatch;
break;
case AST.BinaryExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
break;
case AST.LogicalExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.ConditionalExpression:
findConstantAndWatchExpressions(ast.test, $filter);
findConstantAndWatchExpressions(ast.alternate, $filter);
findConstantAndWatchExpressions(ast.consequent, $filter);
ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.Identifier:
ast.constant = false;
ast.toWatch = [ast];
break;
case AST.MemberExpression:
findConstantAndWatchExpressions(ast.object, $filter);
if (ast.computed) {
findConstantAndWatchExpressions(ast.property, $filter);
}
ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
ast.toWatch = [ast];
break;
case AST.CallExpression:
allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
argsToWatch = [];
forEach(ast.arguments, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
break;
case AST.AssignmentExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = [ast];
break;
case AST.ArrayExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.elements, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ObjectExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.properties, function(property) {
findConstantAndWatchExpressions(property.value, $filter);
allConstants = allConstants && property.value.constant;
if (!property.value.constant) {
argsToWatch.push.apply(argsToWatch, property.value.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ThisExpression:
ast.constant = false;
ast.toWatch = [];
break;
}
}
function getInputs(body) {
if (body.length != 1) return;
var lastExpression = body[0].expression;
var candidate = lastExpression.toWatch;
if (candidate.length !== 1) return candidate;
return candidate[0] !== lastExpression ? candidate : undefined;
}
function isAssignable(ast) {
return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
}
function assignableAST(ast) {
if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
}
}
function isLiteral(ast) {
return ast.body.length === 0 ||
ast.body.length === 1 && (
ast.body[0].expression.type === AST.Literal ||
ast.body[0].expression.type === AST.ArrayExpression ||
ast.body[0].expression.type === AST.ObjectExpression);
}
function isConstant(ast) {
return ast.constant;
}
function ASTCompiler(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTCompiler.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.state = {
nextId: 0,
filters: {},
expensiveChecks: expensiveChecks,
fn: {vars: [], body: [], own: {}},
assign: {vars: [], body: [], own: {}},
inputs: []
};
findConstantAndWatchExpressions(ast, self.$filter);
var extra = '';
var assignable;
this.stage = 'assign';
if ((assignable = assignableAST(ast))) {
this.state.computing = 'assign';
var result = this.nextId();
this.recurse(assignable, result);
extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
}
var toWatch = getInputs(ast.body);
self.stage = 'inputs';
forEach(toWatch, function(watch, key) {
var fnKey = 'fn' + key;
self.state[fnKey] = {vars: [], body: [], own: {}};
self.state.computing = fnKey;
var intoId = self.nextId();
self.recurse(watch, intoId);
self.return_(intoId);
self.state.inputs.push(fnKey);
watch.watchId = key;
});
this.state.computing = 'fn';
this.stage = 'main';
this.recurse(ast);
var fnString =
// The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
// This is a workaround for this until we do a better job at only removing the prefix only when we should.
'"' + this.USE + ' ' + this.STRICT + '";\n' +
this.filterPrefix() +
'var fn=' + this.generateFunction('fn', 's,l,a,i') +
extra +
this.watchFns() +
'return fn;';
/* jshint -W054 */
var fn = (new Function('$filter',
'ensureSafeMemberName',
'ensureSafeObject',
'ensureSafeFunction',
'ifDefined',
'plus',
'text',
fnString))(
this.$filter,
ensureSafeMemberName,
ensureSafeObject,
ensureSafeFunction,
ifDefined,
plusFn,
expression);
/* jshint +W054 */
this.state = this.stage = undefined;
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
USE: 'use',
STRICT: 'strict',
watchFns: function() {
var result = [];
var fns = this.state.inputs;
var self = this;
forEach(fns, function(name) {
result.push('var ' + name + '=' + self.generateFunction(name, 's'));
});
if (fns.length) {
result.push('fn.inputs=[' + fns.join(',') + '];');
}
return result.join('');
},
generateFunction: function(name, params) {
return 'function(' + params + '){' +
this.varsPrefix(name) +
this.body(name) +
'};';
},
filterPrefix: function() {
var parts = [];
var self = this;
forEach(this.state.filters, function(id, filter) {
parts.push(id + '=$filter(' + self.escape(filter) + ')');
});
if (parts.length) return 'var ' + parts.join(',') + ';';
return '';
},
varsPrefix: function(section) {
return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
},
body: function(section) {
return this.state[section].body.join('');
},
recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var left, right, self = this, args, expression;
recursionFn = recursionFn || noop;
if (!skipWatchIdCheck && isDefined(ast.watchId)) {
intoId = intoId || this.nextId();
this.if_('i',
this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
);
return;
}
switch (ast.type) {
case AST.Program:
forEach(ast.body, function(expression, pos) {
self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
if (pos !== ast.body.length - 1) {
self.current().body.push(right, ';');
} else {
self.return_(right);
}
});
break;
case AST.Literal:
expression = this.escape(ast.value);
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.UnaryExpression:
this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.BinaryExpression:
this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
if (ast.operator === '+') {
expression = this.plus(left, right);
} else if (ast.operator === '-') {
expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
} else {
expression = '(' + left + ')' + ast.operator + '(' + right + ')';
}
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.LogicalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.left, intoId);
self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
recursionFn(intoId);
break;
case AST.ConditionalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.test, intoId);
self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
recursionFn(intoId);
break;
case AST.Identifier:
intoId = intoId || this.nextId();
if (nameId) {
nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
nameId.computed = false;
nameId.name = ast.name;
}
ensureSafeMemberName(ast.name);
self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
function() {
self.if_(self.stage === 'inputs' || 's', function() {
if (create && create !== 1) {
self.if_(
self.not(self.nonComputedMember('s', ast.name)),
self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
}
self.assign(intoId, self.nonComputedMember('s', ast.name));
});
}, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
self.addEnsureSafeObject(intoId);
}
recursionFn(intoId);
break;
case AST.MemberExpression:
left = nameId && (nameId.context = this.nextId()) || this.nextId();
intoId = intoId || this.nextId();
self.recurse(ast.object, left, undefined, function() {
self.if_(self.notNull(left), function() {
if (ast.computed) {
right = self.nextId();
self.recurse(ast.property, right);
self.addEnsureSafeMemberName(right);
if (create && create !== 1) {
self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
}
expression = self.ensureSafeObject(self.computedMember(left, right));
self.assign(intoId, expression);
if (nameId) {
nameId.computed = true;
nameId.name = right;
}
} else {
ensureSafeMemberName(ast.property.name);
if (create && create !== 1) {
self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
}
expression = self.nonComputedMember(left, ast.property.name);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
expression = self.ensureSafeObject(expression);
}
self.assign(intoId, expression);
if (nameId) {
nameId.computed = false;
nameId.name = ast.property.name;
}
}
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
}, !!create);
break;
case AST.CallExpression:
intoId = intoId || this.nextId();
if (ast.filter) {
right = self.filter(ast.callee.name);
args = [];
forEach(ast.arguments, function(expr) {
var argument = self.nextId();
self.recurse(expr, argument);
args.push(argument);
});
expression = right + '(' + args.join(',') + ')';
self.assign(intoId, expression);
recursionFn(intoId);
} else {
right = self.nextId();
left = {};
args = [];
self.recurse(ast.callee, right, left, function() {
self.if_(self.notNull(right), function() {
self.addEnsureSafeFunction(right);
forEach(ast.arguments, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(self.ensureSafeObject(argument));
});
});
if (left.name) {
if (!self.state.expensiveChecks) {
self.addEnsureSafeObject(left.context);
}
expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
} else {
expression = right + '(' + args.join(',') + ')';
}
expression = self.ensureSafeObject(expression);
self.assign(intoId, expression);
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
});
}
break;
case AST.AssignmentExpression:
right = this.nextId();
left = {};
if (!isAssignable(ast.left)) {
throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
}
this.recurse(ast.left, undefined, left, function() {
self.if_(self.notNull(left.context), function() {
self.recurse(ast.right, right);
self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
self.assign(intoId, expression);
recursionFn(intoId || expression);
});
}, 1);
break;
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(argument);
});
});
expression = '[' + args.join(',') + ']';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
self.recurse(property.value, self.nextId(), undefined, function(expr) {
args.push(self.escape(
property.key.type === AST.Identifier ? property.key.name :
('' + property.key.value)) +
':' + expr);
});
});
expression = '{' + args.join(',') + '}';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ThisExpression:
this.assign(intoId, 's');
recursionFn('s');
break;
case AST.NGValueParameter:
this.assign(intoId, 'v');
recursionFn('v');
break;
}
},
getHasOwnProperty: function(element, property) {
var key = element + '.' + property;
var own = this.current().own;
if (!own.hasOwnProperty(key)) {
own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
}
return own[key];
},
assign: function(id, value) {
if (!id) return;
this.current().body.push(id, '=', value, ';');
return id;
},
filter: function(filterName) {
if (!this.state.filters.hasOwnProperty(filterName)) {
this.state.filters[filterName] = this.nextId(true);
}
return this.state.filters[filterName];
},
ifDefined: function(id, defaultValue) {
return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
},
plus: function(left, right) {
return 'plus(' + left + ',' + right + ')';
},
return_: function(id) {
this.current().body.push('return ', id, ';');
},
if_: function(test, alternate, consequent) {
if (test === true) {
alternate();
} else {
var body = this.current().body;
body.push('if(', test, '){');
alternate();
body.push('}');
if (consequent) {
body.push('else{');
consequent();
body.push('}');
}
}
},
not: function(expression) {
return '!(' + expression + ')';
},
notNull: function(expression) {
return expression + '!=null';
},
nonComputedMember: function(left, right) {
return left + '.' + right;
},
computedMember: function(left, right) {
return left + '[' + right + ']';
},
member: function(left, right, computed) {
if (computed) return this.computedMember(left, right);
return this.nonComputedMember(left, right);
},
addEnsureSafeObject: function(item) {
this.current().body.push(this.ensureSafeObject(item), ';');
},
addEnsureSafeMemberName: function(item) {
this.current().body.push(this.ensureSafeMemberName(item), ';');
},
addEnsureSafeFunction: function(item) {
this.current().body.push(this.ensureSafeFunction(item), ';');
},
ensureSafeObject: function(item) {
return 'ensureSafeObject(' + item + ',text)';
},
ensureSafeMemberName: function(item) {
return 'ensureSafeMemberName(' + item + ',text)';
},
ensureSafeFunction: function(item) {
return 'ensureSafeFunction(' + item + ',text)';
},
lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var self = this;
return function() {
self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
};
},
lazyAssign: function(id, value) {
var self = this;
return function() {
self.assign(id, value);
};
},
stringEscapeRegex: /[^ a-zA-Z0-9]/g,
stringEscapeFn: function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
},
escape: function(value) {
if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
if (isNumber(value)) return value.toString();
if (value === true) return 'true';
if (value === false) return 'false';
if (value === null) return 'null';
if (typeof value === 'undefined') return 'undefined';
throw $parseMinErr('esc', 'IMPOSSIBLE');
},
nextId: function(skip, init) {
var id = 'v' + (this.state.nextId++);
if (!skip) {
this.current().vars.push(id + (init ? '=' + init : ''));
}
return id;
},
current: function() {
return this.state[this.state.computing];
}
};
function ASTInterpreter(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTInterpreter.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.expression = expression;
this.expensiveChecks = expensiveChecks;
findConstantAndWatchExpressions(ast, self.$filter);
var assignable;
var assign;
if ((assignable = assignableAST(ast))) {
assign = this.recurse(assignable);
}
var toWatch = getInputs(ast.body);
var inputs;
if (toWatch) {
inputs = [];
forEach(toWatch, function(watch, key) {
var input = self.recurse(watch);
watch.input = input;
inputs.push(input);
watch.watchId = key;
});
}
var expressions = [];
forEach(ast.body, function(expression) {
expressions.push(self.recurse(expression.expression));
});
var fn = ast.body.length === 0 ? function() {} :
ast.body.length === 1 ? expressions[0] :
function(scope, locals) {
var lastValue;
forEach(expressions, function(exp) {
lastValue = exp(scope, locals);
});
return lastValue;
};
if (assign) {
fn.assign = function(scope, value, locals) {
return assign(scope, locals, value);
};
}
if (inputs) {
fn.inputs = inputs;
}
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
recurse: function(ast, context, create) {
var left, right, self = this, args, expression;
if (ast.input) {
return this.inputs(ast.input, ast.watchId);
}
switch (ast.type) {
case AST.Literal:
return this.value(ast.value, context);
case AST.UnaryExpression:
right = this.recurse(ast.argument);
return this['unary' + ast.operator](right, context);
case AST.BinaryExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.LogicalExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.ConditionalExpression:
return this['ternary?:'](
this.recurse(ast.test),
this.recurse(ast.alternate),
this.recurse(ast.consequent),
context
);
case AST.Identifier:
ensureSafeMemberName(ast.name, self.expression);
return self.identifier(ast.name,
self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
context, create, self.expression);
case AST.MemberExpression:
left = this.recurse(ast.object, false, !!create);
if (!ast.computed) {
ensureSafeMemberName(ast.property.name, self.expression);
right = ast.property.name;
}
if (ast.computed) right = this.recurse(ast.property);
return ast.computed ?
this.computedMember(left, right, context, create, self.expression) :
this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
case AST.CallExpression:
args = [];
forEach(ast.arguments, function(expr) {
args.push(self.recurse(expr));
});
if (ast.filter) right = this.$filter(ast.callee.name);
if (!ast.filter) right = this.recurse(ast.callee, true);
return ast.filter ?
function(scope, locals, assign, inputs) {
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(args[i](scope, locals, assign, inputs));
}
var value = right.apply(undefined, values, inputs);
return context ? {context: undefined, name: undefined, value: value} : value;
} :
function(scope, locals, assign, inputs) {
var rhs = right(scope, locals, assign, inputs);
var value;
if (rhs.value != null) {
ensureSafeObject(rhs.context, self.expression);
ensureSafeFunction(rhs.value, self.expression);
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
}
value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
}
return context ? {value: value} : value;
};
case AST.AssignmentExpression:
left = this.recurse(ast.left, true, 1);
right = this.recurse(ast.right);
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
ensureSafeObject(lhs.value, self.expression);
lhs.context[lhs.name] = rhs;
return context ? {value: rhs} : rhs;
};
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
args.push(self.recurse(expr));
});
return function(scope, locals, assign, inputs) {
var value = [];
for (var i = 0; i < args.length; ++i) {
value.push(args[i](scope, locals, assign, inputs));
}
return context ? {value: value} : value;
};
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
args.push({key: property.key.type === AST.Identifier ?
property.key.name :
('' + property.key.value),
value: self.recurse(property.value)
});
});
return function(scope, locals, assign, inputs) {
var value = {};
for (var i = 0; i < args.length; ++i) {
value[args[i].key] = args[i].value(scope, locals, assign, inputs);
}
return context ? {value: value} : value;
};
case AST.ThisExpression:
return function(scope) {
return context ? {value: scope} : scope;
};
case AST.NGValueParameter:
return function(scope, locals, assign, inputs) {
return context ? {value: assign} : assign;
};
}
},
'unary+': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = +arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary-': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = -arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary!': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = !argument(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary+': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = plusFn(lhs, rhs);
return context ? {value: arg} : arg;
};
},
'binary-': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
return context ? {value: arg} : arg;
};
},
'binary*': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary/': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary%': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary===': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary&&': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary||': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'ternary?:': function(test, alternate, consequent, context) {
return function(scope, locals, assign, inputs) {
var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
value: function(value, context) {
return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
},
identifier: function(name, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var base = locals && (name in locals) ? locals : scope;
if (create && create !== 1 && base && !(base[name])) {
base[name] = {};
}
var value = base ? base[name] : undefined;
if (expensiveChecks) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: base, name: name, value: value};
} else {
return value;
}
};
},
computedMember: function(left, right, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs;
var value;
if (lhs != null) {
rhs = right(scope, locals, assign, inputs);
ensureSafeMemberName(rhs, expression);
if (create && create !== 1 && lhs && !(lhs[rhs])) {
lhs[rhs] = {};
}
value = lhs[rhs];
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: rhs, value: value};
} else {
return value;
}
};
},
nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
if (create && create !== 1 && lhs && !(lhs[right])) {
lhs[right] = {};
}
var value = lhs != null ? lhs[right] : undefined;
if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: right, value: value};
} else {
return value;
}
};
},
inputs: function(input, watchId) {
return function(scope, value, locals, inputs) {
if (inputs) return inputs[watchId];
return input(scope, value, locals);
};
}
};
/**
* @constructor
*/
var Parser = function(lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
this.ast = new AST(this.lexer);
this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
new ASTCompiler(this.ast, $filter);
};
Parser.prototype = {
constructor: Parser,
parse: function(text) {
return this.astCompiler.compile(text, this.options.expensiveChecks);
}
};
var getterFnCacheDefault = createMap();
var getterFnCacheExpensive = createMap();
function isPossiblyDangerousMemberName(name) {
return name == 'constructor';
}
var objectValueOf = Object.prototype.valueOf;
function getValueOf(value) {
return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}
///////////////////////////////////
/**
* @ngdoc service
* @name $parse
* @kind function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* ```js
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* ```
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc provider
* @name $parseProvider
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cacheDefault = createMap();
var cacheExpensive = createMap();
this.$get = ['$filter', function($filter) {
var noUnsafeEval = csp().noUnsafeEval;
var $parseOptions = {
csp: noUnsafeEval,
expensiveChecks: false
},
$parseOptionsExpensive = {
csp: noUnsafeEval,
expensiveChecks: true
};
return function $parse(exp, interceptorFn, expensiveChecks) {
var parsedExpression, oneTime, cacheKey;
switch (typeof exp) {
case 'string':
exp = exp.trim();
cacheKey = exp;
var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
parsedExpression = cache[cacheKey];
if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
}
var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
var lexer = new Lexer(parseOptions);
var parser = new Parser(lexer, $filter, parseOptions);
parsedExpression = parser.parse(exp);
if (parsedExpression.constant) {
parsedExpression.$$watchDelegate = constantWatchDelegate;
} else if (oneTime) {
parsedExpression.$$watchDelegate = parsedExpression.literal ?
oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
} else if (parsedExpression.inputs) {
parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
case 'function':
return addInterceptor(exp, interceptorFn);
default:
return noop;
}
};
function expressionInputDirtyCheck(newValue, oldValueOfValue) {
if (newValue == null || oldValueOfValue == null) { // null/undefined
return newValue === oldValueOfValue;
}
if (typeof newValue === 'object') {
// attempt to convert the value to a primitive type
// TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
// be cheaply dirty-checked
newValue = getValueOf(newValue);
if (typeof newValue === 'object') {
// objects/arrays are not supported - deep-watching them would be too expensive
return false;
}
// fall-through to the primitive equality check
}
//Primitive or NaN
return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
}
function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
var inputExpressions = parsedExpression.inputs;
var lastResult;
if (inputExpressions.length === 1) {
var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
inputExpressions = inputExpressions[0];
return scope.$watch(function expressionInputWatch(scope) {
var newInputValue = inputExpressions(scope);
if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
oldInputValueOf = newInputValue && getValueOf(newInputValue);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
var oldInputValueOfValues = [];
var oldInputValues = [];
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
oldInputValues[i] = null;
}
return scope.$watch(function expressionInputsWatch(scope) {
var changed = false;
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
var newInputValue = inputExpressions[i](scope);
if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
oldInputValues[i] = newInputValue;
oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
}
}
if (changed) {
lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.apply(this, arguments);
}
if (isDefined(value)) {
scope.$$postDigest(function() {
if (isDefined(lastValue)) {
unwatch();
}
});
}
}, objectEquality);
}
function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.call(this, value, old, scope);
}
if (isAllDefined(value)) {
scope.$$postDigest(function() {
if (isAllDefined(lastValue)) unwatch();
});
}
}, objectEquality);
function isAllDefined(value) {
var allDefined = true;
forEach(value, function(val) {
if (!isDefined(val)) allDefined = false;
});
return allDefined;
}
}
function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
return parsedExpression(scope);
}, function constantListener(value, old, scope) {
if (isFunction(listener)) {
listener.apply(this, arguments);
}
unwatch();
}, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
if (!interceptorFn) return parsedExpression;
var watchDelegate = parsedExpression.$$watchDelegate;
var regularWatch =
watchDelegate !== oneTimeLiteralWatchDelegate &&
watchDelegate !== oneTimeWatchDelegate;
var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
return interceptorFn(value, scope, locals);
} : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
var result = interceptorFn(value, scope, locals);
// we only return the interceptor's result if the
// initial value is defined (for bind-once)
return isDefined(value) ? result : value;
};
// Propagate $$watchDelegates other then inputsWatchDelegate
if (parsedExpression.$$watchDelegate &&
parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
} else if (!interceptorFn.$stateful) {
// If there is an interceptor, but no watchDelegate then treat the interceptor like
// we treat filters - it is assumed to be a pure function unless flagged with $stateful
fn.$$watchDelegate = inputsWatchDelegate;
fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
}
return fn;
}
}];
}
/**
* @ngdoc service
* @name $q
* @requires $rootScope
*
* @description
* A service that helps you run functions asynchronously, and use their return values (or exceptions)
* when they are done processing.
*
* This is an implementation of promises/deferred objects inspired by
* [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
* implementations, and the other which resembles ES6 promises to some degree.
*
* # $q constructor
*
* The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
* function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
* see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
*
* While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
* available yet.
*
* It can be used like so:
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* // perform some asynchronous operation, resolve or reject the promise when appropriate.
* return $q(function(resolve, reject) {
* setTimeout(function() {
* if (okToGreet(name)) {
* resolve('Hello, ' + name + '!');
* } else {
* reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
* });
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* ```
*
* Note: progress/notify callbacks are not currently supported via the ES6-style interface.
*
* However, the more traditional CommonJS-style usage is still available, and documented below.
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* deferred.notify('About to greet ' + name + '.');
*
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* }, function(update) {
* alert('Got notification: ' + update);
* });
* ```
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of guarantees that promise and deferred APIs make, see
* https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion, as well as the status
* of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
* - `notify(value)` - provides updates on the status of the promise's execution. This may be called
* multiple times before the promise is either resolved or rejected.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
* will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
* as soon as the result is available. The callbacks are called with a single argument: the result
* or rejection reason. Additionally, the notify callback may be called zero or more times to
* provide a progress indication, before the promise is resolved or rejected.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
* with the value which is resolved in that promise using
* [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
* It also notifies via the return value of the `notifyCallback` method. The promise cannot be
* resolved or rejected from the notifyCallback method.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
*
* - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
* but to do so without modifying the final value. This is useful to release resources or do some
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
* more information.
*
* # Chaining promises
*
* Because calling the `then` method of a promise returns a new derived promise, it is easily
* possible to create a chain of promises:
*
* ```js
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value
* // will be the result of promiseA incremented by 1
* ```
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are two main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* ```js
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* }));
* ```
*
* @param {function(function, function)} resolver Function which is responsible for resolving or
* rejecting the newly created promise. The first parameter is a function which resolves the
* promise, the second parameter is a function which rejects the promise.
*
* @returns {Promise} The newly created promise.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
function $$QProvider() {
this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
return qFactory(function(callback) {
$browser.defer(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
var $qMinErr = minErr('$q', TypeError);
function callOnce(self, resolveFn, rejectFn) {
var called = false;
function wrap(fn) {
return function(value) {
if (called) return;
called = true;
fn.call(self, value);
};
}
return [wrap(resolveFn), wrap(rejectFn)];
}
/**
* @ngdoc method
* @name ng.$q#defer
* @kind function
*
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
return new Deferred();
};
function Promise() {
this.$$state = { status: 0 };
}
extend(Promise.prototype, {
then: function(onFulfilled, onRejected, progressBack) {
if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
return this;
}
var result = new Deferred();
this.$$state.pending = this.$$state.pending || [];
this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
return result.promise;
},
"catch": function(callback) {
return this.then(null, callback);
},
"finally": function(callback, progressBack) {
return this.then(function(value) {
return handleCallback(value, true, callback);
}, function(error) {
return handleCallback(error, false, callback);
}, progressBack);
}
});
//Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
function simpleBind(context, fn) {
return function(value) {
fn.call(context, value);
};
}
function processQueue(state) {
var fn, deferred, pending;
pending = state.pending;
state.processScheduled = false;
state.pending = undefined;
for (var i = 0, ii = pending.length; i < ii; ++i) {
deferred = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
deferred.resolve(fn(state.value));
} else if (state.status === 1) {
deferred.resolve(state.value);
} else {
deferred.reject(state.value);
}
} catch (e) {
deferred.reject(e);
exceptionHandler(e);
}
}
}
function scheduleProcessQueue(state) {
if (state.processScheduled || !state.pending) return;
state.processScheduled = true;
nextTick(function() { processQueue(state); });
}
function Deferred() {
this.promise = new Promise();
//Necessary to support unbound execution :/
this.resolve = simpleBind(this, this.resolve);
this.reject = simpleBind(this, this.reject);
this.notify = simpleBind(this, this.notify);
}
extend(Deferred.prototype, {
resolve: function(val) {
if (this.promise.$$state.status) return;
if (val === this.promise) {
this.$$reject($qMinErr(
'qcycle',
"Expected promise to be resolved with value other than itself '{0}'",
val));
} else {
this.$$resolve(val);
}
},
$$resolve: function(val) {
var then, fns;
fns = callOnce(this, this.$$resolve, this.$$reject);
try {
if ((isObject(val) || isFunction(val))) then = val && val.then;
if (isFunction(then)) {
this.promise.$$state.status = -1;
then.call(val, fns[0], fns[1], this.notify);
} else {
this.promise.$$state.value = val;
this.promise.$$state.status = 1;
scheduleProcessQueue(this.promise.$$state);
}
} catch (e) {
fns[1](e);
exceptionHandler(e);
}
},
reject: function(reason) {
if (this.promise.$$state.status) return;
this.$$reject(reason);
},
$$reject: function(reason) {
this.promise.$$state.value = reason;
this.promise.$$state.status = 2;
scheduleProcessQueue(this.promise.$$state);
},
notify: function(progress) {
var callbacks = this.promise.$$state.pending;
if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
nextTick(function() {
var callback, result;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
result = callbacks[i][0];
callback = callbacks[i][3];
try {
result.notify(isFunction(callback) ? callback(progress) : progress);
} catch (e) {
exceptionHandler(e);
}
}
});
}
}
});
/**
* @ngdoc method
* @name $q#reject
* @kind function
*
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* ```js
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* ```
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
var result = new Deferred();
result.reject(reason);
return result.promise;
};
var makePromise = function makePromise(value, resolved) {
var result = new Deferred();
if (resolved) {
result.resolve(value);
} else {
result.reject(value);
}
return result.promise;
};
var handleCallback = function handleCallback(value, isResolved, callback) {
var callbackOutput = null;
try {
if (isFunction(callback)) callbackOutput = callback();
} catch (e) {
return makePromise(e, false);
}
if (isPromiseLike(callbackOutput)) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
} else {
return makePromise(value, isResolved);
}
};
/**
* @ngdoc method
* @name $q#when
* @kind function
*
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @param {Function=} successCallback
* @param {Function=} errorCallback
* @param {Function=} progressCallback
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback, progressBack) {
var result = new Deferred();
result.resolve(value);
return result.promise.then(callback, errback, progressBack);
};
/**
* @ngdoc method
* @name $q#resolve
* @kind function
*
* @description
* Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
*
* @param {*} value Value or a promise
* @param {Function=} successCallback
* @param {Function=} errorCallback
* @param {Function=} progressCallback
* @returns {Promise} Returns a promise of the passed value or promise
*/
var resolve = when;
/**
* @ngdoc method
* @name $q#all
* @kind function
*
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
* each value corresponding to the promise at the same index/key in the `promises` array/hash.
* If any of the promises is resolved with a rejection, this resulting promise will be rejected
* with the same rejection value.
*/
function all(promises) {
var deferred = new Deferred(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
when(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (results.hasOwnProperty(key)) return;
deferred.reject(reason);
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
var $Q = function Q(resolver) {
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}
if (!(this instanceof Q)) {
// More useful when $Q is the Promise itself.
return new Q(resolver);
}
var deferred = new Deferred();
function resolveFn(value) {
deferred.resolve(value);
}
function rejectFn(reason) {
deferred.reject(reason);
}
resolver(resolveFn, rejectFn);
return deferred.promise;
};
$Q.defer = defer;
$Q.reject = reject;
$Q.when = when;
$Q.resolve = resolve;
$Q.all = all;
return $Q;
}
function $$RAFProvider() { //rAF
this.$get = ['$window', '$timeout', function($window, $timeout) {
var requestAnimationFrame = $window.requestAnimationFrame ||
$window.webkitRequestAnimationFrame;
var cancelAnimationFrame = $window.cancelAnimationFrame ||
$window.webkitCancelAnimationFrame ||
$window.webkitCancelRequestAnimationFrame;
var rafSupported = !!requestAnimationFrame;
var rafFn = rafSupported
? function(fn) {
var id = requestAnimationFrame(fn);
return function() {
cancelAnimationFrame(id);
};
}
: function(fn) {
var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
return function() {
$timeout.cancel(timer);
};
};
queueFn.supported = rafSupported;
var cancelLastRAF;
var taskCount = 0;
var taskQueue = [];
return queueFn;
function flush() {
for (var i = 0; i < taskQueue.length; i++) {
var task = taskQueue[i];
if (task) {
taskQueue[i] = null;
task();
}
}
taskCount = taskQueue.length = 0;
}
function queueFn(asyncFn) {
var index = taskQueue.length;
taskCount++;
taskQueue.push(asyncFn);
if (index === 0) {
cancelLastRAF = rafFn(flush);
}
return function cancelQueueFn() {
if (index >= 0) {
taskQueue[index] = null;
index = null;
if (--taskCount === 0 && cancelLastRAF) {
cancelLastRAF();
cancelLastRAF = null;
taskQueue.length = 0;
}
}
};
}
}];
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (unshift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc provider
* @name $rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc method
* @name $rootScopeProvider#digestTtl
* @description
*
* Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* In complex applications it's possible that the dependencies between `$watch`s will result in
* several digest iterations. However if an application needs more than the default 10 digest
* iterations for its model to stabilize then you should investigate what is causing the model to
* continuously change during the digest.
*
* Increasing the TTL could have performance implications, so you should not change it without
* proper justification.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc service
* @name $rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are descendant scopes of the root scope. Scopes provide separation
* between the model and the view, via a mechanism for watching the model for changes.
* They also provide an event emission/broadcast and subscription facility. See the
* {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider() {
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
var lastDirtyWatch = null;
var applyAsyncId = null;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
function createChildScopeClass(parent) {
function ChildScope() {
this.$$watchers = this.$$nextSibling =
this.$$childHead = this.$$childTail = null;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$id = nextUid();
this.$$ChildScope = null;
}
ChildScope.prototype = parent;
return ChildScope;
}
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
function($injector, $exceptionHandler, $parse, $browser) {
function destroyChildScope($event) {
$event.currentScope.$$destroyed = true;
}
/**
* @ngdoc type
* @name $rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link auto.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
* an in-depth introduction and usage examples.
*
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* ```js
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* ```
*
* When interacting with `Scope` in tests, additional helper methods are available on the
* instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
* details.
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be
* provided for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy
* when unit-testing and having the need to override a default
* service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this.$root = this;
this.$$destroyed = false;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$$isolateBindings = null;
}
/**
* @ngdoc property
* @name $rootScope.Scope#$id
*
* @description
* Unique scope ID (monotonically increasing) useful for debugging.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$parent
*
* @description
* Reference to the parent scope.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$root
*
* @description
* Reference to the root scope.
*/
Scope.prototype = {
constructor: Scope,
/**
* @ngdoc method
* @name $rootScope.Scope#$new
* @kind function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
* The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
* desired for the scope and its child scopes to be permanently detached from the parent and
* thus stop participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate If true, then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets, it is useful for the widget to not accidentally read parent
* state.
*
* @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
* of the newly created scope. Defaults to `this` scope if not provided.
* This is used when creating a transclude scope to correctly place it
* in the scope hierarchy while maintaining the correct prototypical
* inheritance.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate, parent) {
var child;
parent = parent || this;
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
// Only create a child scope class if somebody asks for one,
// but cache it to allow the VM to optimize lookups.
if (!this.$$ChildScope) {
this.$$ChildScope = createChildScopeClass(this);
}
child = new this.$$ChildScope();
}
child.$parent = parent;
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
parent.$$childHead = parent.$$childTail = child;
}
// When the new scope is not isolated or we inherit from `this`, and
// the parent scope is destroyed, the property `$$destroyed` is inherited
// prototypically. In all other cases, this property needs to be set
// when the parent scope is destroyed.
// The listener needs to be added after the parent is set
if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
return child;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watch
* @kind function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
* $digest()} and should return the value that will be watched. (Since
* {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
* `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). Inequality is determined according to reference inequality,
* [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
* via the `!==` Javascript operator, unless `objectEquality == true`
* (see next point)
* - When `objectEquality == true`, inequality of the `watchExpression` is determined
* according to the {@link angular.equals} function. To save the value of the object for
* later comparison, the {@link angular.copy} function is used. This therefore means that
* watching complex objects will have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire.
* This is achieved by rerunning the watchers until no changes are detected. The rerun
* iteration limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Be prepared for
* multiple calls to your `watchExpression` because it will execute multiple times in a
* single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
*
* # Example
* ```js
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
// Using a function as a watchExpression
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
// This function returns the value being watched. It is called for each turn of the $digest loop
function() { return food; },
// This is the change listener, called when the value returned from the above function changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);
// No digest has been run so the counter will be zero
expect(scope.foodCounter).toEqual(0);
// Run the digest but since food has not changed count will still be zero
scope.$digest();
expect(scope.foodCounter).toEqual(0);
// Update food and run digest. Now the counter will increment
food = 'cheeseburger';
scope.$digest();
expect(scope.foodCounter).toEqual(1);
* ```
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
* a call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
* of `watchExpression` changes.
*
* - `newVal` contains the current value of the `watchExpression`
* - `oldVal` contains the previous value of the `watchExpression`
* - `scope` refers to the current scope
* @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
* comparing for reference equality.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
var get = $parse(watchExp);
if (get.$$watchDelegate) {
return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
}
var scope = this,
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: prettyPrintExpression || watchExp,
eq: !!objectEquality
};
lastDirtyWatch = null;
if (!isFunction(listener)) {
watcher.fn = noop;
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
incrementWatchersCount(this, 1);
return function deregisterWatch() {
if (arrayRemove(array, watcher) >= 0) {
incrementWatchersCount(scope, -1);
}
lastDirtyWatch = null;
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchGroup
* @kind function
*
* @description
* A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
* If any one expression in the collection changes the `listener` is executed.
*
* - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
* call to $digest() to see if any items changes.
* - The `listener` is called whenever any expression in the `watchExpressions` array changes.
*
* @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
* watched using {@link ng.$rootScope.Scope#$watch $watch()}
*
* @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
* expression in `watchExpressions` changes
* The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* The `scope` refers to the current scope.
* @returns {function()} Returns a de-registration function for all listeners.
*/
$watchGroup: function(watchExpressions, listener) {
var oldValues = new Array(watchExpressions.length);
var newValues = new Array(watchExpressions.length);
var deregisterFns = [];
var self = this;
var changeReactionScheduled = false;
var firstRun = true;
if (!watchExpressions.length) {
// No expressions means we call the listener ASAP
var shouldCall = true;
self.$evalAsync(function() {
if (shouldCall) listener(newValues, newValues, self);
});
return function deregisterWatchGroup() {
shouldCall = false;
};
}
if (watchExpressions.length === 1) {
// Special case size of one
return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
newValues[0] = value;
oldValues[0] = oldValue;
listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
});
}
forEach(watchExpressions, function(expr, i) {
var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
newValues[i] = value;
oldValues[i] = oldValue;
if (!changeReactionScheduled) {
changeReactionScheduled = true;
self.$evalAsync(watchGroupAction);
}
});
deregisterFns.push(unwatchFn);
});
function watchGroupAction() {
changeReactionScheduled = false;
if (firstRun) {
firstRun = false;
listener(newValues, newValues, self);
} else {
listener(newValues, oldValues, self);
}
}
return function deregisterWatchGroup() {
while (deregisterFns.length) {
deregisterFns.shift()();
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchCollection
* @kind function
*
* @description
* Shallow watches the properties of an object and fires whenever any of the properties change
* (for arrays, this implies watching the array items; for object maps, this implies watching
* the properties). If a change is detected, the `listener` callback is fired.
*
* - The `obj` collection is observed via standard $watch operation and is examined on every
* call to $digest() to see if any items have been added, removed, or moved.
* - The `listener` is called whenever anything within the `obj` has changed. Examples include
* adding, removing, and moving items belonging to an object or array.
*
*
* # Example
* ```js
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
* ```
*
*
* @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
* expression value should evaluate to an object or an array which is observed on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
* collection will trigger a call to the `listener`.
*
* @param {function(newCollection, oldCollection, scope)} listener a callback function called
* when a change is detected.
* - The `newCollection` object is the newly modified data obtained from the `obj` expression
* - The `oldCollection` object is a copy of the former collection data.
* Due to performance considerations, the`oldCollection` value is computed only if the
* `listener` function declares two or more arguments.
* - The `scope` argument refers to the current scope.
*
* @returns {function()} Returns a de-registration function for this listener. When the
* de-registration function is executed, the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
$watchCollectionInterceptor.$stateful = true;
var self = this;
// the current value, updated on each dirty-check run
var newValue;
// a shallow copy of the newValue from the last dirty-check run,
// updated to match newValue during dirty-check run
var oldValue;
// a shallow copy of the newValue from when the last change happened
var veryOldValue;
// only track veryOldValue if the listener is asking for it
var trackVeryOldValue = (listener.length > 1);
var changeDetected = 0;
var changeDetector = $parse(obj, $watchCollectionInterceptor);
var internalArray = [];
var internalObject = {};
var initRun = true;
var oldLength = 0;
function $watchCollectionInterceptor(_value) {
newValue = _value;
var newLength, key, bothNaN, newItem, oldItem;
// If the new value is undefined, then return undefined as the watch may be a one-time watch
if (isUndefined(newValue)) return;
if (!isObject(newValue)) { // if primitive
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
}
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
oldLength = oldValue.length = 0;
changeDetected++;
}
newLength = newValue.length;
if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
oldItem = oldValue[i];
newItem = newValue[i];
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[i] = newItem;
}
}
} else {
if (oldValue !== internalObject) {
// we are transitioning from something which was not an object into object.
oldValue = internalObject = {};
oldLength = 0;
changeDetected++;
}
// copy the items to oldValue and look for changes.
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
newItem = newValue[key];
oldItem = oldValue[key];
if (key in oldValue) {
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[key] = newItem;
}
} else {
oldLength++;
oldValue[key] = newItem;
changeDetected++;
}
}
}
if (oldLength > newLength) {
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for (key in oldValue) {
if (!newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
}
}
}
return changeDetected;
}
function $watchCollectionAction() {
if (initRun) {
initRun = false;
listener(newValue, newValue, self);
} else {
listener(newValue, veryOldValue, self);
}
// make a copy for the next time a collection is changed
if (trackVeryOldValue) {
if (!isObject(newValue)) {
//primitive
veryOldValue = newValue;
} else if (isArrayLike(newValue)) {
veryOldValue = new Array(newValue.length);
for (var i = 0; i < newValue.length; i++) {
veryOldValue[i] = newValue[i];
}
} else { // if object
veryOldValue = {};
for (var key in newValue) {
if (hasOwnProperty.call(newValue, key)) {
veryOldValue[key] = newValue[key];
}
}
}
}
}
return this.$watch(changeDetector, $watchCollectionAction);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$digest
* @kind function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
* its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
* the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
* until no more listeners are firing. This means that it is possible to get into an infinite
* loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
* iterations exceeds 10.
*
* Usually, you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
* a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with
* {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
*
* In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
*
* # Example
* ```js
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
* ```
*
*/
$digest: function() {
var watch, value, last,
watchers,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg, asyncTask;
beginPhase('$digest');
// Check for changes to browser url that happened in sync before the call to $digest
$browser.$$checkUrlChange();
if (this === $rootScope && applyAsyncId !== null) {
// If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
// cancel the scheduled $apply and flush the queue of expressions to be evaluated.
$browser.defer.cancel(applyAsyncId);
flushApplyAsync();
}
lastDirtyWatch = null;
do { // "while dirty" loop
dirty = false;
current = target;
while (asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
} catch (e) {
$exceptionHandler(e);
}
lastDirtyWatch = null;
}
traverseScopesLoop:
do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch) {
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value === 'number' && typeof last === 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
lastDirtyWatch = watch;
watch.last = watch.eq ? copy(value, null) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
watchLog[logIdx].push({
msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
newVal: value,
oldVal: last
});
}
} else if (watch === lastDirtyWatch) {
// If the most recently dirty watcher is now clean, short circuit since the remaining watchers
// have already been tested.
dirty = false;
break traverseScopesLoop;
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = ((current.$$watchersCount && current.$$childHead) ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
// `break traverseScopesLoop;` takes us to here
if ((dirty || asyncQueue.length) && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: {1}',
TTL, watchLog);
}
} while (dirty || asyncQueue.length);
clearPhase();
while (postDigestQueue.length) {
try {
postDigestQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
},
/**
* @ngdoc event
* @name $rootScope.Scope#$destroy
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
/**
* @ngdoc method
* @name $rootScope.Scope#$destroy
* @kind function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it a chance to
* perform any necessary cleanup.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// We can't destroy a scope that has been already destroyed.
if (this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (this === $rootScope) {
//Remove handlers attached to window when $rootScope is removed
$browser.$$applicationDestroyed();
}
incrementWatchersCount(this, -this.$$watchersCount);
for (var eventName in this.$$listenerCount) {
decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
}
// sever all the references to parent scopes (after this cleanup, the current scope should
// not be retained by any of our references and should be eligible for garbage collection)
if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// Disable listeners, watchers and apply/digest methods
this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
this.$on = this.$watch = this.$watchGroup = function() { return noop; };
this.$$listeners = {};
// All of the code below is bogus code that works around V8's memory leak via optimized code
// and inline caches.
//
// see:
// - https://code.google.com/p/v8/issues/detail?id=2073#c26
// - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
// - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = this.$root = this.$$watchers = null;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$eval
* @kind function
*
* @description
* Executes the `expression` on the current scope and returns the result. Any exceptions in
* the expression are propagated (uncaught). This is useful when evaluating Angular
* expressions.
*
* # Example
* ```js
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* ```
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$evalAsync
* @kind function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
* that:
*
* - it will execute after the function that scheduled the evaluation (preferably before DOM
* rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
* will be scheduled. However, it is encouraged to always call code that changes the model
* from within an `$apply` call. That includes code evaluated via `$evalAsync`.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
*/
$evalAsync: function(expr, locals) {
// if we are outside of an $digest loop and this is the first time we are scheduling async
// task also schedule async auto-flush
if (!$rootScope.$$phase && !asyncQueue.length) {
$browser.defer(function() {
if (asyncQueue.length) {
$rootScope.$digest();
}
});
}
asyncQueue.push({scope: this, expression: expr, locals: locals});
},
$$postDigest: function(fn) {
postDigestQueue.push(fn);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$apply
* @kind function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life
* cycle of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* ```js
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* ```
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
* expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
try {
return this.$eval(expr);
} finally {
clearPhase();
}
} catch (e) {
$exceptionHandler(e);
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$applyAsync
* @kind function
*
* @description
* Schedule the invocation of $apply to occur at a later time. The actual time difference
* varies across browsers, but is typically around ~10 milliseconds.
*
* This can be used to queue up multiple expressions which need to be evaluated in the same
* digest.
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*/
$applyAsync: function(expr) {
var scope = this;
expr && applyAsyncQueue.push($applyAsyncExpression);
scheduleApplyAsync();
function $applyAsyncExpression() {
scope.$eval(expr);
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$on
* @kind function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
* discussion of event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
* `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
* event propagates through the scope hierarchy, this property is set to null.
* - `name` - `{string}`: name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
* further event propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
* to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, ...args)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
var current = this;
do {
if (!current.$$listenerCount[name]) {
current.$$listenerCount[name] = 0;
}
current.$$listenerCount[name]++;
} while ((current = current.$parent));
var self = this;
return function() {
var indexOfListener = namedListeners.indexOf(listener);
if (indexOfListener !== -1) {
namedListeners[indexOfListener] = null;
decrementListenerCount(self, 1, name);
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$emit
* @kind function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event traverses upwards toward the root scope and calls all
* registered listeners along the way. The event will stop propagating if one of the listeners
* cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i = 0, length = namedListeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
//allow all listeners attached to the current scope to run
namedListeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
//if any listener on the current scope stops propagation, prevent bubbling
if (stopPropagation) {
event.currentScope = null;
return event;
}
//traverse upwards
scope = scope.$parent;
} while (scope);
event.currentScope = null;
return event;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$broadcast
* @kind function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event propagates to all direct and indirect scopes of the current
* scope and calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
};
if (!target.$$listenerCount[name]) return event;
var listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
while ((current = next)) {
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i = 0, length = listeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
// (though it differs due to having the extra check for $$listenerCount)
if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
}
event.currentScope = null;
return event;
}
};
var $rootScope = new Scope();
//The internal queues. Expose them on the $rootScope for debugging/testing purposes.
var asyncQueue = $rootScope.$$asyncQueue = [];
var postDigestQueue = $rootScope.$$postDigestQueue = [];
var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function incrementWatchersCount(current, count) {
do {
current.$$watchersCount += count;
} while ((current = current.$parent));
}
function decrementListenerCount(current, count, name) {
do {
current.$$listenerCount[name] -= count;
if (current.$$listenerCount[name] === 0) {
delete current.$$listenerCount[name];
}
} while ((current = current.$parent));
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
function flushApplyAsync() {
while (applyAsyncQueue.length) {
try {
applyAsyncQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
applyAsyncId = null;
}
function scheduleApplyAsync() {
if (applyAsyncId === null) {
applyAsyncId = $browser.defer(function() {
$rootScope.$apply(flushApplyAsync);
});
}
}
}];
}
/**
* @description
* Private service to sanitize uris for links and images. Used by $compile and $sanitize.
*/
function $$SanitizeUriProvider() {
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = function() {
return function sanitizeUri(uri, isImage) {
var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
var normalizedVal;
normalizedVal = urlResolve(uri).href;
if (normalizedVal !== '' && !normalizedVal.match(regex)) {
return 'unsafe:' + normalizedVal;
}
return uri;
};
};
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $sceMinErr = minErr('$sce');
var SCE_CONTEXTS = {
HTML: 'html',
CSS: 'css',
URL: 'url',
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
// url. (e.g. ng-include, script src, templateUrl)
RESOURCE_URL: 'resourceUrl',
JS: 'js'
};
// Helper functions follow.
function adjustMatcher(matcher) {
if (matcher === 'self') {
return matcher;
} else if (isString(matcher)) {
// Strings match exactly except for 2 wildcards - '*' and '**'.
// '*' matches any character except those from the set ':/.?&'.
// '**' matches any character (like .* in a RegExp).
// More than 2 *'s raises an error as it's ill defined.
if (matcher.indexOf('***') > -1) {
throw $sceMinErr('iwcard',
'Illegal sequence *** in string matcher. String: {0}', matcher);
}
matcher = escapeForRegexp(matcher).
replace('\\*\\*', '.*').
replace('\\*', '[^:/.?&;]*');
return new RegExp('^' + matcher + '$');
} else if (isRegExp(matcher)) {
// The only other type of matcher allowed is a Regexp.
// Match entire URL / disallow partial matches.
// Flags are reset (i.e. no global, ignoreCase or multiline)
return new RegExp('^' + matcher.source + '$');
} else {
throw $sceMinErr('imatcher',
'Matchers may only be "self", string patterns or RegExp objects');
}
}
function adjustMatchers(matchers) {
var adjustedMatchers = [];
if (isDefined(matchers)) {
forEach(matchers, function(matcher) {
adjustedMatchers.push(adjustMatcher(matcher));
});
}
return adjustedMatchers;
}
/**
* @ngdoc service
* @name $sceDelegate
* @kind function
*
* @description
*
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
* Contextual Escaping (SCE)} services to AngularJS.
*
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
* work because `$sce` delegates to `$sceDelegate` for these operations.
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
*
* The default instance of `$sceDelegate` should work out of the box with little pain. While you
* can override it completely to change the behavior of `$sce`, the common case would
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
* templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
* $sceDelegateProvider.resourceUrlWhitelist} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*/
/**
* @ngdoc provider
* @name $sceDelegateProvider
* @description
*
* The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
* that the URLs used for sourcing Angular templates are safe. Refer {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
* {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*
* For the general details about this service in Angular, read the main page for {@link ng.$sce
* Strict Contextual Escaping (SCE)}.
*
* **Example**: Consider the following case. <a name="example"></a>
*
* - your app is hosted at url `http://myapp.example.com/`
* - but some of your templates are hosted on other domains you control such as
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
*
* Here is what a secure configuration for this scenario might look like:
*
* ```
* angular.module('myApp', []).config(function($sceDelegateProvider) {
* $sceDelegateProvider.resourceUrlWhitelist([
* // Allow same origin resource loads.
* 'self',
* // Allow loading from our assets domain. Notice the difference between * and **.
* 'http://srv*.assets.example.com/**'
* ]);
*
* // The blacklist overrides the whitelist so the open redirect here is blocked.
* $sceDelegateProvider.resourceUrlBlacklist([
* 'http://myapp.example.com/clickThru**'
* ]);
* });
* ```
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
// Resource URLs can also be trusted by policy.
var resourceUrlWhitelist = ['self'],
resourceUrlBlacklist = [];
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlWhitelist
* @kind function
*
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* Note: **an empty whitelist array will block all URLs**!
*
* @return {Array} the currently set whitelist array.
*
* The **default value** when no whitelist has been explicitly set is `['self']` allowing only
* same origin resource requests.
*
* @description
* Sets/Gets the whitelist of trusted resource URLs.
*/
this.resourceUrlWhitelist = function(value) {
if (arguments.length) {
resourceUrlWhitelist = adjustMatchers(value);
}
return resourceUrlWhitelist;
};
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlBlacklist
* @kind function
*
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* The typical usage for the blacklist is to **block
* [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
* these would otherwise be trusted but actually return content from the redirected domain.
*
* Finally, **the blacklist overrides the whitelist** and has the final say.
*
* @return {Array} the currently set blacklist array.
*
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
* is no blacklist.)
*
* @description
* Sets/Gets the blacklist of trusted resource URLs.
*/
this.resourceUrlBlacklist = function(value) {
if (arguments.length) {
resourceUrlBlacklist = adjustMatchers(value);
}
return resourceUrlBlacklist;
};
this.$get = ['$injector', function($injector) {
var htmlSanitizer = function htmlSanitizer(html) {
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
};
if ($injector.has('$sanitize')) {
htmlSanitizer = $injector.get('$sanitize');
}
function matchUrl(matcher, parsedUrl) {
if (matcher === 'self') {
return urlIsSameOrigin(parsedUrl);
} else {
// definitely a regex. See adjustMatchers()
return !!matcher.exec(parsedUrl.href);
}
}
function isResourceUrlAllowedByPolicy(url) {
var parsedUrl = urlResolve(url.toString());
var i, n, allowed = false;
// Ensure that at least one item from the whitelist allows this url.
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
allowed = true;
break;
}
}
if (allowed) {
// Ensure that no item from the blacklist blocked this url.
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
allowed = false;
break;
}
}
}
return allowed;
}
function generateHolderType(Base) {
var holderType = function TrustedValueHolderType(trustedValue) {
this.$$unwrapTrustedValue = function() {
return trustedValue;
};
};
if (Base) {
holderType.prototype = new Base();
}
holderType.prototype.valueOf = function sceValueOf() {
return this.$$unwrapTrustedValue();
};
holderType.prototype.toString = function sceToString() {
return this.$$unwrapTrustedValue().toString();
};
return holderType;
}
var trustedValueHolderBase = generateHolderType(),
byType = {};
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
/**
* @ngdoc method
* @name $sceDelegate#trustAs
*
* @description
* Returns an object that is trusted by angular for use in specified strict
* contextual escaping contexts (such as ng-bind-html, ng-include, any src
* attribute interpolation, any dom event binding attribute interpolation
* such as for onclick, etc.) that uses the provided value.
* See {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
function trustAs(type, trustedValue) {
var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (!Constructor) {
throw $sceMinErr('icontext',
'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
type, trustedValue);
}
if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
return trustedValue;
}
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
// mutable objects, we ensure here that the value passed in is actually a string.
if (typeof trustedValue !== 'string') {
throw $sceMinErr('itype',
'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
type);
}
return new Constructor(trustedValue);
}
/**
* @ngdoc method
* @name $sceDelegate#valueOf
*
* @description
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
*
* If the passed parameter is not a value that had been returned by {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
*
* @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
* call or anything else.
* @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
* `value` unchanged.
*/
function valueOf(maybeTrusted) {
if (maybeTrusted instanceof trustedValueHolderBase) {
return maybeTrusted.$$unwrapTrustedValue();
} else {
return maybeTrusted;
}
}
/**
* @ngdoc method
* @name $sceDelegate#getTrusted
*
* @description
* Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
* returns the originally supplied value if the queried context type is a supertype of the
* created type. If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
*/
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
}
/**
* @ngdoc provider
* @name $sceProvider
* @description
*
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
* - enable/disable Strict Contextual Escaping (SCE) in a module
* - override the default implementation with a custom delegate
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
/* jshint maxlen: false*/
/**
* @ngdoc service
* @name $sce
* @kind function
*
* @description
*
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
*
* # Strict Contextual Escaping
*
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
* contexts to result in a value that is marked as safe to use for that context. One example of
* such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
* to these contexts as privileged or SCE contexts.
*
* As of version 1.2, Angular ships with SCE enabled by default.
*
* Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
* one to execute arbitrary javascript by the use of the expression() syntax. Refer
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
* to the top of your HTML document.
*
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
* ```
* <input ng-model="userHtml" aria-label="User input">
* <div ng-bind-html="userHtml"></div>
* ```
*
* Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
* security vulnerabilities.)
*
* For the case of HTML, you might use a library, either on the client side, or on the server side,
* to sanitize unsafe HTML before binding to the value and rendering it in the document.
*
* How would you ensure that every place that used these types of bindings was bound to a value that
* was sanitized by your library (or returned as safe for rendering by your server?) How can you
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
* properties/fields and forgot to update the binding to the sanitized value?
*
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can
* determine that something explicitly says it's safe to use a value for binding in that
* context. You can then audit your code (a simple grep would do) to ensure that this is only done
* for those values that you can easily tell are safe - because they were received from your server,
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps
* allowing only the files in a specific directory to do this. Ensuring that the internal API
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
*
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
* (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
* obtain values that will be accepted by SCE / privileged contexts.
*
*
* ## How does it work?
*
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
* ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
* {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
* ```
* var ngBindHtmlDirective = ['$sce', function($sce) {
* return function(scope, element, attr) {
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
* element.html(value || '');
* });
* };
* }];
* ```
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
*
* By default, Angular only loads templates from the same domain and protocol as the application
* document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
* protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
* them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
*
* *Please note*:
* The browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy apply in addition to this and may further restrict whether the template is successfully
* loaded. This means that without the right CORS policy, loading templates from a different domain
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some
* browsers.
*
* ## This feels like too much overhead
*
* It's important to remember that SCE only applies to interpolation expressions.
*
* If your expressions are constant literals, they're automatically trusted and you don't need to
* call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
* `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
*
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
* through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
*
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
* templates in `ng-include` from your application's domain without having to even know about SCE.
* It blocks loading templates from other domains or loading templates over http from an https
* served document. You can change these by setting your own custom {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
*
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an
* application that's secure and can be audited to verify that with much more ease than bolting
* security onto an application later.
*
* <a name="contexts"></a>
* ## What trusted context types are supported?
*
* | Context | Notes |
* |---------------------|----------------|
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
*
* ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
*
* Each element in these arrays must be one of the following:
*
* - **'self'**
* - The special **string**, `'self'`, can be used to match against all URLs of the **same
* domain** as the application document using the **same protocol**.
* - **String** (except the special value `'self'`)
* - The string is matched against the full *normalized / absolute URL* of the resource
* being tested (substring matches are not good enough.)
* - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
* match themselves.
* - `*`: matches zero or more occurrences of any character other than one of the following 6
* characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
* in a whitelist.
* - `**`: matches zero or more occurrences of *any* character. As such, it's not
* appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
* http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
* not have been the intention.) Its usage at the very end of the path is ok. (e.g.
* http://foo.example.com/templates/**).
* - **RegExp** (*see caveat below*)
* - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
* (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
* accidentally introduce a bug when one updates a complex expression (imho, all regexes should
* have good test coverage). For instance, the use of `.` in the regex is correct only in a
* small number of cases. A `.` character in the regex used when matching the scheme or a
* subdomain could be matched against a `:` or literal `.` that was likely not intended. It
* is highly recommended to use the string patterns and only fall back to regular expressions
* as a last resort.
* - The regular expression must be an instance of RegExp (i.e. not a string.) It is
* matched against the **entire** *normalized / absolute URL* of the resource being tested
* (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
* present on the RegExp (such as multiline, global, ignoreCase) are ignored.
* - If you are generating your JavaScript from some other templating engine (not
* recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
* remember to escape your regular expression (and be aware that you might need more than
* one level of escaping depending on your templating engine and the way you interpolated
* the value.) Do make use of your platform's escaping mechanism as it might be good
* enough before coding your own. E.g. Ruby has
* [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
* and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
* Javascript lacks a similar built in function for escaping. Take a look at Google
* Closure library's [goog.string.regExpEscape(s)](
* http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
*
* ## Show me an example using SCE.
*
* <example module="mySceApp" deps="angular-sanitize.js">
* <file name="index.html">
* <div ng-controller="AppController as myCtrl">
* <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
* <b>User comments</b><br>
* By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
* $sanitize is available. If $sanitize isn't available, this results in an error instead of an
* exploit.
* <div class="well">
* <div ng-repeat="userComment in myCtrl.userComments">
* <b>{{userComment.name}}</b>:
* <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
* <br>
* </div>
* </div>
* </div>
* </file>
*
* <file name="script.js">
* angular.module('mySceApp', ['ngSanitize'])
* .controller('AppController', ['$http', '$templateCache', '$sce',
* function($http, $templateCache, $sce) {
* var self = this;
* $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
* self.userComments = userComments;
* });
* self.explicitlyTrustedHtml = $sce.trustAsHtml(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* }]);
* </file>
*
* <file name="test_data.json">
* [
* { "name": "Alice",
* "htmlComment":
* "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
* },
* { "name": "Bob",
* "htmlComment": "<i>Yes!</i> Am I the only other one?"
* }
* ]
* </file>
*
* <file name="protractor.js" type="protractor">
* describe('SCE doc demo', function() {
* it('should sanitize untrusted values', function() {
* expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
* .toBe('<span>Is <i>anyone</i> reading this?</span>');
* });
*
* it('should NOT sanitize explicitly trusted values', function() {
* expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* });
* });
* </file>
* </example>
*
*
*
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
* ```
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
* // Completely disable SCE. For demonstration purposes only!
* // Do not use in new projects.
* $sceProvider.enabled(false);
* });
* ```
*
*/
/* jshint maxlen: 100 */
function $SceProvider() {
var enabled = true;
/**
* @ngdoc method
* @name $sceProvider#enabled
* @kind function
*
* @param {boolean=} value If provided, then enables/disables SCE.
* @return {boolean} true if SCE is enabled, false otherwise.
*
* @description
* Enables/disables SCE and returns the current value.
*/
this.enabled = function(value) {
if (arguments.length) {
enabled = !!value;
}
return enabled;
};
/* Design notes on the default implementation for SCE.
*
* The API contract for the SCE delegate
* -------------------------------------
* The SCE delegate object must provide the following 3 methods:
*
* - trustAs(contextEnum, value)
* This method is used to tell the SCE service that the provided value is OK to use in the
* contexts specified by contextEnum. It must return an object that will be accepted by
* getTrusted() for a compatible contextEnum and return this value.
*
* - valueOf(value)
* For values that were not produced by trustAs(), return them as is. For values that were
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if
* trustAs is wrapping the given values into some type, this operation unwraps it when given
* such a value.
*
* - getTrusted(contextEnum, value)
* This function should return the a value that is safe to use in the context specified by
* contextEnum or throw and exception otherwise.
*
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
* opaque or wrapped in some holder object. That happens to be an implementation detail. For
* instance, an implementation could maintain a registry of all trusted objects by context. In
* such a case, trustAs() would return the same object that was passed in. getTrusted() would
* return the same object passed in if it was found in the registry under a compatible context or
* throw an exception otherwise. An implementation might only wrap values some of the time based
* on some criteria. getTrusted() might return a value and not throw an exception for special
* constants or objects even if not wrapped. All such implementations fulfill this contract.
*
*
* A note on the inheritance model for SCE contexts
* ------------------------------------------------
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
* is purely an implementation details.
*
* The contract is simply this:
*
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
* will also succeed.
*
* Inheritance happens to capture this in a natural way. In some future, we
* may not use inheritance anymore. That is OK because no code outside of
* sce.js and sceSpecs.js would need to be aware of this detail.
*/
this.$get = ['$parse', '$sceDelegate', function(
$parse, $sceDelegate) {
// Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
// the "expression(javascript expression)" syntax which is insecure.
if (enabled && msie < 8) {
throw $sceMinErr('iequirks',
'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
}
var sce = shallowCopy(SCE_CONTEXTS);
/**
* @ngdoc method
* @name $sce#isEnabled
* @kind function
*
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
*
* @description
* Returns a boolean indicating if SCE is enabled.
*/
sce.isEnabled = function() {
return enabled;
};
sce.trustAs = $sceDelegate.trustAs;
sce.getTrusted = $sceDelegate.getTrusted;
sce.valueOf = $sceDelegate.valueOf;
if (!enabled) {
sce.trustAs = sce.getTrusted = function(type, value) { return value; };
sce.valueOf = identity;
}
/**
* @ngdoc method
* @name $sce#parseAs
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
* *result*)}
*
* @param {string} type The kind of SCE context in which this result will be used.
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
sce.parseAs = function sceParseAs(type, expr) {
var parsed = $parse(expr);
if (parsed.literal && parsed.constant) {
return parsed;
} else {
return $parse(expr, function(value) {
return sce.getTrusted(type, value);
});
}
};
/**
* @ngdoc method
* @name $sce#trustAs
*
* @description
* Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
* returns an object that is trusted by angular for use in specified strict contextual
* escaping contexts (such as ng-bind-html, ng-include, any src attribute
* interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
* that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
* escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
/**
* @ngdoc method
* @name $sce#trustAsHtml
*
* @description
* Shorthand method. `$sce.trustAsHtml(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsUrl
*
* @description
* Shorthand method. `$sce.trustAsUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsResourceUrl
*
* @description
* Shorthand method. `$sce.trustAsResourceUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the return
* value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsJs
*
* @description
* Shorthand method. `$sce.trustAsJs(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#getTrusted
*
* @description
* Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
* takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
* originally supplied value if the queried context type is a supertype of the created type.
* If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
* call.
* @returns {*} The value the was originally provided to
* {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
* Otherwise, throws an exception.
*/
/**
* @ngdoc method
* @name $sce#getTrustedHtml
*
* @description
* Shorthand method. `$sce.getTrustedHtml(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedCss
*
* @description
* Shorthand method. `$sce.getTrustedCss(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedUrl
*
* @description
* Shorthand method. `$sce.getTrustedUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedResourceUrl
*
* @description
* Shorthand method. `$sce.getTrustedResourceUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to pass to `$sceDelegate.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedJs
*
* @description
* Shorthand method. `$sce.getTrustedJs(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
*/
/**
* @ngdoc method
* @name $sce#parseAsHtml
*
* @description
* Shorthand method. `$sce.parseAsHtml(expression string)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsCss
*
* @description
* Shorthand method. `$sce.parseAsCss(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsUrl
*
* @description
* Shorthand method. `$sce.parseAsUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsResourceUrl
*
* @description
* Shorthand method. `$sce.parseAsResourceUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsJs
*
* @description
* Shorthand method. `$sce.parseAsJs(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
// Shorthand delegations.
var parse = sce.parseAs,
getTrusted = sce.getTrusted,
trustAs = sce.trustAs;
forEach(SCE_CONTEXTS, function(enumValue, name) {
var lName = lowercase(name);
sce[camelCase("parse_as_" + lName)] = function(expr) {
return parse(enumValue, expr);
};
sce[camelCase("get_trusted_" + lName)] = function(value) {
return getTrusted(enumValue, value);
};
sce[camelCase("trust_as_" + lName)] = function(value) {
return trustAs(enumValue, value);
};
});
return sce;
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name $sniffer
* @requires $window
* @requires $document
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} transitions Does the browser support CSS transition events ?
* @property {boolean} animations Does the browser support CSS animation events ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android =
toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
document = $document[0] || {},
vendorPrefix,
vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for (var prop in bodyStyle) {
if (match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
if (!vendorPrefix) {
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions || !animations)) {
transitions = isString(bodyStyle.webkitTransition);
animations = isString(bodyStyle.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
// older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
// so let's not use the history API also
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
// jshint -W018
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
// jshint +W018
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
// IE10+ implements 'input' event but it erroneously fires under various situations,
// e.g. when placeholder changes, or a form is focused.
if (event === 'input' && msie <= 11) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: csp(),
vendorPrefix: vendorPrefix,
transitions: transitions,
animations: animations,
android: android
};
}];
}
var $compileMinErr = minErr('$compile');
/**
* @ngdoc service
* @name $templateRequest
*
* @description
* The `$templateRequest` service runs security checks then downloads the provided template using
* `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
* fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
* exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
* contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
* when `tpl` is of type string and `$templateCache` has the matching entry.
*
* @param {string|TrustedResourceUrl} tpl The HTTP request template URL
* @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
*
* @return {Promise} a promise for the HTTP response data of the given URL.
*
* @property {number} totalPendingRequests total amount of pending template requests being downloaded.
*/
function $TemplateRequestProvider() {
this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
function handleRequestFn(tpl, ignoreRequestError) {
handleRequestFn.totalPendingRequests++;
// We consider the template cache holds only trusted templates, so
// there's no need to go through whitelisting again for keys that already
// are included in there. This also makes Angular accept any script
// directive, no matter its name. However, we still need to unwrap trusted
// types.
if (!isString(tpl) || !$templateCache.get(tpl)) {
tpl = $sce.getTrustedResourceUrl(tpl);
}
var transformResponse = $http.defaults && $http.defaults.transformResponse;
if (isArray(transformResponse)) {
transformResponse = transformResponse.filter(function(transformer) {
return transformer !== defaultHttpResponseTransform;
});
} else if (transformResponse === defaultHttpResponseTransform) {
transformResponse = null;
}
var httpOptions = {
cache: $templateCache,
transformResponse: transformResponse
};
return $http.get(tpl, httpOptions)
['finally'](function() {
handleRequestFn.totalPendingRequests--;
})
.then(function(response) {
$templateCache.put(tpl, response.data);
return response.data;
}, handleError);
function handleError(resp) {
if (!ignoreRequestError) {
throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
tpl, resp.status, resp.statusText);
}
return $q.reject(resp);
}
}
handleRequestFn.totalPendingRequests = 0;
return handleRequestFn;
}];
}
function $$TestabilityProvider() {
this.$get = ['$rootScope', '$browser', '$location',
function($rootScope, $browser, $location) {
/**
* @name $testability
*
* @description
* The private $$testability service provides a collection of methods for use when debugging
* or by automated test and debugging tools.
*/
var testability = {};
/**
* @name $$testability#findBindings
*
* @description
* Returns an array of elements that are bound (via ng-bind or {{}})
* to expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The binding expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression. Filters and whitespace are ignored.
*/
testability.findBindings = function(element, expression, opt_exactMatch) {
var bindings = element.getElementsByClassName('ng-binding');
var matches = [];
forEach(bindings, function(binding) {
var dataBinding = angular.element(binding).data('$binding');
if (dataBinding) {
forEach(dataBinding, function(bindingName) {
if (opt_exactMatch) {
var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
if (matcher.test(bindingName)) {
matches.push(binding);
}
} else {
if (bindingName.indexOf(expression) != -1) {
matches.push(binding);
}
}
});
}
});
return matches;
};
/**
* @name $$testability#findModels
*
* @description
* Returns an array of elements that are two-way found via ng-model to
* expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The model expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression.
*/
testability.findModels = function(element, expression, opt_exactMatch) {
var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
for (var p = 0; p < prefixes.length; ++p) {
var attributeEquals = opt_exactMatch ? '=' : '*=';
var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
var elements = element.querySelectorAll(selector);
if (elements.length) {
return elements;
}
}
};
/**
* @name $$testability#getLocation
*
* @description
* Shortcut for getting the location in a browser agnostic way. Returns
* the path, search, and hash. (e.g. /path?a=b#hash)
*/
testability.getLocation = function() {
return $location.url();
};
/**
* @name $$testability#setLocation
*
* @description
* Shortcut for navigating to a location without doing a full page reload.
*
* @param {string} url The location url (path, search and hash,
* e.g. /path?a=b#hash) to go to.
*/
testability.setLocation = function(url) {
if (url !== $location.url()) {
$location.url(url);
$rootScope.$digest();
}
};
/**
* @name $$testability#whenStable
*
* @description
* Calls the callback when $timeout and $http requests are completed.
*
* @param {function} callback
*/
testability.whenStable = function(callback) {
$browser.notifyWhenNoOutstandingRequests(callback);
};
return testability;
}];
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
function($rootScope, $browser, $q, $$q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc service
* @name $timeout
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of calling `$timeout` is a promise, which will be resolved when
* the delay has passed and the timeout function, if provided, is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* If you only want a promise that will be resolved after some specified delay
* then you can call `$timeout` without the `fn` function.
*
* @param {function()=} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @param {...*=} Pass additional parameters to the executed function.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*
*/
function timeout(fn, delay, invokeApply) {
if (!isFunction(fn)) {
invokeApply = delay;
delay = fn;
fn = noop;
}
var args = sliceArgs(arguments, 3),
skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise,
timeoutId;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn.apply(null, args));
} catch (e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $timeout#cancel
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
delete deferreds[promise.$$timeoutId];
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
// NOTE: The usage of window and document instead of $window and $document here is
// deliberate. This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here. There is little value is mocking these out for this
// service.
var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href);
/**
*
* Implementation Notes for non-IE browsers
* ----------------------------------------
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
* results both in the normalizing and parsing of the URL. Normalizing means that a relative
* URL will be resolved into an absolute URL in the context of the application document.
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
* properties are all populated to reflect the normalized URL. This approach has wide
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
*
* Implementation Notes for IE
* ---------------------------
* IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
* browsers. However, the parsed components will not be set if the URL assigned did not specify
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
* work around that by performing the parsing in a 2nd step by taking a previously normalized
* URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
* properties such as protocol, hostname, port, etc.
*
* References:
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
* http://url.spec.whatwg.org/#urlutils
* https://github.com/angular/angular.js/pull/2902
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @kind function
* @param {string} url The URL to be parsed.
* @description Normalizes and parses a URL.
* @returns {object} Returns the normalized URL as a dictionary.
*
* | member name | Description |
* |---------------|----------------|
* | href | A normalized version of the provided URL if it was not an absolute URL |
* | protocol | The protocol including the trailing colon |
* | host | The host and port (if the port is non-default) of the normalizedUrl |
* | search | The search params, minus the question mark |
* | hash | The hash string, minus the hash symbol
* | hostname | The hostname
* | port | The port, without ":"
* | pathname | The pathname, beginning with "/"
*
*/
function urlResolve(url) {
var href = url;
if (msie) {
// Normalize before parse. Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/')
? urlParsingNode.pathname
: '/' + urlParsingNode.pathname
};
}
/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
* @returns {boolean} Whether the request is for the same origin as the application document.
*/
function urlIsSameOrigin(requestUrl) {
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
/**
* @ngdoc service
* @name $window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overridden, removed or mocked for testing.
*
* Expressions, like the one defined for the `ngClick` directive in the example
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
<example module="windowExample">
<file name="index.html">
<script>
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
$window.alert(greeting);
};
}]);
</script>
<div ng-controller="ExampleController">
<input type="text" ng-model="greeting" aria-label="greeting" />
<button ng-click="doGreeting(greeting)">ALERT</button>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should display the greeting in the input box', function() {
element(by.model('greeting')).sendKeys('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</file>
</example>
*/
function $WindowProvider() {
this.$get = valueFn(window);
}
/**
* @name $$cookieReader
* @requires $document
*
* @description
* This is a private service for reading cookies used by $http and ngCookies
*
* @return {Object} a key/value map of the current cookies
*/
function $$CookieReader($document) {
var rawDocument = $document[0] || {};
var lastCookies = {};
var lastCookieString = '';
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
return function() {
var cookieArray, cookie, i, index, name;
var currentCookieString = rawDocument.cookie || '';
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
}
$$CookieReader.$inject = ['$document'];
function $$CookieReaderProvider() {
this.$get = $$CookieReader;
}
/* global currencyFilter: true,
dateFilter: true,
filterFilter: true,
jsonFilter: true,
limitToFilter: true,
lowercaseFilter: true,
numberFilter: true,
orderByFilter: true,
uppercaseFilter: true,
*/
/**
* @ngdoc provider
* @name $filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be
* Dependency Injected. To achieve this a filter definition consists of a factory function which is
* annotated with dependencies and is responsible for creating a filter function.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*
* ```js
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* ```
*
* The filter function is registered with the `$injector` under the filter name suffix with
* `Filter`.
*
* ```js
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* ```
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/filter Filters} in the Angular Developer Guide.
*/
/**
* @ngdoc service
* @name $filter
* @kind function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
* @example
<example name="$filter" module="filterExample">
<file name="index.html">
<div ng-controller="MainCtrl">
<h3>{{ originalText }}</h3>
<h3>{{ filteredText }}</h3>
</div>
</file>
<file name="script.js">
angular.module('filterExample', [])
.controller('MainCtrl', function($scope, $filter) {
$scope.originalText = 'hello';
$scope.filteredText = $filter('uppercase')($scope.originalText);
});
</file>
</example>
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
/**
* @ngdoc method
* @name $filterProvider#register
* @param {string|Object} name Name of the filter function, or an object map of filters where
* the keys are the filter names and the values are the filter factories.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
* @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map
* of the registered filter instances.
*/
function register(name, factory) {
if (isObject(name)) {
var filters = {};
forEach(name, function(filter, key) {
filters[key] = register(key, filter);
});
return filters;
} else {
return $provide.factory(name + suffix, factory);
}
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
};
}];
////////////////////////////////////////
/* global
currencyFilter: false,
dateFilter: false,
filterFilter: false,
jsonFilter: false,
limitToFilter: false,
lowercaseFilter: false,
numberFilter: false,
orderByFilter: false,
uppercaseFilter: false,
*/
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name filter
* @kind function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: The string is used for matching against the contents of the `array`. All strings or
* objects with string properties in `array` that match this string will be returned. This also
* applies to nested object properties.
* The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object or its nested object properties. That's equivalent to the simple
* substring match with a `string` as described above. The predicate can be negated by prefixing
* the string with `!`.
* For example `{name: "!M"}` predicate will return an array of items which have property `name`
* not containing "M".
*
* Note that a named property will match properties on the same level only, while the special
* `$` property will match properties on the same level or deeper. E.g. an array item like
* `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
* **will** be matched by `{$: 'John'}`.
*
* - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
* The function is called for each element of the array, with the element, its index, and
* the entire array itself as arguments.
*
* The final result is an array of those elements that the predicate returned true for.
*
* @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
* the object in the array) should be considered a match.
*
* Can be one of:
*
* - `function(actual, expected)`:
* The function will be given the object value and the predicate value to compare and
* should return true if both values should be considered equal.
*
* - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
* This is essentially strict comparison of expected and actual.
*
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* Primitive values are converted to strings. Objects are not compared against primitives,
* unless they have a custom `toString` method (e.g. `Date` objects).
*
* @example
<example>
<file name="index.html">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
<label>Any: <input ng-model="search.$"></label> <br>
<label>Name only <input ng-model="search.name"></label><br>
<label>Phone only <input ng-model="search.phone"></label><br>
<label>Equality <input type="checkbox" ng-model="strict"></label><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in friends | filter:search:strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</file>
<file name="protractor.js" type="protractor">
var expectFriendNames = function(expectedNames, key) {
element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
arr.forEach(function(wd, i) {
expect(wd.getText()).toMatch(expectedNames[i]);
});
});
};
it('should search across all fields when filtering with a string', function() {
var searchText = element(by.model('searchText'));
searchText.clear();
searchText.sendKeys('m');
expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
searchText.clear();
searchText.sendKeys('76');
expectFriendNames(['John', 'Julie'], 'friend');
});
it('should search in specific fields when filtering with a predicate object', function() {
var searchAny = element(by.model('search.$'));
searchAny.clear();
searchAny.sendKeys('i');
expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
});
it('should use a equal comparison when comparator is true', function() {
var searchName = element(by.model('search.name'));
var strict = element(by.model('strict'));
searchName.clear();
searchName.sendKeys('Julie');
strict.click();
expectFriendNames(['Julie'], 'friendObj');
});
</file>
</example>
*/
function filterFilter() {
return function(array, expression, comparator) {
if (!isArrayLike(array)) {
if (array == null) {
return array;
} else {
throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
}
}
var expressionType = getTypeForFilter(expression);
var predicateFn;
var matchAgainstAnyProp;
switch (expressionType) {
case 'function':
predicateFn = expression;
break;
case 'boolean':
case 'null':
case 'number':
case 'string':
matchAgainstAnyProp = true;
//jshint -W086
case 'object':
//jshint +W086
predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
break;
default:
return array;
}
return Array.prototype.filter.call(array, predicateFn);
};
}
// Helper functions for `filterFilter`
function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
var predicateFn;
if (comparator === true) {
comparator = equals;
} else if (!isFunction(comparator)) {
comparator = function(actual, expected) {
if (isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
actual = lowercase('' + actual);
expected = lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function(item) {
if (shouldMatchPrimitives && !isObject(item)) {
return deepCompare(item, expression.$, comparator, false);
}
return deepCompare(item, expression, comparator, matchAgainstAnyProp);
};
return predicateFn;
}
function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
var actualType = getTypeForFilter(actual);
var expectedType = getTypeForFilter(expected);
if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
} else if (isArray(actual)) {
// In case `actual` is an array, consider it a match
// if ANY of it's items matches `expected`
return actual.some(function(item) {
return deepCompare(item, expected, comparator, matchAgainstAnyProp);
});
}
switch (actualType) {
case 'object':
var key;
if (matchAgainstAnyProp) {
for (key in actual) {
if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
return true;
}
}
return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
} else if (expectedType === 'object') {
for (key in expected) {
var expectedVal = expected[key];
if (isFunction(expectedVal) || isUndefined(expectedVal)) {
continue;
}
var matchAnyProperty = key === '$';
var actualVal = matchAnyProperty ? actual : actual[key];
if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
return false;
}
}
return true;
} else {
return comparator(actual, expected);
}
break;
case 'function':
return false;
default:
return comparator(actual, expected);
}
}
// Used for easily differentiating between `null` and actual `object`
function getTypeForFilter(val) {
return (val === null) ? 'null' : typeof val;
}
/**
* @ngdoc filter
* @name currency
* @kind function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
* @returns {string} Formatted number.
*
*
* @example
<example module="currencyExample">
<file name="index.html">
<script>
angular.module('currencyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.amount = 1234.56;
}]);
</script>
<div ng-controller="ExampleController">
<input type="number" ng-model="amount" aria-label="amount"> <br>
default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should init with 1234.56', function() {
expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
});
it('should update', function() {
if (browser.params.browser == 'safari') {
// Safari does not understand the minus key. See
// https://github.com/angular/protractor/issues/481
return;
}
element(by.model('amount')).clear();
element(by.model('amount')).sendKeys('-1234');
expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
});
</file>
</example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol, fractionSize) {
if (isUndefined(currencySymbol)) {
currencySymbol = formats.CURRENCY_SYM;
}
if (isUndefined(fractionSize)) {
fractionSize = formats.PATTERNS[1].maxFrac;
}
// if null or undefined pass it through
return (amount == null)
? amount
: formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name number
* @kind function
*
* @description
* Formats a number as text.
*
* If the input is null or undefined, it will just be returned.
* If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
* If the input is not a number an empty string is returned.
*
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<example module="numberFilterExample">
<file name="index.html">
<script>
angular.module('numberFilterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter number: <input ng-model='val'></label><br>
Default formatting: <span id='number-default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should format numbers', function() {
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
});
it('should update', function() {
element(by.model('val')).clear();
element(by.model('val')).sendKeys('3374.333');
expect(element(by.id('number-default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});
</file>
</example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
// if null or undefined pass it through
return (number == null)
? number
: formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isObject(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var isInfinity = number === Infinity;
if (!isInfinity && !isFinite(number)) return '';
var numStr = number + '',
formatedText = '',
hasExponent = false,
parts = [];
if (isInfinity) formatedText = '\u221e';
if (!isInfinity && numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
number = 0;
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!isInfinity && !hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
// safely round numbers in JS without hitting imprecisions of floating-point arithmetics
// inspired by:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var i, pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (i = 0; i < pos; i++) {
if ((pos - i) % group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i) % lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while (fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number < 1) {
formatedText = number.toFixed(fractionSize);
number = parseFloat(formatedText);
}
}
if (number === 0) {
isNegative = false;
}
parts.push(isNegative ? pattern.negPre : pattern.posPre,
formatedText,
isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim) {
num = num.substr(num.length - digits);
}
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset) {
value += offset;
}
if (value === 0 && offset == -12) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date, formats, offset) {
var zone = -1 * offset;
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function getFirstThursdayOfYear(year) {
// 0 = index of January
var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
// 4 = index of Thursday (+1 to account for 1st = 5)
// 11 = index of *next* Thursday (+1 account for 1st = 12)
return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
}
function getThursdayThisWeek(datetime) {
return new Date(datetime.getFullYear(), datetime.getMonth(),
// 4 = index of Thursday
datetime.getDate() + (4 - datetime.getDay()));
}
function weekGetter(size) {
return function(date) {
var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
thisThurs = getThursdayThisWeek(date);
var diff = +thisThurs - +firstThurs,
result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
return padNumber(result, size);
};
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
function eraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
}
function longEraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter,
ww: weekGetter(2),
w: weekGetter(1),
G: eraGetter,
GG: eraGetter,
GGG: eraGetter,
GGGG: longEraGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
NUMBER_STRING = /^\-?\d+$/;
/**
* @ngdoc filter
* @name date
* @kind function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in AM/PM, padded (01-12)
* * `'h'`: Hour in AM/PM, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'sss'`: Millisecond in second, padded (000-999)
* * `'a'`: AM/PM marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
* * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
* * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
* * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
* * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 PM)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
*
* `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
* `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
* continental US time zone abbreviations, but for general use, use a time zone offset, for
* example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
* If not specified, the timezone of the browser will be used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<example>
<file name="index.html">
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
<span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
</file>
<file name="protractor.js" type="protractor">
it('should format date', function() {
expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
</file>
</example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = toInt(match[9] + match[10]);
tzMin = toInt(match[9] + match[11]);
}
dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
var h = toInt(match[4] || 0) - tzHour;
var m = toInt(match[5] || 0) - tzMin;
var s = toInt(match[6] || 0);
var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format, timezone) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date) || !isFinite(date.getTime())) {
return date;
}
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
var dateTimezoneOffset = date.getTimezoneOffset();
if (timezone) {
dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
date = convertTimezoneToLocal(date, timezone, true);
}
forEach(parts, function(value) {
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name json
* @kind function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
* @returns {string} JSON string.
*
*
* @example
<example>
<file name="index.html">
<pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
<pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
</file>
<file name="protractor.js" type="protractor">
it('should jsonify filtered objects', function() {
expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
});
</file>
</example>
*
*/
function jsonFilter() {
return function(object, spacing) {
if (isUndefined(spacing)) {
spacing = 2;
}
return toJson(object, spacing);
};
}
/**
* @ngdoc filter
* @name lowercase
* @kind function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name uppercase
* @kind function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc filter
* @name limitTo
* @kind function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array, string or number, as specified by
* the value and sign (positive or negative) of `limit`. If a number is used as input, it is
* converted to a string.
*
* @param {Array|string|number} input Source array, string or number to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
* the input will be returned unchanged.
* @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
* indicates an offset from the end of `input`. Defaults to `0`.
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<example module="limitToExample">
<file name="index.html">
<script>
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.longNumber = 2345432342;
$scope.numLimit = 3;
$scope.letterLimit = 3;
$scope.longNumberLimit = 3;
}]);
</script>
<div ng-controller="ExampleController">
<label>
Limit {{numbers}} to:
<input type="number" step="1" ng-model="numLimit">
</label>
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
<label>
Limit {{letters}} to:
<input type="number" step="1" ng-model="letterLimit">
</label>
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
<label>
Limit {{longNumber}} to:
<input type="number" step="1" ng-model="longNumberLimit">
</label>
<p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
</div>
</file>
<file name="protractor.js" type="protractor">
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
// There is a bug in safari and protractor that doesn't like the minus key
// it('should update the output when -3 is entered', function() {
// numLimitInput.clear();
// numLimitInput.sendKeys('-3');
// letterLimitInput.clear();
// letterLimitInput.sendKeys('-3');
// longNumberLimitInput.clear();
// longNumberLimitInput.sendKeys('-3');
// expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
// expect(limitedLetters.getText()).toEqual('Output letters: ghi');
// expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
// });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
});
</file>
</example>
*/
function limitToFilter() {
return function(input, limit, begin) {
if (Math.abs(Number(limit)) === Infinity) {
limit = Number(limit);
} else {
limit = toInt(limit);
}
if (isNaN(limit)) return input;
if (isNumber(input)) input = input.toString();
if (!isArray(input) && !isString(input)) return input;
begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
if (limit >= 0) {
return input.slice(begin, begin + limit);
} else {
if (begin === 0) {
return input.slice(limit, input.length);
} else {
return input.slice(Math.max(0, begin + limit), begin);
}
}
};
}
/**
* @ngdoc filter
* @name orderBy
* @kind function
*
* @description
* Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
* for strings and numerically for numbers. Note: if you notice numbers are not being sorted
* as expected, make sure they are actually being saved as numbers and not strings.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `===`, `>` operator.
* - `string`: An Angular expression. The result of this expression is used to compare elements
* (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
* 3 first characters of a property called `name`). The result of a constant expression
* is interpreted as a property name to be used in comparisons (for example `"special name"`
* to sort object by the value of their `special name` property). An expression can be
* optionally prefixed with `+` or `-` to control ascending or descending sort order
* (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
* element itself is used to compare where sorting.
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* If the predicate is missing or empty then it defaults to `'+'`.
*
* @param {boolean=} reverse Reverse the order of the array.
* @returns {Array} Sorted copy of the source array.
*
*
* @example
* The example below demonstrates a simple ngRepeat, where the data is sorted
* by age in descending order (predicate is set to `'-age'`).
* `reverse` is not set, which means it defaults to `false`.
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
}]);
</script>
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'-age'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* The predicate and reverse parameters can be controlled dynamically through scope properties,
* as shown in the next example.
* @example
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
$scope.predicate = 'age';
$scope.reverse = true;
$scope.order = function(predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}]);
</script>
<style type="text/css">
.sortorder:after {
content: '\25b2';
}
.sortorder.reverse:after {
content: '\25bc';
}
</style>
<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th>
<a href="" ng-click="order('name')">Name</a>
<span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
</th>
<th>
<a href="" ng-click="order('phone')">Phone Number</a>
<span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
</th>
<th>
<a href="" ng-click="order('age')">Age</a>
<span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
* filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
* desired parameters.
*
* Example:
*
* @example
<example module="orderByExample">
<file name="index.html">
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
(<a href="" ng-click="order('-name',false)">^</a>)</th>
<th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
<th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
</tr>
<tr ng-repeat="friend in friends">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
<file name="script.js">
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
var orderBy = $filter('orderBy');
$scope.friends = [
{ name: 'John', phone: '555-1212', age: 10 },
{ name: 'Mary', phone: '555-9876', age: 19 },
{ name: 'Mike', phone: '555-4321', age: 21 },
{ name: 'Adam', phone: '555-5678', age: 35 },
{ name: 'Julie', phone: '555-8765', age: 29 }
];
$scope.order = function(predicate, reverse) {
$scope.friends = orderBy($scope.friends, predicate, reverse);
};
$scope.order('-age',false);
}]);
</file>
</example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
return function(array, sortPredicate, reverseOrder) {
if (!(isArrayLike(array))) return array;
if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
if (sortPredicate.length === 0) { sortPredicate = ['+']; }
var predicates = processPredicates(sortPredicate, reverseOrder);
// Add a predicate at the end that evaluates to the element index. This makes the
// sort stable as it works as a tie-breaker when all the input predicates cannot
// distinguish between two elements.
predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
// The next three lines are a version of a Swartzian Transform idiom from Perl
// (sometimes called the Decorate-Sort-Undecorate idiom)
// See https://en.wikipedia.org/wiki/Schwartzian_transform
var compareValues = Array.prototype.map.call(array, getComparisonObject);
compareValues.sort(doComparison);
array = compareValues.map(function(item) { return item.value; });
return array;
function getComparisonObject(value, index) {
return {
value: value,
predicateValues: predicates.map(function(predicate) {
return getPredicateValue(predicate.get(value), index);
})
};
}
function doComparison(v1, v2) {
var result = 0;
for (var index=0, length = predicates.length; index < length; ++index) {
result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
if (result) break;
}
return result;
}
};
function processPredicates(sortPredicate, reverseOrder) {
reverseOrder = reverseOrder ? -1 : 1;
return sortPredicate.map(function(predicate) {
var descending = 1, get = identity;
if (isFunction(predicate)) {
get = predicate;
} else if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-' ? -1 : 1;
predicate = predicate.substring(1);
}
if (predicate !== '') {
get = $parse(predicate);
if (get.constant) {
var key = get();
get = function(value) { return value[key]; };
}
}
}
return { get: get, descending: descending * reverseOrder };
});
}
function isPrimitive(value) {
switch (typeof value) {
case 'number': /* falls through */
case 'boolean': /* falls through */
case 'string':
return true;
default:
return false;
}
}
function objectValue(value, index) {
// If `valueOf` is a valid function use that
if (typeof value.valueOf === 'function') {
value = value.valueOf();
if (isPrimitive(value)) return value;
}
// If `toString` is a valid function and not the one from `Object.prototype` use that
if (hasCustomToString(value)) {
value = value.toString();
if (isPrimitive(value)) return value;
}
// We have a basic object so we use the position of the object in the collection
return index;
}
function getPredicateValue(value, index) {
var type = typeof value;
if (value === null) {
type = 'string';
value = 'null';
} else if (type === 'string') {
value = value.toLowerCase();
} else if (type === 'object') {
value = objectValue(value, index);
}
return { value: value, type: type };
}
function compare(v1, v2) {
var result = 0;
if (v1.type === v2.type) {
if (v1.value !== v2.value) {
result = v1.value < v2.value ? -1 : 1;
}
} else {
result = v1.type < v2.type ? -1 : 1;
}
return result;
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
};
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name a
* @restrict E
*
* @description
* Modifies the default behavior of the html A tag so that the default action is prevented when
* the href attribute is empty.
*
* This change permits the easy creation of action links with the `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="list.addItem()">Add Item</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (!attr.href && !attr.xlinkHref) {
return function(scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') return;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
};
}
}
});
/**
* @ngdoc directive
* @name ngHref
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in an href attribute will
* make the link go to the wrong URL if the user clicks it before
* Angular has a chance to replace the `{{hash}}` markup with its
* value. Until Angular replaces the markup the link will be broken
* and will most likely return a 404 error. The `ngHref` directive
* solves this problem.
*
* The wrong way to write it:
* ```html
* <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* The correct way to write it:
* ```html
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
* in links and their different behaviors:
<example>
<file name="index.html">
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</file>
<file name="protractor.js" type="protractor">
it('should execute ng-click but not reload when href without value', function() {
element(by.id('link-1')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('1');
expect(element(by.id('link-1')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when href empty string', function() {
element(by.id('link-2')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('2');
expect(element(by.id('link-2')).getAttribute('href')).toBe('');
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
element(by.id('link-3')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/123$/);
});
}, 5000, 'page should navigate to /123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element(by.id('link-4')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('4');
expect(element(by.id('link-4')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element(by.id('link-5')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('5');
expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
});
it('should only change url when only ng-href', function() {
element(by.model('value')).clear();
element(by.model('value')).sendKeys('6');
expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
element(by.id('link-6')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/6$/);
});
}, 5000, 'page should navigate to /6');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSrc
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
* ```
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngSrcset
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrcset` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
* ```
*
* @element IMG
* @param {template} ngSrcset any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngDisabled
* @restrict A
* @priority 100
*
* @description
*
* This directive sets the `disabled` attribute on the element if the
* {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
*
* A special directive is necessary because we cannot use interpolation inside the `disabled`
* attribute. The following example would make the button enabled on Chrome/Firefox
* but not on older IEs:
*
* ```html
* <!-- See below for an example of ng-disabled being used correctly -->
* <div ng-init="isDisabled = false">
* <button disabled="{{isDisabled}}">Disabled</button>
* </div>
* ```
*
* This is because the HTML specification does not require browsers to preserve the values of
* boolean attributes such as `disabled` (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
*
* @example
<example>
<file name="index.html">
<label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</file>
<file name="protractor.js" type="protractor">
it('should toggle button', function() {
expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
* then the `disabled` attribute will be set on the element
*/
/**
* @ngdoc directive
* @name ngChecked
* @restrict A
* @priority 100
*
* @description
* Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
*
* Note that this directive should not be used together with {@link ngModel `ngModel`},
* as this can lead to unexpected behavior.
*
* ### Why do we need `ngChecked`?
*
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as checked. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngChecked` directive solves this problem for the `checked` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
<input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
</file>
<file name="protractor.js" type="protractor">
it('should check both checkBoxes', function() {
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
element(by.model('master')).click();
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
* then the `checked` attribute will be set on the element
*/
/**
* @ngdoc directive
* @name ngReadonly
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as readonly. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngReadonly` directive solves this problem for the `readonly` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
<input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
</file>
<file name="protractor.js" type="protractor">
it('should toggle readonly attr', function() {
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
* then special attribute "readonly" will be set on the element
*/
/**
* @ngdoc directive
* @name ngSelected
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as selected. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngSelected` directive solves this problem for the `selected` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
*
* @example
<example>
<file name="index.html">
<label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
<select aria-label="ngSelected demo">
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</file>
<file name="protractor.js" type="protractor">
it('should select Greetings!', function() {
expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
element(by.model('selected')).click();
expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
});
</file>
</example>
*
* @element OPTION
* @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
* then special attribute "selected" will be set on the element
*/
/**
* @ngdoc directive
* @name ngOpen
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as open. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngOpen` directive solves this problem for the `open` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
<details id="details" ng-open="open">
<summary>Show/Hide me</summary>
</details>
</file>
<file name="protractor.js" type="protractor">
it('should toggle open', function() {
expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
element(by.model('open')).click();
expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
});
</file>
</example>
*
* @element DETAILS
* @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
* then special attribute "open" will be set on the element
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;
function defaultLinkFn(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
}
var normalized = directiveNormalize('ng-' + attrName);
var linkFn = defaultLinkFn;
if (propName === 'checked') {
linkFn = function(scope, element, attr) {
// ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
if (attr.ngModel !== attr[normalized]) {
defaultLinkFn(scope, element, attr);
}
};
}
ngAttributeAliasDirectives[normalized] = function() {
return {
restrict: 'A',
priority: 100,
link: linkFn
};
};
});
// aliased input attrs are evaluated
forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
ngAttributeAliasDirectives[ngAttr] = function() {
return {
priority: 100,
link: function(scope, element, attr) {
//special case ngPattern when a literal regular expression value
//is used as the expression (this way we don't have to watch anything).
if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
if (match) {
attr.$set("ngPattern", new RegExp(match[1], match[2]));
return;
}
}
scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
attr.$set(ngAttr, value);
});
}
};
};
});
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
var propName = attrName,
name = attrName;
if (attrName === 'href' &&
toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
name = 'xlinkHref';
attr.$attr[name] = 'xlink:href';
propName = null;
}
attr.$observe(normalized, function(value) {
if (!value) {
if (attrName === 'href') {
attr.$set(name, null);
}
return;
}
attr.$set(name, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie && propName) element.prop(propName, attr[name]);
});
}
};
};
});
/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
*/
var nullFormCtrl = {
$addControl: noop,
$$renameControl: nullFormRenameControl,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop,
$setPristine: noop,
$setSubmitted: noop
},
SUBMITTED_CLASS = 'ng-submitted';
function nullFormRenameControl(control, name) {
control.$name = name;
}
/**
* @ngdoc type
* @name form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
* @property {boolean} $submitted True if user has submitted the form even if its invalid.
*
* @property {Object} $error Is an object hash, containing references to controls or
* forms with failing validators, where:
*
* - keys are validation tokens (error names),
* - values are arrays of controls or forms that have a failing validator for given error name.
*
* Built-in validation tokens:
*
* - `email`
* - `max`
* - `maxlength`
* - `min`
* - `minlength`
* - `number`
* - `pattern`
* - `required`
* - `url`
* - `date`
* - `datetimelocal`
* - `time`
* - `week`
* - `month`
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as the state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
function FormController(element, attrs, $scope, $animate, $interpolate) {
var form = this,
controls = [];
var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
// init state
form.$error = {};
form.$$success = {};
form.$pending = undefined;
form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
form.$submitted = false;
parentForm.$addControl(form);
/**
* @ngdoc method
* @name form.FormController#$rollbackViewValue
*
* @description
* Rollback all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is typically needed by the reset button of
* a form that uses `ng-model-options` to pend updates.
*/
form.$rollbackViewValue = function() {
forEach(controls, function(control) {
control.$rollbackViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$commitViewValue
*
* @description
* Commit all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
form.$commitViewValue = function() {
forEach(controls, function(control) {
control.$commitViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$addControl
*
* @description
* Register a control with the form.
*
* Input elements using ngModelController do this automatically when they are linked.
*/
form.$addControl = function(control) {
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
// and not added to the scope. Now we throw an error.
assertNotHasOwnProperty(control.$name, 'input');
controls.push(control);
if (control.$name) {
form[control.$name] = control;
}
};
// Private API: rename a form control
form.$$renameControl = function(control, newName) {
var oldName = control.$name;
if (form[oldName] === control) {
delete form[oldName];
}
form[newName] = control;
control.$name = newName;
};
/**
* @ngdoc method
* @name form.FormController#$removeControl
*
* @description
* Deregister a control from the form.
*
* Input elements using ngModelController do this automatically when they are destroyed.
*/
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(form.$pending, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$error, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$$success, function(value, name) {
form.$setValidity(name, null, control);
});
arrayRemove(controls, control);
};
/**
* @ngdoc method
* @name form.FormController#$setValidity
*
* @description
* Sets the validity of a form control.
*
* This method will also propagate to parent forms.
*/
addSetValidityMethod({
ctrl: this,
$element: element,
set: function(object, property, controller) {
var list = object[property];
if (!list) {
object[property] = [controller];
} else {
var index = list.indexOf(controller);
if (index === -1) {
list.push(controller);
}
}
},
unset: function(object, property, controller) {
var list = object[property];
if (!list) {
return;
}
arrayRemove(list, controller);
if (list.length === 0) {
delete object[property];
}
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name form.FormController#$setDirty
*
* @description
* Sets the form to a dirty state.
*
* This method can be called to add the 'ng-dirty' class and set the form to a dirty
* state (ng-dirty class). This method will also propagate to parent forms.
*/
form.$setDirty = function() {
$animate.removeClass(element, PRISTINE_CLASS);
$animate.addClass(element, DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name form.FormController#$setPristine
*
* @description
* Sets the form to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine
* state (ng-pristine class). This method will also propagate to all the controls contained
* in this form.
*
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
* saving or resetting it.
*/
form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};
/**
* @ngdoc method
* @name form.FormController#$setUntouched
*
* @description
* Sets the form to its untouched state.
*
* This method can be called to remove the 'ng-touched' class and set the form controls to their
* untouched state (ng-untouched class).
*
* Setting a form controls back to their untouched state is often useful when setting the form
* back to its pristine state.
*/
form.$setUntouched = function() {
forEach(controls, function(control) {
control.$setUntouched();
});
};
/**
* @ngdoc method
* @name form.FormController#$setSubmitted
*
* @description
* Sets the form to its submitted state.
*/
form.$setSubmitted = function() {
$animate.addClass(element, SUBMITTED_CLASS);
form.$submitted = true;
parentForm.$setSubmitted();
};
}
/**
* @ngdoc directive
* @name ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* Note: the purpose of `ngForm` is to group controls,
* but not to be a replacement for the `<form>` tag with all of its capabilities
* (e.g. posting to the server, ...).
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name form
* @restrict E
*
* @description
* Directive that instantiates
* {@link form.FormController FormController}.
*
* If the `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In Angular, forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
* Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
* `<form>` but can be nested. This allows you to have nested forms, which is very useful when
* using Angular validation directives in forms that are dynamically generated using the
* {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
* attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
* `ngForm` directive and nest these in an outer `form` element.
*
*
* # CSS classes
* - `ng-valid` is set if the form is valid.
* - `ng-invalid` is set if the form is invalid.
* - `ng-pristine` is set if the form is pristine.
* - `ng-dirty` is set if the form is dirty.
* - `ng-submitted` is set if the form was submitted.
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
*
* # Submitting a form and preventing the default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in an application-specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
* or {@link ng.directive:ngClick ngClick} directives.
* This is because of the following form submission rules in the HTML specification:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
* submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* ## Animation Hooks
*
* Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
* These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
* other validations that are performed within the form. Animations in ngForm are similar to how
* they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
* as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style a form element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-form {
* transition:0.5s linear all;
* background: white;
* }
* .my-form.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
<example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
<file name="index.html">
<script>
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
</script>
<style>
.my-form {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-form.ng-invalid {
background: red;
}
</style>
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<code>userType = {{userType}}</code><br>
<code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
<code>myForm.input.$error = {{myForm.input.$error}}</code><br>
<code>myForm.$valid = {{myForm.$valid}}</code><br>
<code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should initialize to model', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
expect(userType.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
var userInput = element(by.model('userType'));
userInput.clear();
userInput.sendKeys('');
expect(userType.getText()).toEqual('userType =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', '$parse', function($timeout, $parse) {
var formDirective = {
name: 'form',
restrict: isNgForm ? 'EAC' : 'E',
controller: FormController,
compile: function ngFormCompile(formElement, attr) {
// Setup initial state of the control
formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
return {
pre: function ngFormPreLink(scope, formElement, attr, controller) {
// if `action` attr is not present on the form, prevent the default action (submission)
if (!('action' in attr)) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.on('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
}, 0, false);
});
}
var parentFormCtrl = controller.$$parentForm;
var setter = nameAttr ? getSetter(controller.$name) : noop;
if (nameAttr) {
setter(scope, controller);
attr.$observe(nameAttr, function(newValue) {
if (controller.$name === newValue) return;
setter(scope, undefined);
parentFormCtrl.$$renameControl(controller, newValue);
setter = getSetter(controller.$name);
setter(scope, controller);
});
}
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
setter(scope, undefined);
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
};
}
};
return formDirective;
function getSetter(expression) {
if (expression === '') {
//create an assignable expression, so forms with an empty name can be renamed later
return $parse('this[""]').assign;
}
return $parse(expression).assign || noop;
}
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
/* global VALID_CLASS: false,
INVALID_CLASS: false,
PRISTINE_CLASS: false,
DIRTY_CLASS: false,
UNTOUCHED_CLASS: false,
TOUCHED_CLASS: false,
ngModelMinErr: false,
*/
// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var inputType = {
/**
* @ngdoc input
* @name input[text]
*
* @description
* Standard HTML text input with angular data binding, inherited by most of the `input` elements.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
text: 'guest',
word: /^\s*\w*\s*$/
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Single word:
<input type="text" name="input" ng-model="example.text"
ng-pattern="example.word" required ng-trim="false">
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
</div>
<tt>text = {{example.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('example.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if multi word', function() {
input.clear();
input.sendKeys('hello world');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'text': textInputType,
/**
* @ngdoc input
* @name input[date]
*
* @description
* Input with date validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
* date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO date string (yyyy-MM-dd).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO date string (yyyy-MM-dd).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="date-input-directive" module="dateInputExample">
<file name="index.html">
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 22)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date in 2013:</label>
<input type="date" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.date">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10-22');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'date': createDateInputType('date', DATE_REGEXP,
createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
'yyyy-MM-dd'),
/**
* @ngdoc input
* @name input[datetime-local]
*
* @description
* Input with datetime validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="datetimelocal-input-directive" module="dateExample">
<file name="index.html">
<script>
angular.module('dateExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2010, 11, 28, 14, 57)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date between in 2013:</label>
<input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.datetimelocal">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2010-12-28T14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01T23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[time]
*
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
* Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="time-input-directive" module="timeExample">
<file name="index.html">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 57, 0)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a between 8am and 5pm:</label>
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'time': createDateInputType('time', TIME_REGEXP,
createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
'HH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[week]
*
* @description
* Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO week format (yyyy-W##).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO week format (yyyy-W##).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="week-input-directive" module="weekExample">
<file name="index.html">
<script>
angular.module('weekExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 0, 3)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label>Pick a date between in 2013:
<input id="exampleInput" type="week" name="input" ng-model="example.value"
placeholder="YYYY-W##" min="2012-W32"
max="2013-W52" required />
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.week">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-W01');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-W01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
/**
* @ngdoc input
* @name input[month]
*
* @description
* Input with month validation and transformation. In browsers that do not yet support
* the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* month format (yyyy-MM), for example: `2009-01`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
* If the model is not set to the first of the month, the next view to model update will set it
* to the first of the month.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
* a valid ISO month format (yyyy-MM).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
* be a valid ISO month format (yyyy-MM).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="month-input-directive" module="monthExample">
<file name="index.html">
<script>
angular.module('monthExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 1)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a month in 2013:</label>
<input id="exampleInput" type="month" name="input" ng-model="example.value"
placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.month">
Not a valid month!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'month': createDateInputType('month', MONTH_REGEXP,
createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
'yyyy-MM'),
/**
* @ngdoc input
* @name input[number]
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* <div class="alert alert-warning">
* The model must always be of type `number` otherwise Angular will throw an error.
* Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
* error docs for more information and an example of how to convert your model if necessary.
* </div>
*
* ## Issues with HTML5 constraint validation
*
* In browsers that follow the
* [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
* `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
* If a non-number is entered in the input, the browser will report the value as an empty string,
* which means the view / model values in `ngModel` and subsequently the scope value
* will also be an empty string.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
value: 12
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Number:
<input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
</div>
<tt>value = {{example.value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
it('should initialize to model', function() {
expect(value.getText()).toContain('12');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if over max', function() {
input.clear();
input.sendKeys('123');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'number': numberInputType,
/**
* @ngdoc input
* @name input[url]
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* <div class="alert alert-warning">
* **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
* used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
* the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.url = {
text: 'http://google.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>URL:
<input type="url" name="input" ng-model="url.text" required>
<label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
</div>
<tt>text = {{url.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('url.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('url.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('http://google.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not url', function() {
input.clear();
input.sendKeys('box');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'url': urlInputType,
/**
* @ngdoc input
* @name input[email]
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* <div class="alert alert-warning">
* **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
* used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
* use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.email = {
text: '[email protected]'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Email:
<input type="email" name="input" ng-model="email.text" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
</div>
<tt>text = {{email.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('email.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('email.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('[email protected]');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not email', function() {
input.clear();
input.sendKeys('xxx');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'email': emailInputType,
/**
* @ngdoc input
* @name input[radio]
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the `ngModel` expression should be set when selected.
* Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
* too. Use `ngValue` if you need complex models (`number`, `object`, ...).
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
* is selected. Should be used instead of the `value` attribute if you need
* a non-string `ngModel` (`boolean`, `array`, ...).
*
* @example
<example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
<input type="radio" ng-model="color.name" value="red">
Red
</label><br/>
<label>
<input type="radio" ng-model="color.name" ng-value="specialValue">
Green
</label><br/>
<label>
<input type="radio" ng-model="color.name" value="blue">
Blue
</label><br/>
<tt>color = {{color.name | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var color = element(by.binding('color.name'));
expect(color.getText()).toContain('blue');
element.all(by.model('color.name')).get(0).click();
expect(color.getText()).toContain('red');
});
</file>
</example>
*/
'radio': radioInputType,
/**
* @ngdoc input
* @name input[checkbox]
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ngTrueValue The value to which the expression should be set when selected.
* @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.checkboxModel = {
value1 : true,
value2 : 'YES'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Value1:
<input type="checkbox" ng-model="checkboxModel.value1">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.value2"
ng-true-value="'YES'" ng-false-value="'NO'">
</label><br/>
<tt>value1 = {{checkboxModel.value1}}</tt><br/>
<tt>value2 = {{checkboxModel.value2}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var value1 = element(by.binding('checkboxModel.value1'));
var value2 = element(by.binding('checkboxModel.value2'));
expect(value1.getText()).toContain('true');
expect(value2.getText()).toContain('YES');
element(by.model('checkboxModel.value1')).click();
element(by.model('checkboxModel.value2')).click();
expect(value1.getText()).toContain('false');
expect(value2.getText()).toContain('NO');
});
</file>
</example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop,
'file': noop
};
function stringBasedInputType(ctrl) {
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? value : value.toString();
});
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
}
function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var type = lowercase(element[0].type);
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
var composing = false;
element.on('compositionstart', function(data) {
composing = true;
});
element.on('compositionend', function() {
composing = false;
listener();
});
}
var listener = function(ev) {
if (timeout) {
$browser.defer.cancel(timeout);
timeout = null;
}
if (composing) return;
var value = element.val(),
event = ev && ev.type;
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// If input type is 'password', the value is never trimmed
if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
// If a control is suffering from bad input (due to native validators), browsers discard its
// value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
// control's value is the same empty value twice in a row.
if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
ctrl.$setViewValue(value, event);
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function(ev, input, origValue) {
if (!timeout) {
timeout = $browser.defer(function() {
timeout = null;
if (!input || input.value !== origValue) {
listener(ev);
}
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event, this, this.value);
});
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
// if user paste into input using mouse on older browser
// or form autocomplete on newer browser, we need "change" event to catch it
element.on('change', listener);
ctrl.$render = function() {
// Workaround for Firefox validation #12102.
var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
if (element.val() !== value) {
element.val(value);
}
};
}
function weekParser(isoWeek, existingDate) {
if (isDate(isoWeek)) {
return isoWeek;
}
if (isString(isoWeek)) {
WEEK_REGEXP.lastIndex = 0;
var parts = WEEK_REGEXP.exec(isoWeek);
if (parts) {
var year = +parts[1],
week = +parts[2],
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
firstThurs = getFirstThursdayOfYear(year),
addDays = (week - 1) * 7;
if (existingDate) {
hours = existingDate.getHours();
minutes = existingDate.getMinutes();
seconds = existingDate.getSeconds();
milliseconds = existingDate.getMilliseconds();
}
return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
}
}
return NaN;
}
function createDateParser(regexp, mapping) {
return function(iso, date) {
var parts, map;
if (isDate(iso)) {
return iso;
}
if (isString(iso)) {
// When a date is JSON'ified to wraps itself inside of an extra
// set of double quotes. This makes the date parsing code unable
// to match the date string and parse it as a date.
if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
iso = iso.substring(1, iso.length - 1);
}
if (ISO_DATE_REGEXP.test(iso)) {
return new Date(iso);
}
regexp.lastIndex = 0;
parts = regexp.exec(iso);
if (parts) {
parts.shift();
if (date) {
map = {
yyyy: date.getFullYear(),
MM: date.getMonth() + 1,
dd: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds(),
sss: date.getMilliseconds() / 1000
};
} else {
map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
}
forEach(parts, function(part, index) {
if (index < mapping.length) {
map[mapping[index]] = +part;
}
});
return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
}
}
return NaN;
};
}
function createDateInputType(type, regexp, parseDate, format) {
return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
var previousDate;
ctrl.$$parserName = type;
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (regexp.test(value)) {
// Note: We cannot read ctrl.$modelValue, as there might be a different
// parser/formatter in the processing chain so that the model
// contains some different data format!
var parsedDate = parseDate(value, previousDate);
if (timezone) {
parsedDate = convertTimezoneToLocal(parsedDate, timezone);
}
return parsedDate;
}
return undefined;
});
ctrl.$formatters.push(function(value) {
if (value && !isDate(value)) {
throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
}
if (isValidDate(value)) {
previousDate = value;
if (previousDate && timezone) {
previousDate = convertTimezoneToLocal(previousDate, timezone, true);
}
return $filter('date')(value, format, timezone);
} else {
previousDate = null;
return '';
}
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
function isValidDate(value) {
// Invalid Date: getTime() returns NaN
return value && !(value.getTime && value.getTime() !== value.getTime());
}
function parseObservedDateValue(val) {
return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
}
};
}
function badInputChecker(scope, element, attr, ctrl) {
var node = element[0];
var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
if (nativeValidation) {
ctrl.$parsers.push(function(value) {
var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
// Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
// - also sets validity.badInput (should only be validity.typeMismatch).
// - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
// - can ignore this case as we can still read out the erroneous email...
return validity.badInput && !validity.typeMismatch ? undefined : value;
});
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (NUMBER_REGEXP.test(value)) return parseFloat(value);
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isNumber(value)) {
throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
}
value = value.toString();
}
return value;
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
attr.$observe('min', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
minVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
attr.$observe('max', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'url';
ctrl.$validators.url = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'email';
ctrl.$validators.email = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
var listener = function(ev) {
if (element[0].checked) {
ctrl.$setViewValue(attr.value, ev && ev.type);
}
};
element.on('click', listener);
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function parseConstantExpr($parse, context, name, expression, fallback) {
var parseFn;
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
}
return fallback;
}
function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
// This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
// it to a boolean.
ctrl.$isEmpty = function(value) {
return value === false;
};
ctrl.$formatters.push(function(value) {
return equals(value, trueValue);
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*/
/**
* @ngdoc directive
* @name input
* @restrict E
*
* @description
* HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
* input state control, and validation.
* Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
*
* <div class="alert alert-warning">
* **Note:** Not every feature offered is available for all input types.
* Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="input-directive" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
</div>
</file>
<file name="protractor.js" type="protractor">
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
</file>
</example>
*/
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
$browser, $filter, $parse);
}
}
}
};
}];
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ngValue
*
* @description
* Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
* so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
* the bound value.
*
* `ngValue` is useful when dynamically generating lists of radio buttons using
* {@link ngRepeat `ngRepeat`}, as shown below.
*
* Likewise, `ngValue` can be used to generate `<option>` elements for
* the {@link select `select`} element. In that case however, only strings are supported
* for the `value `attribute, so the resulting `ngModel` will always be a string.
* Support for `select` models with non-string values is available via `ngOptions`.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
<example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>
</file>
<file name="protractor.js" type="protractor">
var favorite = element(by.binding('my.favorite'));
it('should initialize to model', function() {
expect(favorite.getText()).toContain('unicorns');
});
it('should bind the values to the inputs', function() {
element.all(by.model('my.favorite')).get(0).click();
expect(favorite.getText()).toContain('pizza');
});
</file>
</example>
*/
var ngValueDirective = function() {
return {
restrict: 'A',
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ngBind
* @restrict AC
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var nameInput = element(by.model('name'));
expect(element(by.binding('name')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('name')).getText()).toBe('world');
});
</file>
</example>
*/
var ngBindDirective = ['$compile', function($compile) {
return {
restrict: 'AC',
compile: function ngBindCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBind);
element = element[0];
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}]);
</script>
<div ng-controller="ExampleController">
<label>Salutation: <input type="text" ng-model="salutation"></label><br>
<label>Name: <input type="text" ng-model="name"></label><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var salutationElem = element(by.binding('salutation'));
var salutationInput = element(by.model('salutation'));
var nameInput = element(by.model('name'));
expect(salutationElem.getText()).toBe('Hello World!');
salutationInput.clear();
salutationInput.sendKeys('Greetings');
nameInput.clear();
nameInput.sendKeys('user');
expect(salutationElem.getText()).toBe('Greetings user!');
});
</file>
</example>
*/
var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
return {
compile: function ngBindTemplateCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindTemplateLink(scope, element, attr) {
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
$compile.$$addBindingInfo(element, interpolateFn.expressions);
element = element[0];
attr.$observe('ngBindTemplate', function(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindHtml
*
* @description
* Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
* the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
* To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
* ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
* in your module's dependencies, you need to include "angular-sanitize.js" in your application.
*
* You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
<example module="bindHtmlExample" deps="angular-sanitize.js">
<file name="index.html">
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</file>
<file name="script.js">
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind-html', function() {
expect(element(by.binding('myHTML')).getText()).toBe(
'I am an HTMLstring with links! and other stuff');
});
</file>
</example>
*/
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBindHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-evaluate the expr because we want a TrustedValueHolderType
// for $sce, not a string
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngChange
*
* @description
* Evaluate the given expression when the user changes the input.
* The expression is evaluated immediately, unlike the JavaScript onchange event
* which only triggers at the end of a change (usually, when the user leaves the
* form element or presses the return key).
*
* The `ngChange` expression is only evaluated when a change in the input value causes
* a new value to be committed to the model.
*
* It will not be evaluated:
* * if the value returned from the `$parsers` transformation pipeline has not changed
* * if the input has continued to be invalid since the model will stay `null`
* * if the model is changed programmatically and not by a change to the input value
*
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
* in input value.
*
* @example
* <example name="ngChange-directive" module="changeExample">
* <file name="index.html">
* <script>
* angular.module('changeExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }]);
* </script>
* <div ng-controller="ExampleController">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* <tt>debug = {{confirmed}}</tt><br/>
* <tt>counter = {{counter}}</tt><br/>
* </div>
* </file>
* <file name="protractor.js" type="protractor">
* var counter = element(by.binding('counter'));
* var debug = element(by.binding('confirmed'));
*
* it('should evaluate the expression if changing from view', function() {
* expect(counter.getText()).toContain('0');
*
* element(by.id('ng-change-example1')).click();
*
* expect(counter.getText()).toContain('1');
* expect(debug.getText()).toContain('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element(by.id('ng-change-example2')).click();
* expect(counter.getText()).toContain('0');
* expect(debug.getText()).toContain('true');
* });
* </file>
* </example>
*/
var ngChangeDirective = valueFn({
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
function classDirective(name, selector) {
name = 'ngClass' + name;
return ['$animate', function($animate) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
ngClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
// jshint bitwise: false
var mod = $index & 1;
if (mod !== (old$index & 1)) {
var classes = arrayClasses(scope.$eval(attr[name]));
mod === selector ?
addClasses(classes) :
removeClasses(classes);
}
});
}
function addClasses(classes) {
var newClasses = digestClassCounts(classes, 1);
attr.$addClass(newClasses);
}
function removeClasses(classes) {
var newClasses = digestClassCounts(classes, -1);
attr.$removeClass(newClasses);
}
function digestClassCounts(classes, count) {
// Use createMap() to prevent class assumptions involving property
// names in Object.prototype
var classCounts = element.data('$classCounts') || createMap();
var classesToUpdate = [];
forEach(classes, function(className) {
if (count > 0 || classCounts[className]) {
classCounts[className] = (classCounts[className] || 0) + count;
if (classCounts[className] === +(count > 0)) {
classesToUpdate.push(className);
}
}
});
element.data('$classCounts', classCounts);
return classesToUpdate.join(' ');
}
function updateClasses(oldClasses, newClasses) {
var toAdd = arrayDifference(newClasses, oldClasses);
var toRemove = arrayDifference(oldClasses, newClasses);
toAdd = digestClassCounts(toAdd, 1);
toRemove = digestClassCounts(toRemove, -1);
if (toAdd && toAdd.length) {
$animate.addClass(element, toAdd);
}
if (toRemove && toRemove.length) {
$animate.removeClass(element, toRemove);
}
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
var newClasses = arrayClasses(newVal || []);
if (!oldVal) {
addClasses(newClasses);
} else if (!equals(newVal,oldVal)) {
var oldClasses = arrayClasses(oldVal);
updateClasses(oldClasses, newClasses);
}
}
oldVal = shallowCopy(newVal);
}
}
};
function arrayDifference(tokens1, tokens2) {
var values = [];
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
}
function arrayClasses(classVal) {
var classes = [];
if (isArray(classVal)) {
forEach(classVal, function(v) {
classes = classes.concat(arrayClasses(v));
});
return classes;
} else if (isString(classVal)) {
return classVal.split(' ');
} else if (isObject(classVal)) {
forEach(classVal, function(v, k) {
if (v) {
classes = classes.concat(k.split(' '));
}
});
return classes;
}
return classVal;
}
}];
}
/**
* @ngdoc directive
* @name ngClass
* @restrict AC
*
* @description
* The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
* an expression that represents all classes to be added.
*
* The directive operates in three different ways, depending on which of three types the expression
* evaluates to:
*
* 1. If the expression evaluates to a string, the string should be one or more space-delimited class
* names.
*
* 2. If the expression evaluates to an object, then for each key-value pair of the
* object with a truthy value the corresponding key is used as a class name.
*
* 3. If the expression evaluates to an array, each element of the array should either be a string as in
* type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
* to give you more control over what CSS classes appear. See the code below for an example of this.
*
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then are the
* new classes added.
*
* @animations
* **add** - happens just before the class is applied to the elements
*
* **remove** - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demonstrates basic bindings via ngClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
<label>
<input type="checkbox" ng-model="deleted">
deleted (apply "strike" class)
</label><br>
<label>
<input type="checkbox" ng-model="important">
important (apply "bold" class)
</label><br>
<label>
<input type="checkbox" ng-model="error">
error (apply "has-error" class)
</label>
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style"
placeholder="Type: bold strike red" aria-label="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
<input ng-model="style2"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
<input ng-model="style3"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
<hr>
<p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
<input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
<label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
.has-error {
color: red;
background-color: yellow;
}
.orange {
color: orange;
}
</file>
<file name="protractor.js" type="protractor">
var ps = element.all(by.css('p'));
it('should let you toggle the class', function() {
expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
element(by.model('important')).click();
expect(ps.first().getAttribute('class')).toMatch(/bold/);
element(by.model('error')).click();
expect(ps.first().getAttribute('class')).toMatch(/has-error/);
});
it('should let you toggle string example', function() {
expect(ps.get(1).getAttribute('class')).toBe('');
element(by.model('style')).clear();
element(by.model('style')).sendKeys('red');
expect(ps.get(1).getAttribute('class')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(ps.get(2).getAttribute('class')).toBe('');
element(by.model('style1')).sendKeys('bold');
element(by.model('style2')).sendKeys('strike');
element(by.model('style3')).sendKeys('red');
expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
});
it('array with map example should have 2 classes', function() {
expect(ps.last().getAttribute('class')).toBe('');
element(by.model('style4')).sendKeys('bold');
element(by.model('warning')).click();
expect(ps.last().getAttribute('class')).toBe('bold orange');
});
</file>
</example>
## Animations
The example below demonstrates how to perform animations using ngClass.
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.base-class {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.base-class.my-class {
color: red;
font-size:3em;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class', function() {
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
element(by.id('setbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).
toMatch(/my-class/);
element(by.id('clearbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
});
</file>
</example>
## ngClass and pre-existing CSS3 Transitions/Animations
The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
to view the step by step details of {@link $animate#addClass $animate.addClass} and
{@link $animate#removeClass $animate.removeClass}.
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ngClassOdd
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ngClassEven
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ngCloak
* @restrict AC
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but the preferred usage is to apply
* multiple `ngCloak` directives to small portions of the page to permit progressive rendering
* of the browser view.
*
* `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
* `angular.min.js`.
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```css
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none !important;
* }
* ```
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, making
* the compiled element visible.
*
* For the best result, the `angular.js` script must be loaded in the head section of the html
* document; alternatively, the css rule above must be included in the external stylesheet of the
* application.
*
* @element ANY
*
* @example
<example>
<file name="index.html">
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" class="ng-cloak">{{ 'world' }}</div>
</file>
<file name="protractor.js" type="protractor">
it('should remove the template directive and css class', function() {
expect($('#template1').getAttribute('ng-cloak')).
toBeNull();
expect($('#template2').getAttribute('ng-cloak')).
toBeNull();
});
</file>
</example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ngController
*
* @description
* The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
* are accessed through bindings.
* * View — The template (HTML with data bindings) that is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class contains business
* logic behind the application to decorate the scope with functions and values
*
* Note that you can also attach controllers to the DOM by declaring it in a route definition
* via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
* again using `ng-controller` in the template itself. This will cause the controller to be attached
* and executed twice.
*
* @element ANY
* @scope
* @priority 500
* @param {expression} ngController Name of a constructor function registered with the current
* {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
* that on the current scope evaluates to a constructor function.
*
* The controller instance can be published into a scope property by specifying
* `ng-controller="as propertyName"`.
*
* If the current `$controllerProvider` is configured to use globals (via
* {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
* also be the name of a globally accessible constructor function (not recommended).
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Any changes to the data are automatically reflected
* in the View without the need for a manual update.
*
* Two different declaration styles are included below:
*
* * one binds methods and properties directly onto the controller using `this`:
* `ng-controller="SettingsController1 as settings"`
* * one injects `$scope` into the controller:
* `ng-controller="SettingsController2"`
*
* The second option is more common in the Angular community, and is generally used in boilerplates
* and in this guide. However, there are advantages to binding properties directly to the controller
* and avoiding scope.
*
* * Using `controller as` makes it obvious which controller you are accessing in the template when
* multiple controllers apply to an element.
* * If you are writing your controllers as classes you have easier access to the properties and
* methods, which will appear on the scope, from inside the controller code.
* * Since there is always a `.` in the bindings, you don't have to worry about prototypal
* inheritance masking primitives.
*
* This example demonstrates the `controller as` syntax.
*
* <example name="ngControllerAs" module="controllerAsExample">
* <file name="index.html">
* <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
* <label>Name: <input type="text" ng-model="settings.name"/></label>
* <button ng-click="settings.greet()">greet</button><br/>
* Contact:
* <ul>
* <li ng-repeat="contact in settings.contacts">
* <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
* <button ng-click="settings.clearContact(contact)">clear</button>
* <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
* </li>
* <li><button ng-click="settings.addContact()">add</button></li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerAsExample', [])
* .controller('SettingsController1', SettingsController1);
*
* function SettingsController1() {
* this.name = "John Smith";
* this.contacts = [
* {type: 'phone', value: '408 555 1212'},
* {type: 'email', value: '[email protected]'} ];
* }
*
* SettingsController1.prototype.greet = function() {
* alert(this.name);
* };
*
* SettingsController1.prototype.addContact = function() {
* this.contacts.push({type: 'email', value: '[email protected]'});
* };
*
* SettingsController1.prototype.removeContact = function(contactToRemove) {
* var index = this.contacts.indexOf(contactToRemove);
* this.contacts.splice(index, 1);
* };
*
* SettingsController1.prototype.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller as', function() {
* var container = element(by.id('ctrl-as-exmpl'));
* expect(container.element(by.model('settings.name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in settings.contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in settings.contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
*
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('[email protected]');
*
* firstRepeat.element(by.buttonText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.buttonText('add')).click();
*
* expect(container.element(by.repeater('contact in settings.contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('[email protected]');
* });
* </file>
* </example>
*
* This example demonstrates the "attach to `$scope`" style of controller.
*
* <example name="ngController" module="controllerExample">
* <file name="index.html">
* <div id="ctrl-exmpl" ng-controller="SettingsController2">
* <label>Name: <input type="text" ng-model="name"/></label>
* <button ng-click="greet()">greet</button><br/>
* Contact:
* <ul>
* <li ng-repeat="contact in contacts">
* <select ng-model="contact.type" id="select_{{$index}}">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
* <button ng-click="clearContact(contact)">clear</button>
* <button ng-click="removeContact(contact)">X</button>
* </li>
* <li>[ <button ng-click="addContact()">add</button> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerExample', [])
* .controller('SettingsController2', ['$scope', SettingsController2]);
*
* function SettingsController2($scope) {
* $scope.name = "John Smith";
* $scope.contacts = [
* {type:'phone', value:'408 555 1212'},
* {type:'email', value:'[email protected]'} ];
*
* $scope.greet = function() {
* alert($scope.name);
* };
*
* $scope.addContact = function() {
* $scope.contacts.push({type:'email', value:'[email protected]'});
* };
*
* $scope.removeContact = function(contactToRemove) {
* var index = $scope.contacts.indexOf(contactToRemove);
* $scope.contacts.splice(index, 1);
* };
*
* $scope.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* }
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller', function() {
* var container = element(by.id('ctrl-exmpl'));
*
* expect(container.element(by.model('name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('[email protected]');
*
* firstRepeat.element(by.buttonText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.buttonText('add')).click();
*
* expect(container.element(by.repeater('contact in contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('[email protected]');
* });
* </file>
*</example>
*/
var ngControllerDirective = [function() {
return {
restrict: 'A',
scope: true,
controller: '@',
priority: 500
};
}];
/**
* @ngdoc directive
* @name ngCsp
*
* @element html
* @description
*
* Angular has some features that can break certain
* [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
*
* If you intend to implement these rules then you must tell Angular not to use these features.
*
* This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
*
*
* The following rules affect Angular:
*
* * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
* (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
* increase in the speed of evaluating Angular expressions.
*
* * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
* makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
* To make these directives work when a CSP rule is blocking inline styles, you must link to the
* `angular-csp.css` in your HTML manually.
*
* If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
* and automatically deactivates this feature in the {@link $parse} service. This autodetection,
* however, triggers a CSP error to be logged in the console:
*
* ```
* Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
* script in the following Content Security Policy directive: "default-src 'self'". Note that
* 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
* ```
*
* This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
* directive on an element of the HTML document that appears before the `<script>` tag that loads
* the `angular.js` file.
*
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
*
* You can specify which of the CSP related Angular features should be deactivated by providing
* a value for the `ng-csp` attribute. The options are as follows:
*
* * no-inline-style: this stops Angular from injecting CSS styles into the DOM
*
* * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
*
* You can use these values in the following combinations:
*
*
* * No declaration means that Angular will assume that you can do inline styles, but it will do
* a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
* of Angular.
*
* * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
* styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
* of Angular.
*
* * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
* inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
*
* * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
* run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
*
* * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
* styles nor use eval, which is the same as an empty: ng-csp.
* E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
```
* @example
// Note: the suffix `.csp` in the example name triggers
// csp mode in our http server!
<example name="example.csp" module="cspExample" ng-csp="true">
<file name="index.html">
<div ng-controller="MainController as ctrl">
<div>
<button ng-click="ctrl.inc()" id="inc">Increment</button>
<span id="counter">
{{ctrl.counter}}
</span>
</div>
<div>
<button ng-click="ctrl.evil()" id="evil">Evil</button>
<span id="evilError">
{{ctrl.evilError}}
</span>
</div>
</div>
</file>
<file name="script.js">
angular.module('cspExample', [])
.controller('MainController', function() {
this.counter = 0;
this.inc = function() {
this.counter++;
};
this.evil = function() {
// jshint evil:true
try {
eval('1+2');
} catch (e) {
this.evilError = e.message;
}
};
});
</file>
<file name="protractor.js" type="protractor">
var util, webdriver;
var incBtn = element(by.id('inc'));
var counter = element(by.id('counter'));
var evilBtn = element(by.id('evil'));
var evilError = element(by.id('evilError'));
function getAndClearSevereErrors() {
return browser.manage().logs().get('browser').then(function(browserLog) {
return browserLog.filter(function(logEntry) {
return logEntry.level.value > webdriver.logging.Level.WARNING.value;
});
});
}
function clearErrors() {
getAndClearSevereErrors();
}
function expectNoErrors() {
getAndClearSevereErrors().then(function(filteredLog) {
expect(filteredLog.length).toEqual(0);
if (filteredLog.length) {
console.log('browser console errors: ' + util.inspect(filteredLog));
}
});
}
function expectError(regex) {
getAndClearSevereErrors().then(function(filteredLog) {
var found = false;
filteredLog.forEach(function(log) {
if (log.message.match(regex)) {
found = true;
}
});
if (!found) {
throw new Error('expected an error that matches ' + regex);
}
});
}
beforeEach(function() {
util = require('util');
webdriver = require('protractor/node_modules/selenium-webdriver');
});
// For now, we only test on Chrome,
// as Safari does not load the page with Protractor's injected scripts,
// and Firefox webdriver always disables content security policy (#6358)
if (browser.params.browser !== 'chrome') {
return;
}
it('should not report errors when the page is loaded', function() {
// clear errors so we are not dependent on previous tests
clearErrors();
// Need to reload the page as the page is already loaded when
// we come here
browser.driver.getCurrentUrl().then(function(url) {
browser.get(url);
});
expectNoErrors();
});
it('should evaluate expressions', function() {
expect(counter.getText()).toEqual('0');
incBtn.click();
expect(counter.getText()).toEqual('1');
expectNoErrors();
});
it('should throw and report an error when using "eval"', function() {
evilBtn.click();
expect(evilError.getText()).toMatch(/Content Security Policy/);
expectError(/Content Security Policy/);
});
</file>
</example>
*/
// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
// bootstrap the system (before $parse is instantiated), for this reason we just have
// the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
/**
* @ngdoc directive
* @name ngClick
*
* @description
* The ngClick directive allows you to specify custom behavior when
* an element is clicked.
*
* @element ANY
* @priority 0
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
<span>
count: {{count}}
</span>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-click', function() {
expect(element(by.binding('count')).getText()).toMatch('0');
element(by.css('button')).click();
expect(element(by.binding('count')).getText()).toMatch('1');
});
</file>
</example>
*/
/*
* A collection of directives that allows creation of custom event handlers that are defined as
* angular expressions and are compiled and executed within the current scope.
*/
var ngEventDirectives = {};
// For events that might fire synchronously during DOM manipulation
// we need to execute their event handlers asynchronously using $evalAsync,
// so that they are not executed in an inconsistent state.
var forceAsyncEvents = {
'blur': true,
'focus': true
};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(eventName) {
var directiveName = directiveNormalize('ng-' + eventName);
ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
// We expose the powerful $event object on the scope that provides access to the Window,
// etc. that isn't protected by the fast paths in $parse. We explicitly request better
// checks at the cost of speed since event handler expressions are not executed as
// frequently as regular change detection.
var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
return function ngEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
};
}
};
}];
}
);
/**
* @ngdoc directive
* @name ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
*
* @element ANY
* @priority 0
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* a dblclick. (The Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<button ng-dblclick="count = count + 1" ng-init="count=0">
Increment (on double click)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousedown="count = count + 1" ng-init="count=0">
Increment (on mouse down)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseup="count = count + 1" ng-init="count=0">
Increment (on mouse up)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseover="count = count + 1" ng-init="count=0">
Increment (when mouse is over)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseenter="count = count + 1" ng-init="count=0">
Increment (when mouse enters)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseleave="count = count + 1" ng-init="count=0">
Increment (when mouse leaves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousemove="count = count + 1" ng-init="count=0">
Increment (when mouse moves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeydown
*
* @description
* Specify custom behavior on keydown event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keydown="count = count + 1" ng-init="count=0">
key down count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeyup
*
* @description
* Specify custom behavior on keyup event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<p>Typing in the input box below updates the key count</p>
<input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
<p>Typing in the input box below updates the keycode</p>
<input ng-keyup="event=$event">
<p>event keyCode: {{ event.keyCode }}</p>
<p>event altKey: {{ event.altKey }}</p>
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeypress
*
* @description
* Specify custom behavior on keypress event.
*
* @element ANY
* @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
* keypress. ({@link guide/expression#-event- Event object is available as `$event`}
* and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keypress="count = count + 1" ng-init="count=0">
key press count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page), but only if the form does not contain `action`,
* `data-action`, or `x-action` attributes.
*
* <div class="alert alert-warning">
* **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
* `ngSubmit` handlers together. See the
* {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
* for a detailed discussion of when `ngSubmit` may be triggered.
* </div>
*
* @element form
* @priority 0
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
* ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example module="submitExample">
<file name="index.html">
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-submit', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
expect(element(by.model('text')).getAttribute('value')).toBe('');
});
it('should ignore empty strings', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngFocus
*
* @description
* Specify custom behavior on focus event.
*
* Note: As the `focus` event is executed synchronously when calling `input.focus()`
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
* focus. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngBlur
*
* @description
* Specify custom behavior on blur event.
*
* A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
* an element has lost focus.
*
* Note: As the `blur` event is executed synchronously also during DOM manipulations
* (e.g. removing a focussed input),
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
* blur. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngCopy
*
* @description
* Specify custom behavior on copy event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
* copy. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
copied: {{copied}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngCut
*
* @description
* Specify custom behavior on cut event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
* cut. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
cut: {{cut}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngPaste
*
* @description
* Specify custom behavior on paste event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
* paste. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
pasted: {{paste}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngIf
* @restrict A
* @multiElement
*
* @description
* The `ngIf` directive removes or recreates a portion of the DOM tree based on an
* {expression}. If the expression assigned to `ngIf` evaluates to a false
* value then the element is removed from the DOM, otherwise a clone of the
* element is reinserted into the DOM.
*
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
* is created when the element is restored. The scope created within `ngIf` inherits from
* its parent scope using
* [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
* An important implication of this is if `ngModel` is used within `ngIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `ngIf` recreates elements using their compiled state. An example of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
* and `leave` effects.
*
* @animations
* enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
* leave - happens just before the `ngIf` contents are removed from the DOM
*
* @element ANY
* @scope
* @priority 600
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree. If it is truthy a copy of the compiled
* element is added to the DOM tree.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-leave,
.animate-if.ng-enter.ng-enter-active {
opacity:1;
}
</file>
</example>
*/
var ngIfDirective = ['$animate', function($animate) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
});
}
};
}];
/**
* @ngdoc directive
* @name ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* By default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link $sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
* you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
* {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
* ng.$sce Strict Contextual Escaping}.
*
* In addition, the browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy may further restrict whether the template is successfully loaded.
* For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers.
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example module="includeExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <code>{{template.url}}</code>
<hr/>
<div class="slide-animate-container">
<div class="slide-animate" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
angular.module('includeExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'},
{ name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}]);
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="animations.css">
.slide-animate-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.slide-animate {
padding:10px;
}
.slide-animate.ng-enter, .slide-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
display:block;
padding:10px;
}
.slide-animate.ng-enter {
top:-50px;
}
.slide-animate.ng-enter.ng-enter-active {
top:0;
}
.slide-animate.ng-leave {
top:0;
}
.slide-animate.ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="protractor.js" type="protractor">
var templateSelect = element(by.model('template'));
var includeElem = element(by.css('[ng-include]'));
it('should load template1.html', function() {
expect(includeElem.getText()).toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
// See https://github.com/angular/protractor/issues/480
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(2).click();
expect(includeElem.getText()).toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(0).click();
expect(includeElem.isPresent()).toBe(false);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentRequested
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentLoaded
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentError
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
function($templateRequest, $anchorScroll, $animate) {
return {
restrict: 'ECA',
priority: 400,
terminal: true,
transclude: 'element',
controller: angular.noop,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, $element, $attr, ctrl, $transclude) {
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var afterAnimation = function() {
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
};
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
ctrl.template = response;
// Note: This will also link all children of ng-include that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-include on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, null, $element).then(afterAnimation);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
scope.$eval(onloadExp);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
ctrl.template = null;
}
});
};
}
};
}];
// This directive is called during the $transclude call of the first `ngInclude` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngInclude
// is called.
var ngIncludeFillContentDirective = ['$compile',
function($compile) {
return {
restrict: 'ECA',
priority: -400,
require: 'ngInclude',
link: function(scope, $element, $attr, ctrl) {
if (/SVG/.test($element[0].toString())) {
// WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
// support innerHTML, so detect this here and try to generate the contents
// specially.
$element.empty();
$compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
function namespaceAdaptedClone(clone) {
$element.append(clone);
}, {futureParentElement: $element});
return;
}
$element.html(ctrl.template);
$compile($element.contents())(scope);
}
};
}];
/**
* @ngdoc directive
* @name ngInit
* @restrict AC
*
* @description
* The `ngInit` directive allows you to evaluate an expression in the
* current scope.
*
* <div class="alert alert-danger">
* The only appropriate use of `ngInit` is for aliasing special properties of
* {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
* should use {@link guide/controller controllers} rather than `ngInit`
* to initialize values on a scope.
* </div>
* <div class="alert alert-warning">
* **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
* sure you have parenthesis for correct precedence:
* <pre class="prettyprint">
* `<div ng-init="test1 = (data | orderBy:'name')"></div>`
* </pre>
* </div>
*
* @priority 450
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<example module="initExample">
<file name="index.html">
<script>
angular.module('initExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should alias index positions', function() {
var elements = element.all(by.css('.example-init'));
expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
});
</file>
</example>
*/
var ngInitDirective = ngDirective({
priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});
/**
* @ngdoc directive
* @name ngList
*
* @description
* Text input that converts between a delimited string and an array of strings. The default
* delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
* delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
*
* The behaviour of the directive is affected by the use of the `ngTrim` attribute.
* * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
* list item is respected. This implies that the user of the directive is responsible for
* dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
* tab or newline character.
* * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
* when joining the list items back together) and whitespace around each list item is stripped
* before it is added to the model.
*
* ### Example with Validation
*
* <example name="ngList-directive" module="listExample">
* <file name="app.js">
* angular.module('listExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.names = ['morpheus', 'neo', 'trinity'];
* }]);
* </file>
* <file name="index.html">
* <form name="myForm" ng-controller="ExampleController">
* <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
* <span role="alert">
* <span class="error" ng-show="myForm.namesInput.$error.required">
* Required!</span>
* </span>
* <br>
* <tt>names = {{names}}</tt><br/>
* <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
* <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
* <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
* <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
* </form>
* </file>
* <file name="protractor.js" type="protractor">
* var listInput = element(by.model('names'));
* var names = element(by.exactBinding('names'));
* var valid = element(by.binding('myForm.namesInput.$valid'));
* var error = element(by.css('span.error'));
*
* it('should initialize to model', function() {
* expect(names.getText()).toContain('["morpheus","neo","trinity"]');
* expect(valid.getText()).toContain('true');
* expect(error.getCssValue('display')).toBe('none');
* });
*
* it('should be invalid if empty', function() {
* listInput.clear();
* listInput.sendKeys('');
*
* expect(names.getText()).toContain('');
* expect(valid.getText()).toContain('false');
* expect(error.getCssValue('display')).not.toBe('none');
* });
* </file>
* </example>
*
* ### Example - splitting on whitespace
* <example name="ngList-directive-newlines">
* <file name="index.html">
* <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
* <pre>{{ list | json }}</pre>
* </file>
* <file name="protractor.js" type="protractor">
* it("should split the text by newlines", function() {
* var listInput = element(by.model('list'));
* var output = element(by.binding('list | json'));
* listInput.sendKeys('abc\ndef\nghi');
* expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
* });
* </file>
* </example>
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value.
*/
var ngListDirective = function() {
return {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
};
/* global VALID_CLASS: true,
INVALID_CLASS: true,
PRISTINE_CLASS: true,
DIRTY_CLASS: true,
UNTOUCHED_CLASS: true,
TOUCHED_CLASS: true,
*/
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
TOUCHED_CLASS = 'ng-touched',
PENDING_CLASS = 'ng-pending';
var ngModelMinErr = minErr('ngModel');
/**
* @ngdoc type
* @name ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. The functions are called in array order, each passing
its return value through to the next. The last return value is forwarded to the
{@link ngModel.NgModelController#$validators `$validators`} collection.
Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
`$viewValue`}.
Returning `undefined` from a parser means a parse error occurred. In that case,
no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
is set to `true`. The parse error is stored in `ngModel.$error.parse`.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. The functions are called in reverse array order, each passing the value through to the
next. The last return value is used as the actual DOM value.
Used to format / convert values for display in the control.
* ```js
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* ```
*
* @property {Object.<string, function>} $validators A collection of validators that are applied
* whenever the model value changes. The key value within the object refers to the name of the
* validator while the function refers to the validation operation. The validation operation is
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
* ```js
* ngModel.$validators.validCharacters = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
* return /[0-9]+/.test(value) &&
* /[a-z]+/.test(value) &&
* /[A-Z]+/.test(value) &&
* /\W+/.test(value);
* };
* ```
*
* @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
* perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
* is expected to return a promise when it is run during the model validation process. Once the promise
* is delivered then the validation status will be set to true when fulfilled and false when rejected.
* When the asynchronous validators are triggered, each of the validators will run in parallel and the model
* value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
* is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
* will only run once all synchronous validators have passed.
*
* Please note that if $http is used then it is important that the server returns a success HTTP response code
* in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
*
* ```js
* ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
*
* // Lookup user by username
* return $http.get('/api/users/' + value).
* then(function resolved() {
* //username exists, this means validation fails
* return $q.reject('exists');
* }, function rejected() {
* //username does not exist, therefore this validation passes
* return true;
* });
* };
* ```
*
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
* @property {Object} $error An object hash with all failing validator ids as keys.
* @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
* @property {string} $name The name attribute of the control.
*
* @description
*
* `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
* The controller contains services for data-binding, validation, CSS updates, and value formatting
* and parsing. It purposefully does not contain any logic which deals with DOM rendering or
* listening to DOM events.
* Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding to control elements.
* Angular provides this DOM logic for most {@link input `input`} elements.
* At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
* custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
*
* @example
* ### Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user.
*
* We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
* module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
* However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
* that content using the `$sce` service.
*
* <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if ( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should data-bind and become invalid', function() {
if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
// SafariDriver can't handle contenteditable
// and Firefox driver can't clear contenteditables very well
return;
}
var contentEditable = element(by.css('[contenteditable]'));
var content = 'Change me!';
expect(contentEditable.getText()).toEqual(content);
contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$untouched = true;
this.$touched = false;
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$error = {}; // keep invalid keys here
this.$$success = {}; // keep valid keys here
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
var parsedNgModel = $parse($attr.ngModel),
parsedNgModelAssign = parsedNgModel.assign,
ngModelGet = parsedNgModel,
ngModelSet = parsedNgModelAssign,
pendingDebounce = null,
parserValid,
ctrl = this;
this.$$setOptions = function(options) {
ctrl.$options = options;
if (options && options.getterSetter) {
var invokeModelGetter = $parse($attr.ngModel + '()'),
invokeModelSetter = $parse($attr.ngModel + '($$$p)');
ngModelGet = function($scope) {
var modelValue = parsedNgModel($scope);
if (isFunction(modelValue)) {
modelValue = invokeModelGetter($scope);
}
return modelValue;
};
ngModelSet = function($scope, newValue) {
if (isFunction(parsedNgModel($scope))) {
invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
} else {
parsedNgModelAssign($scope, ctrl.$modelValue);
}
};
} else if (!parsedNgModel.assign) {
throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$render
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*
* The `$render()` method is invoked in the following situations:
*
* * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
* committed value then `$render()` is called to update the input control.
* * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
* the `$viewValue` are different from last time.
*
* Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
* `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
* or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
* invoked if you only change a property on the objects.
*/
this.$render = noop;
/**
* @ngdoc method
* @name ngModel.NgModelController#$isEmpty
*
* @description
* This is called when we need to determine if the value of an input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
*
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different from the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
* @param {*} value The value of the input to check for emptiness.
* @returns {boolean} True if `value` is "empty".
*/
this.$isEmpty = function(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
currentValidationRunId = 0;
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
* Change the validity state, and notify the form.
*
* This method can be called within $parsers/$formatters or a custom validation implementation.
* However, in most cases it should be sufficient to use the `ngModel.$validators` and
* `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
*
* @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
* to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
* (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
* or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
* Skipped is used by Angular when validators do not run because of parse errors and
* when `$asyncValidators` do not run because any of the `$validators` failed.
*/
addSetValidityMethod({
ctrl: this,
$element: $element,
set: function(object, property) {
object[property] = true;
},
unset: function(object, property) {
delete object[property];
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name ngModel.NgModelController#$setPristine
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the `ng-dirty` class and set the control to its pristine
* state (`ng-pristine` class). A model is considered to be pristine when the control
* has not been changed from when first compiled.
*/
this.$setPristine = function() {
ctrl.$dirty = false;
ctrl.$pristine = true;
$animate.removeClass($element, DIRTY_CLASS);
$animate.addClass($element, PRISTINE_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setDirty
*
* @description
* Sets the control to its dirty state.
*
* This method can be called to remove the `ng-pristine` class and set the control to its dirty
* state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
* from when first compiled.
*/
this.$setDirty = function() {
ctrl.$dirty = true;
ctrl.$pristine = false;
$animate.removeClass($element, PRISTINE_CLASS);
$animate.addClass($element, DIRTY_CLASS);
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setUntouched
*
* @description
* Sets the control to its untouched state.
*
* This method can be called to remove the `ng-touched` class and set the control to its
* untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
* by default, however this function can be used to restore that state if the model has
* already been touched by the user.
*/
this.$setUntouched = function() {
ctrl.$touched = false;
ctrl.$untouched = true;
$animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setTouched
*
* @description
* Sets the control to its touched state.
*
* This method can be called to remove the `ng-untouched` class and set the control to its
* touched state (`ng-touched` class). A model is considered to be touched when the user has
* first focused the control element and then shifted focus away from the control (blur event).
*/
this.$setTouched = function() {
ctrl.$touched = true;
ctrl.$untouched = false;
$animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$rollbackViewValue
*
* @description
* Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
* which may be caused by a pending debounced event or because the input is waiting for a some
* future event.
*
* If you have an input that uses `ng-model-options` to set up debounced events or events such
* as blur you can have a situation where there is a period when the `$viewValue`
* is out of synch with the ngModel's `$modelValue`.
*
* In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
* programmatically before these debounced/future events have resolved/occurred, because Angular's
* dirty checking mechanism is not able to tell whether the model has actually changed or not.
*
* The `$rollbackViewValue()` method should be called before programmatically changing the model of an
* input which may have such events pending. This is important in order to make sure that the
* input field will be updated with the new model value and any pending operations are cancelled.
*
* <example name="ng-model-cancel-update" module="cancel-update-example">
* <file name="app.js">
* angular.module('cancel-update-example', [])
*
* .controller('CancelUpdateController', ['$scope', function($scope) {
* $scope.resetWithCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myForm.myInput1.$rollbackViewValue();
* $scope.myValue = '';
* }
* };
* $scope.resetWithoutCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myValue = '';
* }
* };
* }]);
* </file>
* <file name="index.html">
* <div ng-controller="CancelUpdateController">
* <p>Try typing something in each input. See that the model only updates when you
* blur off the input.
* </p>
* <p>Now see what happens if you start typing then press the Escape key</p>
*
* <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
* <p id="inputDescription1">With $rollbackViewValue()</p>
* <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
* ng-keydown="resetWithCancel($event)"><br/>
* myValue: "{{ myValue }}"
*
* <p id="inputDescription2">Without $rollbackViewValue()</p>
* <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
* ng-keydown="resetWithoutCancel($event)"><br/>
* myValue: "{{ myValue }}"
* </form>
* </div>
* </file>
* </example>
*/
this.$rollbackViewValue = function() {
$timeout.cancel(pendingDebounce);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
ctrl.$render();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$validate
*
* @description
* Runs each of the registered validators (first synchronous validators and then
* asynchronous validators).
* If the validity changes to invalid, the model will be set to `undefined`,
* unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
* If the validity changes to valid, it will set the model to the last available valid
* `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
*/
this.$validate = function() {
// ignore $validate before model is initialized
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
var viewValue = ctrl.$$lastCommittedViewValue;
// Note: we use the $$rawModelValue as $modelValue might have been
// set to undefined during a view -> model update that found validation
// errors. We can't parse the view here, since that could change
// the model although neither viewValue nor the model on the scope changed
var modelValue = ctrl.$$rawModelValue;
var prevValid = ctrl.$valid;
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
// If there was no change in validity, don't update the model
// This prevents changing an invalid modelValue to undefined
if (!allowInvalid && prevValid !== allValid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
});
};
this.$$runValidators = function(modelValue, viewValue, doneCallback) {
currentValidationRunId++;
var localValidationRunId = currentValidationRunId;
// check parser error
if (!processParseErrors()) {
validationDone(false);
return;
}
if (!processSyncValidators()) {
validationDone(false);
return;
}
processAsyncValidators();
function processParseErrors() {
var errorKey = ctrl.$$parserName || 'parse';
if (parserValid === undefined) {
setValidity(errorKey, null);
} else {
if (!parserValid) {
forEach(ctrl.$validators, function(v, name) {
setValidity(name, null);
});
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
}
// Set the parse error last, to prevent unsetting it, should a $validators key == parserName
setValidity(errorKey, parserValid);
return parserValid;
}
return true;
}
function processSyncValidators() {
var syncValidatorsValid = true;
forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
if (!syncValidatorsValid) {
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
return true;
}
function processAsyncValidators() {
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw ngModelMinErr("$asyncValidators",
"Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
}
setValidity(name, undefined);
validatorPromises.push(promise.then(function() {
setValidity(name, true);
}, function(error) {
allValid = false;
setValidity(name, false);
}));
});
if (!validatorPromises.length) {
validationDone(true);
} else {
$q.all(validatorPromises).then(function() {
validationDone(allValid);
}, noop);
}
}
function setValidity(name, isValid) {
if (localValidationRunId === currentValidationRunId) {
ctrl.$setValidity(name, isValid);
}
}
function validationDone(allValid) {
if (localValidationRunId === currentValidationRunId) {
doneCallback(allValid);
}
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$commitViewValue
*
* @description
* Commit a pending update to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
// If the view value has not changed then we should just exit, except in the case where there is
// a native validator on the element. In this case the validation state may have changed even though
// the viewValue has stayed empty.
if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
// change to dirty
if (ctrl.$pristine) {
this.$setDirty();
}
this.$$parseAndValidate();
};
this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
parserValid = isUndefined(modelValue) ? undefined : true;
if (parserValid) {
for (var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet($scope);
}
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$rawModelValue = modelValue;
if (allowInvalid) {
ctrl.$modelValue = modelValue;
writeToModelIfNeeded();
}
// Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
// This can happen if e.g. $setViewValue is called from inside a parser
ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
if (!allowInvalid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
writeToModelIfNeeded();
}
});
function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
};
this.$$writeModelToScope = function() {
ngModelSet($scope, ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
$exceptionHandler(e);
}
});
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setViewValue
*
* @description
* Update the view value.
*
* This method should be called when an input directive want to change the view value; typically,
* this is done from within a DOM event handler.
*
* For example {@link ng.directive:input input} calls it when the value of the input changes and
* {@link ng.directive:select select} calls it when an option is selected.
*
* If the new `value` is an object (rather than a string or a number), we should make a copy of the
* object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
* watch of objects, it only looks for a change of identity. If you only change the property of
* the object then ngModel will not realise that the object has changed and will not invoke the
* `$parsers` and `$validators` pipelines.
*
* For this reason, you should not change properties of the copy once it has been passed to
* `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
*
* When this method is called, the new `value` will be staged for committing through the `$parsers`
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute.
*
* Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
* `updateOn` events is triggered on the DOM element.
* All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
* directive is used with a custom debounce for this particular event.
*
* Note that calling this function does not trigger a `$digest`.
*
* @param {string} value Value from the view.
* @param {string} trigger Event that triggered the update.
*/
this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (!ctrl.$options || ctrl.$options.updateOnDefault) {
ctrl.$$debounceViewValueCommit(trigger);
}
};
this.$$debounceViewValueCommit = function(trigger) {
var debounceDelay = 0,
options = ctrl.$options,
debounce;
if (options && isDefined(options.debounce)) {
debounce = options.debounce;
if (isNumber(debounce)) {
debounceDelay = debounce;
} else if (isNumber(debounce[trigger])) {
debounceDelay = debounce[trigger];
} else if (isNumber(debounce['default'])) {
debounceDelay = debounce['default'];
}
}
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
ctrl.$commitViewValue();
}, debounceDelay);
} else if ($rootScope.$$phase) {
ctrl.$commitViewValue();
} else {
$scope.$apply(function() {
ctrl.$commitViewValue();
});
}
};
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
var modelValue = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue &&
// checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
(ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
parserValid = undefined;
var formatters = ctrl.$formatters,
idx = formatters.length;
var viewValue = modelValue;
while (idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
ctrl.$$runValidators(modelValue, viewValue, noop);
}
}
return modelValue;
});
}];
/**
* @ngdoc directive
* @name ngModel
*
* @element input
* @priority 1
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link input[text] text}
* - {@link input[checkbox] checkbox}
* - {@link input[radio] radio}
* - {@link input[number] number}
* - {@link input[email] email}
* - {@link input[url] url}
* - {@link input[date] date}
* - {@link input[datetime-local] datetime-local}
* - {@link input[time] time}
* - {@link input[month] month}
* - {@link input[week] week}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
* # CSS classes
* The following CSS classes are added and removed on the associated input/select/textarea element
* depending on the validity of the model.
*
* - `ng-valid`: the model is valid
* - `ng-invalid`: the model is invalid
* - `ng-valid-[key]`: for each valid key added by `$setValidity`
* - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
* - `ng-pristine`: the control hasn't been interacted with yet
* - `ng-dirty`: the control has been interacted with
* - `ng-touched`: the control has been blurred
* - `ng-untouched`: the control hasn't been blurred
* - `ng-pending`: any `$asyncValidators` are unfulfilled
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
* ## Animation Hooks
*
* Animations within models are triggered when any of the associated CSS classes are added and removed
* on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
* `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
* The animations that are triggered within ngModel are similar to how they work in ngClass and
* animations can be hooked into using CSS transitions, keyframes as well as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style an input element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-input {
* transition:0.5s linear all;
* background: white;
* }
* .my-input.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
* <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
<p id="inputDescription">
Update input to see transitions when valid/invalid.
Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
</form>
</file>
* </example>
*
* ## Binding to a getter/setter
*
* Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
* function that returns a representation of the model when called with zero arguments, and sets
* the internal state of a model when called with an argument. It's sometimes useful to use this
* for models that have an internal representation that's different from what the model exposes
* to the view.
*
* <div class="alert alert-success">
* **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
* frequently than other parts of your code.
* </div>
*
* You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
* has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
* a `<form>`, which will enable this behavior for all `<input>`s within it. See
* {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
*
* The following example shows how to use `ngModel` with a getter/setter:
*
* @example
* <example name="ngModel-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
</file>
* </example>
*/
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
formCtrl.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function(ev) {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
}];
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
/**
* @ngdoc directive
* @name ngModelOptions
*
* @description
* Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
* events that will trigger a model update and/or a debouncing delay so that the actual update only
* takes place when a timer expires; this timer will be reset after another change takes place.
*
* Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
* be different from the value in the actual model. This means that if you update the model you
* should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
* order to make sure it is synchronized with the model and that any debounced action is canceled.
*
* The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
* method is by making sure the input is placed inside a form that has a `name` attribute. This is
* important because `form` controllers are published to the related scope under the name in their
* `name` attribute.
*
* Any pending changes will take place immediately when an enclosing form is submitted via the
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* `ngModelOptions` has an effect on the element it's declared on and its descendants.
*
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should the input be bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
* matches the default events belonging of the control.
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
* `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
* - `allowInvalid`: boolean value which indicates that the model can be set with values that did
* not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
`ngModel` as getters/setters.
* - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
* `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
* continental US time zone abbreviations, but for general use, use a time zone offset, for
* example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
* If not specified, the timezone of the browser will be used.
*
* @example
The following example shows how to override immediate updates. Changes on the inputs within the
form will update the model only when the control loses focus (blur event). If `escape` key is
pressed while the input field is focused, the value is reset to the value in the current model.
<example name="ngModelOptions-directive-blur" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" />
</label><br />
<label>Other data:
<input type="text" ng-model="user.data" />
</label><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say', data: '' };
$scope.cancel = function(e) {
if (e.keyCode == 27) {
$scope.userForm.userName.$rollbackViewValue();
}
};
}]);
</file>
<file name="protractor.js" type="protractor">
var model = element(by.binding('user.name'));
var input = element(by.model('user.name'));
var other = element(by.model('user.data'));
it('should allow custom events', function() {
input.sendKeys(' hello');
input.click();
expect(model.getText()).toEqual('say');
other.click();
expect(model.getText()).toEqual('say hello');
});
it('should $rollbackViewValue when model changes', function() {
input.sendKeys(' hello');
expect(input.getAttribute('value')).toEqual('say hello');
input.sendKeys(protractor.Key.ESCAPE);
expect(input.getAttribute('value')).toEqual('say');
other.click();
expect(model.getText()).toEqual('say');
});
</file>
</example>
This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
<example name="ngModelOptions-directive-debounce" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ debounce: 1000 }" />
</label>
<button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
<br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say' };
}]);
</file>
</example>
This one shows how to bind to getter/setters:
<example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
</file>
</example>
*/
var ngModelOptionsDirective = function() {
return {
restrict: 'A',
controller: ['$scope', '$attrs', function($scope, $attrs) {
var that = this;
this.$options = copy($scope.$eval($attrs.ngModelOptions));
// Allow adding/overriding bound events
if (this.$options.updateOn !== undefined) {
this.$options.updateOnDefault = false;
// extract "default" pseudo-event from list of events that can trigger a model update
this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
that.$options.updateOnDefault = true;
return ' ';
}));
} else {
this.$options.updateOnDefault = true;
}
}]
};
};
// helper methods
function addSetValidityMethod(context) {
var ctrl = context.ctrl,
$element = context.$element,
classCache = {},
set = context.set,
unset = context.unset,
parentForm = context.parentForm,
$animate = context.$animate;
classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
ctrl.$setValidity = setValidity;
function setValidity(validationErrorKey, state, controller) {
if (state === undefined) {
createAndSet('$pending', validationErrorKey, controller);
} else {
unsetAndCleanup('$pending', validationErrorKey, controller);
}
if (!isBoolean(state)) {
unset(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
} else {
if (state) {
unset(ctrl.$error, validationErrorKey, controller);
set(ctrl.$$success, validationErrorKey, controller);
} else {
set(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
}
}
if (ctrl.$pending) {
cachedToggleClass(PENDING_CLASS, true);
ctrl.$valid = ctrl.$invalid = undefined;
toggleValidationCss('', null);
} else {
cachedToggleClass(PENDING_CLASS, false);
ctrl.$valid = isObjectEmpty(ctrl.$error);
ctrl.$invalid = !ctrl.$valid;
toggleValidationCss('', ctrl.$valid);
}
// re-read the state as the set/unset methods could have
// combined state in ctrl.$error[validationError] (used for forms),
// where setting/unsetting only increments/decrements the value,
// and does not replace it.
var combinedState;
if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
combinedState = undefined;
} else if (ctrl.$error[validationErrorKey]) {
combinedState = false;
} else if (ctrl.$$success[validationErrorKey]) {
combinedState = true;
} else {
combinedState = null;
}
toggleValidationCss(validationErrorKey, combinedState);
parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
}
function createAndSet(name, value, controller) {
if (!ctrl[name]) {
ctrl[name] = {};
}
set(ctrl[name], value, controller);
}
function unsetAndCleanup(name, value, controller) {
if (ctrl[name]) {
unset(ctrl[name], value, controller);
}
if (isObjectEmpty(ctrl[name])) {
ctrl[name] = undefined;
}
}
function cachedToggleClass(className, switchValue) {
if (switchValue && !classCache[className]) {
$animate.addClass($element, className);
classCache[className] = true;
} else if (!switchValue && classCache[className]) {
$animate.removeClass($element, className);
classCache[className] = false;
}
}
function toggleValidationCss(validationErrorKey, isValid) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
}
}
function isObjectEmpty(obj) {
if (obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
}
return true;
}
/**
* @ngdoc directive
* @name ngNonBindable
* @restrict AC
* @priority 1000
*
* @description
* The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
* DOM element. This is useful if the element contains what appears to be Angular directives and
* bindings but which should be ignored by Angular. This could be the case if you have a site that
* displays snippets of code, for instance.
*
* @element ANY
*
* @example
* In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
* but the one wrapped in `ngNonBindable` is left alone.
*
* @example
<example>
<file name="index.html">
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-non-bindable', function() {
expect(element(by.binding('1 + 2')).getText()).toContain('3');
expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
});
</file>
</example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/* global jqLiteRemove */
var ngOptionsMinErr = minErr('ngOptions');
/**
* @ngdoc directive
* @name ngOptions
* @restrict A
*
* @description
*
* The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for the `<select>` element using the array or object obtained by evaluating the
* `ngOptions` comprehension expression.
*
* In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
* similar result. However, `ngOptions` provides some benefits such as reducing memory and
* increasing speed by not creating a new scope for each repeated instance, as well as providing
* more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
* comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
* to a non-string value. This is because an option element can only be bound to string values at
* present.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* ## Complex Models (objects or collections)
*
* **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
* binding any input directive to a model that is an object or a collection.
*
* Since this is a common situation for `ngOptions` the directive additionally watches the model using
* `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
* the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
* object/collection has not changed identity but only a property on the object or an item in the collection
* changes.
*
* Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
* if the model is an array). This means that changing a property deeper inside the object/collection that the
* first level will not trigger a re-rendering.
*
*
* ## `select` **`as`**
*
* Using `select` **`as`** will bind the result of the `select` expression to the model, but
* the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
* or property name (for object data sources) of the value within the collection. If a **`track by`** expression
* is used, the result of that expression will be set as the value of the `option` and `select` elements.
*
*
* ### `select` **`as`** and **`track by`**
*
* <div class="alert alert-warning">
* Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
* </div>
*
* Consider the following example:
*
* ```html
* <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"></select>
* ```
*
* ```js
* $scope.values = [{
* id: 1,
* label: 'aLabel',
* subItem: { name: 'aSubItem' }
* }, {
* id: 2,
* label: 'bLabel',
* subItem: { name: 'bSubItem' }
* }];
*
* $scope.selected = { name: 'aSubItem' };
* ```
*
* With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
* of the data source (to `item` in this example). To calculate whether an element is selected, we do the
* following:
*
* 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
* 2. Apply **`track by`** to the already selected value in `ngModel`.
* In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
* value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
* a wrong object, the selected element can't be found, `<select>` is always reset to the "not
* selected" option.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
* (for including a filter with `track by`)
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`disable when`** `disable`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `disable`: The result of this expression will be used to disable the rendered `<option>`
* element. Return `true` to disable.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`). With this the selection is preserved
* even when the options are recreated (e.g. reloaded from the server).
*
* @example
<example module="selectExample">
<file name="index.html">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light', notAnOption: true},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark', notAnOption: true},
{name:'yellow', shade:'light', notAnOption: false}
];
$scope.myColor = $scope.colors[2]; // red
}]);
</script>
<div ng-controller="ExampleController">
<ul>
<li ng-repeat="color in colors">
<label>Name: <input ng-model="color.name"></label>
<label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
<button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
</li>
<li>
<button ng-click="colors.push({})">add</button>
</li>
</ul>
<hr/>
<label>Color (null not allowed):
<select ng-model="myColor" ng-options="color.name for color in colors"></select>
</label><br/>
<label>Color (null allowed):
<span class="nullable">
<select ng-model="myColor" ng-options="color.name for color in colors">
<option value="">-- choose color --</option>
</select>
</span></label><br/>
<label>Color grouped by shade:
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
</select>
</label><br/>
<label>Color grouped by shade, with some disabled:
<select ng-model="myColor"
ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
</select>
</label><br/>
Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
<br/>
<hr/>
Currently selected: {{ {selected_color:myColor} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':myColor.name}">
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-options', function() {
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
element.all(by.model('myColor')).first().click();
element.all(by.css('select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
element(by.css('.nullable select[ng-model="myColor"]')).click();
element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
});
</file>
</example>
*/
// jshint maxlen: false
// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
// 1: value expression (valueFn)
// 2: label expression (displayFn)
// 3: group by expression (groupByFn)
// 4: disable when expression (disableWhenFn)
// 5: array item variable name
// 6: object item key variable name
// 7: object item value variable name
// 8: collection expression
// 9: track by expression
// jshint maxlen: 100
var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
function parseOptionsExpression(optionsExp, selectElement, scope) {
var match = optionsExp.match(NG_OPTIONS_REGEXP);
if (!(match)) {
throw ngOptionsMinErr('iexp',
"Expected expression in form of " +
"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '{0}'. Element: {1}",
optionsExp, startingTag(selectElement));
}
// Extract the parts from the ngOptions expression
// The variable name for the value of the item in the collection
var valueName = match[5] || match[7];
// The variable name for the key of the item in the collection
var keyName = match[6];
// An expression that generates the viewValue for an option if there is a label expression
var selectAs = / as /.test(match[0]) && match[1];
// An expression that is used to track the id of each object in the options collection
var trackBy = match[9];
// An expression that generates the viewValue for an option if there is no label expression
var valueFn = $parse(match[2] ? match[1] : valueName);
var selectAsFn = selectAs && $parse(selectAs);
var viewValueFn = selectAsFn || valueFn;
var trackByFn = trackBy && $parse(trackBy);
// Get the value by which we are going to track the option
// if we have a trackFn then use that (passing scope and locals)
// otherwise just hash the given viewValue
var getTrackByValueFn = trackBy ?
function(value, locals) { return trackByFn(scope, locals); } :
function getHashOfValue(value) { return hashKey(value); };
var getTrackByValue = function(value, key) {
return getTrackByValueFn(value, getLocals(value, key));
};
var displayFn = $parse(match[2] || match[1]);
var groupByFn = $parse(match[3] || '');
var disableWhenFn = $parse(match[4] || '');
var valuesFn = $parse(match[8]);
var locals = {};
var getLocals = keyName ? function(value, key) {
locals[keyName] = key;
locals[valueName] = value;
return locals;
} : function(value) {
locals[valueName] = value;
return locals;
};
function Option(selectValue, viewValue, label, group, disabled) {
this.selectValue = selectValue;
this.viewValue = viewValue;
this.label = label;
this.group = group;
this.disabled = disabled;
}
function getOptionValuesKeys(optionValues) {
var optionValuesKeys;
if (!keyName && isArrayLike(optionValues)) {
optionValuesKeys = optionValues;
} else {
// if object, extract keys, in enumeration order, unsorted
optionValuesKeys = [];
for (var itemKey in optionValues) {
if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
optionValuesKeys.push(itemKey);
}
}
}
return optionValuesKeys;
}
return {
trackBy: trackBy,
getTrackByValue: getTrackByValue,
getWatchables: $parse(valuesFn, function(optionValues) {
// Create a collection of things that we would like to watch (watchedArray)
// so that they can all be watched using a single $watchCollection
// that only runs the handler once if anything changes
var watchedArray = [];
optionValues = optionValues || [];
var optionValuesKeys = getOptionValuesKeys(optionValues);
var optionValuesLength = optionValuesKeys.length;
for (var index = 0; index < optionValuesLength; index++) {
var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
var value = optionValues[key];
var locals = getLocals(optionValues[key], key);
var selectValue = getTrackByValueFn(optionValues[key], locals);
watchedArray.push(selectValue);
// Only need to watch the displayFn if there is a specific label expression
if (match[2] || match[1]) {
var label = displayFn(scope, locals);
watchedArray.push(label);
}
// Only need to watch the disableWhenFn if there is a specific disable expression
if (match[4]) {
var disableWhen = disableWhenFn(scope, locals);
watchedArray.push(disableWhen);
}
}
return watchedArray;
}),
getOptions: function() {
var optionItems = [];
var selectValueMap = {};
// The option values were already computed in the `getWatchables` fn,
// which must have been called to trigger `getOptions`
var optionValues = valuesFn(scope) || [];
var optionValuesKeys = getOptionValuesKeys(optionValues);
var optionValuesLength = optionValuesKeys.length;
for (var index = 0; index < optionValuesLength; index++) {
var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
var value = optionValues[key];
var locals = getLocals(value, key);
var viewValue = viewValueFn(scope, locals);
var selectValue = getTrackByValueFn(viewValue, locals);
var label = displayFn(scope, locals);
var group = groupByFn(scope, locals);
var disabled = disableWhenFn(scope, locals);
var optionItem = new Option(selectValue, viewValue, label, group, disabled);
optionItems.push(optionItem);
selectValueMap[selectValue] = optionItem;
}
return {
items: optionItems,
selectValueMap: selectValueMap,
getOptionFromViewValue: function(value) {
return selectValueMap[getTrackByValue(value)];
},
getViewValueFromOption: function(option) {
// If the viewValue could be an object that may be mutated by the application,
// we need to make a copy and not return the reference to the value on the option.
return trackBy ? angular.copy(option.viewValue) : option.viewValue;
}
};
}
};
}
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
var optionTemplate = document.createElement('option'),
optGroupTemplate = document.createElement('optgroup');
return {
restrict: 'A',
terminal: true,
require: ['select', '?ngModel'],
link: function(scope, selectElement, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
var ngModelCtrl = ctrls[1];
if (!ngModelCtrl) return;
var selectCtrl = ctrls[0];
var multiple = attr.multiple;
// The emptyOption allows the application developer to provide their own custom "empty"
// option when the viewValue does not match any of the option values.
var emptyOption;
for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
if (children[i].value === '') {
emptyOption = children.eq(i);
break;
}
}
var providedEmptyOption = !!emptyOption;
var unknownOption = jqLite(optionTemplate.cloneNode(false));
unknownOption.val('?');
var options;
var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
var renderEmptyOption = function() {
if (!providedEmptyOption) {
selectElement.prepend(emptyOption);
}
selectElement.val('');
emptyOption.prop('selected', true); // needed for IE
emptyOption.attr('selected', true);
};
var removeEmptyOption = function() {
if (!providedEmptyOption) {
emptyOption.remove();
}
};
var renderUnknownOption = function() {
selectElement.prepend(unknownOption);
selectElement.val('?');
unknownOption.prop('selected', true); // needed for IE
unknownOption.attr('selected', true);
};
var removeUnknownOption = function() {
unknownOption.remove();
};
// Update the controller methods for multiple selectable options
if (!multiple) {
selectCtrl.writeValue = function writeNgOptionsValue(value) {
var option = options.getOptionFromViewValue(value);
if (option && !option.disabled) {
if (selectElement[0].value !== option.selectValue) {
removeUnknownOption();
removeEmptyOption();
selectElement[0].value = option.selectValue;
option.element.selected = true;
option.element.setAttribute('selected', 'selected');
}
} else {
if (value === null || providedEmptyOption) {
removeUnknownOption();
renderEmptyOption();
} else {
removeEmptyOption();
renderUnknownOption();
}
}
};
selectCtrl.readValue = function readNgOptionsValue() {
var selectedOption = options.selectValueMap[selectElement.val()];
if (selectedOption && !selectedOption.disabled) {
removeEmptyOption();
removeUnknownOption();
return options.getViewValueFromOption(selectedOption);
}
return null;
};
// If we are using `track by` then we must watch the tracked value on the model
// since ngModel only watches for object identity change
if (ngOptions.trackBy) {
scope.$watch(
function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
function() { ngModelCtrl.$render(); }
);
}
} else {
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};
selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
options.items.forEach(function(option) {
option.element.selected = false;
});
if (value) {
value.forEach(function(item) {
var option = options.getOptionFromViewValue(item);
if (option && !option.disabled) option.element.selected = true;
});
}
};
selectCtrl.readValue = function readNgOptionsMultiple() {
var selectedValues = selectElement.val() || [],
selections = [];
forEach(selectedValues, function(value) {
var option = options.selectValueMap[value];
if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
});
return selections;
};
// If we are using `track by` then we must watch these tracked values on the model
// since ngModel only watches for object identity change
if (ngOptions.trackBy) {
scope.$watchCollection(function() {
if (isArray(ngModelCtrl.$viewValue)) {
return ngModelCtrl.$viewValue.map(function(value) {
return ngOptions.getTrackByValue(value);
});
}
}, function() {
ngModelCtrl.$render();
});
}
}
if (providedEmptyOption) {
// we need to remove it before calling selectElement.empty() because otherwise IE will
// remove the label from the element. wtf?
emptyOption.remove();
// compile the element since there might be bindings in it
$compile(emptyOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
emptyOption.removeClass('ng-scope');
} else {
emptyOption = jqLite(optionTemplate.cloneNode(false));
}
// We need to do this here to ensure that the options object is defined
// when we first hit it in writeNgOptionsValue
updateOptions();
// We will re-render the option elements if the option values or labels change
scope.$watchCollection(ngOptions.getWatchables, updateOptions);
// ------------------------------------------------------------------ //
function updateOptionElement(option, element) {
option.element = element;
element.disabled = option.disabled;
if (option.value !== element.value) element.value = option.selectValue;
if (option.label !== element.label) {
element.label = option.label;
element.textContent = option.label;
}
}
function addOrReuseElement(parent, current, type, templateElement) {
var element;
// Check whether we can reuse the next element
if (current && lowercase(current.nodeName) === type) {
// The next element is the right type so reuse it
element = current;
} else {
// The next element is not the right type so create a new one
element = templateElement.cloneNode(false);
if (!current) {
// There are no more elements so just append it to the select
parent.appendChild(element);
} else {
// The next element is not a group so insert the new one
parent.insertBefore(element, current);
}
}
return element;
}
function removeExcessElements(current) {
var next;
while (current) {
next = current.nextSibling;
jqLiteRemove(current);
current = next;
}
}
function skipEmptyAndUnknownOptions(current) {
var emptyOption_ = emptyOption && emptyOption[0];
var unknownOption_ = unknownOption && unknownOption[0];
if (emptyOption_ || unknownOption_) {
while (current &&
(current === emptyOption_ ||
current === unknownOption_)) {
current = current.nextSibling;
}
}
return current;
}
function updateOptions() {
var previousValue = options && selectCtrl.readValue();
options = ngOptions.getOptions();
var groupMap = {};
var currentElement = selectElement[0].firstChild;
// Ensure that the empty option is always there if it was explicitly provided
if (providedEmptyOption) {
selectElement.prepend(emptyOption);
}
currentElement = skipEmptyAndUnknownOptions(currentElement);
options.items.forEach(function updateOption(option) {
var group;
var groupElement;
var optionElement;
if (option.group) {
// This option is to live in a group
// See if we have already created this group
group = groupMap[option.group];
if (!group) {
// We have not already created this group
groupElement = addOrReuseElement(selectElement[0],
currentElement,
'optgroup',
optGroupTemplate);
// Move to the next element
currentElement = groupElement.nextSibling;
// Update the label on the group element
groupElement.label = option.group;
// Store it for use later
group = groupMap[option.group] = {
groupElement: groupElement,
currentOptionElement: groupElement.firstChild
};
}
// So now we have a group for this option we add the option to the group
optionElement = addOrReuseElement(group.groupElement,
group.currentOptionElement,
'option',
optionTemplate);
updateOptionElement(option, optionElement);
// Move to the next element
group.currentOptionElement = optionElement.nextSibling;
} else {
// This option is not in a group
optionElement = addOrReuseElement(selectElement[0],
currentElement,
'option',
optionTemplate);
updateOptionElement(option, optionElement);
// Move to the next element
currentElement = optionElement.nextSibling;
}
});
// Now remove all excess options and group
Object.keys(groupMap).forEach(function(key) {
removeExcessElements(groupMap[key].currentOptionElement);
});
removeExcessElements(currentElement);
ngModelCtrl.$render();
// Check to see if the value has changed due to the update to the options
if (!ngModelCtrl.$isEmpty(previousValue)) {
var nextValue = selectCtrl.readValue();
if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
ngModelCtrl.$setViewValue(nextValue);
ngModelCtrl.$render();
}
}
}
}
};
}];
/**
* @ngdoc directive
* @name ngPluralize
* @restrict EA
*
* @description
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* in Angular's default en-US locale: "one" and "other".
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. There are examples of plural categories
* and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
* ```html
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*```
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* If no rule is defined for a category, then an empty string is displayed and a warning is generated.
* Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* ```html
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* ```
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bound to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<example module="pluralizeExample">
<file name="index.html">
<script>
angular.module('pluralizeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}]);
</script>
<div ng-controller="ExampleController">
<label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
<label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
<label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should show correct pluralized string', function() {
var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var countInput = element(by.model('personCount'));
expect(withoutOffset.getText()).toEqual('1 person is viewing.');
expect(withOffset.getText()).toEqual('Igor is viewing.');
countInput.clear();
countInput.sendKeys('0');
expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
expect(withOffset.getText()).toEqual('Nobody is viewing.');
countInput.clear();
countInput.sendKeys('2');
expect(withoutOffset.getText()).toEqual('2 people are viewing.');
expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
countInput.clear();
countInput.sendKeys('3');
expect(withoutOffset.getText()).toEqual('3 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
countInput.clear();
countInput.sendKeys('4');
expect(withoutOffset.getText()).toEqual('4 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
});
it('should show data-bound names', function() {
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var personCount = element(by.model('personCount'));
var person1 = element(by.model('person1'));
var person2 = element(by.model('person2'));
personCount.clear();
personCount.sendKeys('4');
person1.clear();
person1.sendKeys('Di');
person2.clear();
person2.sendKeys('Vojta');
expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
});
</file>
</example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
var BRACE = /{}/g,
IS_WHEN = /^when(Minus)?(.+)$/;
return {
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
watchRemover = angular.noop,
lastCount;
forEach(attr, function(expression, attributeName) {
var tmpMatch = IS_WHEN.exec(attributeName);
if (tmpMatch) {
var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
whens[whenKey] = element.attr(attr.$attr[attributeName]);
}
});
forEach(whens, function(expression, key) {
whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
});
scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
var count = parseFloat(newVal);
var countIsNaN = isNaN(count);
if (!countIsNaN && !(count in whens)) {
// If an explicit number rule such as 1, 2, 3... is defined, just use it.
// Otherwise, check it against pluralization rules in $locale service.
count = $locale.pluralCat(count - offset);
}
// If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
// In JS `NaN !== NaN`, so we have to exlicitly check.
if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
watchRemover();
var whenExpFn = whensExpFns[count];
if (isUndefined(whenExpFn)) {
if (newVal != null) {
$log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
}
watchRemover = noop;
updateElementText();
} else {
watchRemover = scope.$watch(whenExpFn, updateElementText);
}
lastCount = count;
}
});
function updateElementText(newText) {
element.text(newText || '');
}
}
};
}];
/**
* @ngdoc directive
* @name ngRepeat
* @multiElement
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
* Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
* This may be useful when, for instance, nesting ngRepeats.
*
*
* # Iterating over object properties
*
* It is possible to get `ngRepeat` to iterate over the properties of an object using the following
* syntax:
*
* ```js
* <div ng-repeat="(key, value) in myObj"> ... </div>
* ```
*
* You need to be aware that the JavaScript specification does not define the order of keys
* returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
* used to sort the keys alphabetically.)
*
* Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
* when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
* keys in the order in which they were defined, although there are exceptions when keys are deleted
* and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
*
* If this is not desired, the recommended workaround is to convert your object into an array
* that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
* do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
* or implement a `$watch` on the object yourself.
*
*
* # Tracking and Duplicates
*
* When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
* there are duplicates, it is not possible to maintain a one-to-one mapping between collection
* items and DOM elements.
*
* If you do need to repeat duplicate items, you can substitute the default tracking behavior
* with your own using the `track by` expression.
*
* For example, you may track items by the index of each item in the collection, using the
* special scope property `$index`:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by $index">
* {{n}}
* </div>
* ```
*
* You may use arbitrary expressions in `track by`, including references to custom functions
* on the scope:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
* {{n}}
* </div>
* ```
*
* If you are working with objects that have an identifier property, you can track
* by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
* will not have to rebuild the DOM elements for items it has already rendered, even if the
* JavaScript objects in the collection have been substituted for new ones:
* ```html
* <div ng-repeat="model in collection track by model.id">
* {{model.name}}
* </div>
* ```
*
* When no `track by` expression is provided, it is equivalent to tracking by the built-in
* `$id` function, which tracks items by their identity:
* ```html
* <div ng-repeat="obj in collection track by $id(obj)">
* {{obj.prop}}
* </div>
* ```
*
* <div class="alert alert-warning">
* **Note:** `track by` must always be the last expression:
* </div>
* ```
* <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
* {{model.name}}
* </div>
* ```
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* ```html
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* ```
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
* ```html
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* ```
*
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* **.enter** - when a new item is added to the list or when an item is revealed after a filter
*
* **.leave** - when an item is removed from the list or when an item is filtered out
*
* **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
* which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
* is specified, ng-repeat associates elements by identity. It is an error to have
* more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.)
*
* Note that the tracking expression must come last, after any filters, and the alias expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way in the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
* intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
* when a filter is active on the repeater, but the filtered result set is empty.
*
* For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
* the items have been processed through the filter.
*
* Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
* (and not as operator, inside an expression).
*
* For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0 10px;
}
.animate-repeat {
line-height:40px;
list-style:none;
box-sizing:border-box;
}
.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
}
.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
opacity:0;
max-height:0;
}
.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
opacity:1;
max-height:40px;
}
</file>
<file name="protractor.js" type="protractor">
var friends = element.all(by.repeater('friend in friends'));
it('should render initial data set', function() {
expect(friends.count()).toBe(10);
expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
expect(element(by.binding('friends.length')).getText())
.toMatch("I have 10 friends. They are:");
});
it('should update repeater when filter predicate changes', function() {
expect(friends.count()).toBe(10);
element(by.model('q')).sendKeys('ma');
expect(friends.count()).toBe(2);
expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
});
</file>
</example>
*/
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
// TODO(perf): generate setters to shave off ~40ms or 1-1.5%
scope[valueIdentifier] = value;
if (keyIdentifier) scope[keyIdentifier] = key;
scope.$index = index;
scope.$first = (index === 0);
scope.$last = (index === (arrayLength - 1));
scope.$middle = !(scope.$first || scope.$last);
// jshint bitwise: false
scope.$odd = !(scope.$even = (index&1) === 0);
// jshint bitwise: true
};
var getBlockStart = function(block) {
return block.clone[0];
};
var getBlockEnd = function(block) {
return block.clone[block.clone.length - 1];
};
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function ngRepeatCompile($element, $attr) {
var expression = $attr.ngRepeat;
var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1];
var rhs = match[2];
var aliasAs = match[3];
var trackByExp = match[4];
match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if (!match) {
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
aliasAs);
}
var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
var hashFnLocals = {$id: hashKey};
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
}
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
//
// We are using no-proto object so that we don't need to guard against inherited props via
// hasOwnProperty.
var lastBlockMap = createMap();
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection) {
var index, length,
previousNode = $element[0], // node that cloned nodes should be inserted after
// initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = createMap(),
collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder,
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, in enumeration order, unsorted
collectionKeys = [];
for (var itemKey in collection) {
if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
collectionKeys.push(itemKey);
}
}
}
collectionLength = collectionKeys.length;
nextBlockOrder = new Array(collectionLength);
// locate existing items
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
if (lastBlockMap[trackById]) {
// found previously seen block
block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap[trackById]) {
// if collision detected. restore lastBlockMap and throw an error
forEach(nextBlockOrder, function(block) {
if (block && block.scope) lastBlockMap[block.id] = block;
});
throw ngRepeatMinErr('dupes',
"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
expression, trackById, value);
} else {
// new never before seen block
nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
nextBlockMap[trackById] = true;
}
}
// remove leftover items
for (var blockKey in lastBlockMap) {
block = lastBlockMap[blockKey];
elementsToRemove = getBlockNodes(block.clone);
$animate.leave(elementsToRemove);
if (elementsToRemove[0].parentNode) {
// if the element was not removed yet because of pending animation, mark it as deleted
// so that we can ignore it later
for (index = 0, length = elementsToRemove.length; index < length; index++) {
elementsToRemove[index][NG_REMOVED] = true;
}
}
block.scope.$destroy();
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
nextNode = previousNode;
// skip nodes that are already pending removal via leave animation
do {
nextNode = nextNode.nextSibling;
} while (nextNode && nextNode[NG_REMOVED]);
if (getBlockStart(block) != nextNode) {
// existing item which got moved
$animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
}
previousNode = getBlockEnd(block);
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
} else {
// new item which we don't know about
$transclude(function ngRepeatTransclude(clone, scope) {
block.scope = scope;
// http://jsperf.com/clone-vs-createcomment
var endNode = ngRepeatEndComment.cloneNode(false);
clone[clone.length++] = endNode;
// TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block.clone = clone;
nextBlockMap[block.id] = block;
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
var NG_HIDE_CLASS = 'ng-hide';
var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
/**
* @ngdoc directive
* @name ngShow
* @multiElement
*
* @description
* The `ngShow` directive shows or hides the given HTML element based on the expression
* provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
* the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* ```
*
* When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
* with extra animation classes that can be added.
*
* ```css
* .ng-hide:not(.ng-hide-animate) {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngShow`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
* you must also include the !important flag to override the display property
* so that you can perform an animation when the element is hidden during the time of the animation.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* /* this is required as of 1.3x to properly
* apply all styling in a show/hide animation */
* transition: 0s linear all;
* }
*
* .my-element.ng-hide-add-active,
* .my-element.ng-hide-remove-active {
* /* the transition is defined in the active class */
* transition: 1s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-show {
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-show.ng-hide-add.ng-hide-add-active,
.animate-show.ng-hide-remove.ng-hide-remove-active {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
}
.animate-show.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngShowDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
// we're adding a temporary, animation-specific class for ng-hide since this way
// we can control when the element is actually displayed on screen without having
// to have a global/greedy CSS selector that breaks when other animations are run.
// Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
$animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngHide
* @multiElement
*
* @description
* The `ngHide` directive shows or hides the given HTML element based on the expression
* provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue" class="ng-hide"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue"></div>
* ```
*
* When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class in CSS:
*
* ```css
* .ng-hide {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngHide`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
* CSS class is added and removed for you instead of your own CSS class.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition: 0.5s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-hide {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-hide.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngHideDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
// The comment inside of the ngShowDirective explains why we add and
// remove a temporary class for the show/hide animation
$animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngStyle
* @restrict AC
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle
*
* {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* Since some CSS style names are not valid keys for an object, they must be quoted.
* See the 'background-color' style in the example below.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="protractor.js" type="protractor">
var colorSpan = element(by.css('span'));
it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
element(by.css('input[value=\'set color\']')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
element(by.css('input[value=clear]')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ngSwitch
* @restrict EA
*
* @description
* The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`on="..."` attribute**
* (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* <div class="alert alert-info">
* Be aware that the attribute values to match against cannot be expressions. They are interpreted
* as literal string values to match against.
* For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
* value of the expression `$scope.someVal`.
* </div>
* @animations
* enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
*
* ```
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
* ```
*
*
* @scope
* @priority 1200
* @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
* On child elements add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `ngSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example module="switchExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="selection" ng-options="item for item in items">
</select>
<code>selection={{selection}}</code>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
angular.module('switchExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}]);
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top:-50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top:0;
}
</file>
<file name="protractor.js" type="protractor">
var switchElem = element(by.css('[ng-switch]'));
var select = element(by.model('selection'));
it('should start in settings', function() {
expect(switchElem.getText()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select.all(by.css('option')).get(1).click();
expect(switchElem.getText()).toMatch(/Home Span/);
});
it('should select default', function() {
select.all(by.css('option')).get(2).click();
expect(switchElem.getText()).toMatch(/default/);
});
</file>
</example>
*/
var ngSwitchDirective = ['$animate', function($animate) {
return {
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ngSwitchController) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes = [],
selectedElements = [],
previousLeaveAnimations = [],
selectedScopes = [];
var spliceFactory = function(array, index) {
return function() { array.splice(index, 1); };
};
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
var i, ii;
for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
$animate.cancel(previousLeaveAnimations[i]);
}
previousLeaveAnimations.length = 0;
for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
var selected = getBlockNodes(selectedElements[i].clone);
selectedScopes[i].$destroy();
var promise = previousLeaveAnimations[i] = $animate.leave(selected);
promise.then(spliceFactory(previousLeaveAnimations, i));
}
selectedElements.length = 0;
selectedScopes.length = 0;
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
var anchor = selectedTransclude.element;
caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
var block = { clone: caseElement };
selectedElements.push(block);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
};
}];
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attrs, ctrl, $transclude) {
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
});
/**
* @ngdoc directive
* @name ngTransclude
* @restrict EAC
*
* @description
* Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
*
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
*
* @element ANY
*
* @example
<example module="transcludeExample">
<file name="index.html">
<script>
angular.module('transcludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<ng-transclude></ng-transclude>' +
'</div>'
};
})
.controller('ExampleController', ['$scope', function($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}]);
</script>
<div ng-controller="ExampleController">
<input ng-model="title" aria-label="title"> <br/>
<textarea ng-model="text" aria-label="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should have transcluded', function() {
var titleElement = element(by.model('title'));
titleElement.clear();
titleElement.sendKeys('TITLE');
var textElement = element(by.model('text'));
textElement.clear();
textElement.sendKeys('TEXT');
expect(element(by.binding('title')).getText()).toEqual('TITLE');
expect(element(by.binding('text')).getText()).toEqual('TEXT');
});
</file>
</example>
*
*/
var ngTranscludeDirective = ngDirective({
restrict: 'EAC',
link: function($scope, $element, $attrs, controller, $transclude) {
if (!$transclude) {
throw minErr('ngTransclude')('orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: {0}',
startingTag($element));
}
$transclude(function(clone) {
$element.empty();
$element.append(clone);
});
}
});
/**
* @ngdoc directive
* @name script
* @restrict E
*
* @description
* Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
* template can be used by {@link ng.directive:ngInclude `ngInclude`},
* {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
* `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
* assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
*
* @param {string} type Must be set to `'text/ng-template'`.
* @param {string} id Cache name of the template.
*
* @example
<example>
<file name="index.html">
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</file>
<file name="protractor.js" type="protractor">
it('should load template defined inside script tag', function() {
element(by.css('#tpl-link')).click();
expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
});
</file>
</example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
var noopNgModelController = { $setViewValue: noop, $render: noop };
/**
* @ngdoc type
* @name select.SelectController
* @description
* The controller for the `<select>` directive. This provides support for reading
* and writing the selected value(s) of the control and also coordinates dynamically
* added `<option>` elements, perhaps by an `ngRepeat` directive.
*/
var SelectController =
['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = new HashMap();
// If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
self.ngModelCtrl = noopNgModelController;
// The "unknown" option is one that is prepended to the list if the viewValue
// does not match any of the options. When it is rendered the value of the unknown
// option is '? XXX ?' where XXX is the hashKey of the value that is not known.
//
// We can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
self.unknownOption = jqLite(document.createElement('option'));
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
self.unknownOption.val(unknownVal);
$element.prepend(self.unknownOption);
$element.val(unknownVal);
};
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
self.removeUnknownOption = function() {
if (self.unknownOption.parent()) self.unknownOption.remove();
};
// Read the value of the select control, the implementation of this changes depending
// upon whether the select can have multiple values and whether ngOptions is at work.
self.readValue = function readSingleValue() {
self.removeUnknownOption();
return $element.val();
};
// Write the value to the select control, the implementation of this changes depending
// upon whether the select can have multiple values and whether ngOptions is at work.
self.writeValue = function writeSingleValue(value) {
if (self.hasOption(value)) {
self.removeUnknownOption();
$element.val(value);
if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (value == null && self.emptyOption) {
self.removeUnknownOption();
$element.val('');
} else {
self.renderUnknownOption(value);
}
}
};
// Tell the select control that an option, with the given value, has been added
self.addOption = function(value, element) {
assertNotHasOwnProperty(value, '"option value"');
if (value === '') {
self.emptyOption = element;
}
var count = optionsMap.get(value) || 0;
optionsMap.put(value, count + 1);
};
// Tell the select control that an option, with the given value, has been removed
self.removeOption = function(value) {
var count = optionsMap.get(value);
if (count) {
if (count === 1) {
optionsMap.remove(value);
if (value === '') {
self.emptyOption = undefined;
}
} else {
optionsMap.put(value, count - 1);
}
}
};
// Check whether the select control has an option matching the given value
self.hasOption = function(value) {
return !!optionsMap.get(value);
};
}];
/**
* @ngdoc directive
* @name select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
* ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
* memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
* more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
* comprehension expression.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* If the viewValue contains a value that doesn't match any of the options then the control
* will automatically add an "unknown" option, which it then removes when this is resolved.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* <div class="alert alert-info">
* The value of a `select` directive used without `ngOptions` is always a string.
* When the model needs to be bound to a non-string value, you must either explictly convert it
* using a directive (see example below) or use `ngOptions` to specify the set of options.
* This is because an option element can only be bound to string values at present.
* </div>
*
* ### Example (binding `select` to a non-string value)
*
* <example name="select-with-non-string-options" module="nonStringSelect">
* <file name="index.html">
* <select ng-model="model.id" convert-to-number>
* <option value="0">Zero</option>
* <option value="1">One</option>
* <option value="2">Two</option>
* </select>
* {{ model }}
* </file>
* <file name="app.js">
* angular.module('nonStringSelect', [])
* .run(function($rootScope) {
* $rootScope.model = { id: 2 };
* })
* .directive('convertToNumber', function() {
* return {
* require: 'ngModel',
* link: function(scope, element, attrs, ngModel) {
* ngModel.$parsers.push(function(val) {
* return parseInt(val, 10);
* });
* ngModel.$formatters.push(function(val) {
* return '' + val;
* });
* }
* };
* });
* </file>
* <file name="protractor.js" type="protractor">
* it('should initialize to model', function() {
* var select = element(by.css('select'));
* expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
* });
* </file>
* </example>
*
*/
var selectDirective = function() {
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: SelectController,
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
var ngModelCtrl = ctrls[1];
if (!ngModelCtrl) return;
var selectCtrl = ctrls[0];
selectCtrl.ngModelCtrl = ngModelCtrl;
// We delegate rendering to the `writeValue` method, which can be changed
// if the select can have multiple selected values or if the options are being
// generated by `ngOptions`
ngModelCtrl.$render = function() {
selectCtrl.writeValue(ngModelCtrl.$viewValue);
};
// When the selected item(s) changes we delegate getting the value of the select control
// to the `readValue` method, which can be changed if the select can have multiple
// selected values or if the options are being generated by `ngOptions`
element.on('change', function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(selectCtrl.readValue());
});
});
// If the select allows multiple values then we need to modify how we read and write
// values from and to the control; also what it means for the value to be empty and
// we have to add an extra watch since ngModel doesn't work well with arrays - it
// doesn't trigger rendering if only an item in the array changes.
if (attr.multiple) {
// Read value now needs to check each option to see if it is selected
selectCtrl.readValue = function readMultipleValue() {
var array = [];
forEach(element.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
return array;
};
// Write value now needs to set the selected property of each matching option
selectCtrl.writeValue = function writeMultipleValue(value) {
var items = new HashMap(value);
forEach(element.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
var lastView, lastViewRef = NaN;
scope.$watch(function selectMultipleWatch() {
if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
lastView = shallowCopy(ngModelCtrl.$viewValue);
ngModelCtrl.$render();
}
lastViewRef = ngModelCtrl.$viewValue;
});
// If we are a multiple select then value is now a collection
// so the meaning of $isEmpty changes
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};
}
}
};
};
// The option directive is purely designed to communicate the existence (or lack of)
// of dynamically created (and destroyed) option elements to their containing select
// directive via its controller.
var optionDirective = ['$interpolate', function($interpolate) {
function chromeHack(optionElement) {
// Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
// Adding an <option selected="selected"> element to a <select required="required"> should
// automatically select the new element
if (optionElement[0].hasAttribute('selected')) {
optionElement[0].selected = true;
}
}
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
// If the value attribute is not defined then we fall back to the
// text content of the option element, which may be interpolated
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function(scope, element, attr) {
// This is an optimization over using ^^ since we don't want to have to search
// all the way to the root of the DOM for every single option element
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
// Only update trigger option updates if this is an option within a `select`
// that also has `ngModel` attached
if (selectCtrl && selectCtrl.ngModelCtrl) {
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (oldVal !== newVal) {
selectCtrl.removeOption(oldVal);
}
selectCtrl.addOption(newVal, element);
selectCtrl.ngModelCtrl.$render();
chromeHack(element);
});
} else {
selectCtrl.addOption(attr.value, element);
selectCtrl.ngModelCtrl.$render();
chromeHack(element);
}
element.on('$destroy', function() {
selectCtrl.removeOption(attr.value);
selectCtrl.ngModelCtrl.$render();
});
}
};
}
};
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: false
});
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(modelValue, viewValue) {
return !attr.required || !ctrl.$isEmpty(viewValue);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};
var patternDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var regexp, patternExp = attr.ngPattern || attr.pattern;
attr.$observe('pattern', function(regex) {
if (isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
if (regex && !regex.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
regex, startingTag(elm));
}
regexp = regex || undefined;
ctrl.$validate();
});
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
};
}
};
};
var maxlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var maxlength = -1;
attr.$observe('maxlength', function(value) {
var intVal = toInt(value);
maxlength = isNaN(intVal) ? -1 : intVal;
ctrl.$validate();
});
ctrl.$validators.maxlength = function(modelValue, viewValue) {
return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
};
}
};
};
var minlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var minlength = 0;
attr.$observe('minlength', function(value) {
minlength = toInt(value) || 0;
ctrl.$validate();
});
ctrl.$validators.minlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
};
}
};
};
if (window.angular.bootstrap) {
//AngularJS is already loaded, so we can return here...
console.log('WARNING: Tried to load angular more than once.');
return;
}
//try to bind to jquery now so that one can write jqLite(document).ready()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-us",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');
},{}],9:[function(require,module,exports){
require('./angular');
module.exports = angular;
},{"./angular":8}],10:[function(require,module,exports){
module.exports = {
debug: false
};
},{}],11:[function(require,module,exports){
module.exports = require('./src/Scheduler');
},{"./src/Scheduler":26}],12:[function(require,module,exports){
'use strict';
var cocktail = require('cocktail');
/**
* @trait Configurable
* A trait/talent which provides configure(options) method into the host class.
*/
cocktail.mix({
'@exports' : module,
'@as' : 'class',
'@static': {
/**
* @factory
* @static
* @method withOptions
* Returns a Configurable Trait.
* The setter for a given key will be resolved by looking on the options map for setter names.
* If key is not in the map it will default to set{Key} method.
* @param options {Object}
*/
withOptions: function (options) {
var Configurable = this,
configurable = {};
options = options || {};
return cocktail.mix(configurable, {
'@talents': [
{
talent: Configurable,
alias: {
_getSetter: '_baseSetter'
}
}
],
_getSetter: function (key) {
return options[key] || this._baseSetter(key);
}
})
}
},
/**
* @public
* @method configure
* Configures the host class by calling setters on each property defined in the given options
* @params options {Object}
*/
configure: function (options) {
var key, option, setter, setterName;
for(key in options) {
option = options[key];
setterName = this._getSetter(key);
setter = this[setterName];
if(setter){
setter.call(this, option);
}
}
},
_getSetter: function (key) {
var camelKey = (key.charAt(0).toUpperCase() + key.slice(1));
return 'set'+camelKey;
}
});
},{"cocktail":13}],13:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('./processor/sequence');
var defaults = require('./processor/defaults');
var ANNOTATION_REG_EXP = /^@/;
var cocktail;
cocktail = {
/**
* @public
* SEQUENCE is used to define an enumeration of priorities for annotations
*/
SEQUENCE: sequence,
/**
* @private
* The processors class list.
*/
_DEFAULT_PROCESSORS: defaults,
/**
* @private
* Stack of _queues
*/
_qStack: [],
/**
* @private
* The queue of processors instances for the given mix
*/
_queue: [],
/**
*@private
* Current processor list map
*/
_processors: {},
/**
* @protected
* Returns the processor list map
*/
getProcessors : function () {
return this._processors;
},
/**
* @protected
* sets the processor object list. It is an Object used as a map
*/
setProcessors: function (processor) {
this._processors = processor;
},
/**
* @protected
* returns the list of default processors
*/
getDefaultProcessors: function () {
return cocktail._DEFAULT_PROCESSORS;
},
/**
* @protected
* registers a processor definition
* @param processorsConfig {Object} a key-value pair of processors
*/
registerProcessors: function (processorsConfig) {
var processors = this.getProcessors(),
key;
for (key in processorsConfig){
if (processorsConfig.hasOwnProperty(key)) {
processors[key] = processorsConfig[key];
}
}
},
/**
* @public
*/
use: function (annotation) {
var name = annotation.name || (annotation.prototype && annotation.prototype.name),
processor = {};
if (name && annotation.prototype) {
processor[name] = annotation;
this.registerProcessors(processor);
}
},
/**
* @private
* returns a processor instance for the given key or a NoOp instance if it is not found.
*/
_getProcessorFor: function (key) {
var processors = this.getProcessors(),
P;
P = (processors[key] || processors['no-op']);
return new P();
},
/**
* @private
* applies default options to the given options parameter.
* As of today, the only default option is the configuration for the merge annotation
*/
_applyDefaultsOptions: function (options) {
if (options && !('@merge' in options)) {
options['@merge'] = 'single';
}
},
/**
* @private
* iterates over options to find annotations and adds processors to the queue.
*/
_configureProcessorsWith: function (options) {
var key, value, processor;
this._cleanQueue();
if (options) {
for (key in options) {
if (options.hasOwnProperty(key) && ANNOTATION_REG_EXP.test(key)) {
value = options[key];
//get the processor instance for this annotation
processor = this._getProcessorFor(key);
//configure the annotation parameter
processor.setParameter(value);
//check if the annotation should be removed
if (!processor.retain) {
delete options[key];
}
//add the processor to the queue
this._addProcessorToQueue(processor);
}
}
}
},
/**
* @private
* stacks current queue
*/
_pushQueue: function () {
this._qStack.push(this._queue);
this._queue = [];
},
/**
* @private
* restore current queue
*/
_popQueue: function () {
this._queue = this._qStack.pop();
},
/**
* @private
* Cleans the processor queue
*/
_cleanQueue: function () {
this._queue.length = 0;
},
/**
* @private
* Adds the given processor to the queue
*/
_addProcessorToQueue: function (processor) {
if (processor && processor.priority !== -1) {
this._queue.push(processor);
}
},
/**
* @private
* Sorts the queue by its processor's priorities
*/
_sortQueueByPriority: function () {
this._queue.sort(function(a, b){
return a.priority - b.priority;
});
},
/**
* @private
* Runs all the processors in the queue over the given subject
*/
_executeProcessorsOn: function (subject, options) {
var processors = this._queue,
l = processors.length,
i;
this._sortQueueByPriority();
for (i = 0; i < l; i++) {
processors[i].process(subject, options);
}
},
/**
* @private
* returns true if the given subject has a pseudo annotation `@as` with the given value.
*/
_isSubjectDefinedAs: function (subject, asType) {
return (subject && subject['@as'] && subject['@as'].toLowerCase() === asType);
},
/**
* @private
* returns true if the given subject is a class definition object.
*/
_isClassDefition: function (subject) {
var isClassDef = this._isSubjectDefinedAs(subject, 'class'),
definitionProps = ['constructor', '@extends', '@traits', '@requires', '@annotation'],
key;
if (!isClassDef) {
for (key in subject) {
if (definitionProps.indexOf(key) > -1) {
isClassDef = true;
break;
}
}
}
return isClassDef;
},
/**
* @private
* returns true if the given subject is a module definition object.
*/
_isModuleDefinition: function (subject) {
return this._isSubjectDefinedAs(subject, 'module');
},
/**
* @private
* If the subject has a property construtor returns it,
* if no constructor on subject but it extends then return a function() calling super constructor,
* or a function definition otherwise.
*/
_getDefaultClassConstructor: function (subject) {
var ctor, parent;
if (this._isPropertyDefinedIn('constructor', subject)) {
ctor = subject.constructor;
} else if (this._isPropertyDefinedIn('@extends', subject)) {
parent = subject['@extends'];
ctor = function(){
parent.prototype.constructor.apply(this, arguments);
};
} else {
ctor = function(){};
}
return ctor;
},
/**
* @private
* checks if the given property is enumerable and defined in the obj
*/
_isPropertyDefinedIn: function (property, obj) {
var k;
for (k in obj) {
if (property === k) {
return true;
}
}
return false;
},
/**
* @private
* returns a call to mix() with the subject constructor and options
*/
_processClassDefition: function (subject) {
var defaultConstructor, options;
defaultConstructor = this._getDefaultClassConstructor(subject);
if (this._isPropertyDefinedIn('constructor', subject)) {
delete subject.constructor;
}
options = subject;
return this.mix(defaultConstructor, options);
},
/**
* @private
* @experimental 0.5.1
* returns a call to mix() with the subject module and options
*/
_processModuleDefinition: function (subject) {
var options = subject;
return this.mix(subject, options);
},
/**
* @public
*/
mix: function (subject, options) {
if (!options) {
if (this._isClassDefition(subject)) {
return this._processClassDefition(subject);
}
if (this._isModuleDefinition(subject)) {
return this._processModuleDefinition(subject);
}
}
if (subject) {
this._pushQueue();
this._applyDefaultsOptions(options);
this._configureProcessorsWith(options);
this._executeProcessorsOn(subject, options);
this._popQueue();
}
return subject;
}
};
//register processors
cocktail.registerProcessors(cocktail._DEFAULT_PROCESSORS);
//export module
module.exports = cocktail;
},{"./processor/defaults":24,"./processor/sequence":25}],14:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('./sequence');
var NoOp = function () {};
NoOp.prototype = {
retain : false,
priority : sequence.NO_OP,
name : 'noOp',
setParameter: function(){},
getParameter: function(){}
};
module.exports = NoOp;
},{"./sequence":25}],15:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Annotation () {}
Annotation.prototype = {
retain : false,
priority : sequence.ANNOTATION,
name : '@annotation',
_value: undefined,
setParameter: function (value) {
this._value = value;
},
getParameter: function () {
return this._value;
},
process: function (subject) {
var name = '@' + this.getParameter();
subject.prototype.name = name;
}
};
module.exports = Annotation;
},{"../sequence":25}],16:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Exports () {}
Exports.prototype = {
retain : false,
priority : sequence.EXPORTS,
name : '@extends',
_parameter: undefined,
setParameter: function (value) {
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject /*, proto*/) {
var value = this.getParameter();
if (value && typeof value === 'object') {
value.exports = subject;
}
}
};
module.exports = Exports;
},{"../sequence":25}],17:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Extends () {}
Extends.prototype = {
retain : false,
priority : sequence.EXTENDS,
name : '@extends',
_parameter: undefined,
setParameter: function (value) {
if (!(value && value.prototype)) {
throw new Error('@extends parameter should have a prototype');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var parent = this.getParameter(),
sp;
subject.prototype = sp = Object.create(parent.prototype);
sp.$super = parent;
sp.callSuper = function(methodName){
var mthd = this.$super.prototype[methodName],
mthdArgs = Array.prototype.slice.call(arguments, 1);
if (!mthd) {
throw new Error('callSuper: There is no method named ' + mthd + ' in parent class.');
}
return mthd.apply(this, mthdArgs);
};
}
};
module.exports = Extends;
},{"../sequence":25}],18:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var _STRATEGIES_ = {
'single' : '_mergeMine',
'mine' : '_mergeMine',
'their' : '_mergeTheir',
'deep-mine' : '_mergeDeepMine',
'deep-their' : '_mergeDeepTheir',
'properties' : '_mergeOnlyProperties'
};
/**
* @constructor
*/
function Merge (options) {
var useProto;
if (options) {
useProto = options.usePrototypeWhenSubjectIsClass;
this._usePrototypeWhenSubjectIsClass = (useProto === false) ? useProto : true;
}
}
Merge.prototype = {
retain : false,
priority : sequence.MERGE,
name : '@merge',
_parameter : undefined,
_usePrototypeWhenSubjectIsClass: true,
setParameter: function (value) {
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
_doMerge : function (mine, their, method) {
var key;
for (key in their) {
if (their.hasOwnProperty(key)) {
method.call(this, key);
}
}
},
/**
* mine merge strategy: mine params over their. If params is already defined it gets overriden.
*/
_mergeMine : function (mine, their) {
this._doMerge(mine, their, function(k){
mine[k] = their[k];
});
return mine;
},
_mergeOnlyProperties : function (mine, their) {
this._doMerge(mine, their, function(k){
if (typeof their[k] !== 'function'){
mine[k] = their[k];
}
});
return mine;
},
/**
* deepMine merge strategy: mine params over their.
* If params is already defined and it is an object it is merged with strategy mine,
* if params is already defined and it is an array it is concatenated,
* otherwise it gets overriden with mine.
*/
_mergeDeepMine : function (mine, their) {
return this._mergeDeep(mine, their, '_mergeMine');
},
/**
* their merge strategy: their params over mine. If params is already defined it doesn't get overriden.
*/
_mergeTheir : function (mine, their) {
this._doMerge(mine, their, function(k){
if (mine[k] === undefined) {
mine[k] = their[k];
}
});
return mine;
},
/**
* deepMine merge strategy: their params over mine.
* If params is already defined and it is an object it is merged with strategy their,
* if params is already defined and it is an array it is concatenated,
* otherwise it gets overriden with mine.
*/
_mergeDeepTheir : function (mine, their) {
return this._mergeDeep(mine, their, '_mergeTheir');
},
/**
* runs the deep merge using the given strategy
*/
_mergeDeep: function (mine, their, strategy) {
this._doMerge(mine, their, function(key){
if (typeof their[key] === 'object') {
if (their[key] instanceof Array) {
mine[key] = [].concat(mine[key], their[key]);
} else {
mine[key] = this[strategy](mine[key], their[key]);
}
}else if (mine[key] === undefined ) {
mine[key] = their[key];
}
});
return mine;
},
_shouldUsePrototypeWhenSubjectIsClass: function () {
return this._usePrototypeWhenSubjectIsClass;
},
process: function (subject, options) {
var their = options,
useProto = this._shouldUsePrototypeWhenSubjectIsClass(),
mine = (useProto && subject.prototype) || subject,
strategy = _STRATEGIES_[this.getParameter()];
this[strategy](mine, their);
}
};
module.exports = Merge;
},{"../sequence":25}],19:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Properties () {}
Properties.prototype = {
retain : false,
priority : sequence.PROPERTIES,
name : '@properties',
_parameter: undefined,
setParameter: function (value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
throw new Error('@properties parameter should be an Object');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
_capitalizeName: function (name) {
return (name.charAt(0).toUpperCase() + name.slice(1));
},
_getterName: function (property, value) {
return (value !== false && value !== true ? 'get' : 'is') + this._capitalizeName(property);
},
_setterName: function (property) {
return 'set' + this._capitalizeName(property);
},
_createPropertyFor: function (subject, name, value, doNotOverride) {
if (typeof subject[name] === 'undefined' || doNotOverride !== true) {
subject[name] = value;
}
subject[this._getterName(name, value)] = function(){
return this[name];
};
subject[this._setterName(name)] = function(set){
this[name] = set;
};
},
process: function (subject) {
var properties = this.getParameter(),
isObject = !(subject.prototype),
key;
for (key in properties) {
if (properties.hasOwnProperty(key)) {
this._createPropertyFor(subject.prototype || subject, key, properties[key], isObject);
}
}
}
};
module.exports = Properties;
},{"../sequence":25}],20:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function $$required$$ () {
throw new Error('method is marked as required but it has not been defined');
}
function Requires () {}
Requires.requiredMethod = $$required$$;
Requires.prototype = {
retain : false,
priority : sequence.REQUIRES,
name : '@requires',
_parameter: [],
setParameter: function (value) {
//TODO: validate parameter
this._parameter = [].concat(value);
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var reqs = this.getParameter(), // always an []
l = reqs.length,
i;
for (i = 0; i < l; i++) {
this._createRequiredMethod(subject, reqs[i]);
}
},
_createRequiredMethod: function(sub, methodName){
var subject = (sub.prototype || sub);
if (!subject[methodName]) {
subject[methodName] = Requires.requiredMethod;
}
}
};
module.exports = Requires;
},{"../sequence":25}],21:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var Merge = require('./Merge');
function Static () {}
Static.prototype = {
retain : false,
priority : sequence.POST_MERGE,
name : '@static',
_parameter: undefined,
setParameter: function (value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
throw new Error('@static parameter should be an Object');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var statics = this.getParameter(),
merger = new Merge({usePrototypeWhenSubjectIsClass: false});
merger.setParameter('mine');
merger.process(subject, statics);
}
};
module.exports = Static;
},{"../sequence":25,"./Merge":18}],22:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var Traits = require('./Traits');
function Talents () {
Traits.call(this);
}
Talents.prototype = Object.create(Traits.prototype);
Talents.prototype._configName = 'talent';
Talents.prototype.process = function (subject) {
var talents = this.getParameter(), // always an []
l = talents.length,
i;
for (i = 0; i < l; i++) {
this._applyTo(subject, talents[i]);
}
};
module.exports = Talents;
},{"./Traits":23}],23:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var Requires = require('./Requires');
function Traits () {}
Traits.prototype = {
retain : false,
priority : sequence.TRAITS,
name : '@traits',
_configName: 'trait',
_parameter: [],
setParameter: function (value) {
//TODO: validate parameter
this._parameter = [].concat(value);
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var traits = this.getParameter(), // always an []
l = traits.length,
i;
for (i = 0; i < l; i++) {
this._applyTo(subject.prototype || subject, traits[i]);
}
},
_isApplicable: function (option) {
var type = this._configName;
return (typeof option === 'function') || (option && !option[type]);
},
_applyTo: function (subject, options) {
var me = this,
type = me._configName,
o = {},
tp, excluded, aliases, t;
if (me._isApplicable(options)) {
o[type] = options;
return me._applyTo(subject, o);
}
excluded = [].concat(options.excludes);
aliases = options.alias || {};
t = options[type];
tp = t.prototype || t;
Object.getOwnPropertyNames(tp)
.filter(function(key){
return !key.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/);
})
.forEach(function(key){
me._raiseErrorIfItIsState(key, tp);
me._applyIfNotExcluded(key, excluded, aliases, subject, tp);
});
},
_applyIfNotExcluded: function (key, excluded, aliases, subject, tp) {
var alias;
if (excluded.indexOf(key) === -1) {
alias = aliases[key] || key;
this._raiseErrorIfConflict(alias, subject, tp);
if (!subject[alias] || subject[alias] === Requires.requiredMethod) {
Object.defineProperty(subject, alias, Object.getOwnPropertyDescriptor(tp, key));
}
}
},
_raiseErrorIfItIsState: function (key, traitProto) {
if (typeof traitProto[key] !== 'function') {
throw new Error('Trait MUST NOT contain any state. Found: ' + key + ' as state while processing trait');
}
},
_raiseErrorIfConflict: function (methodName, subjectProto, traitProto) {
var requiredMethodName = Requires.requiredMethod.name,
subjectMethod = subjectProto[methodName],
traitMethod = traitProto[methodName],
sameMethodName = (subjectMethod && traitMethod),
methodsAreNotTheSame = sameMethodName && (subjectMethod.toString() !== traitMethod.toString()),
traitMethodIsNotARequired = sameMethodName && (traitMethod.name !== requiredMethodName),
subjecMethodIsNotARequired = sameMethodName && (subjectMethod.name !== requiredMethodName);
if (sameMethodName && methodsAreNotTheSame && traitMethodIsNotARequired && subjecMethodIsNotARequired) {
throw new Error('Same method named: ' + methodName + ' is defined in trait and Class.' );
}
}
};
module.exports = Traits;
},{"../sequence":25,"./Requires":20}],24:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
module.exports = {
'no-op' : require('./NoOp'),
'@as' : undefined, /*pseudo-processor*/
'@merge' : require('./annotation/Merge'),
'@extends' : require('./annotation/Extends'),
'@properties' : require('./annotation/Properties'),
'@traits' : require('./annotation/Traits'),
'@requires' : require('./annotation/Requires'),
'@talents' : require('./annotation/Talents'),
'@annotation' : require('./annotation/Annotation'),
'@exports' : require('./annotation/Exports'),
'@static' : require('./annotation/Static')
};
},{"./NoOp":14,"./annotation/Annotation":15,"./annotation/Exports":16,"./annotation/Extends":17,"./annotation/Merge":18,"./annotation/Properties":19,"./annotation/Requires":20,"./annotation/Static":21,"./annotation/Talents":22,"./annotation/Traits":23}],25:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
/**
* sequence list
The processors will use one of the defined priorities in this list
The priorities are organized in groups:
[-1] No Op.
[1..99) Object/Class creation.
[99..999) Merge - Traits and talents are considered merge stage since we copy the structure into the subject.
[999..) Miscelaneous - Annotation definition makes no changes over the Subject itself.
*/
module.exports = {
NO_OP : -1,
PRE_EXTENDS : 9,
EXTENDS : 10,
POST_EXTENDS : 11,
PRE_PROPERTIES : 19,
PROPERTIES : 20,
POST_PROPERTIES : 21,
PRE_REQUIRES : 29,
REQUIRES : 30,
POST_REQUIRES : 31,
PRE_MERGE : 99,
MERGE : 100,
POST_MERGE : 101,
PRE_TRAITS : 109,
TRAITS : 110,
POST_TRAITS : 111,
PRE_ANNOTATION : 999,
ANNOTATION : 1000,
POST_ANNOTATION : 1001,
PRE_EXPORTS : 1009,
EXPORTS : 1010,
POST_EXPORTS : 1011
};
},{}],26:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('./annotations/Logger');
var Fifo = require('./algorithms/Fifo');
var Lru = require('./algorithms/Lru');
var Memory = require('./common/Memory');
var Requirement = require('./common/Requirement');
var FixedEvenAssignmentPolicy = require('./assignment_filters/FixedEvenAssignmentPolicy');
var AsyncFlushAssignmentPolicy = require('./assignment_filters/AsyncFlushAssignmentPolicy');
cocktail.use(Logger);
cocktail.mix({
'@exports' : module,
'@as' : 'class',
'@logger' : [console, "Scheduler:"],
constructor: function() {
this._memory = undefined;
this._memorySize = 0;
this._moments = [];
this._algorithm = undefined;
this._rawRequirements = [];
this._requirements = [];
this._assignmentPolicies = [];
this.log("Created.");
},
getAlgorithm: function() {
if ( this._algorithm !== undefined ) {
if (this._algorithm instanceof Lru)
return 'lru';
if (this._algorithm instanceof Fifo)
return 'fifo';
}
return undefined;
},
getMemorySize: function() {
return this._memorySize;
},
getRequirements: function() {
return this._rawRequirements;
},
isFixedEvenAssignmentPolicy: function() {
return this._assignmentPolicies[0] !== undefined;
},
isLocalReplacementPolicy: function() {
if (this._algorithm){
return this._algorithm.isLocalReplacementPolicy();
} else {
return undefined;
}
},
isAsyncFlushPolicy: function() {
return this._assignmentPolicies[1] !== undefined;
},
getSecondChanceReplacementPolicy: function() {
return this._algorithm.isSecondChanceReplacementPolicy();
},
isSecondChanceReplacementPolicy: function() {
if (this._algorithm){
return this._algorithm.isSecondChanceReplacementPolicy();
} else {
return undefined;
}
},
setAlgorithm: function(algorithm) {
if (!algorithm) {
return;
}
switch (algorithm) {
case 'fifo':
this.clearPolicies();
this._algorithm = new Fifo();
break;
case 'lru':
this.clearPolicies();
this._algorithm = new Lru();
break;
default:
return;
}
},
setFixedEvenAssignmentPolicy: function(size) {
if (size === undefined) {
return;
}
if (size) {
this._assignmentPolicies[0] = new FixedEvenAssignmentPolicy(size);
} else {
delete this._assignmentPolicies[0];
}
},
setLocalReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm) {
this._algorithm.setLocalReplacementPolicy(enabled);
}
},
setAsyncFlushReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm && enabled) {
var policy = new AsyncFlushAssignmentPolicy()
this._assignmentPolicies[1] = policy;
this._algorithm.setAsyncFlushReplacementPolicy(true, policy);
} else {
delete this._assignmentPolicies[1];
this._algorithm.setAsyncFlushReplacementPolicy(false);
}
},
setSecondChanceReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm) {
this._algorithm.setSecondChanceReplacementPolicy(enabled);
}
},
clearPolicies: function() {
this._assignmentPolicies = [];
if (this._algorithm) {
this._algorithm.clearPolicies();
}
this.log("All policies cleared.")
},
_clearBuffers: function(arguments) {
if (this._memorySize) {
this._memory = new Memory(this._memorySize);
}
this._moments = [];
this._resetPolicies();
this.log("All buffers cleared.");
},
_resetPolicies: function() {
if (this.isFixedEvenAssignmentPolicy()) {
this.setFixedEvenAssignmentPolicy(this._assignmentPolicies[0].localSize());
}
if (this.isLocalReplacementPolicy()) {
this.setLocalReplacementPolicy(true);
}
if (this.isAsyncFlushPolicy()) {
this.setAsyncFlushReplacementPolicy(true);
}
if (this.isSecondChanceReplacementPolicy()) {
this.setSecondChanceReplacementPolicy(true);
}
},
setMemorySize: function(size) {
if (!size) {
return;
}
this._memory = new Memory(size);
this._memorySize = size;
// this._resetPolicies();
this._updatePolicies();
},
addRequirements: function(requirements) {
if (!requirements) {
return;
}
this._rawRequirements = requirements;
this._requirements = [];
this.log("---Started generating the requirements queue.---");
this._rawRequirements.forEach(function(elem) {
this._requirements.push(new Requirement(elem));
}, this);
this.log("---Finished generating the requirements queue.---\n");
},
run: function() {
if (!this._memory || !this._algorithm || !this._requirements.length) {
throw new Error("Some initialization is missing!!");
}
this._algorithm.initialize(this._requirements);
this._processRequirements();
/*
* _processRequirements will save all data in _moments.
* We'll need to parse it before sending it back to the client.
*/
var allMoments = this._dataMoments();
//Dispose all arrays.
this._clearBuffers();
return allMoments;
},
_dataMoments: function() {
this.log("---Started generating the output matrix.---");
var allMoments = [];
//Here we use the context to bind the array in which i want the pages to be added.
this._moments.forEach(function(moment) {
var singleMoment = {
requirement: moment.requirement,
pageFault: moment.pageFault,
frames: moment.instant,
victim: moment.victim,
potentialVictims: moment.potentialVictims
}
this.push(singleMoment);
}, allMoments);
this.log("---Finished generating the output matrix.---\n");
return allMoments;
},
// To be implemented with FixedEven assignment filter.
_assignmentFiltersAproves: function(requirement) {
var hasSpace = !this._memory.isFull();
var i = 0;
var length = this._assignmentPolicies.length;
for (; i < length; i++) {
if (this._assignmentPolicies[i]) {
hasSpace &= this._assignmentPolicies[i].hasFreeFrameFor(requirement, this._memory, this);
}
}
return hasSpace;
},
_saveMoment: function(requirement, pageFault, victim) {
this.log("Saving moment " + this._moments.length + ".");
var moment = {
requirement: requirement.asDataObject(),
instant: [],
pageFault: pageFault,
victim: victim? victim.asVictim(): undefined,
potentialVictims: []
};
this._memory.forEach(function(frame) {
this.push(frame.asDataObject());
}, moment.instant);
this._algorithm.getVictimsStructure().forEach(function(potentialVictim) {
this.push(potentialVictim.asVictim());
}, moment.potentialVictims);
this._moments.push(moment);
this.log("Moment " + (this._moments.length -1) + " saved.\n");
},
_update: function(requirement, pageFault, victim) {
this._algorithm.update(requirement);
this._updateMemory(requirement, pageFault);
this._updatePolicies();
},
_updateMemory: function(requirement, pageFault) {
// Assume that the requirement is already in memory.
var page = this._memory.at(this._memory.getFrameOf(requirement));
page.setRequired(true);
if (requirement.getMode() === "write") {
page.setModified(true);
}
if (!pageFault) {
page.setReferenced(true);
} else {
page.setPageFault(true);
}
},
_updatePolicies: function() {
this._assignmentPolicies.forEach(function(policy) {
policy.update(this._memory, this)
}, this);
},
_clearTemporalFlags: function() {
this._memory.forEach(function(page) {
page.clearRequired();
page.clearPageFault();
}, this);
this.log("Temporal page flags cleared.");
},
_processRequirements: function() {
this._requirements.forEach(function(requirement) {
// Start with a clean image of the frames.
this._clearTemporalFlags();
//Declare victim here because it'll be used for update.
var victim = {
frame: undefined,
page: undefined
};
var pageFault = false;
if (this._memory.contains(requirement)) {
this.log("---Memory hit! Updating reference.---\n")
} else {
/*
* This is a pageFault.
* Steps to follow:
* 1) Ask to the assignment policy if the requirement
* needs to replace a page.
* 2a) No need to replace. Ask the memory for a free frame to use.
* 2b) We need to replace. Ask the algorithm for the page to replace,
* then find it in the memory.
* 3) Load the requirement to the memory as a page.
*/
this.log("---Page Fault.---");
pageFault = true;
var frame;
if(this._assignmentFiltersAproves(requirement)) {
this.log("---Free frame available.---\n");
frame = this._memory.getFreeFrame();
} else {
this.log("---Searching for a victim muajajaja!---\n");
victim = this._algorithm.victimFor(requirement);
frame = this._memory.getFrameOf(victim.frame);
}
this._memory.atPut(frame, requirement.asPage());
}
this._update(requirement, pageFault, victim.page);
this._saveMoment(requirement, pageFault, victim.page);
}, this);
}
});
},{"./algorithms/Fifo":29,"./algorithms/Lru":30,"./annotations/Logger":31,"./assignment_filters/AsyncFlushAssignmentPolicy":33,"./assignment_filters/FixedEvenAssignmentPolicy":34,"./common/Memory":36,"./common/Requirement":38,"cocktail":13}],27:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var LocalReplacementPolicy = require('../replacement_filters/LocalReplacementPolicy');
var SecondChanceReplacementPolicy = require('../replacement_filters/SecondChanceReplacementPolicy');
var AsyncFlushReplacementPolicy = require('../replacement_filters/AsyncFlushReplacementPolicy');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Base:"],
constructor: function() {
//Should be initialized by some especification of this class.
this._victims = undefined;
this._requirements = undefined;
this._filters = [];
},
getVictimsStructure: function() {
return this._victims;
},
initialize: function(requirements) {
this._requirements = requirements;
},
victimFor: function(requirement) {
this.log("---Started applying replacement filters.---");
var filteredVictims = this._victims.clone();
var i = 0;
var length = this._filters.length;
for (; i < length; i++) {
if (this._filters[i]) {
this._filters[i].apply(filteredVictims, requirement, this);
}
}
this.log("Finished applying replacement filters.---\n");
this.log("The selected victim is: " + filteredVictims.peek() + ".\n");
this._victims.remove(filteredVictims.peek());
// A pedidio de Cristian S.
var position = filteredVictims.first();
var victim = position;
if (position.isReservedForAsyncFlush()) {
victim = this._filters[1]._counterpart._memory.at(this._filters[1]._counterpart._position);
}
var result = {
frame: position,
page: victim
}
return result;
},
addPage: function(requirement) {
throw new Error("Subclass responsibility.")
},
getPage: function(requirement) {
throw new Error("Subclass responsibility.")
},
update: function(requirement) {
throw new Error("Subclass responsibility.")
},
recycle: function(requirement) {
throw new Error("Subclass responsibility.")
},
setLocalReplacementPolicy: function(enabled) {
if (enabled) {
this._filters[0] = new LocalReplacementPolicy();
} else {
delete this._filters[0];
}
},
setAsyncFlushReplacementPolicy: function(enabled, counterpartFilter) {
if (enabled) {
this._filters[1] = new AsyncFlushReplacementPolicy(counterpartFilter);
} else {
delete this._filters[1];
}
},
setSecondChanceReplacementPolicy: function(enabled) {
if (enabled) {
this._filters[2] = new SecondChanceReplacementPolicy();
} else {
delete this._filters[2];
}
},
isLocalReplacementPolicy: function() {
return this._filters[0] !== undefined;
},
isSecondChanceReplacementPolicy: function() {
return this._filters[2] !== undefined;
},
clearPolicies: function() {
this._filters = [];
}
});
},{"../annotations/Logger":31,"../replacement_filters/AsyncFlushReplacementPolicy":42,"../replacement_filters/LocalReplacementPolicy":43,"../replacement_filters/SecondChanceReplacementPolicy":45,"./AlgorithmInterface":28,"cocktail":13}],28:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': [
'victimFor',
'addPage',
'getPage',
'update',
'recycle',
'clearPolicies',
'setLocalReplacementPolicy',
'setAsyncFlushReplacementPolicy',
'setSecondChanceReplacementPolicy',
]
});
},{"cocktail":13}],29:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var Algorithm = require('./Algorithm');
var Queue = require('../common/VictimsStructures/Queue');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@extends': Algorithm,
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Fifo:"],
constructor: function() {
this.callSuper("constructor");
this._victims = new Queue();
this.log("Created.");
},
initialize: function(requirements) {
this.callSuper("initialize", requirements);
this._victims = new Queue();
},
addPage: function(requirement) {
this._victims.add(requirement.asPage().clearAll());
},
getPage: function(page) {
return this._victims.pageOf(page);
},
update: function(requirement) {
if (this._victims.contains(requirement)) {
this.addPage(requirement);
if (requirement.getMode() === "read") {
this._victims.pageOf(requirement).setReferenced(true);
this.log("Updated victim queue, referenced.");
}
if(requirement.getMode() === "write") {
this._victims.pageOf(requirement).setReferenced(true);
this._victims.pageOf(requirement).setModified(true);
this.log("Updated victim queue, modified & referenced.");
}
return;
}
this.addPage(requirement);
},
//Just recycle the page.
recycle: function(requirement) {
this._victims.recycle(requirement);
},
});
},{"../annotations/Logger":31,"../common/VictimsStructures/Queue":39,"./Algorithm":27,"./AlgorithmInterface":28,"cocktail":13}],30:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var Fifo = require('./Fifo');
var ReQueueQueue = require('../common/VictimsStructures/ReQueueQueue');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@extends': Fifo,
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Lru:"],
constructor: function() {
this.callSuper("constructor");
this._victims = new ReQueueQueue();
this.log("Created.");
},
initialize: function(requirements) {
this.callSuper("initialize", requirements);
this._victims = new ReQueueQueue();
}
});
},{"../annotations/Logger":31,"../common/VictimsStructures/ReQueueQueue":40,"./AlgorithmInterface":28,"./Fifo":29,"cocktail":13}],31:[function(require,module,exports){
var cocktail = require('cocktail');
var config = require('../../config');
cocktail.mix({
//Create logger cocktail annotation and export it as a module.
'@annotation': 'logger',
'@exports': module,
//_logger should implement the log method.
_logger: undefined,
_prefix: undefined,
_debug: undefined,
//Called to initialize when the anotation is used.
//Cocktail enforces this method to recive a single parameter.
setParameter: function(parameter) {
/**********************************************************
* SET THIS VARIABLE TO FALSE WHEN GOING TO PRODUCTION! *
**********************************************************
*/
this._debug = config.debug;
//Check if the object passed has the method that we will use to log.
if(typeof parameter[0].log == "function") {
this._logger = parameter[0];
} else {
//Define a default logger if the one provided by the class was invalid.
this._logger = console;
}
this._prefix = parameter[1];
},
//Here is defined what to do if the annotation is called.
process: function(subject, options) {
//When set to false, logs wont be displayed.
var debug = this._debug;
var logger = this._logger;
var prefix = this._prefix;
host = subject.prototype || subject;
//Host is the object I want to add functionality to.
host.log = function(message){
if(debug && logger) {
logger.log.call(logger, prefix ,message);
}
};
}
});
},{"../../config":10,"cocktail":13}],32:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': ['hasFreeFrameFor, update']
});
},{"cocktail":13}],33:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AssignmentFilterInterface = require('./AssignmentFilterInterface');
var Page = require('../common/Page');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AssignmentFilterInterface],
'@logger' : [console, "AsyncFlushAssignmentPolicy:"],
constructor: function() {
this._reserved = new Page(
{
'process': '',
'pageNumber': 0,
'mode' : 'reserved',
'pageFault' : false,
'required' : false,
'referenced': false,
'modified': false,
'reservedForAsyncFlush': true
});
this._position = 0;
this._memory = undefined;
this.log("Created.");
},
hasFreeFrameFor: function(requirement, memory, context) {
//Save a reference to the actual memory.
this._memory = memory;
return true;
},
update: function(memory, context) {
this._updateMemory(memory, context);
},
_updateMemory: function(memory, context) {
memory.atPut(this._position, this._reserved.clone());
this.log("The reserved Async Flush Frame was updated.");
},
updatePosition: function(requirement) {
this._position = this._memory.getFrameOf(requirement);
this.log("The reserved Async Flush reference was updated, " + this._position + ".");
},
getReserved: function() {
return this._reserved.clone();
}
});
},{"../annotations/Logger":31,"../common/Page":37,"./AssignmentFilterInterface":32,"cocktail":13}],34:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AssignmentFilterInterface = require('./AssignmentFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AssignmentFilterInterface],
'@logger' : [console, "FixedEvenAssignmentPolicy:"],
constructor: function(localitySize) {
this._size = localitySize;
this.log("Created with " + this._size + ".");
},
hasFreeFrameFor: function(requirement, memory, context) {
var processCount = {
process: requirement.getProcess(),
count: 0
};
memory.forEach(function(frame) {
if (this.process == frame.getProcess()) {
this.count++;
}
}, processCount);
return (this._size > processCount.count);
},
update: function(memory, context) {
//Nothing to do here.
},
localSize: function() {
return this._size;
}
});
},{"../annotations/Logger":31,"./AssignmentFilterInterface":32,"cocktail":13}],35:[function(require,module,exports){
var cocktail = require('cocktail');
cocktail.mix({
//Create Behavior cocktail module and export it.
'@exports': module,
'@as': 'module',
/*
* Checks whether the equals method is defined and return a function
* that takes two arguments and returns if they are equal
* using the method it defined for that request.
*/
ComparingMethod: function(value){
if(!value) {
return (function(a, b) {
return b === undefined;
});
}
if (typeof value.equals == "function") {
return (function(a, b) {
return a.equals(b);
});
}
return (function(a, b) {
return a === b;
});
},
/*
* Checks whether the clone method is defined and return a function
* that takes an argument and returns a copy of it
* using the method it defined for that request.
*/
CloningMethod: function(value) {
if(typeof value.clone == "function") {
return (function(a) {
return a.clone();
});
}
return (function(a){
return a;
});
}
});
},{"cocktail":13}],36:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Using Behavior class.
var Behavior = require('./Behavior');
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
//var Configurable = require('cocktail-trait-configurable');
/*
**********************************************************************
* This Memory defines Equals and Clone method. *
* This Memory allows to have the same element twice. *
**********************************************************************
*/
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
//'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Memory:"],
/*
* Instance variables of the class.
* Since we want them to be private, we'll define them in the constructor.
*/
// '@properties': {
// array: undefined,
// size: 0,
// used: 0
// },
/*
* Creates a memory with 'size' ammount of frames.
* The proper initialization of the properties must be here.
*/
constructor: function(size) {
this._size = size;
this._array = [];
this._used = 0;
this.log("Created with " + size + " frames.");
},
/*
* Return whether the memory is full or not.
*/
isFull: function() {
if (this._used === this._size) {
return true;
}
return false;
},
/*
* Short circuit search for a free frame.
* Returns the index of a free frame if there is one.
* Otherwise return -1.
*/
getFreeFrame: function() {
//Ensure there is space before searching for it.
if(this.isFull()) {
return -1;
}
//Move all initializations out of the loop.
var i = 0;
var array = this._array;
var length = this._size;
for (; i < length; i++) {
if (array[i] == undefined) {
return i;
}
}
},
/*
* Look for the frame that contains the element.
* If the element isn't found, return -1.
* This method is identical to Queue.js indexOf.
*/
getFrameOf: function(element) {
//Move all asignations out of the loop.
var i = 0;
var array = this._array;
var length = array.length;
//Ask for the supported comparing method of the element.
var areEquals = Behavior.ComparingMethod(element);
for(; i< length; i++) {
if(areEquals(element, array[i])) {
return i;
}
}
return -1
},
/*
* Returns whether an element is already in the Memory.
*/
contains: function(element) {
if(this.getFrameOf(element) === -1) {
return false;
}
return true;
},
/*
* Returns a reference to the frame in the position of the Memory.
* If the request ask for a frame out of bounds, return undefined.
*
* BEWARE THAT THIS METHOD DOESN'T DIFFERENCE BETWEEN ACCESSING TO
* AN OUT OF BOUND POSITION OR ACCESING TO AN UNDEFINED FRAME.
*
* **Should it return a copy(C++ const.)?**
*/
at: function(position) {
//Check if the position is out of the array.
if(position < 0 || position >= this._size) {
this.log("Access to the position " + position + " out of bounds. Access denied.");
return undefined;
}
return this._array[position];
},
/*
* Add an element to a certain position of the Memory.
* If the position is out of bounds, return false.
* Return true when the operation is completed succesfully.
*/
atPut: function(position, element) {
//Check if the position is out of the array.
if(position < 0 || position >= this._size) {
this.log("Access to the position " + position + " out of bounds. Access denied.");
return false;
}
//Check if the element is not defined or is empty
if(!element || (typeof element === 'object' && !Object.keys(element).length)) {
this.log("Element should be not undefined or empty");
return false;
}
//Check if the position was free and add 1 to the used acumulator.
//Log all replaced elements.
if(this.at(position) === undefined) {
this._used = this._used + 1;
} else {
this.log(this.at(position).toString() + " at frame[" + position + "] being replaced.");
}
//Finally add the element to the Memory and log it.
this._array[position] = element;
this.log(element.toString() + " added to the frame[" + position + "].");
return true;
},
/*
* Determines the comparing method used in the Memory objects.
* This is a deep equivalency comparission.
*/
equals: function(obj) {
//For performance improvement, check if they hold the same reference.
if (!obj) {
return false;
}
if(this === obj) {
return true;
}
/*
* Check that the objects are the same class,
* were instantiated with the same params and
* if the internal state of the objects at this given time is "similar".
*/
if(this.constructor !== obj.constructor || this._size !== obj._size || this._used !== obj._used) {
return false;
}
//Then it's time for a deep check.
//Move all asignations out of the loop.
var i = 0;
var myArray = this._array;
var herArray = obj._array;
var length = myArray.length;
/*
* Don't use a forEach loop beacuse it skips undefined values.
* We want to check for those too.
* Also we want to stop in
*/
for(; i < length; i++) {
var myElement = myArray[i];
var herElement = herArray[i];
/*
* If self holds a reference to obj and
* at the same time obj holds a reference to self,
* That would cause an infinite loop so we skip it.
*/
if(myElement !== obj || herElement !== this) {
/*
* Use Behavior to ask for the comparing method of myElement.
* Then call the function with myElement and herElement.
*/
if(!Behavior.ComparingMethod(myElement)(myElement, herElement)) {
return false;
}
}
}
//After iterating all the elements we know for sure that the objects are equivalents.
return true;
},
/*
* Generate a new object equivalent to this one.
* Tries to do a deep clone.
*/
clone: function() {
this.log("---Start of Clonation.---");
//Using Memory class.
var Memory = require('./Memory');
var aux = new Memory(this._size);
var myArray = this._array;
myArray.forEach(function(element, index) {
//Check that the Memory holds a reference to itself.
//Then add a reference to the new object.
if(element == this) {
aux.atPut(index, aux);
} else {
/*
* Use Behavior to ask for the cloning method of element.
* Then call the function with element and assign it to the new Memory.
*/
aux.atPut(index, Behavior.CloningMethod(element)(element));
}
}, this);
this.log("---End of Clonation.---\n");
return aux;
},
forEach: function(exec, that) {
var myArray = this._array;
if ( typeof exec !== 'function')
throw new Error('First param must be a function')
if(that) {
myArray.forEach(function(element, index) {
//Use the contex passed by the caller in the execution of the function.
exec.call(that, element, index);
},that);
} else {
//If no contex was especified use a simple forEach.
myArray.forEach(function(element, index) {
exec(element, index);
});
}
}
});
},{"../annotations/Logger":31,"./Behavior":35,"./Memory":36,"cocktail":13}],37:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Inheriting from Requirement Class.
var Requirement = require('./Requirement');
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
var Configurable = require('cocktail-trait-configurable');
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
'@extends' : Requirement,
'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Page:"],
//Instance variables of the class.
'@properties': {
pageFault: false,
required : false,
referenced: false,
modified: false,
reservedForAsyncFlush: false
},
/*
* The constructor accept an object like this:
* {
* 'process': 'A',
* 'pageNumber': 1,
* 'mode' : 'write',
* 'pageFault' : false,
* 'required' : false,
* 'referenced': false,
* 'modified' : false,
* 'reservedForAsyncFlush' : false
* }
* Automaticaly is maped to the corresponding properties
* thanks to the Configurable trait.
*/
//@Override
asDataObject: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
pageFault : this.isPageFault(),
required : this.isRequired(),
referenced : this.isReferenced(),
modified: this.isModified(),
reservedForAsyncFlush: this.isReservedForAsyncFlush()
}
return obj;
},
asVictim: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
referenced : this.isReferenced(),
modified: this.isModified(),
}
return obj;
},
//@Override
clone : function() {
var Page = require('./Page');
var aux = new Page(this.asDataObject());
return aux;
},
//Clearing Page flags methods.
clearPageFault: function() {
this.setPageFault(false);
return this;
},
clearRequired: function() {
this.setRequired(false);
return this;
},
clearReferenced: function() {
this.setReferenced(false);
return this;
},
clearModified: function() {
this.setModified(false);
},
clearReservedForAsyncFlush: function() {
this.setReservedForAsyncFlush(false);
},
clearAll: function() {
this.clearPageFault();
this.clearRequired();
this.clearReferenced();
this.clearModified();
this.clearReservedForAsyncFlush();
return this;
},
//@Override
asPage: function() {
return this.clone();
}
});
},{"../annotations/Logger":31,"./Page":37,"./Requirement":38,"cocktail":13,"cocktail-trait-configurable":12}],38:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Using Behavior class.
var Behavior = require('./Behavior');
//This class uses Page class, but its requirement is delayed until runtime.
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
var Configurable = require('cocktail-trait-configurable');
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Requirement:"],
//Instance variables of the class.
'@properties': {
process: "",
pageNumber: 0,
mode: "read"
},
/*
* The constructor accept an object like this:
* {
* 'process': 'A',
* 'pageNumber': 1,
* 'mode' : 'write'
* }
* Automaticaly is maped to the corresponding properties
* thanks to the Configurable trait.
*/
constructor: function(options) {
this.configure(options);
//Check that the object was created fine.
if(this.validate) {
this.log("Created.");
} else {
//This warning should be seen even in production.
console.warn("A requirement was created with default values.");
}
},
validate: function() {
var process = this.getProcess();
var pageNumber = this.getPageNumber();
var mode = this.getMode();
if ((process == "") || (typeof pageNumber !== "number") ||
(mode !== "read" && mode !== "write" && mode !== "finish" && mode !== "reserved")) {
return false;
}
return true;
},
equals: function(obj) {
//For performance improvement, check if they hold the same reference.
if (!obj) {
return false;
}
if(this === obj) {
return true;
}
/*
* Check that the objects are the same class,
* were instantiated with the same params and
* if the internal state of the objects at this given time is "similar".
*/
if(this.constructor !== obj.constructor || this.getProcess() !== obj.getProcess() ||
this.getPageNumber() !== obj.getPageNumber()) {
return false;
}
//Seems like they are the same.
return true;
},
asDataObject: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
mode: this.getMode()
}
return obj;
},
asPage: function() {
var obj = this.asDataObject();
//Set a requirement on page fault by default.
obj.pageFault = false;
obj.required = false;
obj.referenced = false;
obj.modified = false;
obj.reservedForAsyncFlush = false;
//Using Page class.
var Page = require('./Page');
var aux = new Page(obj);
return aux;
},
clone : function() {
var Requirement = require('./Requirement');
var aux = new Requirement(this.asDataObject());
return aux;
},
toString: function() {
return JSON.stringify(this.asDataObject());
}
});
},{"../annotations/Logger":31,"./Behavior":35,"./Page":37,"./Requirement":38,"cocktail":13,"cocktail-trait-configurable":12}],39:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../../annotations/Logger');
var VictimsStructureInterface = require('./VictimsStructureInterface');
cocktail.use(Logger);
cocktail.mix({
//Define this file as a single class module exportable.
'@exports': module,
'@as': 'class',
'@traits': [VictimsStructureInterface],
'@logger' : [console, "VictimsQueue:"],
constructor: function() {
/*
* According to @elmasse default variable initialization must be done
* in the constructor and not in the @properties declaration.
*/
this._array = [];
this.log("Created.");
},
/*
* Add a page to the Queue.
*/
add: function(page) {
if(!this.contains(page)) {
this._array.push(page);
this.log(page.toString() + " added.");
} else {
this.log(page.toString() + " was already on the Queue.")
}
return this;
},
/*
* Add multiple pages to the Queue using the add method.
* collection must implement the forEach method as it is in Array.
*/
addAll: function(collection) {
this.log("Massive assignment started.");
collection.forEach(function(page) {
this.add(page);
}, this);
this.log("Massive assignment finished.");
return this;
},
/*
* Returns the size of the queue at a given time.
*/
size: function() {
return this._array.length;
},
/*
* Returns a reference to the first page of the Queue.
* The page is conserved in the structure.
*/
peek: function() {
return this._array[0];
},
/*
* Returns the first page of the Queue deleting it from the structure.
*/
first: function() {
var page = this._array.shift();
if (page) {
this.log(page.toString() + " removed.");
}
return page;
},
remove: function(requirement) {
var index = this._indexOf(requirement);
if (index != -1) {
return (this._array.splice(index, 1))[0];
}
return undefined;
},
recycle: function(requirement) {
if(this.remove(requirement)) {
this.add(requirement);
}
},
/*
* Determines if a requirement exists in the queue.
* If its found return the index of the element in the array.
* Otherwise return -1.
*/
_indexOf: function (requirement) {
var i = 0;
var array = this._array;
var length = array.length;
//Use a normal looping to stop when a match is encountered.
for(; i < length; i++) {
// console.log(requirement);
if(requirement.equals(array[i])) {
return i;
}
}
return -1
},
/*
* Returns a reference to the page in the queue
* That matches the asked requirement.
*/
pageOf: function(requirement) {
var index = this._indexOf(requirement);
if( index === -1) {
return undefined;
}
return this._array[index];
},
/*
* Returns whether an element is already in the Queue.
*/
contains: function (element) {
if (this._indexOf(element) === -1) {
return false;
}
return true;
},
clone: function() {
var aux = new this.constructor();
this._array.forEach(function(page) {
aux.add(page.clone());
});
return aux;
},
forEach: function(exec, that) {
var myArray = this._array;
if ( typeof exec !== 'function')
throw new Error('First param must be a function')
if(that) {
myArray.forEach(function(element, index) {
//Use the contex passed by the caller in the execution of the function.
exec.call(that, element, index);
},that);
} else {
//If no contex was especified use a simple forEach.
myArray.forEach(function(element, index) {
exec(element, index);
});
}
},
/*
* Removes all objects from the Queue.
*/
clear: function() {
this._array = [];
this.log("Cleared.");
}
});
},{"../../annotations/Logger":31,"./VictimsStructureInterface":41,"cocktail":13}],40:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../../annotations/Logger');
var VictimsStructureInterface = require('./VictimsStructureInterface');
var Queue = require('./Queue');
cocktail.use(Logger);
/*
**********************************************************************
* This Queue doesn't define Equals nor Clone method. Should it? *
* This Queue doesn't allow to have the same element twice. *
**********************************************************************
*/
cocktail.mix({
//Define this file as a single class module exportable.
'@exports': module,
'@as': 'class',
'@extends': Queue,
'@traits': [VictimsStructureInterface],
'@logger' : [console, "VictimsReQQueue:"],
/*
* Add a page to the Queue.
* If the page is already in the queue, remove it,
* then enqueue it again.
*/
//@Override
add: function(page) {
//Don't use contains method here because
//you would have to search again for the index.
var array = this._array;
var index = this._indexOf(page);
if (index != -1) {
array.splice(index ,1);
this.log(page.toString() + " removed. Waiting to requeue.");
}
this.callSuper("add", page);
return this;
},
clone: function() {
var ReQueueQueue = require('./ReQueueQueue');
var aux = new ReQueueQueue();
this._array.forEach(function(page) {
aux.add(page.clone());
});
return aux;
}
});
},{"../../annotations/Logger":31,"./Queue":39,"./ReQueueQueue":40,"./VictimsStructureInterface":41,"cocktail":13}],41:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': [
'add',
'addAll',
'clone',
'first',
'peek',
'remove',
'recycle',
'contains',
'pageOf',
'size',
'clear'
]
});
},{"cocktail":13}],42:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "AsyncFlushReplacementPolicy:"],
constructor: function(counterpartFilter) {
//This counterpart is the AsyncFlushAssignmentPolicy.
this._counterpart = counterpartFilter;
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
//If the next victim was modified, use the async flush reserved memory field.
if (potentialVictim.isModified()) {
this.log("The victim " + potentialVictim + " was modified, applying async flush.");
this._counterpart.updatePosition(potentialVictim);
context._victims.remove(potentialVictim);
var reservedForAsync = this._counterpart.getReserved();
//Ensure that the only posible victim is the reserved field.
filteredVictims.clear();
filteredVictims.add(reservedForAsync);
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}],43:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "LocalReplacementPolicy:"],
constructor: function() {
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
while(filteredVictims.size() && potentialVictim.getProcess() !== requirement.getProcess()) {
this.log("The victim " + potentialVictim + " was isn't from the same process, Applying Local filter.");
//Remove the page from the filteredVictims structure.
filteredVictims.remove(potentialVictim);
//get a new potentialVictim
potentialVictim = filteredVictims.peek();
}
if (!filteredVictims.size()) {
throw new Error("The new process has no free frames to be assigned!!");
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}],44:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': ['apply']
});
},{"cocktail":13}],45:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "SecondChanceReplacementPolicy:"],
constructor: function() {
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
while(potentialVictim.isReferenced()) {
this.log("The victim " + potentialVictim + " was referenced, applying 2nd chance.");
//Recycle the page in the filteredVictims structure until we get one not referenced.
//Clear the potentialVictim referenced flag.
potentialVictim.clearReferenced();
filteredVictims.recycle(potentialVictim);
context.recycle(potentialVictim);
//get a new potentialVictim
potentialVictim = filteredVictims.peek();
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}]},{},[1,2,3,4,5]);
| dist/js/sams.js | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict'
var angular = require('angular');
var angularRouter = require('angular-ui-router');
var app = angular.module('sams', ['sams.controllers', 'sams.locales', 'ui.router']);
app.config(function($stateProvider, $urlRouterProvider){
if ( navigator.userAgent === 'samsteam-app-agent' ) {
$urlRouterProvider.otherwise('/step/requirements');
} else {
$urlRouterProvider.otherwise('/home');
}
/*
| ---------------------------------------------------------------------------
| Routes
| ---------------------------------------------------------------------------
*/
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'HomeController'
});
$stateProvider
.state('about', {
url: '/about',
templateUrl: 'templates/about.html',
controller: 'AboutController'
});
$stateProvider
.state('step', {
url: '/step',
abstract: true,
template: '<ui-view/>'
})
.state('step.requirements', {
url: '/requirements',
templateUrl: 'templates/requirements.html',
controller: 'RequirementsController'
})
.state('step.policies', {
url: '/policies',
templateUrl: 'templates/policies.html',
controller: 'PoliciesController'
})
.state('step.resolution', {
url: '/resolution',
templateUrl: 'templates/resolution.html',
controller: 'ResolutionController',
resolve: {
checkData: function( SchedulerService ){
return SchedulerService.isValidData();
}
}
})
.state('fifo', {
url: '/algorithms/fifo',
templateUrl: 'templates/fifo.html',
controller: 'FifoController'
});
});
},{"angular":9,"angular-ui-router":7}],2:[function(require,module,exports){
'use strict'
var angular = require('angular');
angular.module('sams.controllers', ['sams.services', 'sams.filters'])
/*
| ---------------------------------------------------------------------------
| Main Controller (contains below controllers as childrens)
| ---------------------------------------------------------------------------
*/
.controller('MainController', function($scope, $state, SamsService, $translate){
console.info('In Main Controller');
$scope.locales = SamsService.getLocales();
$scope.locale = SamsService.getDefaultLocale();
$translate.use($scope.locale);
console.log($scope.locale)
$scope.is = function(routeName) {
return $state.is(routeName);
}
$scope.changeLocale = function(val){
$scope.locale = val;
$translate.use($scope.locale);
SamsService.setDefaultLocale($scope.locale)
}
$scope.isDesktopApp = (navigator.userAgent === 'samsteam-app-agent');
})
/*
| ---------------------------------------------------------------------------
| Home Controller
| ---------------------------------------------------------------------------
*/
.controller('HomeController', function($scope){
console.info('In HomeController');
})
/*
| ---------------------------------------------------------------------------
| About Controller
| ---------------------------------------------------------------------------
*/
.controller('AboutController', function($scope, $filter){
console.info('In AboutController');
var devTeam = [
{
'name' : 'Babbini, Ignacio',
'github' : 'https://github.com/inbabbini',
'photo' : 'images/portraits/ignacio_babbini.png'
},
{
'name' : 'Eusebi, Cirano',
'github' : 'https://github.com/magodopado',
'photo' : 'images/portraits/cirano_eusebi.jpg'
},
{
'name' : 'Sottile, Cristian',
'github' : 'https://github.com/cristian-s',
'photo' : 'images/portraits/cristian_sottile.jpg'
},
{
'name' : 'Aparicio, Natalia',
'github' : 'https://github.com/natiidc',
'photo' : 'images/portraits/natalia_aparicio.jpg'
},
{
'name' : 'Cascio, Bruno',
'github' : 'https://github.com/brunocascio',
'photo' : 'images/portraits/bruno_cascio.jpg'
}
];
$scope.devteam = $filter('shuffle')(devTeam);
})
/*
| ---------------------------------------------------------------------------
| Data input
| ---------------------------------------------------------------------------
*/
.controller('RequirementsController', function($scope, $state, SamsService, SchedulerService){
console.info('In Requirements Controller');
$scope.modes = SchedulerService.getModes();
$scope.inputProcesses = [];
$scope.processes = [];
$scope.pages = {};
$scope.secuences = [];
$scope.requirements = SchedulerService.getRequirements();
$scope.loadDefault = function(){
$scope.inputProcesses = ['a','b','c'];
$scope.processes = ['a','b','c'];
$scope.pages = {
a:'1,2,3,4',
b:'5,6,7,8',
c:'9,10,11'
};
$scope.secuences = [
{'process': $scope.processes[0], 'cantPages': 1, 'mode': 'read'},
{'process': $scope.processes[1], 'cantPages': 2, 'mode': 'read'},
{'process': $scope.processes[2], 'cantPages': 1, 'mode': 'write'},
{'process': $scope.processes[1], 'cantPages': 1, 'mode': 'read'}
];
}
$scope.hasPages = function(){
return ($scope.pages && Object.keys($scope.pages).length);
}
$scope.next = function() {
$scope.processRequirements();
$state.go('step.policies');
}
$scope.__needClean = function(){
var isEmptyPages = true;
var isEmptyProcesses = (!$scope.processes || $scope.processes.length == 0);
angular.forEach($scope.pages, function(p,i){
if ( p || p !== '' ) {
isEmptyPages = false;
}
});
if( isEmptyProcesses ){
$scope.pages = {};
$scope.secuences = [];
$scope.processes = [];
}
if ( isEmptyPages ) {
$scope.pages = {};
$scope.secuences = [];
}
}
// parsing comma separated string
$scope.$watch('inputProcesses', function(newVal, oldVal){
// TODO: Validate unique processes
// TODO: multiple commas
$scope.processes = SamsService.stringToArray($scope.processes, newVal, ',');
$scope.__needClean();
});
// parsing comma separated string
$scope.$watch('pages', function(newVal, oldVal){
// TODO: multiple commas
if ( newVal !== undefined ){
$scope.pages = newVal;
}
$scope.__needClean();
}, true);
// add a new box for future requirements
$scope.add = function() {
var req = SamsService.createEmptyRequirement();
$scope.secuences.push(req);
}
// parsing user data input and send to scheduler.
$scope.processRequirements = function(){
//clean old requirements
$scope.requirements = [];
// clone pages
var pages = angular.copy($scope.pages);
// create requeriments
$scope.requirements = SamsService.createRequirements(pages, $scope.secuences);
SchedulerService.addRequirements($scope.requirements);
}
})
/*
| ---------------------------------------------------------------------------
| Policies
| ---------------------------------------------------------------------------
*/
.controller('PoliciesController', function($scope, SamsService, SchedulerService){
console.info('In Policies Controller');
/*
| ---------------------------------------------------------------------------
| Algorithm Selection
| ---------------------------------------------------------------------------
*/
$scope.algorithms = SchedulerService.getAlgorithms();
$scope.algorithmSelected = SchedulerService.getAlgorithm();
$scope.changeAlgorithm = function(){
SchedulerService.setAlgorithm( $scope.algorithmSelected );
}
/*
| ---------------------------------------------------------------------------
| Helper, validate assign with replace policy
| ---------------------------------------------------------------------------
*/
$scope.isAvailable = function(replaceOption) {
var assignOption = $scope.selectedAssignmentOption;
return SamsService.areCompatiblePolicies(replaceOption, assignOption);
}
/*
| ---------------------------------------------------------------------------
| Memory
| ---------------------------------------------------------------------------
*/
$scope.memorySize = SchedulerService.getMemorySize() || 4; // input
$scope.changeMemorySize = function(){
if ( typeof $scope.memorySize == 'number'){
SchedulerService.setMemorySize( $scope.memorySize );
}
}
// run when load (UX: prevent memory 0)
$scope.changeMemorySize();
/*
| ---------------------------------------------------------------------------
| isFixedEvenAssignmentPolicy
| ---------------------------------------------------------------------------
*/
$scope.setAssignmentOption = function(a){
$scope.selectedReplacementOption = null;
$scope.selectedAssignmentOption = a;
var isFixedEven = ($scope.selectedAssignmentOption === 'fixed');
SchedulerService.setFixedEvenAssignmentPolicy( isFixedEven );
SchedulerService.setLocalReplacementPolicy(isFixedEven);
}
$scope.assignmentOptions = SchedulerService.getAssigmentPolicies();
if ( SchedulerService.isFixedEvenAssignmentPolicy() ) {
$scope.selectedAssignmentOption = 'fixed';
SchedulerService.setLocalReplacementPolicy(true);
} else {
$scope.selectedAssignmentOption = 'dynamic';
// update if is not setted
$scope.setAssignmentOption($scope.selectedAssignmentOption);
SchedulerService.setLocalReplacementPolicy(false);
}
/*
| ---------------------------------------------------------------------------
| isAsyncFlushReplacementPolicy
| ---------------------------------------------------------------------------
*/
$scope.queueOptions = SchedulerService.getQueuePolicies();
$scope.hasAlgorithm = function () {
return $scope.algorithmSelected;
}
$scope.changeOptions = function(){
// TODO: check if algorithm is FIFO
SchedulerService.setAsyncFlushReplacementPolicy($scope.queueOptions['async-flush']);
}
})
/*
| ---------------------------------------------------------------------------
| Show results
| ---------------------------------------------------------------------------
*/
.controller('ResolutionController', function($scope, $state, SchedulerService, checkData){
console.info('In Resolution Controller');
if (!checkData)
return $state.go('step.requirements');
try {
$scope.framesTotal = SchedulerService.getMemorySize() - 1;
$scope.results = SchedulerService.run();
$scope.instants = $scope.results.length - 1;
} catch (err) {
console.log(err);
alert(err);
return $state.go('step.requirements');
}
})
},{"angular":9}],3:[function(require,module,exports){
'use strict'
var angular = require('angular');
angular.module('sams.filters', [])
.filter('inArray', function(){
return function(array, value){
return (array.indexOf(value) !== -1);
}
})
.filter('isBoolean', function(){
return function(value){
return (typeof value === 'boolean');
}
})
.filter('capitalize', function(){
return function(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
})
.filter('makeRange', function() {
return function(input) {
var lowBound, highBound;
switch (input.length) {
case 1:
lowBound = 0;
highBound = parseInt(input[0]) - 1;
break;
case 2:
lowBound = parseInt(input[0]);
highBound = parseInt(input[1]);
break;
default:
return input;
}
var result = [];
for (var i = lowBound; i <= highBound; i++)
result.push(i);
return result;
};
})
.filter('shuffle', function() {
return function(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
});
},{"angular":9}],4:[function(require,module,exports){
'use strict'
var angular = require('angular');
var translator = require('angular-translate');
var app = angular.module('sams.locales', ['pascalprecht.translate']);
app.config(function($translateProvider){
/*
| ---------------------------------------------------------------------------
| Translates
| ---------------------------------------------------------------------------
*/
$translateProvider.useSanitizeValueStrategy('escaped');
$translateProvider.translations('en', {
ABOUT_TITLE: 'Devteam',
ABOUT_ABOUTSAMS_TITLE: 'About SAMS', //<small style="color:#488FE7">and it\'s roots</small>',
ABOUT_TUTORIAL_TITLE: 'Tutorial', //<small style="color:#488FE7"></small>',
ABOUT_GITHUB_TITLE: 'Project\'s Github Information', //<small style="color:#488FE7">Fork it!</small>',
ABOUT_SAMS: 'About SAMS',
TUTORIAL: 'Tutorial',
GITHUB: 'GitHub',
HOME_START: 'START',
HOME_DOWNLOAD: 'DOWNLOAD',
HOME_ABOUT: 'ABOUT',
BREADCRUMB_REQUIREMENTS: 'Requirements',
BREADCRUMB_POLICIES: 'Policies',
BREADCRUMB_RESOLUTION: 'Resolution',
});
$translateProvider.translations('es', {
ABOUT_TITLE: 'Desarrolladores',
ABOUT_ABOUTSAMS_TITLE: 'Acerca de SAMS', // <small style="color:#488FE7">y sus comienzos</small>',
ABOUT_TUTORIAL_TITLE: 'Tutorial', //<small style="color:#488FE7"></small>',
ABOUT_GITHUB_TITLE: 'Información del Github del proyecto', // <small style="color:#488FE7">¡Forkealo!</small>',
ABOUT_SAMS: 'Acerca de SAMS',
TUTORIAL: 'Tutorial',
GITHUB: 'GitHub',
HOME_START: 'EMPEZAR',
HOME_DOWNLOAD: 'DESCARGAR',
HOME_ABOUT: 'ACERCA DE',
BREADCRUMB_REQUIREMENTS: 'Requerimientos',
BREADCRUMB_POLICIES: 'Políticas',
BREADCRUMB_RESOLUTION: 'Resolución',
});
$translateProvider.preferredLanguage( 'es' );
});
},{"angular":9,"angular-translate":6}],5:[function(require,module,exports){
'use strict'
var angular = require('angular')
, Scheduler = require('sams');
angular.module('sams.services', [])
/*
| -----------------------------------------------------------------------------
| Validation Service
| -----------------------------------------------------------------------------
|
*/
.factory('ValidationService', function($filter){
return {
checkBooleanType: function(value) {
return $filter('isBoolean')(value);
},
checkIntType: function(value) {
return angular.isNumber(value);
},
checkObjectType: function(obj) {
return angular.isObject(obj);
},
inArray: function(arr, value) {
return $filter('inArray')(arr, value);
}
}
})
/*
| -----------------------------------------------------------------------------
| Sams Service (Helpers)
| -----------------------------------------------------------------------------
|
*/
.factory('SamsService', function(){
return {
getLocales: function(){
return ['es', 'en'];
},
getDefaultLocale: function() {
var locale = window.localStorage.getItem('locale');
return (!locale || locale === '') ? 'es' : locale;
},
setDefaultLocale: function(val) {
window.localStorage.setItem('locale', val);
},
areCompatiblePolicies: function(replacement, assigment){
// Dynamic should be only global
if ( assigment === 'dynamic'){
if ( replacement === 'global' ) {
return false;
}
return true;
// Fixed should be only local
} else if ( assigment === 'fixed' ) {
if ( replacement === 'local' ) {
return false;
}
return true;
}
},
createRequirements: function(pages, secuences){
var reqs = []
angular.forEach(pages, function(pagesString, p){
pages[p] = pagesString.split(',');
});
// create requirements
secuences.forEach(function(obj, index){
for (var i = 0; i < obj.cantPages; i++) {
var req = {};
req['process'] = obj.process;
req['pageNumber'] = pages[obj.process].shift();
req['mode'] = obj.mode;
reqs.push(req);
}
});
return reqs;
},
createEmptyRequirement: function() {
return {
process: null,
cantPages: null,
mode: 'read'
};
},
stringToArray: function(array, stringValue, delimiter) {
delimiter = delimiter || ','
if (typeof stringValue === 'string'){
array = stringValue.split(delimiter);
if (array[array.length-1] == ""){
array.pop()
}
}
return array;
}
}
})
/*
| -----------------------------------------------------------------------------
| Scheduler Service
| -----------------------------------------------------------------------------
|
*/
.factory('SchedulerService', function(ValidationService){
var algorithms = ['fifo', 'fifo2', 'lru', 'nru', 'optimal'];
var modes = ['read', 'write', 'finish'];
var assigmentPolicies = ['fixed', 'dynamic'];
var queuePolicies = {'async-flush': false};
var scheduler = new Scheduler();
return {
/*
| ---------------------------------------
| set algorithm
| ---------------------------------------
*/
setAlgorithm: function(algorithm) {
if ( ! ValidationService.inArray(this.getAlgorithms(), algorithm) )
throw new Error("Algorithm doesn't exists");
if (algorithm === 'fifo2') {
scheduler.setAlgorithm('fifo');
this.setSecondChanceReplacementPolicy(true);
} else {
scheduler.setAlgorithm(algorithm);
}
return this;
},
/*
| ---------------------------------------
| get algorithm
| ---------------------------------------
*/
getAlgorithm: function() {
return scheduler.getAlgorithm();
},
/*
| ---------------------------------------
| get memory size
| ---------------------------------------
*/
getMemorySize: function() {
return scheduler.getMemorySize() || 0;
},
/*
| ---------------------------------------
| is fixed Assigment
| ---------------------------------------
*/
isFixedEvenAssignmentPolicy: function() {
return scheduler.isFixedEvenAssignmentPolicy();
},
/*
| ---------------------------------------
| is local Replacement
| ---------------------------------------
*/
isLocalReplacementPolicy: function() {
return scheduler.isLocalReplacementPolicy();
},
/*
| ---------------------------------------
| set if is fixed or dynamic
| ---------------------------------------
*/
setFixedEvenAssignmentPolicy: function(enabled) {
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setFixedEvenAssignmentPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is local or global
| ---------------------------------------
*/
setLocalReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setLocalReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is async flush
| ---------------------------------------
*/
setAsyncFlushReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setAsyncFlushReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set if is second chance
| ---------------------------------------
*/
setSecondChanceReplacementPolicy: function(enabled){
if ( ! ValidationService.checkBooleanType(enabled) )
throw new Error("value should be a boolean value");
scheduler.setSecondChanceReplacementPolicy(enabled);
return this;
},
/*
| ---------------------------------------
| set size of memory
| ---------------------------------------
*/
setMemorySize: function(size){
if ( ! ValidationService.checkIntType(size) )
throw new Error("value should be a integer value");
scheduler.setMemorySize( parseInt(size) );
return this;
},
/*
| ---------------------------------------
| set parsed requirements
| ---------------------------------------
*/
addRequirements: function(reqs){
if ( !ValidationService.checkObjectType(reqs) )
throw new Error("obj should be an object");
scheduler.addRequirements(reqs);
return this;
},
/*
| ---------------------------------------
| get requirements
| ---------------------------------------
*/
getRequirements: function(){
return scheduler.getRequirements() || [];
},
/*
| ---------------------------------------
| verify if all data is completed
| ---------------------------------------
*/
isValidData: function(){
var memSize = scheduler.getMemorySize();
var algorithm = scheduler.getAlgorithm();
var reqs = scheduler.getRequirements();
return memSize && algorithm && (reqs && reqs.length);
},
/*
| ---------------------------------------
| Helpers
| ---------------------------------------
*/
getAlgorithms: function() {
return algorithms;
},
getAssigmentPolicies: function() {
return assigmentPolicies;
},
getQueuePolicies: function() {
return queuePolicies;
},
getModes: function() {
return modes;
},
/*
| ---------------------------------------
| RUN :D
| ---------------------------------------
*/
run: function(){
return scheduler.run();
}
}
})
},{"angular":9,"sams":11}],6:[function(require,module,exports){
/*!
* angular-translate - v2.7.2 - 2015-06-01
* http://github.com/angular-translate/angular-translate
* Copyright (c) 2015 ; Licensed MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define([], function () {
return (factory());
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
factory();
}
}(this, function () {
/**
* @ngdoc overview
* @name pascalprecht.translate
*
* @description
* The main module which holds everything together.
*/
angular.module('pascalprecht.translate', ['ng'])
.run(runTranslate);
function runTranslate($translate) {
'use strict';
var key = $translate.storageKey(),
storage = $translate.storage();
var fallbackFromIncorrectStorageValue = function () {
var preferred = $translate.preferredLanguage();
if (angular.isString(preferred)) {
$translate.use(preferred);
// $translate.use() will also remember the language.
// So, we don't need to call storage.put() here.
} else {
storage.put(key, $translate.use());
}
};
fallbackFromIncorrectStorageValue.displayName = 'fallbackFromIncorrectStorageValue';
if (storage) {
if (!storage.get(key)) {
fallbackFromIncorrectStorageValue();
} else {
$translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue);
}
} else if (angular.isString($translate.preferredLanguage())) {
$translate.use($translate.preferredLanguage());
}
}
runTranslate.$inject = ['$translate'];
runTranslate.displayName = 'runTranslate';
/**
* @ngdoc object
* @name pascalprecht.translate.$translateSanitizationProvider
*
* @description
*
* Configurations for $translateSanitization
*/
angular.module('pascalprecht.translate').provider('$translateSanitization', $translateSanitizationProvider);
function $translateSanitizationProvider () {
'use strict';
var $sanitize,
currentStrategy = null, // TODO change to either 'sanitize', 'escape' or ['sanitize', 'escapeParameters'] in 3.0.
hasConfiguredStrategy = false,
hasShownNoStrategyConfiguredWarning = false,
strategies;
/**
* Definition of a sanitization strategy function
* @callback StrategyFunction
* @param {string|object} value - value to be sanitized (either a string or an interpolated value map)
* @param {string} mode - either 'text' for a string (translation) or 'params' for the interpolated params
* @return {string|object}
*/
/**
* @ngdoc property
* @name strategies
* @propertyOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Following strategies are built-in:
* <dl>
* <dt>sanitize</dt>
* <dd>Sanitizes HTML in the translation text using $sanitize</dd>
* <dt>escape</dt>
* <dd>Escapes HTML in the translation</dd>
* <dt>sanitizeParameters</dt>
* <dd>Sanitizes HTML in the values of the interpolation parameters using $sanitize</dd>
* <dt>escapeParameters</dt>
* <dd>Escapes HTML in the values of the interpolation parameters</dd>
* <dt>escaped</dt>
* <dd>Support legacy strategy name 'escaped' for backwards compatibility (will be removed in 3.0)</dd>
* </dl>
*
*/
strategies = {
sanitize: function (value, mode) {
if (mode === 'text') {
value = htmlSanitizeValue(value);
}
return value;
},
escape: function (value, mode) {
if (mode === 'text') {
value = htmlEscapeValue(value);
}
return value;
},
sanitizeParameters: function (value, mode) {
if (mode === 'params') {
value = mapInterpolationParameters(value, htmlSanitizeValue);
}
return value;
},
escapeParameters: function (value, mode) {
if (mode === 'params') {
value = mapInterpolationParameters(value, htmlEscapeValue);
}
return value;
}
};
// Support legacy strategy name 'escaped' for backwards compatibility.
// TODO should be removed in 3.0
strategies.escaped = strategies.escapeParameters;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#addStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Adds a sanitization strategy to the list of known strategies.
*
* @param {string} strategyName - unique key for a strategy
* @param {StrategyFunction} strategyFunction - strategy function
* @returns {object} this
*/
this.addStrategy = function (strategyName, strategyFunction) {
strategies[strategyName] = strategyFunction;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#removeStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Removes a sanitization strategy from the list of known strategies.
*
* @param {string} strategyName - unique key for a strategy
* @returns {object} this
*/
this.removeStrategy = function (strategyName) {
delete strategies[strategyName];
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitizationProvider#useStrategy
* @methodOf pascalprecht.translate.$translateSanitizationProvider
*
* @description
* Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
*
* @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
* @returns {object} this
*/
this.useStrategy = function (strategy) {
hasConfiguredStrategy = true;
currentStrategy = strategy;
return this;
};
/**
* @ngdoc object
* @name pascalprecht.translate.$translateSanitization
* @requires $injector
* @requires $log
*
* @description
* Sanitizes interpolation parameters and translated texts.
*
*/
this.$get = ['$injector', '$log', function ($injector, $log) {
var applyStrategies = function (value, mode, selectedStrategies) {
angular.forEach(selectedStrategies, function (selectedStrategy) {
if (angular.isFunction(selectedStrategy)) {
value = selectedStrategy(value, mode);
} else if (angular.isFunction(strategies[selectedStrategy])) {
value = strategies[selectedStrategy](value, mode);
} else {
throw new Error('pascalprecht.translate.$translateSanitization: Unknown sanitization strategy: \'' + selectedStrategy + '\'');
}
});
return value;
};
// TODO: should be removed in 3.0
var showNoStrategyConfiguredWarning = function () {
if (!hasConfiguredStrategy && !hasShownNoStrategyConfiguredWarning) {
$log.warn('pascalprecht.translate.$translateSanitization: No sanitization strategy has been configured. This can have serious security implications. See http://angular-translate.github.io/docs/#/guide/19_security for details.');
hasShownNoStrategyConfiguredWarning = true;
}
};
if ($injector.has('$sanitize')) {
$sanitize = $injector.get('$sanitize');
}
return {
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitization#useStrategy
* @methodOf pascalprecht.translate.$translateSanitization
*
* @description
* Selects a sanitization strategy. When an array is provided the strategies will be executed in order.
*
* @param {string|StrategyFunction|array} strategy The sanitization strategy / strategies which should be used. Either a name of an existing strategy, a custom strategy function, or an array consisting of multiple names and / or custom functions.
*/
useStrategy: (function (self) {
return function (strategy) {
self.useStrategy(strategy);
};
})(this),
/**
* @ngdoc function
* @name pascalprecht.translate.$translateSanitization#sanitize
* @methodOf pascalprecht.translate.$translateSanitization
*
* @description
* Sanitizes a value.
*
* @param {string|object} value The value which should be sanitized.
* @param {string} mode The current sanitization mode, either 'params' or 'text'.
* @param {string|StrategyFunction|array} [strategy] Optional custom strategy which should be used instead of the currently selected strategy.
* @returns {string|object} sanitized value
*/
sanitize: function (value, mode, strategy) {
if (!currentStrategy) {
showNoStrategyConfiguredWarning();
}
if (arguments.length < 3) {
strategy = currentStrategy;
}
if (!strategy) {
return value;
}
var selectedStrategies = angular.isArray(strategy) ? strategy : [strategy];
return applyStrategies(value, mode, selectedStrategies);
}
};
}];
var htmlEscapeValue = function (value) {
var element = angular.element('<div></div>');
element.text(value); // not chainable, see #1044
return element.html();
};
var htmlSanitizeValue = function (value) {
if (!$sanitize) {
throw new Error('pascalprecht.translate.$translateSanitization: Error cannot find $sanitize service. Either include the ngSanitize module (https://docs.angularjs.org/api/ngSanitize) or use a sanitization strategy which does not depend on $sanitize, such as \'escape\'.');
}
return $sanitize(value);
};
var mapInterpolationParameters = function (value, iteratee) {
if (angular.isObject(value)) {
var result = angular.isArray(value) ? [] : {};
angular.forEach(value, function (propertyValue, propertyKey) {
result[propertyKey] = mapInterpolationParameters(propertyValue, iteratee);
});
return result;
} else if (angular.isNumber(value)) {
return value;
} else {
return iteratee(value);
}
};
}
/**
* @ngdoc object
* @name pascalprecht.translate.$translateProvider
* @description
*
* $translateProvider allows developers to register translation-tables, asynchronous loaders
* and similar to configure translation behavior directly inside of a module.
*
*/
angular.module('pascalprecht.translate')
.constant('pascalprechtTranslateOverrider', {})
.provider('$translate', $translate);
function $translate($STORAGE_KEY, $windowProvider, $translateSanitizationProvider, pascalprechtTranslateOverrider) {
'use strict';
var $translationTable = {},
$preferredLanguage,
$availableLanguageKeys = [],
$languageKeyAliases,
$fallbackLanguage,
$fallbackWasString,
$uses,
$nextLang,
$storageFactory,
$storageKey = $STORAGE_KEY,
$storagePrefix,
$missingTranslationHandlerFactory,
$interpolationFactory,
$interpolatorFactories = [],
$loaderFactory,
$cloakClassName = 'translate-cloak',
$loaderOptions,
$notFoundIndicatorLeft,
$notFoundIndicatorRight,
$postCompilingEnabled = false,
$forceAsyncReloadEnabled = false,
NESTED_OBJECT_DELIMITER = '.',
loaderCache,
directivePriority = 0,
statefulFilter = true,
uniformLanguageTagResolver = 'default',
languageTagResolver = {
'default': function (tag) {
return (tag || '').split('-').join('_');
},
java: function (tag) {
var temp = (tag || '').split('-').join('_');
var parts = temp.split('_');
return parts.length > 1 ? (parts[0].toLowerCase() + '_' + parts[1].toUpperCase()) : temp;
},
bcp47: function (tag) {
var temp = (tag || '').split('_').join('-');
var parts = temp.split('-');
return parts.length > 1 ? (parts[0].toLowerCase() + '-' + parts[1].toUpperCase()) : temp;
}
};
var version = '2.7.2';
// tries to determine the browsers language
var getFirstBrowserLanguage = function () {
// internal purpose only
if (angular.isFunction(pascalprechtTranslateOverrider.getLocale)) {
return pascalprechtTranslateOverrider.getLocale();
}
var nav = $windowProvider.$get().navigator,
browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],
i,
language;
// support for HTML 5.1 "navigator.languages"
if (angular.isArray(nav.languages)) {
for (i = 0; i < nav.languages.length; i++) {
language = nav.languages[i];
if (language && language.length) {
return language;
}
}
}
// support for other well known properties in browsers
for (i = 0; i < browserLanguagePropertyKeys.length; i++) {
language = nav[browserLanguagePropertyKeys[i]];
if (language && language.length) {
return language;
}
}
return null;
};
getFirstBrowserLanguage.displayName = 'angular-translate/service: getFirstBrowserLanguage';
// tries to determine the browsers locale
var getLocale = function () {
var locale = getFirstBrowserLanguage() || '';
if (languageTagResolver[uniformLanguageTagResolver]) {
locale = languageTagResolver[uniformLanguageTagResolver](locale);
}
return locale;
};
getLocale.displayName = 'angular-translate/service: getLocale';
/**
* @name indexOf
* @private
*
* @description
* indexOf polyfill. Kinda sorta.
*
* @param {array} array Array to search in.
* @param {string} searchElement Element to search for.
*
* @returns {int} Index of search element.
*/
var indexOf = function(array, searchElement) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === searchElement) {
return i;
}
}
return -1;
};
/**
* @name trim
* @private
*
* @description
* trim polyfill
*
* @returns {string} The string stripped of whitespace from both ends
*/
var trim = function() {
return this.toString().replace(/^\s+|\s+$/g, '');
};
var negotiateLocale = function (preferred) {
var avail = [],
locale = angular.lowercase(preferred),
i = 0,
n = $availableLanguageKeys.length;
for (; i < n; i++) {
avail.push(angular.lowercase($availableLanguageKeys[i]));
}
if (indexOf(avail, locale) > -1) {
return preferred;
}
if ($languageKeyAliases) {
var alias;
for (var langKeyAlias in $languageKeyAliases) {
var hasWildcardKey = false;
var hasExactKey = Object.prototype.hasOwnProperty.call($languageKeyAliases, langKeyAlias) &&
angular.lowercase(langKeyAlias) === angular.lowercase(preferred);
if (langKeyAlias.slice(-1) === '*') {
hasWildcardKey = langKeyAlias.slice(0, -1) === preferred.slice(0, langKeyAlias.length-1);
}
if (hasExactKey || hasWildcardKey) {
alias = $languageKeyAliases[langKeyAlias];
if (indexOf(avail, angular.lowercase(alias)) > -1) {
return alias;
}
}
}
}
if (preferred) {
var parts = preferred.split('_');
if (parts.length > 1 && indexOf(avail, angular.lowercase(parts[0])) > -1) {
return parts[0];
}
}
// If everything fails, just return the preferred, unchanged.
return preferred;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#translations
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a new translation table for specific language key.
*
* To register a translation table for specific language, pass a defined language
* key as first parameter.
*
* <pre>
* // register translation table for language: 'de_DE'
* $translateProvider.translations('de_DE', {
* 'GREETING': 'Hallo Welt!'
* });
*
* // register another one
* $translateProvider.translations('en_US', {
* 'GREETING': 'Hello world!'
* });
* </pre>
*
* When registering multiple translation tables for for the same language key,
* the actual translation table gets extended. This allows you to define module
* specific translation which only get added, once a specific module is loaded in
* your app.
*
* Invoking this method with no arguments returns the translation table which was
* registered with no language key. Invoking it with a language key returns the
* related translation table.
*
* @param {string} key A language key.
* @param {object} translationTable A plain old JavaScript object that represents a translation table.
*
*/
var translations = function (langKey, translationTable) {
if (!langKey && !translationTable) {
return $translationTable;
}
if (langKey && !translationTable) {
if (angular.isString(langKey)) {
return $translationTable[langKey];
}
} else {
if (!angular.isObject($translationTable[langKey])) {
$translationTable[langKey] = {};
}
angular.extend($translationTable[langKey], flatObject(translationTable));
}
return this;
};
this.translations = translations;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#cloakClassName
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
*
* Let's you change the class name for `translate-cloak` directive.
* Default class name is `translate-cloak`.
*
* @param {string} name translate-cloak class name
*/
this.cloakClassName = function (name) {
if (!name) {
return $cloakClassName;
}
$cloakClassName = name;
return this;
};
/**
* @name flatObject
* @private
*
* @description
* Flats an object. This function is used to flatten given translation data with
* namespaces, so they are later accessible via dot notation.
*/
var flatObject = function (data, path, result, prevKey) {
var key, keyWithPath, keyWithShortPath, val;
if (!path) {
path = [];
}
if (!result) {
result = {};
}
for (key in data) {
if (!Object.prototype.hasOwnProperty.call(data, key)) {
continue;
}
val = data[key];
if (angular.isObject(val)) {
flatObject(val, path.concat(key), result, key);
} else {
keyWithPath = path.length ? ('' + path.join(NESTED_OBJECT_DELIMITER) + NESTED_OBJECT_DELIMITER + key) : key;
if(path.length && key === prevKey){
// Create shortcut path (foo.bar == foo.bar.bar)
keyWithShortPath = '' + path.join(NESTED_OBJECT_DELIMITER);
// Link it to original path
result[keyWithShortPath] = '@:' + keyWithPath;
}
result[keyWithPath] = val;
}
}
return result;
};
flatObject.displayName = 'flatObject';
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#addInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Adds interpolation services to angular-translate, so it can manage them.
*
* @param {object} factory Interpolation service factory
*/
this.addInterpolation = function (factory) {
$interpolatorFactories.push(factory);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMessageFormatInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use interpolation functionality of messageformat.js.
* This is useful when having high level pluralization and gender selection.
*/
this.useMessageFormatInterpolation = function () {
return this.useInterpolation('$translateMessageFormatInterpolation');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useInterpolation
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate which interpolation style to use as default, application-wide.
* Simply pass a factory/service name. The interpolation service has to implement
* the correct interface.
*
* @param {string} factory Interpolation service name.
*/
this.useInterpolation = function (factory) {
$interpolationFactory = factory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useSanitizeStrategy
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Simply sets a sanitation strategy type.
*
* @param {string} value Strategy type.
*/
this.useSanitizeValueStrategy = function (value) {
$translateSanitizationProvider.useStrategy(value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#preferredLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which of the registered translation tables to use for translation
* at initial startup by passing a language key. Similar to `$translateProvider#use`
* only that it says which language to **prefer**.
*
* @param {string} langKey A language key.
*
*/
this.preferredLanguage = function(langKey) {
setupPreferredLanguage(langKey);
return this;
};
var setupPreferredLanguage = function (langKey) {
if (langKey) {
$preferredLanguage = langKey;
}
return $preferredLanguage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicator
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found. E.g. when
* setting the indicator as 'X' and one tries to translate a translation id
* called `NOT_FOUND`, this will result in `X NOT_FOUND X`.
*
* Internally this methods sets a left indicator and a right indicator using
* `$translateProvider.translationNotFoundIndicatorLeft()` and
* `$translateProvider.translationNotFoundIndicatorRight()`.
*
* **Note**: These methods automatically add a whitespace between the indicators
* and the translation id.
*
* @param {string} indicator An indicator, could be any string.
*/
this.translationNotFoundIndicator = function (indicator) {
this.translationNotFoundIndicatorLeft(indicator);
this.translationNotFoundIndicatorRight(indicator);
return this;
};
/**
* ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found left to the
* translation id.
*
* @param {string} indicator An indicator.
*/
this.translationNotFoundIndicatorLeft = function (indicator) {
if (!indicator) {
return $notFoundIndicatorLeft;
}
$notFoundIndicatorLeft = indicator;
return this;
};
/**
* ngdoc function
* @name pascalprecht.translate.$translateProvider#translationNotFoundIndicatorLeft
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets an indicator which is used when a translation isn't found right to the
* translation id.
*
* @param {string} indicator An indicator.
*/
this.translationNotFoundIndicatorRight = function (indicator) {
if (!indicator) {
return $notFoundIndicatorRight;
}
$notFoundIndicatorRight = indicator;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#fallbackLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which of the registered translation tables to use when missing translations
* at initial startup by passing a language key. Similar to `$translateProvider#use`
* only that it says which language to **fallback**.
*
* @param {string||array} langKey A language key.
*
*/
this.fallbackLanguage = function (langKey) {
fallbackStack(langKey);
return this;
};
var fallbackStack = function (langKey) {
if (langKey) {
if (angular.isString(langKey)) {
$fallbackWasString = true;
$fallbackLanguage = [ langKey ];
} else if (angular.isArray(langKey)) {
$fallbackWasString = false;
$fallbackLanguage = langKey;
}
if (angular.isString($preferredLanguage) && indexOf($fallbackLanguage, $preferredLanguage) < 0) {
$fallbackLanguage.push($preferredLanguage);
}
return this;
} else {
if ($fallbackWasString) {
return $fallbackLanguage[0];
} else {
return $fallbackLanguage;
}
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#use
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Set which translation table to use for translation by given language key. When
* trying to 'use' a language which isn't provided, it'll throw an error.
*
* You actually don't have to use this method since `$translateProvider#preferredLanguage`
* does the job too.
*
* @param {string} langKey A language key.
*/
this.use = function (langKey) {
if (langKey) {
if (!$translationTable[langKey] && (!$loaderFactory)) {
// only throw an error, when not loading translation data asynchronously
throw new Error('$translateProvider couldn\'t find translationTable for langKey: \'' + langKey + '\'');
}
$uses = langKey;
return this;
}
return $uses;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#storageKey
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells the module which key must represent the choosed language by a user in the storage.
*
* @param {string} key A key for the storage.
*/
var storageKey = function(key) {
if (!key) {
if ($storagePrefix) {
return $storagePrefix + $storageKey;
}
return $storageKey;
}
$storageKey = key;
return this;
};
this.storageKey = storageKey;
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useUrlLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateUrlLoader` extension service as loader.
*
* @param {string} url Url
* @param {Object=} options Optional configuration object
*/
this.useUrlLoader = function (url, options) {
return this.useLoader('$translateUrlLoader', angular.extend({ url: url }, options));
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useStaticFilesLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateStaticFilesLoader` extension service as loader.
*
* @param {Object=} options Optional configuration object
*/
this.useStaticFilesLoader = function (options) {
return this.useLoader('$translateStaticFilesLoader', options);
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLoader
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use any other service as loader.
*
* @param {string} loaderFactory Factory name to use
* @param {Object=} options Optional configuration object
*/
this.useLoader = function (loaderFactory, options) {
$loaderFactory = loaderFactory;
$loaderOptions = options || {};
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLocalStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateLocalStorage` service as storage layer.
*
*/
this.useLocalStorage = function () {
return this.useStorage('$translateLocalStorage');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useCookieStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use `$translateCookieStorage` service as storage layer.
*/
this.useCookieStorage = function () {
return this.useStorage('$translateCookieStorage');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useStorage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use custom service as storage layer.
*/
this.useStorage = function (storageFactory) {
$storageFactory = storageFactory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#storagePrefix
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets prefix for storage key.
*
* @param {string} prefix Storage key prefix
*/
this.storagePrefix = function (prefix) {
if (!prefix) {
return prefix;
}
$storagePrefix = prefix;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMissingTranslationHandlerLog
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to use built-in log handler when trying to translate
* a translation Id which doesn't exist.
*
* This is actually a shortcut method for `useMissingTranslationHandler()`.
*
*/
this.useMissingTranslationHandlerLog = function () {
return this.useMissingTranslationHandler('$translateMissingTranslationHandlerLog');
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useMissingTranslationHandler
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Expects a factory name which later gets instantiated with `$injector`.
* This method can be used to tell angular-translate to use a custom
* missingTranslationHandler. Just build a factory which returns a function
* and expects a translation id as argument.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.useMissingTranslationHandler('customHandler');
* });
*
* app.factory('customHandler', function (dep1, dep2) {
* return function (translationId) {
* // something with translationId and dep1 and dep2
* };
* });
* </pre>
*
* @param {string} factory Factory name
*/
this.useMissingTranslationHandler = function (factory) {
$missingTranslationHandlerFactory = factory;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#usePostCompiling
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* If post compiling is enabled, all translated values will be processed
* again with AngularJS' $compile.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.usePostCompiling(true);
* });
* </pre>
*
* @param {string} factory Factory name
*/
this.usePostCompiling = function (value) {
$postCompilingEnabled = !(!value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#forceAsyncReload
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* If force async reload is enabled, async loader will always be called
* even if $translationTable already contains the language key, adding
* possible new entries to the $translationTable.
*
* Example:
* <pre>
* app.config(function ($translateProvider) {
* $translateProvider.forceAsyncReload(true);
* });
* </pre>
*
* @param {boolean} value - valid values are true or false
*/
this.forceAsyncReload = function (value) {
$forceAsyncReloadEnabled = !(!value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#uniformLanguageTag
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate which language tag should be used as a result when determining
* the current browser language.
*
* This setting must be set before invoking {@link pascalprecht.translate.$translateProvider#methods_determinePreferredLanguage determinePreferredLanguage()}.
*
* <pre>
* $translateProvider
* .uniformLanguageTag('bcp47')
* .determinePreferredLanguage()
* </pre>
*
* The resolver currently supports:
* * default
* (traditionally: hyphens will be converted into underscores, i.e. en-US => en_US)
* en-US => en_US
* en_US => en_US
* en-us => en_us
* * java
* like default, but the second part will be always in uppercase
* en-US => en_US
* en_US => en_US
* en-us => en_US
* * BCP 47 (RFC 4646 & 4647)
* en-US => en-US
* en_US => en-US
* en-us => en-US
*
* See also:
* * http://en.wikipedia.org/wiki/IETF_language_tag
* * http://www.w3.org/International/core/langtags/
* * http://tools.ietf.org/html/bcp47
*
* @param {string|object} options - options (or standard)
* @param {string} options.standard - valid values are 'default', 'bcp47', 'java'
*/
this.uniformLanguageTag = function (options) {
if (!options) {
options = {};
} else if (angular.isString(options)) {
options = {
standard: options
};
}
uniformLanguageTagResolver = options.standard;
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#determinePreferredLanguage
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Tells angular-translate to try to determine on its own which language key
* to set as preferred language. When `fn` is given, angular-translate uses it
* to determine a language key, otherwise it uses the built-in `getLocale()`
* method.
*
* The `getLocale()` returns a language key in the format `[lang]_[country]` or
* `[lang]` depending on what the browser provides.
*
* Use this method at your own risk, since not all browsers return a valid
* locale (see {@link pascalprecht.translate.$translateProvider#methods_uniformLanguageTag uniformLanguageTag()}).
*
* @param {Function=} fn Function to determine a browser's locale
*/
this.determinePreferredLanguage = function (fn) {
var locale = (fn && angular.isFunction(fn)) ? fn() : getLocale();
if (!$availableLanguageKeys.length) {
$preferredLanguage = locale;
} else {
$preferredLanguage = negotiateLocale(locale);
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#registerAvailableLanguageKeys
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a set of language keys the app will work with. Use this method in
* combination with
* {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.
* When available languages keys are registered, angular-translate
* tries to find the best fitting language key depending on the browsers locale,
* considering your language key convention.
*
* @param {object} languageKeys Array of language keys the your app will use
* @param {object=} aliases Alias map.
*/
this.registerAvailableLanguageKeys = function (languageKeys, aliases) {
if (languageKeys) {
$availableLanguageKeys = languageKeys;
if (aliases) {
$languageKeyAliases = aliases;
}
return this;
}
return $availableLanguageKeys;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#useLoaderCache
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Registers a cache for internal $http based loaders.
* {@link pascalprecht.translate.$translateProvider#determinePreferredLanguage determinePreferredLanguage}.
* When false the cache will be disabled (default). When true or undefined
* the cache will be a default (see $cacheFactory). When an object it will
* be treat as a cache object itself: the usage is $http({cache: cache})
*
* @param {object} cache boolean, string or cache-object
*/
this.useLoaderCache = function (cache) {
if (cache === false) {
// disable cache
loaderCache = undefined;
} else if (cache === true) {
// enable cache using AJS defaults
loaderCache = true;
} else if (typeof(cache) === 'undefined') {
// enable cache using default
loaderCache = '$translationCache';
} else if (cache) {
// enable cache using given one (see $cacheFactory)
loaderCache = cache;
}
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#directivePriority
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Sets the default priority of the translate directive. The standard value is `0`.
* Calling this function without an argument will return the current value.
*
* @param {number} priority for the translate-directive
*/
this.directivePriority = function (priority) {
if (priority === undefined) {
// getter
return directivePriority;
} else {
// setter with chaining
directivePriority = priority;
return this;
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateProvider#statefulFilter
* @methodOf pascalprecht.translate.$translateProvider
*
* @description
* Since AngularJS 1.3, filters which are not stateless (depending at the scope)
* have to explicit define this behavior.
* Sets whether the translate filter should be stateful or stateless. The standard value is `true`
* meaning being stateful.
* Calling this function without an argument will return the current value.
*
* @param {boolean} state - defines the state of the filter
*/
this.statefulFilter = function (state) {
if (state === undefined) {
// getter
return statefulFilter;
} else {
// setter with chaining
statefulFilter = state;
return this;
}
};
/**
* @ngdoc object
* @name pascalprecht.translate.$translate
* @requires $interpolate
* @requires $log
* @requires $rootScope
* @requires $q
*
* @description
* The `$translate` service is the actual core of angular-translate. It expects a translation id
* and optional interpolate parameters to translate contents.
*
* <pre>
* $translate('HEADLINE_TEXT').then(function (translation) {
* $scope.translatedText = translation;
* });
* </pre>
*
* @param {string|array} translationId A token which represents a translation id
* This can be optionally an array of translation ids which
* results that the function returns an object where each key
* is the translation id and the value the translation.
* @param {object=} interpolateParams An object hash for dynamic values
* @param {string} interpolationId The id of the interpolation to use
* @returns {object} promise
*/
this.$get = [
'$log',
'$injector',
'$rootScope',
'$q',
function ($log, $injector, $rootScope, $q) {
var Storage,
defaultInterpolator = $injector.get($interpolationFactory || '$translateDefaultInterpolation'),
pendingLoader = false,
interpolatorHashMap = {},
langPromises = {},
fallbackIndex,
startFallbackIteration;
var $translate = function (translationId, interpolateParams, interpolationId, defaultTranslationText) {
// Duck detection: If the first argument is an array, a bunch of translations was requested.
// The result is an object.
if (angular.isArray(translationId)) {
// Inspired by Q.allSettled by Kris Kowal
// https://github.com/kriskowal/q/blob/b0fa72980717dc202ffc3cbf03b936e10ebbb9d7/q.js#L1553-1563
// This transforms all promises regardless resolved or rejected
var translateAll = function (translationIds) {
var results = {}; // storing the actual results
var promises = []; // promises to wait for
// Wraps the promise a) being always resolved and b) storing the link id->value
var translate = function (translationId) {
var deferred = $q.defer();
var regardless = function (value) {
results[translationId] = value;
deferred.resolve([translationId, value]);
};
// we don't care whether the promise was resolved or rejected; just store the values
$translate(translationId, interpolateParams, interpolationId, defaultTranslationText).then(regardless, regardless);
return deferred.promise;
};
for (var i = 0, c = translationIds.length; i < c; i++) {
promises.push(translate(translationIds[i]));
}
// wait for all (including storing to results)
return $q.all(promises).then(function () {
// return the results
return results;
});
};
return translateAll(translationId);
}
var deferred = $q.defer();
// trim off any whitespace
if (translationId) {
translationId = trim.apply(translationId);
}
var promiseToWaitFor = (function () {
var promise = $preferredLanguage ?
langPromises[$preferredLanguage] :
langPromises[$uses];
fallbackIndex = 0;
if ($storageFactory && !promise) {
// looks like there's no pending promise for $preferredLanguage or
// $uses. Maybe there's one pending for a language that comes from
// storage.
var langKey = Storage.get($storageKey);
promise = langPromises[langKey];
if ($fallbackLanguage && $fallbackLanguage.length) {
var index = indexOf($fallbackLanguage, langKey);
// maybe the language from storage is also defined as fallback language
// we increase the fallback language index to not search in that language
// as fallback, since it's probably the first used language
// in that case the index starts after the first element
fallbackIndex = (index === 0) ? 1 : 0;
// but we can make sure to ALWAYS fallback to preferred language at least
if (indexOf($fallbackLanguage, $preferredLanguage) < 0) {
$fallbackLanguage.push($preferredLanguage);
}
}
}
return promise;
}());
if (!promiseToWaitFor) {
// no promise to wait for? okay. Then there's no loader registered
// nor is a one pending for language that comes from storage.
// We can just translate.
determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText).then(deferred.resolve, deferred.reject);
} else {
var promiseResolved = function () {
determineTranslation(translationId, interpolateParams, interpolationId, defaultTranslationText).then(deferred.resolve, deferred.reject);
};
promiseResolved.displayName = 'promiseResolved';
promiseToWaitFor['finally'](promiseResolved, deferred.reject);
}
return deferred.promise;
};
/**
* @name applyNotFoundIndicators
* @private
*
* @description
* Applies not fount indicators to given translation id, if needed.
* This function gets only executed, if a translation id doesn't exist,
* which is why a translation id is expected as argument.
*
* @param {string} translationId Translation id.
* @returns {string} Same as given translation id but applied with not found
* indicators.
*/
var applyNotFoundIndicators = function (translationId) {
// applying notFoundIndicators
if ($notFoundIndicatorLeft) {
translationId = [$notFoundIndicatorLeft, translationId].join(' ');
}
if ($notFoundIndicatorRight) {
translationId = [translationId, $notFoundIndicatorRight].join(' ');
}
return translationId;
};
/**
* @name useLanguage
* @private
*
* @description
* Makes actual use of a language by setting a given language key as used
* language and informs registered interpolators to also use the given
* key as locale.
*
* @param {key} Locale key.
*/
var useLanguage = function (key) {
$uses = key;
$rootScope.$emit('$translateChangeSuccess', {language: key});
if ($storageFactory) {
Storage.put($translate.storageKey(), $uses);
}
// inform default interpolator
defaultInterpolator.setLocale($uses);
var eachInterpolator = function (interpolator, id) {
interpolatorHashMap[id].setLocale($uses);
};
eachInterpolator.displayName = 'eachInterpolatorLocaleSetter';
// inform all others too!
angular.forEach(interpolatorHashMap, eachInterpolator);
$rootScope.$emit('$translateChangeEnd', {language: key});
};
/**
* @name loadAsync
* @private
*
* @description
* Kicks of registered async loader using `$injector` and applies existing
* loader options. When resolved, it updates translation tables accordingly
* or rejects with given language key.
*
* @param {string} key Language key.
* @return {Promise} A promise.
*/
var loadAsync = function (key) {
if (!key) {
throw 'No language key specified for loading.';
}
var deferred = $q.defer();
$rootScope.$emit('$translateLoadingStart', {language: key});
pendingLoader = true;
var cache = loaderCache;
if (typeof(cache) === 'string') {
// getting on-demand instance of loader
cache = $injector.get(cache);
}
var loaderOptions = angular.extend({}, $loaderOptions, {
key: key,
$http: angular.extend({}, {
cache: cache
}, $loaderOptions.$http)
});
var onLoaderSuccess = function (data) {
var translationTable = {};
$rootScope.$emit('$translateLoadingSuccess', {language: key});
if (angular.isArray(data)) {
angular.forEach(data, function (table) {
angular.extend(translationTable, flatObject(table));
});
} else {
angular.extend(translationTable, flatObject(data));
}
pendingLoader = false;
deferred.resolve({
key: key,
table: translationTable
});
$rootScope.$emit('$translateLoadingEnd', {language: key});
};
onLoaderSuccess.displayName = 'onLoaderSuccess';
var onLoaderError = function (key) {
$rootScope.$emit('$translateLoadingError', {language: key});
deferred.reject(key);
$rootScope.$emit('$translateLoadingEnd', {language: key});
};
onLoaderError.displayName = 'onLoaderError';
$injector.get($loaderFactory)(loaderOptions)
.then(onLoaderSuccess, onLoaderError);
return deferred.promise;
};
if ($storageFactory) {
Storage = $injector.get($storageFactory);
if (!Storage.get || !Storage.put) {
throw new Error('Couldn\'t use storage \'' + $storageFactory + '\', missing get() or put() method!');
}
}
// if we have additional interpolations that were added via
// $translateProvider.addInterpolation(), we have to map'em
if ($interpolatorFactories.length) {
var eachInterpolationFactory = function (interpolatorFactory) {
var interpolator = $injector.get(interpolatorFactory);
// setting initial locale for each interpolation service
interpolator.setLocale($preferredLanguage || $uses);
// make'em recognizable through id
interpolatorHashMap[interpolator.getInterpolationIdentifier()] = interpolator;
};
eachInterpolationFactory.displayName = 'interpolationFactoryAdder';
angular.forEach($interpolatorFactories, eachInterpolationFactory);
}
/**
* @name getTranslationTable
* @private
*
* @description
* Returns a promise that resolves to the translation table
* or is rejected if an error occurred.
*
* @param langKey
* @returns {Q.promise}
*/
var getTranslationTable = function (langKey) {
var deferred = $q.defer();
if (Object.prototype.hasOwnProperty.call($translationTable, langKey)) {
deferred.resolve($translationTable[langKey]);
} else if (langPromises[langKey]) {
var onResolve = function (data) {
translations(data.key, data.table);
deferred.resolve(data.table);
};
onResolve.displayName = 'translationTableResolver';
langPromises[langKey].then(onResolve, deferred.reject);
} else {
deferred.reject();
}
return deferred.promise;
};
/**
* @name getFallbackTranslation
* @private
*
* @description
* Returns a promise that will resolve to the translation
* or be rejected if no translation was found for the language.
* This function is currently only used for fallback language translation.
*
* @param langKey The language to translate to.
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise}
*/
var getFallbackTranslation = function (langKey, translationId, interpolateParams, Interpolator) {
var deferred = $q.defer();
var onResolve = function (translationTable) {
if (Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
Interpolator.setLocale(langKey);
var translation = translationTable[translationId];
if (translation.substr(0, 2) === '@:') {
getFallbackTranslation(langKey, translation.substr(2), interpolateParams, Interpolator)
.then(deferred.resolve, deferred.reject);
} else {
deferred.resolve(Interpolator.interpolate(translationTable[translationId], interpolateParams));
}
Interpolator.setLocale($uses);
} else {
deferred.reject();
}
};
onResolve.displayName = 'fallbackTranslationResolver';
getTranslationTable(langKey).then(onResolve, deferred.reject);
return deferred.promise;
};
/**
* @name getFallbackTranslationInstant
* @private
*
* @description
* Returns a translation
* This function is currently only used for fallback language translation.
*
* @param langKey The language to translate to.
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {string} translation
*/
var getFallbackTranslationInstant = function (langKey, translationId, interpolateParams, Interpolator) {
var result, translationTable = $translationTable[langKey];
if (translationTable && Object.prototype.hasOwnProperty.call(translationTable, translationId)) {
Interpolator.setLocale(langKey);
result = Interpolator.interpolate(translationTable[translationId], interpolateParams);
if (result.substr(0, 2) === '@:') {
return getFallbackTranslationInstant(langKey, result.substr(2), interpolateParams, Interpolator);
}
Interpolator.setLocale($uses);
}
return result;
};
/**
* @name translateByHandler
* @private
*
* Translate by missing translation handler.
*
* @param translationId
* @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is
* absent
*/
var translateByHandler = function (translationId, interpolateParams) {
// If we have a handler factory - we might also call it here to determine if it provides
// a default text for a translationid that can't be found anywhere in our tables
if ($missingTranslationHandlerFactory) {
var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses, interpolateParams);
if (resultString !== undefined) {
return resultString;
} else {
return translationId;
}
} else {
return translationId;
}
};
/**
* @name resolveForFallbackLanguage
* @private
*
* Recursive helper function for fallbackTranslation that will sequentially look
* for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
*
* @param fallbackLanguageIndex
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise} Promise that will resolve to the translation.
*/
var resolveForFallbackLanguage = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator, defaultTranslationText) {
var deferred = $q.defer();
if (fallbackLanguageIndex < $fallbackLanguage.length) {
var langKey = $fallbackLanguage[fallbackLanguageIndex];
getFallbackTranslation(langKey, translationId, interpolateParams, Interpolator).then(
deferred.resolve,
function () {
// Look in the next fallback language for a translation.
// It delays the resolving by passing another promise to resolve.
resolveForFallbackLanguage(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator, defaultTranslationText).then(deferred.resolve);
}
);
} else {
// No translation found in any fallback language
// if a default translation text is set in the directive, then return this as a result
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
// if no default translation is set and an error handler is defined, send it to the handler
// and then return the result
deferred.resolve(translateByHandler(translationId, interpolateParams));
}
}
return deferred.promise;
};
/**
* @name resolveForFallbackLanguageInstant
* @private
*
* Recursive helper function for fallbackTranslation that will sequentially look
* for a translation in the fallbackLanguages starting with fallbackLanguageIndex.
*
* @param fallbackLanguageIndex
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {string} translation
*/
var resolveForFallbackLanguageInstant = function (fallbackLanguageIndex, translationId, interpolateParams, Interpolator) {
var result;
if (fallbackLanguageIndex < $fallbackLanguage.length) {
var langKey = $fallbackLanguage[fallbackLanguageIndex];
result = getFallbackTranslationInstant(langKey, translationId, interpolateParams, Interpolator);
if (!result) {
result = resolveForFallbackLanguageInstant(fallbackLanguageIndex + 1, translationId, interpolateParams, Interpolator);
}
}
return result;
};
/**
* Translates with the usage of the fallback languages.
*
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {Q.promise} Promise, that resolves to the translation.
*/
var fallbackTranslation = function (translationId, interpolateParams, Interpolator, defaultTranslationText) {
// Start with the fallbackLanguage with index 0
return resolveForFallbackLanguage((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator, defaultTranslationText);
};
/**
* Translates with the usage of the fallback languages.
*
* @param translationId
* @param interpolateParams
* @param Interpolator
* @returns {String} translation
*/
var fallbackTranslationInstant = function (translationId, interpolateParams, Interpolator) {
// Start with the fallbackLanguage with index 0
return resolveForFallbackLanguageInstant((startFallbackIteration>0 ? startFallbackIteration : fallbackIndex), translationId, interpolateParams, Interpolator);
};
var determineTranslation = function (translationId, interpolateParams, interpolationId, defaultTranslationText) {
var deferred = $q.defer();
var table = $uses ? $translationTable[$uses] : $translationTable,
Interpolator = (interpolationId) ? interpolatorHashMap[interpolationId] : defaultInterpolator;
// if the translation id exists, we can just interpolate it
if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
var translation = table[translationId];
// If using link, rerun $translate with linked translationId and return it
if (translation.substr(0, 2) === '@:') {
$translate(translation.substr(2), interpolateParams, interpolationId, defaultTranslationText)
.then(deferred.resolve, deferred.reject);
} else {
deferred.resolve(Interpolator.interpolate(translation, interpolateParams));
}
} else {
var missingTranslationHandlerTranslation;
// for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
if ($missingTranslationHandlerFactory && !pendingLoader) {
missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
}
// since we couldn't translate the inital requested translation id,
// we try it now with one or more fallback languages, if fallback language(s) is
// configured.
if ($uses && $fallbackLanguage && $fallbackLanguage.length) {
fallbackTranslation(translationId, interpolateParams, Interpolator, defaultTranslationText)
.then(function (translation) {
deferred.resolve(translation);
}, function (_translationId) {
deferred.reject(applyNotFoundIndicators(_translationId));
});
} else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
// looks like the requested translation id doesn't exists.
// Now, if there is a registered handler for missing translations and no
// asyncLoader is pending, we execute the handler
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
deferred.resolve(missingTranslationHandlerTranslation);
}
} else {
if (defaultTranslationText) {
deferred.resolve(defaultTranslationText);
} else {
deferred.reject(applyNotFoundIndicators(translationId));
}
}
}
return deferred.promise;
};
var determineTranslationInstant = function (translationId, interpolateParams, interpolationId) {
var result, table = $uses ? $translationTable[$uses] : $translationTable,
Interpolator = defaultInterpolator;
// if the interpolation id exists use custom interpolator
if (interpolatorHashMap && Object.prototype.hasOwnProperty.call(interpolatorHashMap, interpolationId)) {
Interpolator = interpolatorHashMap[interpolationId];
}
// if the translation id exists, we can just interpolate it
if (table && Object.prototype.hasOwnProperty.call(table, translationId)) {
var translation = table[translationId];
// If using link, rerun $translate with linked translationId and return it
if (translation.substr(0, 2) === '@:') {
result = determineTranslationInstant(translation.substr(2), interpolateParams, interpolationId);
} else {
result = Interpolator.interpolate(translation, interpolateParams);
}
} else {
var missingTranslationHandlerTranslation;
// for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise
if ($missingTranslationHandlerFactory && !pendingLoader) {
missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams);
}
// since we couldn't translate the inital requested translation id,
// we try it now with one or more fallback languages, if fallback language(s) is
// configured.
if ($uses && $fallbackLanguage && $fallbackLanguage.length) {
fallbackIndex = 0;
result = fallbackTranslationInstant(translationId, interpolateParams, Interpolator);
} else if ($missingTranslationHandlerFactory && !pendingLoader && missingTranslationHandlerTranslation) {
// looks like the requested translation id doesn't exists.
// Now, if there is a registered handler for missing translations and no
// asyncLoader is pending, we execute the handler
result = missingTranslationHandlerTranslation;
} else {
result = applyNotFoundIndicators(translationId);
}
}
return result;
};
var clearNextLangAndPromise = function(key) {
if ($nextLang === key) {
$nextLang = undefined;
}
langPromises[key] = undefined;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#preferredLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key for the preferred language.
*
* @param {string} langKey language String or Array to be used as preferredLanguage (changing at runtime)
*
* @return {string} preferred language key
*/
$translate.preferredLanguage = function (langKey) {
if(langKey) {
setupPreferredLanguage(langKey);
}
return $preferredLanguage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#cloakClassName
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the configured class name for `translate-cloak` directive.
*
* @return {string} cloakClassName
*/
$translate.cloakClassName = function () {
return $cloakClassName;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#fallbackLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key for the fallback languages or sets a new fallback stack.
*
* @param {string=} langKey language String or Array of fallback languages to be used (to change stack at runtime)
*
* @return {string||array} fallback language key
*/
$translate.fallbackLanguage = function (langKey) {
if (langKey !== undefined && langKey !== null) {
fallbackStack(langKey);
// as we might have an async loader initiated and a new translation language might have been defined
// we need to add the promise to the stack also. So - iterate.
if ($loaderFactory) {
if ($fallbackLanguage && $fallbackLanguage.length) {
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
if (!langPromises[$fallbackLanguage[i]]) {
langPromises[$fallbackLanguage[i]] = loadAsync($fallbackLanguage[i]);
}
}
}
}
$translate.use($translate.use());
}
if ($fallbackWasString) {
return $fallbackLanguage[0];
} else {
return $fallbackLanguage;
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#useFallbackLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Sets the first key of the fallback language stack to be used for translation.
* Therefore all languages in the fallback array BEFORE this key will be skipped!
*
* @param {string=} langKey Contains the langKey the iteration shall start with. Set to false if you want to
* get back to the whole stack
*/
$translate.useFallbackLanguage = function (langKey) {
if (langKey !== undefined && langKey !== null) {
if (!langKey) {
startFallbackIteration = 0;
} else {
var langKeyPosition = indexOf($fallbackLanguage, langKey);
if (langKeyPosition > -1) {
startFallbackIteration = langKeyPosition;
}
}
}
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#proposedLanguage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the language key of language that is currently loaded asynchronously.
*
* @return {string} language key
*/
$translate.proposedLanguage = function () {
return $nextLang;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#storage
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns registered storage.
*
* @return {object} Storage
*/
$translate.storage = function () {
return Storage;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#use
* @methodOf pascalprecht.translate.$translate
*
* @description
* Tells angular-translate which language to use by given language key. This method is
* used to change language at runtime. It also takes care of storing the language
* key in a configured store to let your app remember the choosed language.
*
* When trying to 'use' a language which isn't available it tries to load it
* asynchronously with registered loaders.
*
* Returns promise object with loaded language file data
* @example
* $translate.use("en_US").then(function(data){
* $scope.text = $translate("HELLO");
* });
*
* @param {string} key Language key
* @return {string} Language key
*/
$translate.use = function (key) {
if (!key) {
return $uses;
}
var deferred = $q.defer();
$rootScope.$emit('$translateChangeStart', {language: key});
// Try to get the aliased language key
var aliasedKey = negotiateLocale(key);
if (aliasedKey) {
key = aliasedKey;
}
// if there isn't a translation table for the language we've requested,
// we load it asynchronously
if (($forceAsyncReloadEnabled || !$translationTable[key]) && $loaderFactory && !langPromises[key]) {
$nextLang = key;
langPromises[key] = loadAsync(key).then(function (translation) {
translations(translation.key, translation.table);
deferred.resolve(translation.key);
useLanguage(translation.key);
return translation;
}, function (key) {
$rootScope.$emit('$translateChangeError', {language: key});
deferred.reject(key);
$rootScope.$emit('$translateChangeEnd', {language: key});
return $q.reject(key);
});
langPromises[key]['finally'](function () {
clearNextLangAndPromise(key);
});
} else if ($nextLang === key && langPromises[key]) {
// we are already loading this asynchronously
// resolve our new deferred when the old langPromise is resolved
langPromises[key].then(function (translation) {
deferred.resolve(translation.key);
return translation;
}, function (key) {
deferred.reject(key);
return $q.reject(key);
});
} else {
deferred.resolve(key);
useLanguage(key);
}
return deferred.promise;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#storageKey
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the key for the storage.
*
* @return {string} storage key
*/
$translate.storageKey = function () {
return storageKey();
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#isPostCompilingEnabled
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns whether post compiling is enabled or not
*
* @return {bool} storage key
*/
$translate.isPostCompilingEnabled = function () {
return $postCompilingEnabled;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#isForceAsyncReloadEnabled
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns whether force async reload is enabled or not
*
* @return {boolean} forceAsyncReload value
*/
$translate.isForceAsyncReloadEnabled = function () {
return $forceAsyncReloadEnabled;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#refresh
* @methodOf pascalprecht.translate.$translate
*
* @description
* Refreshes a translation table pointed by the given langKey. If langKey is not specified,
* the module will drop all existent translation tables and load new version of those which
* are currently in use.
*
* Refresh means that the module will drop target translation table and try to load it again.
*
* In case there are no loaders registered the refresh() method will throw an Error.
*
* If the module is able to refresh translation tables refresh() method will broadcast
* $translateRefreshStart and $translateRefreshEnd events.
*
* @example
* // this will drop all currently existent translation tables and reload those which are
* // currently in use
* $translate.refresh();
* // this will refresh a translation table for the en_US language
* $translate.refresh('en_US');
*
* @param {string} langKey A language key of the table, which has to be refreshed
*
* @return {promise} Promise, which will be resolved in case a translation tables refreshing
* process is finished successfully, and reject if not.
*/
$translate.refresh = function (langKey) {
if (!$loaderFactory) {
throw new Error('Couldn\'t refresh translation table, no loader registered!');
}
var deferred = $q.defer();
function resolve() {
deferred.resolve();
$rootScope.$emit('$translateRefreshEnd', {language: langKey});
}
function reject() {
deferred.reject();
$rootScope.$emit('$translateRefreshEnd', {language: langKey});
}
$rootScope.$emit('$translateRefreshStart', {language: langKey});
if (!langKey) {
// if there's no language key specified we refresh ALL THE THINGS!
var tables = [], loadingKeys = {};
// reload registered fallback languages
if ($fallbackLanguage && $fallbackLanguage.length) {
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
tables.push(loadAsync($fallbackLanguage[i]));
loadingKeys[$fallbackLanguage[i]] = true;
}
}
// reload currently used language
if ($uses && !loadingKeys[$uses]) {
tables.push(loadAsync($uses));
}
var allTranslationsLoaded = function (tableData) {
$translationTable = {};
angular.forEach(tableData, function (data) {
translations(data.key, data.table);
});
if ($uses) {
useLanguage($uses);
}
resolve();
};
allTranslationsLoaded.displayName = 'refreshPostProcessor';
$q.all(tables).then(allTranslationsLoaded, reject);
} else if ($translationTable[langKey]) {
var oneTranslationsLoaded = function (data) {
translations(data.key, data.table);
if (langKey === $uses) {
useLanguage($uses);
}
resolve();
};
oneTranslationsLoaded.displayName = 'refreshPostProcessor';
loadAsync(langKey).then(oneTranslationsLoaded, reject);
} else {
reject();
}
return deferred.promise;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#instant
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns a translation instantly from the internal state of loaded translation. All rules
* regarding the current language, the preferred language of even fallback languages will be
* used except any promise handling. If a language was not found, an asynchronous loading
* will be invoked in the background.
*
* @param {string|array} translationId A token which represents a translation id
* This can be optionally an array of translation ids which
* results that the function's promise returns an object where
* each key is the translation id and the value the translation.
* @param {object} interpolateParams Params
* @param {string} interpolationId The id of the interpolation to use
*
* @return {string|object} translation
*/
$translate.instant = function (translationId, interpolateParams, interpolationId) {
// Detect undefined and null values to shorten the execution and prevent exceptions
if (translationId === null || angular.isUndefined(translationId)) {
return translationId;
}
// Duck detection: If the first argument is an array, a bunch of translations was requested.
// The result is an object.
if (angular.isArray(translationId)) {
var results = {};
for (var i = 0, c = translationId.length; i < c; i++) {
results[translationId[i]] = $translate.instant(translationId[i], interpolateParams, interpolationId);
}
return results;
}
// We discarded unacceptable values. So we just need to verify if translationId is empty String
if (angular.isString(translationId) && translationId.length < 1) {
return translationId;
}
// trim off any whitespace
if (translationId) {
translationId = trim.apply(translationId);
}
var result, possibleLangKeys = [];
if ($preferredLanguage) {
possibleLangKeys.push($preferredLanguage);
}
if ($uses) {
possibleLangKeys.push($uses);
}
if ($fallbackLanguage && $fallbackLanguage.length) {
possibleLangKeys = possibleLangKeys.concat($fallbackLanguage);
}
for (var j = 0, d = possibleLangKeys.length; j < d; j++) {
var possibleLangKey = possibleLangKeys[j];
if ($translationTable[possibleLangKey]) {
if (typeof $translationTable[possibleLangKey][translationId] !== 'undefined') {
result = determineTranslationInstant(translationId, interpolateParams, interpolationId);
} else if ($notFoundIndicatorLeft || $notFoundIndicatorRight) {
result = applyNotFoundIndicators(translationId);
}
}
if (typeof result !== 'undefined') {
break;
}
}
if (!result && result !== '') {
// Return translation of default interpolator if not found anything.
result = defaultInterpolator.interpolate(translationId, interpolateParams);
if ($missingTranslationHandlerFactory && !pendingLoader) {
result = translateByHandler(translationId, interpolateParams);
}
}
return result;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#versionInfo
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the current version information for the angular-translate library
*
* @return {string} angular-translate version
*/
$translate.versionInfo = function () {
return version;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translate#loaderCache
* @methodOf pascalprecht.translate.$translate
*
* @description
* Returns the defined loaderCache.
*
* @return {boolean|string|object} current value of loaderCache
*/
$translate.loaderCache = function () {
return loaderCache;
};
// internal purpose only
$translate.directivePriority = function () {
return directivePriority;
};
// internal purpose only
$translate.statefulFilter = function () {
return statefulFilter;
};
if ($loaderFactory) {
// If at least one async loader is defined and there are no
// (default) translations available we should try to load them.
if (angular.equals($translationTable, {})) {
$translate.use($translate.use());
}
// Also, if there are any fallback language registered, we start
// loading them asynchronously as soon as we can.
if ($fallbackLanguage && $fallbackLanguage.length) {
var processAsyncResult = function (translation) {
translations(translation.key, translation.table);
$rootScope.$emit('$translateChangeEnd', { language: translation.key });
return translation;
};
for (var i = 0, len = $fallbackLanguage.length; i < len; i++) {
var fallbackLanguageId = $fallbackLanguage[i];
if ($forceAsyncReloadEnabled || !$translationTable[fallbackLanguageId]) {
langPromises[fallbackLanguageId] = loadAsync(fallbackLanguageId).then(processAsyncResult);
}
}
}
}
return $translate;
}
];
}
$translate.$inject = ['$STORAGE_KEY', '$windowProvider', '$translateSanitizationProvider', 'pascalprechtTranslateOverrider'];
$translate.displayName = 'displayName';
/**
* @ngdoc object
* @name pascalprecht.translate.$translateDefaultInterpolation
* @requires $interpolate
*
* @description
* Uses angular's `$interpolate` services to interpolate strings against some values.
*
* Be aware to configure a proper sanitization strategy.
*
* See also:
* * {@link pascalprecht.translate.$translateSanitization}
*
* @return {object} $translateDefaultInterpolation Interpolator service
*/
angular.module('pascalprecht.translate').factory('$translateDefaultInterpolation', $translateDefaultInterpolation);
function $translateDefaultInterpolation ($interpolate, $translateSanitization) {
'use strict';
var $translateInterpolator = {},
$locale,
$identifier = 'default';
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#setLocale
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Sets current locale (this is currently not use in this interpolation).
*
* @param {string} locale Language key or locale.
*/
$translateInterpolator.setLocale = function (locale) {
$locale = locale;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#getInterpolationIdentifier
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Returns an identifier for this interpolation service.
*
* @returns {string} $identifier
*/
$translateInterpolator.getInterpolationIdentifier = function () {
return $identifier;
};
/**
* @deprecated will be removed in 3.0
* @see {@link pascalprecht.translate.$translateSanitization}
*/
$translateInterpolator.useSanitizeValueStrategy = function (value) {
$translateSanitization.useStrategy(value);
return this;
};
/**
* @ngdoc function
* @name pascalprecht.translate.$translateDefaultInterpolation#interpolate
* @methodOf pascalprecht.translate.$translateDefaultInterpolation
*
* @description
* Interpolates given string agains given interpolate params using angulars
* `$interpolate` service.
*
* @returns {string} interpolated string.
*/
$translateInterpolator.interpolate = function (string, interpolationParams) {
interpolationParams = interpolationParams || {};
interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params');
var interpolatedText = $interpolate(string)(interpolationParams);
interpolatedText = $translateSanitization.sanitize(interpolatedText, 'text');
return interpolatedText;
};
return $translateInterpolator;
}
$translateDefaultInterpolation.$inject = ['$interpolate', '$translateSanitization'];
$translateDefaultInterpolation.displayName = '$translateDefaultInterpolation';
angular.module('pascalprecht.translate').constant('$STORAGE_KEY', 'NG_TRANSLATE_LANG_KEY');
angular.module('pascalprecht.translate')
/**
* @ngdoc directive
* @name pascalprecht.translate.directive:translate
* @requires $compile
* @requires $filter
* @requires $interpolate
* @restrict A
*
* @description
* Translates given translation id either through attribute or DOM content.
* Internally it uses `translate` filter to translate translation id. It possible to
* pass an optional `translate-values` object literal as string into translation id.
*
* @param {string=} translate Translation id which could be either string or interpolated string.
* @param {string=} translate-values Values to pass into translation id. Can be passed as object literal string or interpolated object.
* @param {string=} translate-attr-ATTR translate Translation id and put it into ATTR attribute.
* @param {string=} translate-default will be used unless translation was successful
* @param {boolean=} translate-compile (default true if present) defines locally activation of {@link pascalprecht.translate.$translateProvider#methods_usePostCompiling}
*
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="TranslateCtrl">
<pre translate="TRANSLATION_ID"></pre>
<pre translate>TRANSLATION_ID</pre>
<pre translate translate-attr-title="TRANSLATION_ID"></pre>
<pre translate="{{translationId}}"></pre>
<pre translate>{{translationId}}</pre>
<pre translate="WITH_VALUES" translate-values="{value: 5}"></pre>
<pre translate translate-values="{value: 5}">WITH_VALUES</pre>
<pre translate="WITH_VALUES" translate-values="{{values}}"></pre>
<pre translate translate-values="{{values}}">WITH_VALUES</pre>
<pre translate translate-attr-title="WITH_VALUES" translate-values="{{values}}"></pre>
</div>
</file>
<file name="script.js">
angular.module('ngView', ['pascalprecht.translate'])
.config(function ($translateProvider) {
$translateProvider.translations('en',{
'TRANSLATION_ID': 'Hello there!',
'WITH_VALUES': 'The following value is dynamic: {{value}}'
}).preferredLanguage('en');
});
angular.module('ngView').controller('TranslateCtrl', function ($scope) {
$scope.translationId = 'TRANSLATION_ID';
$scope.values = {
value: 78
};
});
</file>
<file name="scenario.js">
it('should translate', function () {
inject(function ($rootScope, $compile) {
$rootScope.translationId = 'TRANSLATION_ID';
element = $compile('<p translate="TRANSLATION_ID"></p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate="{{translationId}}"></p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate>TRANSLATION_ID</p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate>{{translationId}}</p>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('Hello there!');
element = $compile('<p translate translate-attr-title="TRANSLATION_ID"></p>')($rootScope);
$rootScope.$digest();
expect(element.attr('title')).toBe('Hello there!');
});
});
</file>
</example>
*/
.directive('translate', translateDirective);
function translateDirective($translate, $q, $interpolate, $compile, $parse, $rootScope) {
'use strict';
/**
* @name trim
* @private
*
* @description
* trim polyfill
*
* @returns {string} The string stripped of whitespace from both ends
*/
var trim = function() {
return this.toString().replace(/^\s+|\s+$/g, '');
};
return {
restrict: 'AE',
scope: true,
priority: $translate.directivePriority(),
compile: function (tElement, tAttr) {
var translateValuesExist = (tAttr.translateValues) ?
tAttr.translateValues : undefined;
var translateInterpolation = (tAttr.translateInterpolation) ?
tAttr.translateInterpolation : undefined;
var translateValueExist = tElement[0].outerHTML.match(/translate-value-+/i);
var interpolateRegExp = '^(.*)(' + $interpolate.startSymbol() + '.*' + $interpolate.endSymbol() + ')(.*)',
watcherRegExp = '^(.*)' + $interpolate.startSymbol() + '(.*)' + $interpolate.endSymbol() + '(.*)';
return function linkFn(scope, iElement, iAttr) {
scope.interpolateParams = {};
scope.preText = '';
scope.postText = '';
var translationIds = {};
var initInterpolationParams = function (interpolateParams, iAttr, tAttr) {
// initial setup
if (iAttr.translateValues) {
angular.extend(interpolateParams, $parse(iAttr.translateValues)(scope.$parent));
}
// initially fetch all attributes if existing and fill the params
if (translateValueExist) {
for (var attr in tAttr) {
if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
var attributeName = angular.lowercase(attr.substr(14, 1)) + attr.substr(15);
interpolateParams[attributeName] = tAttr[attr];
}
}
}
};
// Ensures any change of the attribute "translate" containing the id will
// be re-stored to the scope's "translationId".
// If the attribute has no content, the element's text value (white spaces trimmed off) will be used.
var observeElementTranslation = function (translationId) {
// Remove any old watcher
if (angular.isFunction(observeElementTranslation._unwatchOld)) {
observeElementTranslation._unwatchOld();
observeElementTranslation._unwatchOld = undefined;
}
if (angular.equals(translationId , '') || !angular.isDefined(translationId)) {
// Resolve translation id by inner html if required
var interpolateMatches = trim.apply(iElement.text()).match(interpolateRegExp);
// Interpolate translation id if required
if (angular.isArray(interpolateMatches)) {
scope.preText = interpolateMatches[1];
scope.postText = interpolateMatches[3];
translationIds.translate = $interpolate(interpolateMatches[2])(scope.$parent);
var watcherMatches = iElement.text().match(watcherRegExp);
if (angular.isArray(watcherMatches) && watcherMatches[2] && watcherMatches[2].length) {
observeElementTranslation._unwatchOld = scope.$watch(watcherMatches[2], function (newValue) {
translationIds.translate = newValue;
updateTranslations();
});
}
} else {
translationIds.translate = iElement.text().replace(/^\s+|\s+$/g,'');
}
} else {
translationIds.translate = translationId;
}
updateTranslations();
};
var observeAttributeTranslation = function (translateAttr) {
iAttr.$observe(translateAttr, function (translationId) {
translationIds[translateAttr] = translationId;
updateTranslations();
});
};
// initial setup with values
initInterpolationParams(scope.interpolateParams, iAttr, tAttr);
var firstAttributeChangedEvent = true;
iAttr.$observe('translate', function (translationId) {
if (typeof translationId === 'undefined') {
// case of element "<translate>xyz</translate>"
observeElementTranslation('');
} else {
// case of regular attribute
if (translationId !== '' || !firstAttributeChangedEvent) {
translationIds.translate = translationId;
updateTranslations();
}
}
firstAttributeChangedEvent = false;
});
for (var translateAttr in iAttr) {
if (iAttr.hasOwnProperty(translateAttr) && translateAttr.substr(0, 13) === 'translateAttr') {
observeAttributeTranslation(translateAttr);
}
}
iAttr.$observe('translateDefault', function (value) {
scope.defaultText = value;
});
if (translateValuesExist) {
iAttr.$observe('translateValues', function (interpolateParams) {
if (interpolateParams) {
scope.$parent.$watch(function () {
angular.extend(scope.interpolateParams, $parse(interpolateParams)(scope.$parent));
});
}
});
}
if (translateValueExist) {
var observeValueAttribute = function (attrName) {
iAttr.$observe(attrName, function (value) {
var attributeName = angular.lowercase(attrName.substr(14, 1)) + attrName.substr(15);
scope.interpolateParams[attributeName] = value;
});
};
for (var attr in iAttr) {
if (Object.prototype.hasOwnProperty.call(iAttr, attr) && attr.substr(0, 14) === 'translateValue' && attr !== 'translateValues') {
observeValueAttribute(attr);
}
}
}
// Master update function
var updateTranslations = function () {
for (var key in translationIds) {
if (translationIds.hasOwnProperty(key) && translationIds[key] !== undefined) {
updateTranslation(key, translationIds[key], scope, scope.interpolateParams, scope.defaultText);
}
}
};
// Put translation processing function outside loop
var updateTranslation = function(translateAttr, translationId, scope, interpolateParams, defaultTranslationText) {
if (translationId) {
$translate(translationId, interpolateParams, translateInterpolation, defaultTranslationText)
.then(function (translation) {
applyTranslation(translation, scope, true, translateAttr);
}, function (translationId) {
applyTranslation(translationId, scope, false, translateAttr);
});
} else {
// as an empty string cannot be translated, we can solve this using successful=false
applyTranslation(translationId, scope, false, translateAttr);
}
};
var applyTranslation = function (value, scope, successful, translateAttr) {
if (translateAttr === 'translate') {
// default translate into innerHTML
if (!successful && typeof scope.defaultText !== 'undefined') {
value = scope.defaultText;
}
iElement.html(scope.preText + value + scope.postText);
var globallyEnabled = $translate.isPostCompilingEnabled();
var locallyDefined = typeof tAttr.translateCompile !== 'undefined';
var locallyEnabled = locallyDefined && tAttr.translateCompile !== 'false';
if ((globallyEnabled && !locallyDefined) || locallyEnabled) {
$compile(iElement.contents())(scope);
}
} else {
// translate attribute
if (!successful && typeof scope.defaultText !== 'undefined') {
value = scope.defaultText;
}
var attributeName = iAttr.$attr[translateAttr];
if (attributeName.substr(0, 5) === 'data-') {
// ensure html5 data prefix is stripped
attributeName = attributeName.substr(5);
}
attributeName = attributeName.substr(15);
iElement.attr(attributeName, value);
}
};
if (translateValuesExist || translateValueExist || iAttr.translateDefault) {
scope.$watch('interpolateParams', updateTranslations, true);
}
// Ensures the text will be refreshed after the current language was changed
// w/ $translate.use(...)
var unbind = $rootScope.$on('$translateChangeSuccess', updateTranslations);
// ensure translation will be looked up at least one
if (iElement.text().length) {
if (iAttr.translate) {
observeElementTranslation(iAttr.translate);
} else {
observeElementTranslation('');
}
} else if (iAttr.translate) {
// ensure attribute will be not skipped
observeElementTranslation(iAttr.translate);
}
updateTranslations();
scope.$on('$destroy', unbind);
};
}
};
}
translateDirective.$inject = ['$translate', '$q', '$interpolate', '$compile', '$parse', '$rootScope'];
translateDirective.displayName = 'translateDirective';
angular.module('pascalprecht.translate')
/**
* @ngdoc directive
* @name pascalprecht.translate.directive:translateCloak
* @requires $rootScope
* @requires $translate
* @restrict A
*
* $description
* Adds a `translate-cloak` class name to the given element where this directive
* is applied initially and removes it, once a loader has finished loading.
*
* This directive can be used to prevent initial flickering when loading translation
* data asynchronously.
*
* The class name is defined in
* {@link pascalprecht.translate.$translateProvider#cloakClassName $translate.cloakClassName()}.
*
* @param {string=} translate-cloak If a translationId is provided, it will be used for showing
* or hiding the cloak. Basically it relies on the translation
* resolve.
*/
.directive('translateCloak', translateCloakDirective);
function translateCloakDirective($rootScope, $translate) {
'use strict';
return {
compile: function (tElement) {
var applyCloak = function () {
tElement.addClass($translate.cloakClassName());
},
removeCloak = function () {
tElement.removeClass($translate.cloakClassName());
},
removeListener = $rootScope.$on('$translateChangeEnd', function () {
removeCloak();
removeListener();
removeListener = null;
});
applyCloak();
return function linkFn(scope, iElement, iAttr) {
// Register a watcher for the defined translation allowing a fine tuned cloak
if (iAttr.translateCloak && iAttr.translateCloak.length) {
iAttr.$observe('translateCloak', function (translationId) {
$translate(translationId).then(removeCloak, applyCloak);
});
}
};
}
};
}
translateCloakDirective.$inject = ['$rootScope', '$translate'];
translateCloakDirective.displayName = 'translateCloakDirective';
angular.module('pascalprecht.translate')
/**
* @ngdoc filter
* @name pascalprecht.translate.filter:translate
* @requires $parse
* @requires pascalprecht.translate.$translate
* @function
*
* @description
* Uses `$translate` service to translate contents. Accepts interpolate parameters
* to pass dynamized values though translation.
*
* @param {string} translationId A translation id to be translated.
* @param {*=} interpolateParams Optional object literal (as hash or string) to pass values into translation.
*
* @returns {string} Translated text.
*
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="TranslateCtrl">
<pre>{{ 'TRANSLATION_ID' | translate }}</pre>
<pre>{{ translationId | translate }}</pre>
<pre>{{ 'WITH_VALUES' | translate:'{value: 5}' }}</pre>
<pre>{{ 'WITH_VALUES' | translate:values }}</pre>
</div>
</file>
<file name="script.js">
angular.module('ngView', ['pascalprecht.translate'])
.config(function ($translateProvider) {
$translateProvider.translations('en', {
'TRANSLATION_ID': 'Hello there!',
'WITH_VALUES': 'The following value is dynamic: {{value}}'
});
$translateProvider.preferredLanguage('en');
});
angular.module('ngView').controller('TranslateCtrl', function ($scope) {
$scope.translationId = 'TRANSLATION_ID';
$scope.values = {
value: 78
};
});
</file>
</example>
*/
.filter('translate', translateFilterFactory);
function translateFilterFactory($parse, $translate) {
'use strict';
var translateFilter = function (translationId, interpolateParams, interpolation) {
if (!angular.isObject(interpolateParams)) {
interpolateParams = $parse(interpolateParams)(this);
}
return $translate.instant(translationId, interpolateParams, interpolation);
};
if ($translate.statefulFilter()) {
translateFilter.$stateful = true;
}
return translateFilter;
}
translateFilterFactory.$inject = ['$parse', '$translate'];
translateFilterFactory.displayName = 'translateFilterFactory';
angular.module('pascalprecht.translate')
/**
* @ngdoc object
* @name pascalprecht.translate.$translationCache
* @requires $cacheFactory
*
* @description
* The first time a translation table is used, it is loaded in the translation cache for quick retrieval. You
* can load translation tables directly into the cache by consuming the
* `$translationCache` service directly.
*
* @return {object} $cacheFactory object.
*/
.factory('$translationCache', $translationCache);
function $translationCache($cacheFactory) {
'use strict';
return $cacheFactory('translations');
}
$translationCache.$inject = ['$cacheFactory'];
$translationCache.displayName = '$translationCache';
return 'pascalprecht.translate';
}));
},{}],7:[function(require,module,exports){
/**
* State-based routing for AngularJS
* @version v0.2.15
* @link http://angular-ui.github.com/
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = 'ui.router';
}
(function (window, angular, undefined) {
/*jshint globalstrict:true*/
/*global angular:false*/
'use strict';
var isDefined = angular.isDefined,
isFunction = angular.isFunction,
isString = angular.isString,
isObject = angular.isObject,
isArray = angular.isArray,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy;
function inherit(parent, extra) {
return extend(new (extend(function() {}, { prototype: parent }))(), extra);
}
function merge(dst) {
forEach(arguments, function(obj) {
if (obj !== dst) {
forEach(obj, function(value, key) {
if (!dst.hasOwnProperty(key)) dst[key] = value;
});
}
});
return dst;
}
/**
* Finds the common ancestor path between two states.
*
* @param {Object} first The first state.
* @param {Object} second The second state.
* @return {Array} Returns an array of state names in descending order, not including the root.
*/
function ancestors(first, second) {
var path = [];
for (var n in first.path) {
if (first.path[n] !== second.path[n]) break;
path.push(first.path[n]);
}
return path;
}
/**
* IE8-safe wrapper for `Object.keys()`.
*
* @param {Object} object A JavaScript object.
* @return {Array} Returns the keys of the object as an array.
*/
function objectKeys(object) {
if (Object.keys) {
return Object.keys(object);
}
var result = [];
forEach(object, function(val, key) {
result.push(key);
});
return result;
}
/**
* IE8-safe wrapper for `Array.prototype.indexOf()`.
*
* @param {Array} array A JavaScript array.
* @param {*} value A value to search the array for.
* @return {Number} Returns the array index value of `value`, or `-1` if not present.
*/
function indexOf(array, value) {
if (Array.prototype.indexOf) {
return array.indexOf(value, Number(arguments[2]) || 0);
}
var len = array.length >>> 0, from = Number(arguments[2]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) from += len;
for (; from < len; from++) {
if (from in array && array[from] === value) return from;
}
return -1;
}
/**
* Merges a set of parameters with all parameters inherited between the common parents of the
* current state and a given destination state.
*
* @param {Object} currentParams The value of the current state parameters ($stateParams).
* @param {Object} newParams The set of parameters which will be composited with inherited params.
* @param {Object} $current Internal definition of object representing the current state.
* @param {Object} $to Internal definition of object representing state to transition to.
*/
function inheritParams(currentParams, newParams, $current, $to) {
var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
for (var i in parents) {
if (!parents[i].params) continue;
parentParams = objectKeys(parents[i].params);
if (!parentParams.length) continue;
for (var j in parentParams) {
if (indexOf(inheritList, parentParams[j]) >= 0) continue;
inheritList.push(parentParams[j]);
inherited[parentParams[j]] = currentParams[parentParams[j]];
}
}
return extend({}, inherited, newParams);
}
/**
* Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
*
* @param {Object} a The first object.
* @param {Object} b The second object.
* @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
* it defaults to the list of keys in `a`.
* @return {Boolean} Returns `true` if the keys match, otherwise `false`.
*/
function equalForKeys(a, b, keys) {
if (!keys) {
keys = [];
for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
}
for (var i=0; i<keys.length; i++) {
var k = keys[i];
if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
}
return true;
}
/**
* Returns the subset of an object, based on a list of keys.
*
* @param {Array} keys
* @param {Object} values
* @return {Boolean} Returns a subset of `values`.
*/
function filterByKeys(keys, values) {
var filtered = {};
forEach(keys, function (name) {
filtered[name] = values[name];
});
return filtered;
}
// like _.indexBy
// when you know that your index values will be unique, or you want last-one-in to win
function indexBy(array, propName) {
var result = {};
forEach(array, function(item) {
result[item[propName]] = item;
});
return result;
}
// extracted from underscore.js
// Return a copy of the object only containing the whitelisted properties.
function pick(obj) {
var copy = {};
var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
forEach(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
}
// extracted from underscore.js
// Return a copy of the object omitting the blacklisted properties.
function omit(obj) {
var copy = {};
var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
for (var key in obj) {
if (indexOf(keys, key) == -1) copy[key] = obj[key];
}
return copy;
}
function pluck(collection, key) {
var result = isArray(collection) ? [] : {};
forEach(collection, function(val, i) {
result[i] = isFunction(key) ? key(val) : val[key];
});
return result;
}
function filter(collection, callback) {
var array = isArray(collection);
var result = array ? [] : {};
forEach(collection, function(val, i) {
if (callback(val, i)) {
result[array ? result.length : i] = val;
}
});
return result;
}
function map(collection, callback) {
var result = isArray(collection) ? [] : {};
forEach(collection, function(val, i) {
result[i] = callback(val, i);
});
return result;
}
/**
* @ngdoc overview
* @name ui.router.util
*
* @description
* # ui.router.util sub-module
*
* This module is a dependency of other sub-modules. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*
*/
angular.module('ui.router.util', ['ng']);
/**
* @ngdoc overview
* @name ui.router.router
*
* @requires ui.router.util
*
* @description
* # ui.router.router sub-module
*
* This module is a dependency of other sub-modules. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*/
angular.module('ui.router.router', ['ui.router.util']);
/**
* @ngdoc overview
* @name ui.router.state
*
* @requires ui.router.router
* @requires ui.router.util
*
* @description
* # ui.router.state sub-module
*
* This module is a dependency of the main ui.router module. Do not include this module as a dependency
* in your angular app (use {@link ui.router} module instead).
*
*/
angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
/**
* @ngdoc overview
* @name ui.router
*
* @requires ui.router.state
*
* @description
* # ui.router
*
* ## The main module for ui.router
* There are several sub-modules included with the ui.router module, however only this module is needed
* as a dependency within your angular app. The other modules are for organization purposes.
*
* The modules are:
* * ui.router - the main "umbrella" module
* * ui.router.router -
*
* *You'll need to include **only** this module as the dependency within your angular app.*
*
* <pre>
* <!doctype html>
* <html ng-app="myApp">
* <head>
* <script src="js/angular.js"></script>
* <!-- Include the ui-router script -->
* <script src="js/angular-ui-router.min.js"></script>
* <script>
* // ...and add 'ui.router' as a dependency
* var myApp = angular.module('myApp', ['ui.router']);
* </script>
* </head>
* <body>
* </body>
* </html>
* </pre>
*/
angular.module('ui.router', ['ui.router.state']);
angular.module('ui.router.compat', ['ui.router']);
/**
* @ngdoc object
* @name ui.router.util.$resolve
*
* @requires $q
* @requires $injector
*
* @description
* Manages resolution of (acyclic) graphs of promises.
*/
$Resolve.$inject = ['$q', '$injector'];
function $Resolve( $q, $injector) {
var VISIT_IN_PROGRESS = 1,
VISIT_DONE = 2,
NOTHING = {},
NO_DEPENDENCIES = [],
NO_LOCALS = NOTHING,
NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
/**
* @ngdoc function
* @name ui.router.util.$resolve#study
* @methodOf ui.router.util.$resolve
*
* @description
* Studies a set of invocables that are likely to be used multiple times.
* <pre>
* $resolve.study(invocables)(locals, parent, self)
* </pre>
* is equivalent to
* <pre>
* $resolve.resolve(invocables, locals, parent, self)
* </pre>
* but the former is more efficient (in fact `resolve` just calls `study`
* internally).
*
* @param {object} invocables Invocable objects
* @return {function} a function to pass in locals, parent and self
*/
this.study = function (invocables) {
if (!isObject(invocables)) throw new Error("'invocables' must be an object");
var invocableKeys = objectKeys(invocables || {});
// Perform a topological sort of invocables to build an ordered plan
var plan = [], cycle = [], visited = {};
function visit(value, key) {
if (visited[key] === VISIT_DONE) return;
cycle.push(key);
if (visited[key] === VISIT_IN_PROGRESS) {
cycle.splice(0, indexOf(cycle, key));
throw new Error("Cyclic dependency: " + cycle.join(" -> "));
}
visited[key] = VISIT_IN_PROGRESS;
if (isString(value)) {
plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
} else {
var params = $injector.annotate(value);
forEach(params, function (param) {
if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
});
plan.push(key, value, params);
}
cycle.pop();
visited[key] = VISIT_DONE;
}
forEach(invocables, visit);
invocables = cycle = visited = null; // plan is all that's required
function isResolve(value) {
return isObject(value) && value.then && value.$$promises;
}
return function (locals, parent, self) {
if (isResolve(locals) && self === undefined) {
self = parent; parent = locals; locals = null;
}
if (!locals) locals = NO_LOCALS;
else if (!isObject(locals)) {
throw new Error("'locals' must be an object");
}
if (!parent) parent = NO_PARENT;
else if (!isResolve(parent)) {
throw new Error("'parent' must be a promise returned by $resolve.resolve()");
}
// To complete the overall resolution, we have to wait for the parent
// promise and for the promise for each invokable in our plan.
var resolution = $q.defer(),
result = resolution.promise,
promises = result.$$promises = {},
values = extend({}, locals),
wait = 1 + plan.length/3,
merged = false;
function done() {
// Merge parent values we haven't got yet and publish our own $$values
if (!--wait) {
if (!merged) merge(values, parent.$$values);
result.$$values = values;
result.$$promises = result.$$promises || true; // keep for isResolve()
delete result.$$inheritedValues;
resolution.resolve(values);
}
}
function fail(reason) {
result.$$failure = reason;
resolution.reject(reason);
}
// Short-circuit if parent has already failed
if (isDefined(parent.$$failure)) {
fail(parent.$$failure);
return result;
}
if (parent.$$inheritedValues) {
merge(values, omit(parent.$$inheritedValues, invocableKeys));
}
// Merge parent values if the parent has already resolved, or merge
// parent promises and wait if the parent resolve is still in progress.
extend(promises, parent.$$promises);
if (parent.$$values) {
merged = merge(values, omit(parent.$$values, invocableKeys));
result.$$inheritedValues = omit(parent.$$values, invocableKeys);
done();
} else {
if (parent.$$inheritedValues) {
result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
}
parent.then(done, fail);
}
// Process each invocable in the plan, but ignore any where a local of the same name exists.
for (var i=0, ii=plan.length; i<ii; i+=3) {
if (locals.hasOwnProperty(plan[i])) done();
else invoke(plan[i], plan[i+1], plan[i+2]);
}
function invoke(key, invocable, params) {
// Create a deferred for this invocation. Failures will propagate to the resolution as well.
var invocation = $q.defer(), waitParams = 0;
function onfailure(reason) {
invocation.reject(reason);
fail(reason);
}
// Wait for any parameter that we have a promise for (either from parent or from this
// resolve; in that case study() will have made sure it's ordered before us in the plan).
forEach(params, function (dep) {
if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
waitParams++;
promises[dep].then(function (result) {
values[dep] = result;
if (!(--waitParams)) proceed();
}, onfailure);
}
});
if (!waitParams) proceed();
function proceed() {
if (isDefined(result.$$failure)) return;
try {
invocation.resolve($injector.invoke(invocable, self, values));
invocation.promise.then(function (result) {
values[key] = result;
done();
}, onfailure);
} catch (e) {
onfailure(e);
}
}
// Publish promise synchronously; invocations further down in the plan may depend on it.
promises[key] = invocation.promise;
}
return result;
};
};
/**
* @ngdoc function
* @name ui.router.util.$resolve#resolve
* @methodOf ui.router.util.$resolve
*
* @description
* Resolves a set of invocables. An invocable is a function to be invoked via
* `$injector.invoke()`, and can have an arbitrary number of dependencies.
* An invocable can either return a value directly,
* or a `$q` promise. If a promise is returned it will be resolved and the
* resulting value will be used instead. Dependencies of invocables are resolved
* (in this order of precedence)
*
* - from the specified `locals`
* - from another invocable that is part of this `$resolve` call
* - from an invocable that is inherited from a `parent` call to `$resolve`
* (or recursively
* - from any ancestor `$resolve` of that parent).
*
* The return value of `$resolve` is a promise for an object that contains
* (in this order of precedence)
*
* - any `locals` (if specified)
* - the resolved return values of all injectables
* - any values inherited from a `parent` call to `$resolve` (if specified)
*
* The promise will resolve after the `parent` promise (if any) and all promises
* returned by injectables have been resolved. If any invocable
* (or `$injector.invoke`) throws an exception, or if a promise returned by an
* invocable is rejected, the `$resolve` promise is immediately rejected with the
* same error. A rejection of a `parent` promise (if specified) will likewise be
* propagated immediately. Once the `$resolve` promise has been rejected, no
* further invocables will be called.
*
* Cyclic dependencies between invocables are not permitted and will caues `$resolve`
* to throw an error. As a special case, an injectable can depend on a parameter
* with the same name as the injectable, which will be fulfilled from the `parent`
* injectable of the same name. This allows inherited values to be decorated.
* Note that in this case any other injectable in the same `$resolve` with the same
* dependency would see the decorated value, not the inherited value.
*
* Note that missing dependencies -- unlike cyclic dependencies -- will cause an
* (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
* exception.
*
* Invocables are invoked eagerly as soon as all dependencies are available.
* This is true even for dependencies inherited from a `parent` call to `$resolve`.
*
* As a special case, an invocable can be a string, in which case it is taken to
* be a service name to be passed to `$injector.get()`. This is supported primarily
* for backwards-compatibility with the `resolve` property of `$routeProvider`
* routes.
*
* @param {object} invocables functions to invoke or
* `$injector` services to fetch.
* @param {object} locals values to make available to the injectables
* @param {object} parent a promise returned by another call to `$resolve`.
* @param {object} self the `this` for the invoked methods
* @return {object} Promise for an object that contains the resolved return value
* of all invocables, as well as any inherited and local values.
*/
this.resolve = function (invocables, locals, parent, self) {
return this.study(invocables)(locals, parent, self);
};
}
angular.module('ui.router.util').service('$resolve', $Resolve);
/**
* @ngdoc object
* @name ui.router.util.$templateFactory
*
* @requires $http
* @requires $templateCache
* @requires $injector
*
* @description
* Service. Manages loading of templates.
*/
$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
function $TemplateFactory( $http, $templateCache, $injector) {
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromConfig
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template from a configuration object.
*
* @param {object} config Configuration object for which to load a template.
* The following properties are search in the specified order, and the first one
* that is defined is used to create the template:
*
* @param {string|object} config.template html string template or function to
* load via {@link ui.router.util.$templateFactory#fromString fromString}.
* @param {string|object} config.templateUrl url to load or a function returning
* the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
* @param {Function} config.templateProvider function to invoke via
* {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
* @param {object} params Parameters to pass to the template function.
* @param {object} locals Locals to pass to `invoke` if the template is loaded
* via a `templateProvider`. Defaults to `{ params: params }`.
*
* @return {string|object} The template html as a string, or a promise for
* that string,or `null` if no template is configured.
*/
this.fromConfig = function (config, params, locals) {
return (
isDefined(config.template) ? this.fromString(config.template, params) :
isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
null
);
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromString
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template from a string or a function returning a string.
*
* @param {string|object} template html template as a string or function that
* returns an html template as a string.
* @param {object} params Parameters to pass to the template function.
*
* @return {string|object} The template html as a string, or a promise for that
* string.
*/
this.fromString = function (template, params) {
return isFunction(template) ? template(params) : template;
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromUrl
* @methodOf ui.router.util.$templateFactory
*
* @description
* Loads a template from the a URL via `$http` and `$templateCache`.
*
* @param {string|Function} url url of the template to load, or a function
* that returns a url.
* @param {Object} params Parameters to pass to the url function.
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
this.fromUrl = function (url, params) {
if (isFunction(url)) url = url(params);
if (url == null) return null;
else return $http
.get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
.then(function(response) { return response.data; });
};
/**
* @ngdoc function
* @name ui.router.util.$templateFactory#fromProvider
* @methodOf ui.router.util.$templateFactory
*
* @description
* Creates a template by invoking an injectable provider function.
*
* @param {Function} provider Function to invoke via `$injector.invoke`
* @param {Object} params Parameters for the template.
* @param {Object} locals Locals to pass to `invoke`. Defaults to
* `{ params: params }`.
* @return {string|Promise.<string>} The template html as a string, or a promise
* for that string.
*/
this.fromProvider = function (provider, params, locals) {
return $injector.invoke(provider, null, locals || { params: params });
};
}
angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
var $$UMFP; // reference to $UrlMatcherFactoryProvider
/**
* @ngdoc object
* @name ui.router.util.type:UrlMatcher
*
* @description
* Matches URLs against patterns and extracts named parameters from the path or the search
* part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
* of search parameters. Multiple search parameter names are separated by '&'. Search parameters
* do not influence whether or not a URL is matched, but their values are passed through into
* the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
*
* Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
* syntax, which optionally allows a regular expression for the parameter to be specified:
*
* * `':'` name - colon placeholder
* * `'*'` name - catch-all placeholder
* * `'{' name '}'` - curly placeholder
* * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
* regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
*
* Parameter names may contain only word characters (latin letters, digits, and underscore) and
* must be unique within the pattern (across both path and search parameters). For colon
* placeholders or curly placeholders without an explicit regexp, a path parameter matches any
* number of characters other than '/'. For catch-all placeholders the path parameter matches
* any number of characters.
*
* Examples:
*
* * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
* trailing slashes, and patterns have to match the entire path, not just a prefix.
* * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
* '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
* * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
* * `'/user/{id:[^/]*}'` - Same as the previous example.
* * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
* parameter consists of 1 to 8 hex digits.
* * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
* path into the parameter 'path'.
* * `'/files/*path'` - ditto.
* * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
* in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
*
* @param {string} pattern The pattern to compile into a matcher.
* @param {Object} config A configuration object hash:
* @param {Object=} parentMatcher Used to concatenate the pattern/config onto
* an existing UrlMatcher
*
* * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
* * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
*
* @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
* URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
* non-null) will start with this prefix.
*
* @property {string} source The pattern that was passed into the constructor
*
* @property {string} sourcePath The path portion of the source property
*
* @property {string} sourceSearch The search portion of the source property
*
* @property {string} regex The constructed regex that will be used to match against the url when
* it is time to determine which url will match.
*
* @returns {Object} New `UrlMatcher` object
*/
function UrlMatcher(pattern, config, parentMatcher) {
config = extend({ params: {} }, isObject(config) ? config : {});
// Find all placeholders and create a compiled pattern, using either classic or curly syntax:
// '*' name
// ':' name
// '{' name '}'
// '{' name ':' regexp '}'
// The regular expression is somewhat complicated due to the need to allow curly braces
// inside the regular expression. The placeholder regexp breaks down as follows:
// ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
// \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
// (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
// [^{}\\]+ - anything other than curly braces or backslash
// \\. - a backslash escape
// \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
compiled = '^', last = 0, m,
segments = this.segments = [],
parentParams = parentMatcher ? parentMatcher.params : {},
params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
paramNames = [];
function addParameter(id, type, config, location) {
paramNames.push(id);
if (parentParams[id]) return parentParams[id];
if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
params[id] = new $$UMFP.Param(id, type, config, location);
return params[id];
}
function quoteRegExp(string, pattern, squash, optional) {
var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
if (!pattern) return result;
switch(squash) {
case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
case true: surroundPattern = ['?(', ')?']; break;
default: surroundPattern = ['(' + squash + "|", ')?']; break;
}
return result + surroundPattern[0] + pattern + surroundPattern[1];
}
this.source = pattern;
// Split into static segments separated by path parameter placeholders.
// The number of segments is always 1 more than the number of parameters.
function matchDetails(m, isSearch) {
var id, regexp, segment, type, cfg, arrayMode;
id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
cfg = config.params[id];
segment = pattern.substring(last, m.index);
regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });
return {
id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
};
}
var p, param, segment;
while ((m = placeholder.exec(pattern))) {
p = matchDetails(m, false);
if (p.segment.indexOf('?') >= 0) break; // we're into the search part
param = addParameter(p.id, p.type, p.cfg, "path");
compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
segments.push(p.segment);
last = placeholder.lastIndex;
}
segment = pattern.substring(last);
// Find any search parameter names and remove them from the last segment
var i = segment.indexOf('?');
if (i >= 0) {
var search = this.sourceSearch = segment.substring(i);
segment = segment.substring(0, i);
this.sourcePath = pattern.substring(0, last + i);
if (search.length > 0) {
last = 0;
while ((m = searchPlaceholder.exec(search))) {
p = matchDetails(m, true);
param = addParameter(p.id, p.type, p.cfg, "search");
last = placeholder.lastIndex;
// check if ?&
}
}
} else {
this.sourcePath = pattern;
this.sourceSearch = '';
}
compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
segments.push(segment);
this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
this.prefix = segments[0];
this.$$paramNames = paramNames;
}
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#concat
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Returns a new matcher for a pattern constructed by appending the path part and adding the
* search parameters of the specified pattern to this pattern. The current pattern is not
* modified. This can be understood as creating a pattern for URLs that are relative to (or
* suffixes of) the current pattern.
*
* @example
* The following two matchers are equivalent:
* <pre>
* new UrlMatcher('/user/{id}?q').concat('/details?date');
* new UrlMatcher('/user/{id}/details?q&date');
* </pre>
*
* @param {string} pattern The pattern to append.
* @param {Object} config An object hash of the configuration for the matcher.
* @returns {UrlMatcher} A matcher for the concatenated pattern.
*/
UrlMatcher.prototype.concat = function (pattern, config) {
// Because order of search parameters is irrelevant, we can add our own search
// parameters to the end of the new pattern. Parse the new pattern by itself
// and then join the bits together, but it's much easier to do this on a string level.
var defaultConfig = {
caseInsensitive: $$UMFP.caseInsensitive(),
strict: $$UMFP.strictMode(),
squash: $$UMFP.defaultSquashPolicy()
};
return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
};
UrlMatcher.prototype.toString = function () {
return this.source;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#exec
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Tests the specified path against this matcher, and returns an object containing the captured
* parameter values, or null if the path does not match. The returned object contains the values
* of any search parameters that are mentioned in the pattern, but their value may be null if
* they are not present in `searchParams`. This means that search parameters are always treated
* as optional.
*
* @example
* <pre>
* new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
* x: '1', q: 'hello'
* });
* // returns { id: 'bob', q: 'hello', r: null }
* </pre>
*
* @param {string} path The URL path to match, e.g. `$location.path()`.
* @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
* @returns {Object} The captured parameter values.
*/
UrlMatcher.prototype.exec = function (path, searchParams) {
var m = this.regexp.exec(path);
if (!m) return null;
searchParams = searchParams || {};
var paramNames = this.parameters(), nTotal = paramNames.length,
nPath = this.segments.length - 1,
values = {}, i, j, cfg, paramName;
if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
function decodePathArray(string) {
function reverseString(str) { return str.split("").reverse().join(""); }
function unquoteDashes(str) { return str.replace(/\\-/g, "-"); }
var split = reverseString(string).split(/-(?!\\)/);
var allReversed = map(split, reverseString);
return map(allReversed, unquoteDashes).reverse();
}
for (i = 0; i < nPath; i++) {
paramName = paramNames[i];
var param = this.params[paramName];
var paramVal = m[i+1];
// if the param value matches a pre-replace pair, replace the value before decoding.
for (j = 0; j < param.replace; j++) {
if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
}
if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
values[paramName] = param.value(paramVal);
}
for (/**/; i < nTotal; i++) {
paramName = paramNames[i];
values[paramName] = this.params[paramName].value(searchParams[paramName]);
}
return values;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#parameters
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Returns the names of all path and search parameters of this pattern in an unspecified order.
*
* @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
* pattern has no parameters, an empty array is returned.
*/
UrlMatcher.prototype.parameters = function (param) {
if (!isDefined(param)) return this.$$paramNames;
return this.params[param] || null;
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#validate
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Checks an object hash of parameters to validate their correctness according to the parameter
* types of this `UrlMatcher`.
*
* @param {Object} params The object hash of parameters to validate.
* @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
*/
UrlMatcher.prototype.validates = function (params) {
return this.params.$$validates(params);
};
/**
* @ngdoc function
* @name ui.router.util.type:UrlMatcher#format
* @methodOf ui.router.util.type:UrlMatcher
*
* @description
* Creates a URL that matches this pattern by substituting the specified values
* for the path and search parameters. Null values for path parameters are
* treated as empty strings.
*
* @example
* <pre>
* new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
* // returns '/user/bob?q=yes'
* </pre>
*
* @param {Object} values the values to substitute for the parameters in this pattern.
* @returns {string} the formatted URL (path and optionally search part).
*/
UrlMatcher.prototype.format = function (values) {
values = values || {};
var segments = this.segments, params = this.parameters(), paramset = this.params;
if (!this.validates(values)) return null;
var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
function encodeDashes(str) { // Replace dashes with encoded "\-"
return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
}
for (i = 0; i < nTotal; i++) {
var isPathParam = i < nPath;
var name = params[i], param = paramset[name], value = param.value(values[name]);
var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
var squash = isDefaultValue ? param.squash : false;
var encoded = param.type.encode(value);
if (isPathParam) {
var nextSegment = segments[i + 1];
if (squash === false) {
if (encoded != null) {
if (isArray(encoded)) {
result += map(encoded, encodeDashes).join("-");
} else {
result += encodeURIComponent(encoded);
}
}
result += nextSegment;
} else if (squash === true) {
var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
result += nextSegment.match(capture)[1];
} else if (isString(squash)) {
result += squash + nextSegment;
}
} else {
if (encoded == null || (isDefaultValue && squash !== false)) continue;
if (!isArray(encoded)) encoded = [ encoded ];
encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
result += (search ? '&' : '?') + (name + '=' + encoded);
search = true;
}
}
return result;
};
/**
* @ngdoc object
* @name ui.router.util.type:Type
*
* @description
* Implements an interface to define custom parameter types that can be decoded from and encoded to
* string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
* objects when matching or formatting URLs, or comparing or validating parameter values.
*
* See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
* information on registering custom types.
*
* @param {Object} config A configuration object which contains the custom type definition. The object's
* properties will override the default methods and/or pattern in `Type`'s public interface.
* @example
* <pre>
* {
* decode: function(val) { return parseInt(val, 10); },
* encode: function(val) { return val && val.toString(); },
* equals: function(a, b) { return this.is(a) && a === b; },
* is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
* pattern: /\d+/
* }
* </pre>
*
* @property {RegExp} pattern The regular expression pattern used to match values of this type when
* coming from a substring of a URL.
*
* @returns {Object} Returns a new `Type` object.
*/
function Type(config) {
extend(this, config);
}
/**
* @ngdoc function
* @name ui.router.util.type:Type#is
* @methodOf ui.router.util.type:Type
*
* @description
* Detects whether a value is of a particular type. Accepts a native (decoded) value
* and determines whether it matches the current `Type` object.
*
* @param {*} val The value to check.
* @param {string} key Optional. If the type check is happening in the context of a specific
* {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
* parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
* @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
*/
Type.prototype.is = function(val, key) {
return true;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#encode
* @methodOf ui.router.util.type:Type
*
* @description
* Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
* return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
* only needs to be a representation of `val` that has been coerced to a string.
*
* @param {*} val The value to encode.
* @param {string} key The name of the parameter in which `val` is stored. Can be used for
* meta-programming of `Type` objects.
* @returns {string} Returns a string representation of `val` that can be encoded in a URL.
*/
Type.prototype.encode = function(val, key) {
return val;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#decode
* @methodOf ui.router.util.type:Type
*
* @description
* Converts a parameter value (from URL string or transition param) to a custom/native value.
*
* @param {string} val The URL parameter value to decode.
* @param {string} key The name of the parameter in which `val` is stored. Can be used for
* meta-programming of `Type` objects.
* @returns {*} Returns a custom representation of the URL parameter value.
*/
Type.prototype.decode = function(val, key) {
return val;
};
/**
* @ngdoc function
* @name ui.router.util.type:Type#equals
* @methodOf ui.router.util.type:Type
*
* @description
* Determines whether two decoded values are equivalent.
*
* @param {*} a A value to compare against.
* @param {*} b A value to compare against.
* @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
*/
Type.prototype.equals = function(a, b) {
return a == b;
};
Type.prototype.$subPattern = function() {
var sub = this.pattern.toString();
return sub.substr(1, sub.length - 2);
};
Type.prototype.pattern = /.*/;
Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
/** Given an encoded string, or a decoded object, returns a decoded object */
Type.prototype.$normalize = function(val) {
return this.is(val) ? val : this.decode(val);
};
/*
* Wraps an existing custom Type as an array of Type, depending on 'mode'.
* e.g.:
* - urlmatcher pattern "/path?{queryParam[]:int}"
* - url: "/path?queryParam=1&queryParam=2
* - $stateParams.queryParam will be [1, 2]
* if `mode` is "auto", then
* - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
* - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
*/
Type.prototype.$asArray = function(mode, isSearch) {
if (!mode) return this;
if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
function ArrayType(type, mode) {
function bindTo(type, callbackName) {
return function() {
return type[callbackName].apply(type, arguments);
};
}
// Wrap non-array value as array
function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
// Unwrap array value for "auto" mode. Return undefined for empty array.
function arrayUnwrap(val) {
switch(val.length) {
case 0: return undefined;
case 1: return mode === "auto" ? val[0] : val;
default: return val;
}
}
function falsey(val) { return !val; }
// Wraps type (.is/.encode/.decode) functions to operate on each value of an array
function arrayHandler(callback, allTruthyMode) {
return function handleArray(val) {
val = arrayWrap(val);
var result = map(val, callback);
if (allTruthyMode === true)
return filter(result, falsey).length === 0;
return arrayUnwrap(result);
};
}
// Wraps type (.equals) functions to operate on each value of an array
function arrayEqualsHandler(callback) {
return function handleArray(val1, val2) {
var left = arrayWrap(val1), right = arrayWrap(val2);
if (left.length !== right.length) return false;
for (var i = 0; i < left.length; i++) {
if (!callback(left[i], right[i])) return false;
}
return true;
};
}
this.encode = arrayHandler(bindTo(type, 'encode'));
this.decode = arrayHandler(bindTo(type, 'decode'));
this.is = arrayHandler(bindTo(type, 'is'), true);
this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
this.pattern = type.pattern;
this.$normalize = arrayHandler(bindTo(type, '$normalize'));
this.name = type.name;
this.$arrayMode = mode;
}
return new ArrayType(this, mode);
};
/**
* @ngdoc object
* @name ui.router.util.$urlMatcherFactory
*
* @description
* Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
* is also available to providers under the name `$urlMatcherFactoryProvider`.
*/
function $UrlMatcherFactory() {
$$UMFP = this;
var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
string: {
encode: valToString,
decode: valFromString,
// TODO: in 1.0, make string .is() return false if value is undefined/null by default.
// In 0.2.x, string params are optional by default for backwards compat
is: function(val) { return val == null || !isDefined(val) || typeof val === "string"; },
pattern: /[^/]*/
},
int: {
encode: valToString,
decode: function(val) { return parseInt(val, 10); },
is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
pattern: /\d+/
},
bool: {
encode: function(val) { return val ? 1 : 0; },
decode: function(val) { return parseInt(val, 10) !== 0; },
is: function(val) { return val === true || val === false; },
pattern: /0|1/
},
date: {
encode: function (val) {
if (!this.is(val))
return undefined;
return [ val.getFullYear(),
('0' + (val.getMonth() + 1)).slice(-2),
('0' + val.getDate()).slice(-2)
].join("-");
},
decode: function (val) {
if (this.is(val)) return val;
var match = this.capture.exec(val);
return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
},
is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
},
json: {
encode: angular.toJson,
decode: angular.fromJson,
is: angular.isObject,
equals: angular.equals,
pattern: /[^/]*/
},
any: { // does not encode/decode
encode: angular.identity,
decode: angular.identity,
equals: angular.equals,
pattern: /.*/
}
};
function getDefaultConfig() {
return {
strict: isStrictMode,
caseInsensitive: isCaseInsensitive
};
}
function isInjectable(value) {
return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
}
/**
* [Internal] Get the default value of a parameter, which may be an injectable function.
*/
$UrlMatcherFactory.$$getDefaultValue = function(config) {
if (!isInjectable(config.value)) return config.value;
if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
return injector.invoke(config.value);
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#caseInsensitive
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Defines whether URL matching should be case sensitive (the default behavior), or not.
*
* @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
* @returns {boolean} the current value of caseInsensitive
*/
this.caseInsensitive = function(value) {
if (isDefined(value))
isCaseInsensitive = value;
return isCaseInsensitive;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#strictMode
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Defines whether URLs should match trailing slashes, or not (the default behavior).
*
* @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
* @returns {boolean} the current value of strictMode
*/
this.strictMode = function(value) {
if (isDefined(value))
isStrictMode = value;
return isStrictMode;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Sets the default behavior when generating or matching URLs with default parameter values.
*
* @param {string} value A string that defines the default parameter URL squashing behavior.
* `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
* `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
* parameter is surrounded by slashes, squash (remove) one slash from the URL
* any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
* the parameter value from the URL and replace it with this string.
*/
this.defaultSquashPolicy = function(value) {
if (!isDefined(value)) return defaultSquashPolicy;
if (value !== true && value !== false && !isString(value))
throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
defaultSquashPolicy = value;
return value;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#compile
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
*
* @param {string} pattern The URL pattern.
* @param {Object} config The config object hash.
* @returns {UrlMatcher} The UrlMatcher.
*/
this.compile = function (pattern, config) {
return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#isMatcher
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Returns true if the specified object is a `UrlMatcher`, or false otherwise.
*
* @param {Object} object The object to perform the type check against.
* @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
* implementing all the same methods.
*/
this.isMatcher = function (o) {
if (!isObject(o)) return false;
var result = true;
forEach(UrlMatcher.prototype, function(val, name) {
if (isFunction(val)) {
result = result && (isDefined(o[name]) && isFunction(o[name]));
}
});
return result;
};
/**
* @ngdoc function
* @name ui.router.util.$urlMatcherFactory#type
* @methodOf ui.router.util.$urlMatcherFactory
*
* @description
* Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
* generate URLs with typed parameters.
*
* @param {string} name The type name.
* @param {Object|Function} definition The type definition. See
* {@link ui.router.util.type:Type `Type`} for information on the values accepted.
* @param {Object|Function} definitionFn (optional) A function that is injected before the app
* runtime starts. The result of this function is merged into the existing `definition`.
* See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
*
* @returns {Object} Returns `$urlMatcherFactoryProvider`.
*
* @example
* This is a simple example of a custom type that encodes and decodes items from an
* array, using the array index as the URL-encoded value:
*
* <pre>
* var list = ['John', 'Paul', 'George', 'Ringo'];
*
* $urlMatcherFactoryProvider.type('listItem', {
* encode: function(item) {
* // Represent the list item in the URL using its corresponding index
* return list.indexOf(item);
* },
* decode: function(item) {
* // Look up the list item by index
* return list[parseInt(item, 10)];
* },
* is: function(item) {
* // Ensure the item is valid by checking to see that it appears
* // in the list
* return list.indexOf(item) > -1;
* }
* });
*
* $stateProvider.state('list', {
* url: "/list/{item:listItem}",
* controller: function($scope, $stateParams) {
* console.log($stateParams.item);
* }
* });
*
* // ...
*
* // Changes URL to '/list/3', logs "Ringo" to the console
* $state.go('list', { item: "Ringo" });
* </pre>
*
* This is a more complex example of a type that relies on dependency injection to
* interact with services, and uses the parameter name from the URL to infer how to
* handle encoding and decoding parameter values:
*
* <pre>
* // Defines a custom type that gets a value from a service,
* // where each service gets different types of values from
* // a backend API:
* $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
*
* // Matches up services to URL parameter names
* var services = {
* user: Users,
* post: Posts
* };
*
* return {
* encode: function(object) {
* // Represent the object in the URL using its unique ID
* return object.id;
* },
* decode: function(value, key) {
* // Look up the object by ID, using the parameter
* // name (key) to call the correct service
* return services[key].findById(value);
* },
* is: function(object, key) {
* // Check that object is a valid dbObject
* return angular.isObject(object) && object.id && services[key];
* }
* equals: function(a, b) {
* // Check the equality of decoded objects by comparing
* // their unique IDs
* return a.id === b.id;
* }
* };
* });
*
* // In a config() block, you can then attach URLs with
* // type-annotated parameters:
* $stateProvider.state('users', {
* url: "/users",
* // ...
* }).state('users.item', {
* url: "/{user:dbObject}",
* controller: function($scope, $stateParams) {
* // $stateParams.user will now be an object returned from
* // the Users service
* },
* // ...
* });
* </pre>
*/
this.type = function (name, definition, definitionFn) {
if (!isDefined(definition)) return $types[name];
if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
$types[name] = new Type(extend({ name: name }, definition));
if (definitionFn) {
typeQueue.push({ name: name, def: definitionFn });
if (!enqueue) flushTypeQueue();
}
return this;
};
// `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
function flushTypeQueue() {
while(typeQueue.length) {
var type = typeQueue.shift();
if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
angular.extend($types[type.name], injector.invoke(type.def));
}
}
// Register default types. Store them in the prototype of $types.
forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
$types = inherit($types, {});
/* No need to document $get, since it returns this */
this.$get = ['$injector', function ($injector) {
injector = $injector;
enqueue = false;
flushTypeQueue();
forEach(defaultTypes, function(type, name) {
if (!$types[name]) $types[name] = new Type(type);
});
return this;
}];
this.Param = function Param(id, type, config, location) {
var self = this;
config = unwrapShorthand(config);
type = getType(config, type, location);
var arrayMode = getArrayMode();
type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
var isOptional = config.value !== undefined;
var squash = getSquashPolicy(config, isOptional);
var replace = getReplace(config, arrayMode, isOptional, squash);
function unwrapShorthand(config) {
var keys = isObject(config) ? objectKeys(config) : [];
var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
if (isShorthand) config = { value: config };
config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
return config;
}
function getType(config, urlType, location) {
if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
if (urlType) return urlType;
if (!config.type) return (location === "config" ? $types.any : $types.string);
return config.type instanceof Type ? config.type : new Type(config.type);
}
// array config: param name (param[]) overrides default settings. explicit config overrides param name.
function getArrayMode() {
var arrayDefaults = { array: (location === "search" ? "auto" : false) };
var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
return extend(arrayDefaults, arrayParamNomenclature, config).array;
}
/**
* returns false, true, or the squash value to indicate the "default parameter url squash policy".
*/
function getSquashPolicy(config, isOptional) {
var squash = config.squash;
if (!isOptional || squash === false) return false;
if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
if (squash === true || isString(squash)) return squash;
throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
}
function getReplace(config, arrayMode, isOptional, squash) {
var replace, configuredKeys, defaultPolicy = [
{ from: "", to: (isOptional || arrayMode ? undefined : "") },
{ from: null, to: (isOptional || arrayMode ? undefined : "") }
];
replace = isArray(config.replace) ? config.replace : [];
if (isString(squash))
replace.push({ from: squash, to: undefined });
configuredKeys = map(replace, function(item) { return item.from; } );
return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
}
/**
* [Internal] Get the default value of a parameter, which may be an injectable function.
*/
function $$getDefaultValue() {
if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
var defaultValue = injector.invoke(config.$$fn);
if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
return defaultValue;
}
/**
* [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
* default value, which may be the result of an injectable function.
*/
function $value(value) {
function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
function $replace(value) {
var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
return replacement.length ? replacement[0] : value;
}
value = $replace(value);
return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
}
function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
extend(this, {
id: id,
type: type,
location: location,
array: arrayMode,
squash: squash,
replace: replace,
isOptional: isOptional,
value: $value,
dynamic: undefined,
config: config,
toString: toString
});
};
function ParamSet(params) {
extend(this, params || {});
}
ParamSet.prototype = {
$$new: function() {
return inherit(this, extend(new ParamSet(), { $$parent: this}));
},
$$keys: function () {
var keys = [], chain = [], parent = this,
ignore = objectKeys(ParamSet.prototype);
while (parent) { chain.push(parent); parent = parent.$$parent; }
chain.reverse();
forEach(chain, function(paramset) {
forEach(objectKeys(paramset), function(key) {
if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
});
});
return keys;
},
$$values: function(paramValues) {
var values = {}, self = this;
forEach(self.$$keys(), function(key) {
values[key] = self[key].value(paramValues && paramValues[key]);
});
return values;
},
$$equals: function(paramValues1, paramValues2) {
var equal = true, self = this;
forEach(self.$$keys(), function(key) {
var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
if (!self[key].type.equals(left, right)) equal = false;
});
return equal;
},
$$validates: function $$validate(paramValues) {
var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
for (i = 0; i < keys.length; i++) {
param = this[keys[i]];
rawVal = paramValues[keys[i]];
if ((rawVal === undefined || rawVal === null) && param.isOptional)
break; // There was no parameter value, but the param is optional
normalized = param.type.$normalize(rawVal);
if (!param.type.is(normalized))
return false; // The value was not of the correct Type, and could not be decoded to the correct Type
encoded = param.type.encode(normalized);
if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
}
return true;
},
$$parent: undefined
};
this.ParamSet = ParamSet;
}
// Register as a provider so it's available to other providers
angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
/**
* @ngdoc object
* @name ui.router.router.$urlRouterProvider
*
* @requires ui.router.util.$urlMatcherFactoryProvider
* @requires $locationProvider
*
* @description
* `$urlRouterProvider` has the responsibility of watching `$location`.
* When `$location` changes it runs through a list of rules one by one until a
* match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
* a url in a state configuration. All urls are compiled into a UrlMatcher object.
*
* There are several methods on `$urlRouterProvider` that make it useful to use directly
* in your module config.
*/
$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
var rules = [], otherwise = null, interceptDeferred = false, listener;
// Returns a string that is a prefix of all strings matching the RegExp
function regExpPrefix(re) {
var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
}
// Interpolates matched values into a String.replace()-style pattern
function interpolate(pattern, match) {
return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
return match[what === '$' ? 0 : Number(what)];
});
}
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#rule
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Defines rules that are used by `$urlRouterProvider` to find matches for
* specific URLs.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* // Here's an example of how you might allow case insensitive urls
* $urlRouterProvider.rule(function ($injector, $location) {
* var path = $location.path(),
* normalized = path.toLowerCase();
*
* if (path !== normalized) {
* return normalized;
* }
* });
* });
* </pre>
*
* @param {object} rule Handler function that takes `$injector` and `$location`
* services as arguments. You can use them to return a valid path as a string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
this.rule = function (rule) {
if (!isFunction(rule)) throw new Error("'rule' must be a function");
rules.push(rule);
return this;
};
/**
* @ngdoc object
* @name ui.router.router.$urlRouterProvider#otherwise
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Defines a path that is used when an invalid route is requested.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* // if the path doesn't match any of the urls you configured
* // otherwise will take care of routing the user to the
* // specified url
* $urlRouterProvider.otherwise('/index');
*
* // Example of using function rule as param
* $urlRouterProvider.otherwise(function ($injector, $location) {
* return '/a/valid/url';
* });
* });
* </pre>
*
* @param {string|object} rule The url path you want to redirect to or a function
* rule that returns the url path. The function version is passed two params:
* `$injector` and `$location` services, and must return a url string.
*
* @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
*/
this.otherwise = function (rule) {
if (isString(rule)) {
var redirect = rule;
rule = function () { return redirect; };
}
else if (!isFunction(rule)) throw new Error("'rule' must be a function");
otherwise = rule;
return this;
};
function handleIfMatch($injector, handler, match) {
if (!match) return false;
var result = $injector.invoke(handler, handler, { $match: match });
return isDefined(result) ? result : true;
}
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#when
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Registers a handler for a given url matching. if handle is a string, it is
* treated as a redirect, and is interpolated according to the syntax of match
* (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
*
* If the handler is a function, it is injectable. It gets invoked if `$location`
* matches. You have the option of inject the match object as `$match`.
*
* The handler can return
*
* - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
* will continue trying to find another one that matches.
* - **string** which is treated as a redirect and passed to `$location.url()`
* - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
* $urlRouterProvider.when($state.url, function ($match, $stateParams) {
* if ($state.$current.navigable !== state ||
* !equalForKeys($match, $stateParams) {
* $state.transitionTo(state, $match, false);
* }
* });
* });
* </pre>
*
* @param {string|object} what The incoming path that you want to redirect.
* @param {string|object} handler The path you want to redirect your user to.
*/
this.when = function (what, handler) {
var redirect, handlerIsString = isString(handler);
if (isString(what)) what = $urlMatcherFactory.compile(what);
if (!handlerIsString && !isFunction(handler) && !isArray(handler))
throw new Error("invalid 'handler' in when()");
var strategies = {
matcher: function (what, handler) {
if (handlerIsString) {
redirect = $urlMatcherFactory.compile(handler);
handler = ['$match', function ($match) { return redirect.format($match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
}, {
prefix: isString(what.prefix) ? what.prefix : ''
});
},
regex: function (what, handler) {
if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
if (handlerIsString) {
redirect = handler;
handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path()));
}, {
prefix: regExpPrefix(what)
});
}
};
var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
for (var n in check) {
if (check[n]) return this.rule(strategies[n](what, handler));
}
throw new Error("invalid 'what' in when()");
};
/**
* @ngdoc function
* @name ui.router.router.$urlRouterProvider#deferIntercept
* @methodOf ui.router.router.$urlRouterProvider
*
* @description
* Disables (or enables) deferring location change interception.
*
* If you wish to customize the behavior of syncing the URL (for example, if you wish to
* defer a transition but maintain the current URL), call this method at configuration time.
* Then, at run time, call `$urlRouter.listen()` after you have configured your own
* `$locationChangeSuccess` event handler.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.router']);
*
* app.config(function ($urlRouterProvider) {
*
* // Prevent $urlRouter from automatically intercepting URL changes;
* // this allows you to configure custom behavior in between
* // location changes and route synchronization:
* $urlRouterProvider.deferIntercept();
*
* }).run(function ($rootScope, $urlRouter, UserService) {
*
* $rootScope.$on('$locationChangeSuccess', function(e) {
* // UserService is an example service for managing user state
* if (UserService.isLoggedIn()) return;
*
* // Prevent $urlRouter's default handler from firing
* e.preventDefault();
*
* UserService.handleLogin().then(function() {
* // Once the user has logged in, sync the current URL
* // to the router:
* $urlRouter.sync();
* });
* });
*
* // Configures $urlRouter's listener *after* your custom listener
* $urlRouter.listen();
* });
* </pre>
*
* @param {boolean} defer Indicates whether to defer location change interception. Passing
no parameter is equivalent to `true`.
*/
this.deferIntercept = function (defer) {
if (defer === undefined) defer = true;
interceptDeferred = defer;
};
/**
* @ngdoc object
* @name ui.router.router.$urlRouter
*
* @requires $location
* @requires $rootScope
* @requires $injector
* @requires $browser
*
* @description
*
*/
this.$get = $get;
$get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
function $get( $location, $rootScope, $injector, $browser) {
var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
function appendBasePath(url, isHtml5, absolute) {
if (baseHref === '/') return url;
if (isHtml5) return baseHref.slice(0, -1) + url;
if (absolute) return baseHref.slice(1) + url;
return url;
}
// TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
function update(evt) {
if (evt && evt.defaultPrevented) return;
var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
lastPushedUrl = undefined;
// TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
//if (ignoreUpdate) return true;
function check(rule) {
var handled = rule($injector, $location);
if (!handled) return false;
if (isString(handled)) $location.replace().url(handled);
return true;
}
var n = rules.length, i;
for (i = 0; i < n; i++) {
if (check(rules[i])) return;
}
// always check otherwise last to allow dynamic updates to the set of rules
if (otherwise) check(otherwise);
}
function listen() {
listener = listener || $rootScope.$on('$locationChangeSuccess', update);
return listener;
}
if (!interceptDeferred) listen();
return {
/**
* @ngdoc function
* @name ui.router.router.$urlRouter#sync
* @methodOf ui.router.router.$urlRouter
*
* @description
* Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
* This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
* perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
* with the transition by calling `$urlRouter.sync()`.
*
* @example
* <pre>
* angular.module('app', ['ui.router'])
* .run(function($rootScope, $urlRouter) {
* $rootScope.$on('$locationChangeSuccess', function(evt) {
* // Halt state change from even starting
* evt.preventDefault();
* // Perform custom logic
* var meetsRequirement = ...
* // Continue with the update and state transition if logic allows
* if (meetsRequirement) $urlRouter.sync();
* });
* });
* </pre>
*/
sync: function() {
update();
},
listen: function() {
return listen();
},
update: function(read) {
if (read) {
location = $location.url();
return;
}
if ($location.url() === location) return;
$location.url(location);
$location.replace();
},
push: function(urlMatcher, params, options) {
var url = urlMatcher.format(params || {});
// Handle the special hash param, if needed
if (url !== null && params && params['#']) {
url += '#' + params['#'];
}
$location.url(url);
lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
if (options && options.replace) $location.replace();
},
/**
* @ngdoc function
* @name ui.router.router.$urlRouter#href
* @methodOf ui.router.router.$urlRouter
*
* @description
* A URL generation method that returns the compiled URL for a given
* {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
*
* @example
* <pre>
* $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
* person: "bob"
* });
* // $bob == "/about/bob";
* </pre>
*
* @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
* @param {object=} params An object of parameter values to fill the matcher's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
*/
href: function(urlMatcher, params, options) {
if (!urlMatcher.validates(params)) return null;
var isHtml5 = $locationProvider.html5Mode();
if (angular.isObject(isHtml5)) {
isHtml5 = isHtml5.enabled;
}
var url = urlMatcher.format(params);
options = options || {};
if (!isHtml5 && url !== null) {
url = "#" + $locationProvider.hashPrefix() + url;
}
// Handle special hash param, if needed
if (url !== null && params && params['#']) {
url += '#' + params['#'];
}
url = appendBasePath(url, isHtml5, options.absolute);
if (!options.absolute || !url) {
return url;
}
var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
port = (port === 80 || port === 443 ? '' : ':' + port);
return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
}
};
}
}
angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
/**
* @ngdoc object
* @name ui.router.state.$stateProvider
*
* @requires ui.router.router.$urlRouterProvider
* @requires ui.router.util.$urlMatcherFactoryProvider
*
* @description
* The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
* on state.
*
* A state corresponds to a "place" in the application in terms of the overall UI and
* navigation. A state describes (via the controller / template / view properties) what
* the UI looks like and does at that place.
*
* States often have things in common, and the primary way of factoring out these
* commonalities in this model is via the state hierarchy, i.e. parent/child states aka
* nested states.
*
* The `$stateProvider` provides interfaces to declare these states for your app.
*/
$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
// Builds state properties from definition passed to registerState()
var stateBuilder = {
// Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
// state.children = [];
// if (parent) parent.children.push(state);
parent: function(state) {
if (isDefined(state.parent) && state.parent) return findState(state.parent);
// regex matches any valid composite state name
// would match "contact.list" but not "contacts"
var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
return compositeName ? findState(compositeName[1]) : root;
},
// inherit 'data' from parent and override by own values (if any)
data: function(state) {
if (state.parent && state.parent.data) {
state.data = state.self.data = extend({}, state.parent.data, state.data);
}
return state.data;
},
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: function(state) {
var url = state.url, config = { params: state.params || {} };
if (isString(url)) {
if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
return (state.parent.navigable || root).url.concat(url, config);
}
if (!url || $urlMatcherFactory.isMatcher(url)) return url;
throw new Error("Invalid url '" + url + "' in state '" + state + "'");
},
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: function(state) {
return state.url ? state : (state.parent ? state.parent.navigable : null);
},
// Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
ownParams: function(state) {
var params = state.url && state.url.params || new $$UMFP.ParamSet();
forEach(state.params || {}, function(config, id) {
if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
});
return params;
},
// Derive parameters for this state and ensure they're a super-set of parent's parameters
params: function(state) {
return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
},
// If there is no explicit multi-view configuration, make one up so we don't have
// to handle both cases in the view directive later. Note that having an explicit
// 'views' property will mean the default unnamed view properties are ignored. This
// is also a good time to resolve view names to absolute names, so everything is a
// straight lookup at link time.
views: function(state) {
var views = {};
forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
if (name.indexOf('@') < 0) name += '@' + state.parent.name;
views[name] = view;
});
return views;
},
// Keep a full path from the root down to this state as this is needed for state activation.
path: function(state) {
return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
},
// Speed up $state.contains() as it's used a lot
includes: function(state) {
var includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
},
$delegates: {}
};
function isRelative(stateName) {
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
}
function findState(stateOrName, base) {
if (!stateOrName) return undefined;
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
base = findState(base);
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function queueState(parentName, state) {
if (!queue[parentName]) {
queue[parentName] = [];
}
queue[parentName].push(state);
}
function flushQueuedChildren(parentName) {
var queued = queue[parentName] || [];
while(queued.length) {
registerState(queued.shift());
}
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
// Get parent name
var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
: (isString(state.parent)) ? state.parent
: (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
: '';
// If parent is not registered yet, add state to queue and register later
if (parentName && !states[parentName]) {
return queueState(parentName, state.self);
}
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, { inherit: true, location: false });
}
}]);
}
// Register any queued children
flushQueuedChildren(name);
return state;
}
// Checks text to see if it looks like a glob.
function isGlob (text) {
return text.indexOf('*') > -1;
}
// Returns true if glob matches current $state name.
function doesStateMatchGlob (glob) {
var globSegments = glob.split('.'),
segments = $state.$current.name.split('.');
//match single stars
for (var i = 0, l = globSegments.length; i < l; i++) {
if (globSegments[i] === '*') {
segments[i] = '*';
}
}
//match greedy starts
if (globSegments[0] === '**') {
segments = segments.slice(indexOf(segments, globSegments[1]));
segments.unshift('**');
}
//match greedy ends
if (globSegments[globSegments.length - 1] === '**') {
segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
segments.push('**');
}
if (globSegments.length != segments.length) {
return false;
}
return segments.join('') === globSegments.join('');
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#decorator
* @methodOf ui.router.state.$stateProvider
*
* @description
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by `$stateProvider`. This can be used
* to add custom functionality to ui-router, for example inferring templateUrl
* based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* @example
* <pre>
* // Override the internal 'views' builder with a function that takes the state
* // definition, and a reference to the internal function being overridden:
* $stateProvider.decorator('views', function (state, parent) {
* var result = {},
* views = parent(state);
*
* angular.forEach(views, function (config, name) {
* var autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
*
* // ...
*
* $state.go('home');
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* </pre>
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
this.decorator = decorator;
function decorator(name, func) {
/*jshint validthis: true */
if (isString(name) && !isDefined(func)) {
return stateBuilder[name];
}
if (!isFunction(func) || !isString(name)) {
return this;
}
if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
stateBuilder.$delegates[name] = stateBuilder[name];
}
stateBuilder[name] = func;
return this;
}
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#state
* @methodOf ui.router.state.$stateProvider
*
* @description
* Registers a state configuration under a given state name. The stateConfig object
* has the following acceptable properties.
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} stateConfig State configuration object.
* @param {string|function=} stateConfig.template
* <a id='template'></a>
* html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <pre>template:
* "<h1>inline template definition</h1>" +
* "<div ui-view></div>"</pre>
* <pre>template: function(params) {
* return "<h1>generated template</h1>"; }</pre>
* </div>
*
* @param {string|function=} stateConfig.templateUrl
* <a id='templateUrl'></a>
*
* path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <pre>templateUrl: "home.html"</pre>
* <pre>templateUrl: function(params) {
* return myTemplates[params.pageId]; }</pre>
*
* @param {function=} stateConfig.templateProvider
* <a id='templateProvider'></a>
* Provider function that returns HTML content string.
* <pre> templateProvider:
* function(MyTemplateService, params) {
* return MyTemplateService.getTemplate(params.pageId);
* }</pre>
*
* @param {string|function=} stateConfig.controller
* <a id='controller'></a>
*
* Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
* Optionally, the ControllerAs may be declared here.
* <pre>controller: "MyRegisteredController"</pre>
* <pre>controller:
* "MyRegisteredController as fooCtrl"}</pre>
* <pre>controller: function($scope, MyService) {
* $scope.data = MyService.getData(); }</pre>
*
* @param {function=} stateConfig.controllerProvider
* <a id='controllerProvider'></a>
*
* Injectable provider function that returns the actual controller or string.
* <pre>controllerProvider:
* function(MyResolveData) {
* if (MyResolveData.foo)
* return "FooCtrl"
* else if (MyResolveData.bar)
* return "BarCtrl";
* else return function($scope) {
* $scope.baz = "Qux";
* }
* }</pre>
*
* @param {string=} stateConfig.controllerAs
* <a id='controllerAs'></a>
*
* A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
* <pre>controllerAs: "myCtrl"</pre>
*
* @param {string|object=} stateConfig.parent
* <a id='parent'></a>
* Optionally specifies the parent state of this state.
*
* <pre>parent: 'parentState'</pre>
* <pre>parent: parentState // JS variable</pre>
*
* @param {object=} stateConfig.resolve
* <a id='resolve'></a>
*
* An optional map<string, function> of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved before the controller is instantiated.
* If all the promises are resolved successfully, the $stateChangeSuccess event is fired
* and the values of the resolved promises are injected into any controllers that reference them.
* If any of the promises are rejected the $stateChangeError event is fired.
*
* The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <pre>resolve: {
* myResolve1:
* function($http, $stateParams) {
* return $http.get("/api/foos/"+stateParams.fooID);
* }
* }</pre>
*
* @param {string=} stateConfig.url
* <a id='url'></a>
*
* A url fragment with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
* more details on acceptable patterns )
*
* examples:
* <pre>url: "/home"
* url: "/users/:userid"
* url: "/books/{bookid:[a-zA-Z_-]}"
* url: "/books/{categoryid:int}"
* url: "/books/{publishername:string}/{categoryid:int}"
* url: "/messages?before&after"
* url: "/messages?{before:date}&{after:date}"
* url: "/messages/:mailboxid?{before:date}&{after:date}"
* </pre>
*
* @param {object=} stateConfig.views
* <a id='views'></a>
* an optional map<string, object> which defined multiple views, or targets views
* manually/explicitly.
*
* Examples:
*
* Targets three named `ui-view`s in the parent state's template
* <pre>views: {
* header: {
* controller: "headerCtrl",
* templateUrl: "header.html"
* }, body: {
* controller: "bodyCtrl",
* templateUrl: "body.html"
* }, footer: {
* controller: "footCtrl",
* templateUrl: "footer.html"
* }
* }</pre>
*
* Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
* <pre>views: {
* 'header@top': {
* controller: "msgHeaderCtrl",
* templateUrl: "msgHeader.html"
* }, 'body': {
* controller: "messagesCtrl",
* templateUrl: "messages.html"
* }
* }</pre>
*
* @param {boolean=} [stateConfig.abstract=false]
* <a id='abstract'></a>
* An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
* <pre>abstract: true</pre>
*
* @param {function=} stateConfig.onEnter
* <a id='onEnter'></a>
*
* Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function,
* because it won't be automatically annotated by your build tools.
*
* <pre>onEnter: function(MyService, $stateParams) {
* MyService.foo($stateParams.myParam);
* }</pre>
*
* @param {function=} stateConfig.onExit
* <a id='onExit'></a>
*
* Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to explictly annotate this function,
* because it won't be automatically annotated by your build tools.
*
* <pre>onExit: function(MyService, $stateParams) {
* MyService.cleanup($stateParams.myParam);
* }</pre>
*
* @param {boolean=} [stateConfig.reloadOnSearch=true]
* <a id='reloadOnSearch'></a>
*
* If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
* <pre>reloadOnSearch: false</pre>
*
* @param {object=} stateConfig.data
* <a id='data'></a>
*
* Arbitrary data object, useful for custom configuration. The parent state's `data` is
* prototypally inherited. In other words, adding a data property to a state adds it to
* the entire subtree via prototypal inheritance.
*
* <pre>data: {
* requiredRole: 'foo'
* } </pre>
*
* @param {object=} stateConfig.params
* <a id='params'></a>
*
* A map which optionally configures parameters declared in the `url`, or
* defines additional non-url parameters. For each parameter being
* configured, add a configuration object keyed to the name of the parameter.
*
* Each parameter configuration object may contain the following properties:
*
* - ** value ** - {object|function=}: specifies the default value for this
* parameter. This implicitly sets this parameter as optional.
*
* When UI-Router routes to a state and no value is
* specified for this parameter in the URL or transition, the
* default value will be used instead. If `value` is a function,
* it will be injected and invoked, and the return value used.
*
* *Note*: `undefined` is treated as "no default value" while `null`
* is treated as "the default value is `null`".
*
* *Shorthand*: If you only need to configure the default value of the
* parameter, you may use a shorthand syntax. In the **`params`**
* map, instead mapping the param name to a full parameter configuration
* object, simply set map it to the default parameter value, e.g.:
*
* <pre>// define a parameter's default value
* params: {
* param1: { value: "defaultValue" }
* }
* // shorthand default values
* params: {
* param1: "defaultValue",
* param2: "param2Default"
* }</pre>
*
* - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
* treated as an array of values. If you specified a Type, the value will be
* treated as an array of the specified Type. Note: query parameter values
* default to a special `"auto"` mode.
*
* For query parameters in `"auto"` mode, if multiple values for a single parameter
* are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
* are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
* only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
* value (e.g.: `{ foo: '1' }`).
*
* <pre>params: {
* param1: { array: true }
* }</pre>
*
* - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
* the current parameter value is the same as the default value. If `squash` is not set, it uses the
* configured default squash policy.
* (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
*
* There are three squash settings:
*
* - false: The parameter's default value is not squashed. It is encoded and included in the URL
* - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
* by slashes in the state's `url` declaration, then one of those slashes are omitted.
* This can allow for cleaner looking URLs.
* - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
*
* <pre>params: {
* param1: {
* value: "defaultId",
* squash: true
* } }
* // squash "defaultValue" to "~"
* params: {
* param1: {
* value: "defaultValue",
* squash: "~"
* } }
* </pre>
*
*
* @example
* <pre>
* // Some state name examples
*
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* </pre>
*
*/
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
/**
* @ngdoc object
* @name ui.router.state.$state
*
* @requires $rootScope
* @requires $q
* @requires ui.router.state.$view
* @requires $injector
* @requires ui.router.util.$resolve
* @requires ui.router.state.$stateParams
* @requires ui.router.router.$urlRouter
*
* @property {object} params A param object, e.g. {sectionId: section.id)}, that
* you'd like to test against the current active state.
* @property {object} current A reference to the state's config object. However
* you passed it in. Useful for accessing custom data.
* @property {object} transition Currently pending transition. A promise that'll
* resolve or reject.
*
* @description
* `$state` service is responsible for representing states as well as transitioning
* between them. It also provides interfaces to ask for current state or even states
* you're coming from.
*/
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
var TransitionSuperseded = $q.reject(new Error('transition superseded'));
var TransitionPrevented = $q.reject(new Error('transition prevented'));
var TransitionAborted = $q.reject(new Error('transition aborted'));
var TransitionFailed = $q.reject(new Error('transition failed'));
// Handles the case where a state which is the target of a transition is not found, and the user
// can optionally retry or defer the transition
function handleRedirect(redirect, state, params, options) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateNotFound
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when a requested state **cannot be found** using the provided state name during transition.
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
* you can see its three properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
*
* @param {Object} event Event object.
* @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
* @param {State} fromState Current state object.
* @param {Object} fromParams Current state params.
*
* @example
*
* <pre>
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", {a:1, b:2}, {inherit:false});
*
* // somewhere else
* $scope.$on('$stateNotFound',
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* })
* </pre>
*/
var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
if (evt.defaultPrevented) {
$urlRouter.update();
return TransitionAborted;
}
if (!evt.retry) {
return null;
}
// Allow the handler to return a promise to defer state lookup retry
if (options.$retry) {
$urlRouter.update();
return TransitionFailed;
}
var retryTransition = $state.transition = $q.when(evt.retry);
retryTransition.then(function() {
if (retryTransition !== $state.transition) return TransitionSuperseded;
redirect.options.$retry = true;
return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
}, function() {
return TransitionAborted;
});
$urlRouter.update();
return retryTransition;
}
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* A method that force reloads the current state. All resolves are re-resolved,
* controllers reinstantiated, and events re-fired.
*
* @example
* <pre>
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* $state.reload();
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: true
* });
* </pre>
*
* @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
* @example
* <pre>
* //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
* //and current state is 'contacts.detail.item'
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* //will reload 'contact.detail' and 'contact.detail.item' states
* $state.reload('contact.detail');
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: true
* });
* </pre>
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.reload = function reload(state) {
return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});
};
/**
* @ngdoc function
* @name ui.router.state.$state#go
* @methodOf ui.router.state.$state
*
* @description
* Convenience method for transitioning to a new state. `$state.go` calls
* `$state.transitionTo` internally but automatically sets options to
* `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
* This allows you to easily use an absolute or relative to path and specify
* only the parameters you'd like to update (while letting unspecified parameters
* inherit from the currently active ancestor states).
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
* <img src='../ngdoc_assets/StateGoExamples.png'/>
*
* @param {string} to Absolute state name or relative state path. Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
* transitioning to a sibling will get you the parameters for all parents, transitioning to a child
* will get you all current parameters, etc.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition.
*
* Possible success values:
*
* - $state.current
*
* <br/>Possible rejection values:
*
* - 'transition superseded' - when a newer transition has been started after this one
* - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
* - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
* when a `$stateNotFound` `event.retry` promise errors.
* - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
* - *resolve error* - when an error has occurred with a `resolve`
*
*/
$state.go = function go(to, params, options) {
return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string} to State name.
* @param {object=} toParams A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
* if String, then will reload the state with the name given in reload, and any children.
* if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.transitionTo = function transitionTo(to, toParams, options) {
toParams = toParams || {};
options = extend({
location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
}, options || {});
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var evt, toState = findState(to, options.relative);
// Store the hash param for later (since it will be stripped out by various methods)
var hash = toParams['#'];
if (!isDefined(toState)) {
var redirect = { to: to, toParams: toParams, options: options };
var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
if (redirectResult) {
return redirectResult;
}
// Always retry once if the $stateNotFound was not prevented
// (handles either redirect changed or state lazy-definition)
to = redirect.to;
toParams = redirect.toParams;
options = redirect.options;
toState = findState(to, options.relative);
if (!isDefined(toState)) {
if (!options.relative) throw new Error("No such state '" + to + "'");
throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
}
}
if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
if (!toState.params.$$validates(toParams)) return TransitionFailed;
toParams = toState.params.$$values(toParams);
to = toState;
var toPath = to.path;
// Starting from the root of the path, keep all levels that haven't changed
var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
if (!options.reload) {
while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
} else if (isString(options.reload) || isObject(options.reload)) {
if (isObject(options.reload) && !options.reload.name) {
throw new Error('Invalid reload state object');
}
var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
if (options.reload && !reloadState) {
throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
}
while (state && state === fromPath[keep] && state !== reloadState) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
}
// If we're going to the same state and all locals are kept, we've got nothing to do.
// But clear 'transition', as we still want to cancel any other pending transitions.
// TODO: We may not want to bump 'transition' if we're called from a location change
// that we've initiated ourselves, because we might accidentally abort a legitimate
// transition initiated from code?
if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
if (hash) toParams['#'] = hash;
$state.params = toParams;
copy($state.params, $stateParams);
if (options.location && to.navigable && to.navigable.url) {
$urlRouter.push(to.navigable.url, toParams, {
$$avoidResync: true, replace: options.location === 'replace'
});
$urlRouter.update(true);
}
$state.transition = null;
return $q.when($state.current);
}
// Filter parameters before we pass them to event handlers etc.
toParams = filterByKeys(to.params.$$keys(), toParams || {});
// Broadcast start event and cancel the transition if requested
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeStart
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when the state transition **begins**. You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*
* @example
*
* <pre>
* $rootScope.$on('$stateChangeStart',
* function(event, toState, toParams, fromState, fromParams){
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* </pre>
*/
if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
$rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
$urlRouter.update();
return TransitionPrevented;
}
}
// Resolve locals for the remaining states, but don't update any global state just
// yet -- if anything fails to resolve the current state needs to remain untouched.
// We also set up an inheritance chain for the locals here. This allows the view directive
// to quickly look up the correct definition for each view in the current state. Even
// though we create the locals object itself outside resolveState(), it is initially
// empty and gets filled asynchronously. We need to keep track of the promise for the
// (fully resolved) current locals, and pass this down the chain.
var resolved = $q.when(locals);
for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
locals = toLocals[l] = inherit(locals);
resolved = resolveState(state, toParams, state === to, resolved, locals, options);
}
// Once everything is resolved, we are ready to perform the actual transition
// and return a promise for the new state. We also keep track of what the
// current promise is, so that we can detect overlapping transitions and
// keep only the outcome of the last transition.
var transition = $state.transition = resolved.then(function () {
var l, entering, exiting;
if ($state.transition !== transition) return TransitionSuperseded;
// Exit 'from' states not kept
for (l = fromPath.length - 1; l >= keep; l--) {
exiting = fromPath[l];
if (exiting.self.onExit) {
$injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
}
exiting.locals = null;
}
// Enter 'to' states not kept
for (l = keep; l < toPath.length; l++) {
entering = toPath[l];
entering.locals = toLocals[l];
if (entering.self.onEnter) {
$injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
}
}
// Re-add the saved hash before we start returning things
if (hash) toParams['#'] = hash;
// Run it again, to catch any transitions in callbacks
if ($state.transition !== transition) return TransitionSuperseded;
// Update globals in $state
$state.$current = to;
$state.current = to.self;
$state.params = toParams;
copy($state.params, $stateParams);
$state.transition = null;
if (options.location && to.navigable) {
$urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
$$avoidResync: true, replace: options.location === 'replace'
});
}
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeSuccess
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired once the state transition is **complete**.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*/
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
}
$urlRouter.update(true);
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeError
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when an **error occurs** during transition. It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
* @param {Error} error The resolve error object.
*/
evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
return $q.reject(error);
});
return transition;
};
/**
* @ngdoc function
* @name ui.router.state.$state#is
* @methodOf ui.router.state.$state
*
* @description
* Similar to {@link ui.router.state.$state#methods_includes $state.includes},
* but only checks for the full state name. If params is supplied then it will be
* tested for strict equality against the current active params object, so all params
* must match with none missing and no extras.
*
* @example
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // absolute name
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // relative name (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.is('.item')}">Item</div>
* </pre>
*
* @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
* test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it is the state.
*/
$state.is = function is(stateOrName, params, options) {
options = extend({ relative: $state.$current }, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) { return undefined; }
if ($state.$current !== state) { return false; }
return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#includes
* @methodOf ui.router.state.$state
*
* @description
* A method to determine if the current active state is equal to or is the child of the
* state stateName. If any params are passed then they will be tested for a match as well.
* Not all the parameters need to be passed, just the ones you'd like to test for equality.
*
* @example
* Partial and relative names
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // Using partial names
* $state.includes("contacts"); // returns true
* $state.includes("contacts.details"); // returns true
* $state.includes("contacts.details.item"); // returns true
* $state.includes("contacts.list"); // returns false
* $state.includes("about"); // returns false
*
* // Using relative names (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
* </pre>
*
* Basic globbing patterns
* <pre>
* $state.$current.name = 'contacts.details.item.url';
*
* $state.includes("*.details.*.*"); // returns true
* $state.includes("*.details.**"); // returns true
* $state.includes("**.item.**"); // returns true
* $state.includes("*.details.item.url"); // returns true
* $state.includes("*.details.*.url"); // returns true
* $state.includes("*.details.*"); // returns false
* $state.includes("item.**"); // returns false
* </pre>
*
* @param {string} stateOrName A partial name, relative name, or glob pattern
* to be searched for within the current state name.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`,
* that you'd like to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
* .includes will test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it does include the state
*/
$state.includes = function includes(stateOrName, params, options) {
options = extend({ relative: $state.$current }, options || {});
if (isString(stateOrName) && isGlob(stateOrName)) {
if (!doesStateMatchGlob(stateOrName)) {
return false;
}
stateOrName = $state.$current.name;
}
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) { return undefined; }
if (!isDefined($state.$current.includes[state.name])) { return false; }
return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#href
* @methodOf ui.router.state.$state
*
* @description
* A url generation method that returns the compiled url for the given state populated with the given params.
*
* @example
* <pre>
* expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
* </pre>
*
* @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
* @param {object=} params An object of parameter values to fill the state's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
* first parameter, then the constructed href url will be built from the first navigable ancestor (aka
* ancestor with a valid url).
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} compiled state url
*/
$state.href = function href(stateOrName, params, options) {
options = extend({
lossy: true,
inherit: true,
absolute: false,
relative: $state.$current
}, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) return null;
if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
var nav = (state && options.lossy) ? state.navigable : state;
if (!nav || nav.url === undefined || nav.url === null) {
return null;
}
return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
absolute: options.absolute
});
};
/**
* @ngdoc function
* @name ui.router.state.$state#get
* @methodOf ui.router.state.$state
*
* @description
* Returns the state configuration object for any specific state or all states.
*
* @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
* the requested state. If not provided, returns an array of ALL state configs.
* @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
* @returns {Object|Array} State configuration object or array of all objects.
*/
$state.get = function (stateOrName, context) {
if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
var state = findState(stateOrName, context || $state.$current);
return (state && state.self) ? state.self : null;
};
function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
// Make a restricted $stateParams with only the parameters that apply to this state if
// necessary. In addition to being available to the controller and onEnter/onExit callbacks,
// we also need $stateParams to be available for any $injector calls we make during the
// dependency resolution process.
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [dst.resolve.then(function (globals) {
dst.globals = globals;
})];
if (inherited) promises.push(inherited);
function resolveViews() {
var viewsPromises = [];
// Resolve template and dependencies for all views.
forEach(state.views, function (view, name) {
var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
injectables.$template = [ function () {
return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';
}];
viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
// References to the controller (only instantiated at link time)
if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
var injectLocals = angular.extend({}, injectables, dst.globals);
result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
} else {
result.$$controller = view.controller;
}
// Provide access to the state itself for internal use
result.$$state = state;
result.$$controllerAs = view.controllerAs;
dst[name] = result;
}));
});
return $q.all(viewsPromises).then(function(){
return dst.globals;
});
}
// Wait for all the promises and then return the activation object
return $q.all(promises).then(resolveViews).then(function (values) {
return dst;
});
}
return $state;
}
function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
// Return true if there are no differences in non-search (path/object) params, false if there are differences
function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
// Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
function notSearchParam(key) {
return fromAndToState.params[key].location != "search";
}
var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
return nonQueryParamSet.$$equals(fromParams, toParams);
}
// If reload was not explicitly requested
// and we're transitioning to the same state we're already in
// and the locals didn't change
// or they changed in a way that doesn't merit reloading
// (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
// Then return true.
if (!options.reload && to === from &&
(locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
return true;
}
}
}
angular.module('ui.router.state')
.value('$stateParams', {})
.provider('$state', $StateProvider);
$ViewProvider.$inject = [];
function $ViewProvider() {
this.$get = $get;
/**
* @ngdoc object
* @name ui.router.state.$view
*
* @requires ui.router.util.$templateFactory
* @requires $rootScope
*
* @description
*
*/
$get.$inject = ['$rootScope', '$templateFactory'];
function $get( $rootScope, $templateFactory) {
return {
// $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
/**
* @ngdoc function
* @name ui.router.state.$view#load
* @methodOf ui.router.state.$view
*
* @description
*
* @param {string} name name
* @param {object} options option object.
*/
load: function load(name, options) {
var result, defaults = {
template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
};
options = extend(defaults, options);
if (options.view) {
result = $templateFactory.fromConfig(options.view, options.params, options.locals);
}
if (result && options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$viewContentLoading
* @eventOf ui.router.state.$view
* @eventType broadcast on root scope
* @description
*
* Fired once the view **begins loading**, *before* the DOM is rendered.
*
* @param {Object} event Event object.
* @param {Object} viewConfig The view config properties (template, controller, etc).
*
* @example
*
* <pre>
* $scope.$on('$viewContentLoading',
* function(event, viewConfig){
* // Access to all the view config properties.
* // and one special property 'targetView'
* // viewConfig.targetView
* });
* </pre>
*/
$rootScope.$broadcast('$viewContentLoading', options);
}
return result;
}
};
}
}
angular.module('ui.router.state').provider('$view', $ViewProvider);
/**
* @ngdoc object
* @name ui.router.state.$uiViewScrollProvider
*
* @description
* Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
*/
function $ViewScrollProvider() {
var useAnchorScroll = false;
/**
* @ngdoc function
* @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
* @methodOf ui.router.state.$uiViewScrollProvider
*
* @description
* Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
* scrolling based on the url anchor.
*/
this.useAnchorScroll = function () {
useAnchorScroll = true;
};
/**
* @ngdoc object
* @name ui.router.state.$uiViewScroll
*
* @requires $anchorScroll
* @requires $timeout
*
* @description
* When called with a jqLite element, it scrolls the element into view (after a
* `$timeout` so the DOM has time to refresh).
*
* If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
* this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
*/
this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
if (useAnchorScroll) {
return $anchorScroll;
}
return function ($element) {
return $timeout(function () {
$element[0].scrollIntoView();
}, 0, false);
};
}];
}
angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-view
*
* @requires ui.router.state.$state
* @requires $compile
* @requires $controller
* @requires $injector
* @requires ui.router.state.$uiViewScroll
* @requires $document
*
* @restrict ECA
*
* @description
* The ui-view directive tells $state where to place your templates.
*
* @param {string=} name A view name. The name should be unique amongst the other views in the
* same state. You can have views of the same name that live in different states.
*
* @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
* when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
* service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
* scroll ui-view elements into view when they are populated during a state activation.
*
* *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
* functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
*
* @param {string=} onload Expression to evaluate whenever the view updates.
*
* @example
* A view can be unnamed or named.
* <pre>
* <!-- Unnamed -->
* <div ui-view></div>
*
* <!-- Named -->
* <div ui-view="viewName"></div>
* </pre>
*
* You can only have one unnamed view within any template (or root html). If you are only using a
* single view and it is unnamed then you can populate it like so:
* <pre>
* <div ui-view></div>
* $stateProvider.state("home", {
* template: "<h1>HELLO!</h1>"
* })
* </pre>
*
* The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
* config property, by name, in this case an empty name:
* <pre>
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* </pre>
*
* But typically you'll only use the views property if you name your view or have more than one view
* in the same template. There's not really a compelling reason to name a view if its the only one,
* but you could if you wanted, like so:
* <pre>
* <div ui-view="main"></div>
* </pre>
* <pre>
* $stateProvider.state("home", {
* views: {
* "main": {
* template: "<h1>HELLO!</h1>"
* }
* }
* })
* </pre>
*
* Really though, you'll use views to set up multiple views:
* <pre>
* <div ui-view></div>
* <div ui-view="chart"></div>
* <div ui-view="data"></div>
* </pre>
*
* <pre>
* $stateProvider.state("home", {
* views: {
* "": {
* template: "<h1>HELLO!</h1>"
* },
* "chart": {
* template: "<chart_thing/>"
* },
* "data": {
* template: "<data_thing/>"
* }
* }
* })
* </pre>
*
* Examples for `autoscroll`:
*
* <pre>
* <!-- If autoscroll present with no expression,
* then scroll ui-view into view -->
* <ui-view autoscroll/>
*
* <!-- If autoscroll present with valid expression,
* then scroll ui-view into view if expression evaluates to true -->
* <ui-view autoscroll='true'/>
* <ui-view autoscroll='false'/>
* <ui-view autoscroll='scopeVariable'/>
* </pre>
*/
$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
function getService() {
return ($injector.has) ? function(service) {
return $injector.has(service) ? $injector.get(service) : null;
} : function(service) {
try {
return $injector.get(service);
} catch (e) {
return null;
}
};
}
var service = getService(),
$animator = service('$animator'),
$animate = service('$animate');
// Returns a set of DOM manipulation functions based on which Angular version
// it should use
function getRenderer(attrs, scope) {
var statics = function() {
return {
enter: function (element, target, cb) { target.after(element); cb(); },
leave: function (element, cb) { element.remove(); cb(); }
};
};
if ($animate) {
return {
enter: function(element, target, cb) {
var promise = $animate.enter(element, null, target, cb);
if (promise && promise.then) promise.then(cb);
},
leave: function(element, cb) {
var promise = $animate.leave(element, cb);
if (promise && promise.then) promise.then(cb);
}
};
}
if ($animator) {
var animate = $animator && $animator(scope, attrs);
return {
enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
leave: function(element, cb) { animate.leave(element); cb(); }
};
}
return statics();
}
var directive = {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
compile: function (tElement, tAttrs, $transclude) {
return function (scope, $element, attrs) {
var previousEl, currentEl, currentScope, latestLocals,
onloadExp = attrs.onload || '',
autoScrollExp = attrs.autoscroll,
renderer = getRenderer(attrs, scope);
scope.$on('$stateChangeSuccess', function() {
updateView(false);
});
scope.$on('$viewContentLoading', function() {
updateView(false);
});
updateView(true);
function cleanupLastView() {
if (previousEl) {
previousEl.remove();
previousEl = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentEl) {
renderer.leave(currentEl, function() {
previousEl = null;
});
previousEl = currentEl;
currentEl = null;
}
}
function updateView(firstTime) {
var newScope,
name = getUiViewName(scope, attrs, $element, $interpolate),
previousLocals = name && $state.$current && $state.$current.locals[name];
if (!firstTime && previousLocals === latestLocals) return; // nothing to do
newScope = scope.$new();
latestLocals = $state.$current.locals[name];
var clone = $transclude(newScope, function(clone) {
renderer.enter(clone, $element, function onUiViewEnter() {
if(currentScope) {
currentScope.$emit('$viewContentAnimationEnded');
}
if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
$uiViewScroll(clone);
}
});
cleanupLastView();
});
currentEl = clone;
currentScope = newScope;
/**
* @ngdoc event
* @name ui.router.state.directive:ui-view#$viewContentLoaded
* @eventOf ui.router.state.directive:ui-view
* @eventType emits on ui-view directive scope
* @description *
* Fired once the view is **loaded**, *after* the DOM is rendered.
*
* @param {Object} event Event object.
*/
currentScope.$emit('$viewContentLoaded');
currentScope.$eval(onloadExp);
}
};
}
};
return directive;
}
$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
return {
restrict: 'ECA',
priority: -400,
compile: function (tElement) {
var initial = tElement.html();
return function (scope, $element, attrs) {
var current = $state.$current,
name = getUiViewName(scope, attrs, $element, $interpolate),
locals = current && current.locals[name];
if (! locals) {
return;
}
$element.data('$uiView', { name: name, state: locals.$$state });
$element.html(locals.$template ? locals.$template : initial);
var link = $compile($element.contents());
if (locals.$$controller) {
locals.$scope = scope;
locals.$element = $element;
var controller = $controller(locals.$$controller, locals);
if (locals.$$controllerAs) {
scope[locals.$$controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
link(scope);
};
}
};
}
/**
* Shared ui-view code for both directives:
* Given scope, element, and its attributes, return the view's name
*/
function getUiViewName(scope, attrs, element, $interpolate) {
var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
var inherited = element.inheritedData('$uiView');
return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
}
angular.module('ui.router.state').directive('uiView', $ViewDirective);
angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
function parseStateRef(ref, current) {
var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
if (preparsed) ref = current + '(' + preparsed[1] + ')';
parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1], paramExpr: parsed[3] || null };
}
function stateContext(el) {
var stateData = el.parent().inheritedData('$uiView');
if (stateData && stateData.state && stateData.state.name) {
return stateData.state;
}
}
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref
*
* @requires ui.router.state.$state
* @requires $timeout
*
* @restrict A
*
* @description
* A directive that binds a link (`<a>` tag) to a state. If the state has an associated
* URL, the directive will automatically generate & update the `href` attribute via
* the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
* the link will trigger a state transition with optional parameters.
*
* Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
* handled natively by the browser.
*
* You can also use relative state paths within ui-sref, just like the relative
* paths passed to `$state.go()`. You just need to be aware that the path is relative
* to the state that the link lives in, in other words the state that loaded the
* template containing the link.
*
* You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
* using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
* and `reload`.
*
* @example
* Here's an example of how you'd use ui-sref and how it would compile. If you have the
* following template:
* <pre>
* <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
* </li>
* </ul>
* </pre>
*
* Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
* <pre>
* <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
* </li>
* </ul>
*
* <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
* </pre>
*
* @param {string} ui-sref 'stateName' can be any valid absolute or relative state
* @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
*/
$StateRefDirective.$inject = ['$state', '$timeout'];
function $StateRefDirective($state, $timeout) {
var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function(scope, element, attrs, uiSrefActive) {
var ref = parseStateRef(attrs.uiSref, $state.current.name);
var params = null, url = null, base = stateContext(element) || $state.$current;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
var newHref = null, isAnchor = element.prop("tagName").toUpperCase() === "A";
var isForm = element[0].nodeName === "FORM";
var attr = isForm ? "action" : hrefKind, nav = true;
var options = { relative: base, inherit: true };
var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
angular.forEach(allowedOptions, function(option) {
if (option in optionsOverride) {
options[option] = optionsOverride[option];
}
});
var update = function(newVal) {
if (newVal) params = angular.copy(newVal);
if (!nav) return;
newHref = $state.href(ref.state, params, options);
var activeDirective = uiSrefActive[1] || uiSrefActive[0];
if (activeDirective) {
activeDirective.$$addStateInfo(ref.state, params);
}
if (newHref === null) {
nav = false;
return false;
}
attrs.$set(attr, newHref);
};
if (ref.paramExpr) {
scope.$watch(ref.paramExpr, function(newVal, oldVal) {
if (newVal !== params) update(newVal);
}, true);
params = angular.copy(scope.$eval(ref.paramExpr));
}
update();
if (isForm) return;
element.bind("click", function(e) {
var button = e.which || e.button;
if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
var transition = $timeout(function() {
$state.go(ref.state, params, options);
});
e.preventDefault();
// if the state has no URL, ignore one preventDefault from the <a> directive.
var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
e.preventDefault = function() {
if (ignorePreventDefaultCount-- <= 0)
$timeout.cancel(transition);
};
}
});
}
};
}
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref-active
*
* @requires ui.router.state.$state
* @requires ui.router.state.$stateParams
* @requires $interpolate
*
* @restrict A
*
* @description
* A directive working alongside ui-sref to add classes to an element when the
* related ui-sref directive's state is active, and removing them when it is inactive.
* The primary use-case is to simplify the special appearance of navigation menus
* relying on `ui-sref`, by having the "active" state's menu button appear different,
* distinguishing it from the inactive menu items.
*
* ui-sref-active can live on the same element as ui-sref or on a parent element. The first
* ui-sref-active found at the same level or above the ui-sref will be used.
*
* Will activate when the ui-sref's target state or any child state is active. If you
* need to activate only when the ui-sref target state is active and *not* any of
* it's children, then you will use
* {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
*
* @example
* Given the following template:
* <pre>
* <ul>
* <li ui-sref-active="active" class="item">
* <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
* </li>
* </ul>
* </pre>
*
*
* When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
* the resulting HTML will appear as (note the 'active' class):
* <pre>
* <ul>
* <li ui-sref-active="active" class="item active">
* <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
* </li>
* </ul>
* </pre>
*
* The class name is interpolated **once** during the directives link time (any further changes to the
* interpolated value are ignored).
*
* Multiple classes may be specified in a space-separated format:
* <pre>
* <ul>
* <li ui-sref-active='class1 class2 class3'>
* <a ui-sref="app.user">link</a>
* </li>
* </ul>
* </pre>
*/
/**
* @ngdoc directive
* @name ui.router.state.directive:ui-sref-active-eq
*
* @requires ui.router.state.$state
* @requires ui.router.state.$stateParams
* @requires $interpolate
*
* @restrict A
*
* @description
* The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
* when the exact target state used in the `ui-sref` is active; no child states.
*
*/
$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
function $StateRefActiveDirective($state, $stateParams, $interpolate) {
return {
restrict: "A",
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
var states = [], activeClass;
// There probably isn't much point in $observing this
// uiSrefActive and uiSrefActiveEq share the same directive object with some
// slight difference in logic routing
activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
// Allow uiSref to communicate with uiSrefActive[Equals]
this.$$addStateInfo = function (newState, newParams) {
var state = $state.get(newState, stateContext($element));
states.push({
state: state || { name: newState },
params: newParams
});
update();
};
$scope.$on('$stateChangeSuccess', update);
// Update route state
function update() {
if (anyMatch()) {
$element.addClass(activeClass);
} else {
$element.removeClass(activeClass);
}
}
function anyMatch() {
for (var i = 0; i < states.length; i++) {
if (isMatch(states[i].state, states[i].params)) {
return true;
}
}
return false;
}
function isMatch(state, params) {
if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
return $state.is(state.name, params);
} else {
return $state.includes(state.name, params);
}
}
}]
};
}
angular.module('ui.router.state')
.directive('uiSref', $StateRefDirective)
.directive('uiSrefActive', $StateRefActiveDirective)
.directive('uiSrefActiveEq', $StateRefActiveDirective);
/**
* @ngdoc filter
* @name ui.router.state.filter:isState
*
* @requires ui.router.state.$state
*
* @description
* Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
*/
$IsStateFilter.$inject = ['$state'];
function $IsStateFilter($state) {
var isFilter = function (state) {
return $state.is(state);
};
isFilter.$stateful = true;
return isFilter;
}
/**
* @ngdoc filter
* @name ui.router.state.filter:includedByState
*
* @requires ui.router.state.$state
*
* @description
* Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
*/
$IncludedByStateFilter.$inject = ['$state'];
function $IncludedByStateFilter($state) {
var includesFilter = function (state) {
return $state.includes(state);
};
includesFilter.$stateful = true;
return includesFilter;
}
angular.module('ui.router.state')
.filter('isState', $IsStateFilter)
.filter('includedByState', $IncludedByStateFilter);
})(window, window.angular);
},{}],8:[function(require,module,exports){
/**
* @license AngularJS v1.4.4
* (c) 2010-2015 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {'use strict';
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var SKIP_INDEXES = 2;
var templateArgs = arguments,
code = templateArgs[0],
message = '[' + (module ? module + ':' : '') + code + '] ',
template = templateArgs[1],
paramPrefix, i;
message += template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1),
shiftedIndex = index + SKIP_INDEXES;
if (shiftedIndex < templateArgs.length) {
return toDebugString(templateArgs[shiftedIndex]);
}
return match;
});
message += '\nhttp://errors.angularjs.org/1.4.4/' +
(module ? module + '/' : '') + code;
for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
encodeURIComponent(toDebugString(templateArgs[i]));
}
return new ErrorConstructor(message);
};
}
/* We need to tell jshint what variables are being exported */
/* global angular: true,
msie: true,
jqLite: true,
jQuery: true,
slice: true,
splice: true,
push: true,
toString: true,
ngMinErr: true,
angularModule: true,
uid: true,
REGEX_STRING_REGEXP: true,
VALIDITY_STATE_PROPERTY: true,
lowercase: true,
uppercase: true,
manualLowercase: true,
manualUppercase: true,
nodeName_: true,
isArrayLike: true,
forEach: true,
forEachSorted: true,
reverseParams: true,
nextUid: true,
setHashKey: true,
extend: true,
toInt: true,
inherit: true,
merge: true,
noop: true,
identity: true,
valueFn: true,
isUndefined: true,
isDefined: true,
isObject: true,
isBlankObject: true,
isString: true,
isNumber: true,
isDate: true,
isArray: true,
isFunction: true,
isRegExp: true,
isWindow: true,
isScope: true,
isFile: true,
isFormData: true,
isBlob: true,
isBoolean: true,
isPromiseLike: true,
trim: true,
escapeForRegexp: true,
isElement: true,
makeMap: true,
includes: true,
arrayRemove: true,
copy: true,
shallowCopy: true,
equals: true,
csp: true,
jq: true,
concat: true,
sliceArgs: true,
bind: true,
toJsonReplacer: true,
toJson: true,
fromJson: true,
convertTimezoneToLocal: true,
timezoneToOffset: true,
startingTag: true,
tryDecodeURIComponent: true,
parseKeyValue: true,
toKeyValue: true,
encodeUriSegment: true,
encodeUriQuery: true,
angularInit: true,
bootstrap: true,
getTestability: true,
snake_case: true,
bindJQuery: true,
assertArg: true,
assertArgFn: true,
assertNotHasOwnProperty: true,
getter: true,
getBlockNodes: true,
hasOwnProperty: true,
createMap: true,
NODE_TYPE_ELEMENT: true,
NODE_TYPE_ATTRIBUTE: true,
NODE_TYPE_TEXT: true,
NODE_TYPE_COMMENT: true,
NODE_TYPE_DOCUMENT: true,
NODE_TYPE_DOCUMENT_FRAGMENT: true,
*/
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @description
*
* # ng (core module)
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
* <div doc-module-components="ng"></div>
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
/**
* @ngdoc function
* @name angular.lowercase
* @module ng
* @kind function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @ngdoc function
* @name angular.uppercase
* @module ng
* @kind function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
// Support: iOS 8.2 (not reproducible in simulator)
// "length" in obj used to prevent JIT error (gh-11508)
var length = "length" in Object(obj) && obj.length;
if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
}
return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
// Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
// Slow path for objects which do not have a method `hasOwnProperty`
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function forEachSorted(obj, iterator, context) {
var keys = Object.keys(obj).sort();
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value); };
}
/**
* A consistent way of creating unique IDs in angular.
*
* Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
* we hit number precision issues in JavaScript.
*
* Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
*
* @returns {number} an unique alpha-numeric string
*/
function nextUid() {
return ++uid;
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
} else {
delete obj.$$hashKey;
}
}
function baseExtend(dst, objs, deep) {
var h = dst.$$hashKey;
for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i];
if (!isObject(obj) && !isFunction(obj)) continue;
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
var src = obj[key];
if (deep && isObject(src)) {
if (isDate(src)) {
dst[key] = new Date(src.valueOf());
} else if (isRegExp(src)) {
dst[key] = new RegExp(src);
} else {
if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
baseExtend(dst[key], [src], true);
}
} else {
dst[key] = src;
}
}
}
setHashKey(dst, h);
return dst;
}
/**
* @ngdoc function
* @name angular.extend
* @module ng
* @kind function
*
* @description
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
*
* **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
* {@link angular.merge} for this.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
return baseExtend(dst, slice.call(arguments, 1), false);
}
/**
* @ngdoc function
* @name angular.merge
* @module ng
* @kind function
*
* @description
* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
*
* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
* objects, performing a deep copy.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function merge(dst) {
return baseExtend(dst, slice.call(arguments, 1), true);
}
function toInt(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(Object.create(parent), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @module ng
* @kind function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
```js
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
```
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @module ng
* @kind function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
```js
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
```
* @param {*} value to be returned.
* @returns {*} the value passed in.
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
function hasCustomToString(obj) {
return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
var isArray = Array.isArray;
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
function isTypedArray(value) {
return TYPED_ARRAY_REGEXP.test(toString.call(value));
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08');
};
/**
* @ngdoc function
* @name angular.isElement
* @module ng
* @kind function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str) {
var obj = {}, items = str.split(","), i;
for (i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function nodeName_(element) {
return lowercase(element.nodeName || (element[0] && element[0].nodeName));
}
function includes(array, obj) {
return Array.prototype.indexOf.call(array, obj) != -1;
}
function arrayRemove(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
<example module="copyExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}]);
</script>
</file>
</example>
*/
function copy(source, destination, stackSource, stackDest) {
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
"Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (isTypedArray(destination)) {
throw ngMinErr('cpta',
"Can't copy! TypedArray destination cannot be mutated.");
}
if (!destination) {
destination = source;
if (isObject(source)) {
var index;
if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
return stackDest[index];
}
// TypedArray, Date and RegExp have specific copy functionality and must be
// pushed onto the stack before returning.
// Array and other objects create the base object and recurse to copy child
// objects. The array/object will be pushed onto the stack when recursed.
if (isArray(source)) {
return copy(source, [], stackSource, stackDest);
} else if (isTypedArray(source)) {
destination = new source.constructor(source);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else {
var emptyObject = Object.create(getPrototypeOf(source));
return copy(source, emptyObject, stackSource, stackDest);
}
if (stackDest) {
stackSource.push(source);
stackDest.push(destination);
}
}
} else {
if (source === destination) throw ngMinErr('cpi',
"Can't copy! Source and destination are identical.");
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
stackSource.push(source);
stackDest.push(destination);
}
var result, key;
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
destination.push(copy(source[i], null, stackSource, stackDest));
}
} else {
var h = destination.$$hashKey;
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
delete destination[key];
});
}
if (isBlankObject(source)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in source) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
} else if (source && typeof source.hasOwnProperty === 'function') {
// Slow path, which must rely on hasOwnProperty
for (key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
} else {
// Slowest path --- hasOwnProperty can't be called as a method
for (key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = copy(source[key], null, stackSource, stackDest);
}
}
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return equals(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
return isRegExp(o2) ? o1.toString() == o2.toString() : false;
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
var csp = function() {
if (!isDefined(csp.rules)) {
var ngCspElement = (document.querySelector('[ng-csp]') ||
document.querySelector('[data-ng-csp]'));
if (ngCspElement) {
var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
ngCspElement.getAttribute('data-ng-csp');
csp.rules = {
noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
};
} else {
csp.rules = {
noUnsafeEval: noUnsafeEval(),
noInlineStyle: false
};
}
}
return csp.rules;
function noUnsafeEval() {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
return false;
} catch (e) {
return true;
}
}
};
/**
* @ngdoc directive
* @module ng
* @name ngJq
*
* @element ANY
* @param {string=} ngJq the name of the library available under `window`
* to be used for angular.element
* @description
* Use this directive to force the angular.element library. This should be
* used to force either jqLite by leaving ng-jq blank or setting the name of
* the jquery variable under window (eg. jQuery).
*
* Since angular looks for this directive when it is loaded (doesn't wait for the
* DOMContentLoaded event), it must be placed on an element that comes before the script
* which loads angular. Also, only the first instance of `ng-jq` will be used and all
* others ignored.
*
* @example
* This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-jq>
...
...
</html>
```
* @example
* This example shows how to use a jQuery based library of a different name.
* The library name must be available at the top most 'window'.
```html
<!doctype html>
<html ng-app ng-jq="jQueryLib">
...
...
</html>
```
*/
var jq = function() {
if (isDefined(jq.name_)) return jq.name_;
var el;
var i, ii = ngAttrPrefixes.length, prefix, name;
for (i = 0; i < ii; ++i) {
prefix = ngAttrPrefixes[i];
if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
name = el.getAttribute(prefix + 'jq');
break;
}
}
return (jq.name_ = name);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/* jshint -W101 */
/**
* @ngdoc function
* @name angular.bind
* @module ng
* @kind function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
/* jshint +W101 */
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, concat(curryArgs, arguments, 0))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @module ng
* @kind function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
* stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
* If set to an integer, the JSON output will contain that many spaces per indentation.
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
/**
* @ngdoc function
* @name angular.fromJson
* @module ng
* @kind function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|string|number} Deserialized JSON string.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function timezoneToOffset(timezone, fallback) {
var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
reverse = reverse ? -1 : 1;
var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.empty();
} catch (e) {}
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns {Object.<string,boolean|Array>}
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {};
forEach((keyValue || "").split('&'), function(keyValue) {
var splitPoint, key, val;
if (keyValue) {
key = keyValue = keyValue.replace(/\+/g,'%20');
splitPoint = keyValue.indexOf('=');
if (splitPoint !== -1) {
key = keyValue.substring(0, splitPoint);
val = keyValue.substring(splitPoint + 1);
}
key = tryDecodeURIComponent(key);
if (isDefined(key)) {
val = isDefined(val) ? tryDecodeURIComponent(val) : true;
if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if (isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%3B/gi, ';').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
function getNgAttribute(element, ngAttr) {
var attr, i, ii = ngAttrPrefixes.length;
for (i = 0; i < ii; ++i) {
attr = ngAttrPrefixes[i] + ngAttr;
if (isString(attr = element.getAttribute(attr))) {
return attr;
}
}
return null;
}
/**
* @ngdoc directive
* @name ngApp
* @module ng
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
* @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
* created in "strict-di" mode. This means that the application will fail to invoke functions which
* do not use explicit function annotation (and are thus unsuitable for minification), as described
* in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
* tracking down the root of these bugs.
*
* @description
*
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
* designates the **root element** of the application and is typically placed near the root element
* of the page - e.g. on the `<body>` or `<html>` tags.
*
* Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
* found in the document will be used to define the root element to auto-bootstrap as an
* application. To run multiple applications in an HTML document you must manually bootstrap them using
* {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
*
* You can specify an **AngularJS module** to be used as the root module for the application. This
* module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
* should contain the application code needed or have dependencies on other modules that will
* contain the code. See {@link angular.module} for more information.
*
* In the example below if the `ngApp` directive were not placed on the `html` element then the
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
* would not be resolved to `3`.
*
* `ngApp` is the easiest, and most common way to bootstrap an application.
*
<example module="ngAppDemo">
<file name="index.html">
<div ng-controller="ngAppDemoController">
I can add: {{a}} + {{b}} = {{ a+b }}
</div>
</file>
<file name="script.js">
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
$scope.a = 1;
$scope.b = 2;
});
</file>
</example>
*
* Using `ngStrictDi`, you would see something like this:
*
<example ng-app-included="true">
<file name="index.html">
<div ng-app="ngAppStrictDemo" ng-strict-di>
<div ng-controller="GoodController1">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
</p>
</div>
<div ng-controller="GoodController2">
Name: <input ng-model="name"><br />
Hello, {{name}}!
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
</p>
</div>
<div ng-controller="BadController">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
</p>
</div>
</div>
</file>
<file name="script.js">
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = "World";
}
GoodController2.$inject = ['$scope'];
</file>
<file name="style.css">
div[ng-controller] {
margin-bottom: 1em;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;
}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;
}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;
}
</file>
</example>
*/
function angularInit(element, bootstrap) {
var appElement,
module,
config = {};
// The element `element` has priority over any other element
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
appElement = element;
module = element.getAttribute(name);
}
});
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
var candidate;
if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
appElement = candidate;
module = candidate.getAttribute(name);
}
});
if (appElement) {
config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
bootstrap(appElement, module ? [module] : [], config);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @module ng
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link ng.directive:ngApp ngApp}.
*
* Angular will detect if it has been loaded into the browser more than once and only allow the
* first loaded script to be bootstrapped and will report a warning to the browser console for
* each of the subsequent scripts. This prevents strange results in applications, where otherwise
* multiple instances of Angular try to work on the DOM.
*
* ```html
* <!doctype html>
* <html>
* <body>
* <div ng-controller="WelcomeController">
* {{greeting}}
* </div>
*
* <script src="angular.js"></script>
* <script>
* var app = angular.module('demo', [])
* .controller('WelcomeController', function($scope) {
* $scope.greeting = 'Welcome!';
* });
* angular.bootstrap(document, ['demo']);
* </script>
* </body>
* </html>
* ```
*
* @param {DOMElement} element DOM element which is the root of angular application.
* @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
* @param {Object=} config an object for defining configuration options for the application. The
* following keys are supported:
*
* * `strictDi` - disable automatic function annotation for the application. This is meant to
* assist in finding bugs which break minified code. Defaults to `false`.
*
* @returns {auto.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules, config) {
if (!isObject(config)) config = {};
var defaultConfig = {
strictDi: false
};
config = extend(defaultConfig, config);
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === document) ? 'document' : startingTag(element);
//Encode angle brackets to prevent input from being sanitized to empty string #8683
throw ngMinErr(
'btstrpd',
"App Already Bootstrapped with this Element '{0}'",
tag.replace(/</,'<').replace(/>/,'>'));
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
// Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
modules.push(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
config.debugInfoEnabled = true;
window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
}
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
return doBootstrap();
};
if (isFunction(angular.resumeDeferredBootstrap)) {
angular.resumeDeferredBootstrap();
}
}
/**
* @ngdoc function
* @name angular.reloadWithDebugInfo
* @module ng
* @description
* Use this function to reload the current application with debug information turned on.
* This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
*
* See {@link ng.$compileProvider#debugInfoEnabled} for more.
*/
function reloadWithDebugInfo() {
window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
window.location.reload();
}
/**
* @name angular.getTestability
* @module ng
* @description
* Get the testability service for the instance of Angular on the given
* element.
* @param {DOMElement} element DOM element which is the root of angular application.
*/
function getTestability(rootElement) {
var injector = angular.element(rootElement).injector();
if (!injector) {
throw ngMinErr('test',
'no injector found for element argument to getTestability');
}
return injector.get('$$testability');
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
var bindJQueryFired = false;
var skipDestroyOnNextJQueryCleanData;
function bindJQuery() {
var originalCleanData;
if (bindJQueryFired) {
return;
}
// bind to jQuery if present;
var jqName = jq();
jQuery = window.jQuery; // use default jQuery.
if (isDefined(jqName)) { // `ngJq` present
jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
}
// Use jQuery if it exists with proper functionality, otherwise default to us.
// Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
// Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
// versions. It will not work for sure with jQuery <1.7, though.
if (jQuery && jQuery.fn.on) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
// All nodes removed from the DOM via various jQuery APIs like .remove()
// are passed through jQuery.cleanData. Monkey-patch this method to fire
// the $destroy event on all removed nodes.
originalCleanData = jQuery.cleanData;
jQuery.cleanData = function(elems) {
var events;
if (!skipDestroyOnNextJQueryCleanData) {
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
events = jQuery._data(elem, "events");
if (events && events.$destroy) {
jQuery(elem).triggerHandler('$destroy');
}
}
} else {
skipDestroyOnNextJQueryCleanData = false;
}
originalCleanData(elems);
};
} else {
jqLite = JQLite;
}
angular.element = jqLite;
// Prevent double-proxying.
bindJQueryFired = true;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {String} path path to traverse
* @param {boolean} [bindFnToScope=true]
* @returns {Object} value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {jqLite} jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
// collection, otherwise update the original collection.
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes = [node];
do {
node = node.nextSibling;
if (!node) break;
blockNodes.push(node);
} while (node !== endNode);
return jqLite(blockNodes);
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc type
* @name angular.Module
* @module ng
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
var ngMinErr = minErr('ng');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
var angular = ensure(window, 'angular', Object);
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @module ng
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving Angular
* modules.
* All modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* Passing one argument retrieves an existing {@link angular.Module},
* whereas passing more than one argument creates a new {@link angular.Module}
*
*
* # Module
*
* A module is a collection of services, directives, controllers, filters, and configuration information.
* `angular.module` is used to configure the {@link auto.$injector $injector}.
*
* ```js
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(['$locationProvider', function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* }]);
* ```
*
* Then you can create an injector and load your modules like this:
*
* ```js
* var injector = angular.injector(['ng', 'myModule'])
* ```
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {!Array.<string>=} requires If specified then new module is being created. If
* unspecified then the module is being retrieved for further configuration.
* @param {Function=} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
var assertNotHasOwnProperty = function(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
};
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var configBlocks = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @module ng
*
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @module ng
*
* @description
* Name of the module.
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @module ng
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link auto.$provide#provider $provide.provider()}.
*/
provider: invokeLaterAndSetModuleName('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @module ng
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link auto.$provide#factory $provide.factory()}.
*/
factory: invokeLaterAndSetModuleName('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @module ng
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link auto.$provide#service $provide.service()}.
*/
service: invokeLaterAndSetModuleName('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @module ng
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link auto.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @module ng
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link auto.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#decorator
* @module ng
* @param {string} The name of the service to decorate.
* @param {Function} This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance.
* @description
* See {@link auto.$provide#decorator $provide.decorator()}.
*/
decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid angular expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method) {
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
invokeQueue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global: toDebugString: true */
function serializeObject(obj) {
var seen = [];
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '<<already seen>>';
seen.push(val);
}
return val;
});
}
function toDebugString(obj) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (typeof obj === 'undefined') {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj);
}
return obj;
}
/* global angularModule: true,
version: true,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
inputDirective,
formDirective,
scriptDirective,
selectDirective,
styleDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngIncludeFillContentDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
patternDirective,
patternDirective,
requiredDirective,
requiredDirective,
minlengthDirective,
minlengthDirective,
maxlengthDirective,
maxlengthDirective,
ngValueDirective,
ngModelOptionsDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$CoreAnimateCssProvider,
$$CoreAnimateQueueProvider,
$$CoreAnimateRunnerProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DocumentProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$$ForceReflowProvider,
$InterpolateProvider,
$IntervalProvider,
$$HashMapProvider,
$HttpProvider,
$HttpParamSerializerProvider,
$HttpParamSerializerJQLikeProvider,
$HttpBackendProvider,
$LocationProvider,
$LogProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$$QProvider,
$$SanitizeUriProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$TemplateCacheProvider,
$TemplateRequestProvider,
$$TestabilityProvider,
$TimeoutProvider,
$$RAFProvider,
$WindowProvider,
$$jqLiteProvider,
$$CookieReaderProvider
*/
/**
* @ngdoc object
* @name angular.version
* @module ng
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.4.4', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 4,
dot: 4,
codeName: 'pylon-requirement'
};
function publishExternalAPI(angular) {
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'merge': merge,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0},
'getTestability': getTestability,
'$$minErr': minErr,
'$$csp': csp,
'reloadWithDebugInfo': reloadWithDebugInfo
});
angularModule = setupModuleLoader(window);
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
$provide.provider({
$$sanitizeUri: $$SanitizeUriProvider
});
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
pattern: patternDirective,
ngPattern: patternDirective,
required: requiredDirective,
ngRequired: requiredDirective,
minlength: minlengthDirective,
ngMinlength: minlengthDirective,
maxlength: maxlengthDirective,
ngMaxlength: maxlengthDirective,
ngValue: ngValueDirective,
ngModelOptions: ngModelOptionsDirective
}).
directive({
ngInclude: ngIncludeFillContentDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$animateCss: $CoreAnimateCssProvider,
$$animateQueue: $$CoreAnimateQueueProvider,
$$AnimateRunner: $$CoreAnimateRunnerProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$$forceReflow: $$ForceReflowProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$http: $HttpProvider,
$httpParamSerializer: $HttpParamSerializerProvider,
$httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$$q: $$QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$templateRequest: $TemplateRequestProvider,
$$testability: $$TestabilityProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider,
$$jqLite: $$jqLiteProvider,
$$HashMap: $$HashMapProvider,
$$cookieReader: $$CookieReaderProvider
});
}
]);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* global JQLitePrototype: true,
addEventListenerFn: true,
removeEventListenerFn: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true,
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1,
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
},
removeEventListenerFn = function(element, type, fn) {
element.removeEventListener(type, fn, false);
};
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteHasData(node) {
for (var key in jqCache[node.ng339]) {
return true;
}
return false;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = tmp || fragment.appendChild(context.createElement("div"));
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = "";
}
// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants) jqLiteRemoveData(element);
if (element.querySelectorAll) {
var descendants = element.querySelectorAll('*');
for (var i = 0, l = descendants.length; i < l; i++) {
jqLiteRemoveData(descendants[i]);
}
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
removeEventListenerFn(element, type, handle);
}
delete events[type];
}
} else {
forEach(type.split(' '), function(type) {
if (isDefined(fn)) {
var listenerFns = events[type];
arrayRemove(listenerFns || [], fn);
if (listenerFns && listenerFns.length > 0) {
return;
}
}
removeEventListenerFn(element, type, handle);
delete events[type];
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
return;
}
if (expandoStore.handle) {
if (expandoStore.events.$destroy) {
expandoStore.handle({}, '$destroy');
}
jqLiteOff(element);
}
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[key] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[key];
} else { // mass-setter: data({key1: val1, key2: val2})
extend(data, key);
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf(" " + selector + " ") > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType == NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if ((value = jqLite.data(element, names[i])) !== undefined) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behaviour
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document is already loaded
if (document.readyState === 'complete') {
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(element, name) {
var nodeName = element.nodeName;
return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData,
hasData: jqLiteHasData
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var nodeType = element.nodeType;
if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
return;
}
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name) || noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
eventFns[i].call(element, event);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
while (i--) {
type = types[i];
var eventFns = events[type];
if (!eventFns) {
events[type] = [];
if (type === 'mouseenter' || type === 'mouseleave') {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
var target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !target.contains(related))) {
handle(event, type);
}
});
} else {
if (type !== '$destroy') {
addEventListenerFn(element, type, handle);
}
}
eventFns = events[type];
}
eventFns.push(fn);
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
children.push(element);
}
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode).eq(0).clone()[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
// Provider for private $$jqLite service
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType == 'function' || (objType == 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array, isolatedUid) {
if (isolatedUid) {
var uid = 0;
this.nextUid = function() {
return ++uid;
};
}
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key, this.nextUid)] = value;
},
/**
* @param key
* @returns {Object} the value for the key
*/
get: function(key) {
return this[hashKey(key, this.nextUid)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key, this.nextUid)];
delete this[key];
return value;
}
};
var $$HashMapProvider = [function() {
this.$get = [function() {
return HashMap;
}];
}];
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector object that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
* disallows argument name annotation inference.
* @returns {injector} Injector object. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document) {
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running Angular app
* from outside Angular. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
args = fnText.match(FN_ARGS);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector) {
* return $injector;
* })).toBe($injector);
* ```
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. This method of discovering
* annotations is disallowed when the injector is in strict mode.
* *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
* argument names.
*
* ## `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @param {string=} caller An optional string to provide the origin of the function call for error messages.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
* injected according to the {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} name Name of the service to query.
* @returns {boolean} `true` if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* You can disallow this method by using strict injection mode.
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An Angular **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
* Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is the service
* constructor function that will be used to instantiate the service instance.
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
* that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an Angular
* {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service**, such as a string, a number, an array, an object or a function,
* with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an Angular {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
* intercepts the creation of a service, allowing it to override or modify the behaviour of the
* service. The object returned by the decorator may be the original service, or a new service
* object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
}));
forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function enforceReturnValue(name, factory) {
return function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
}
return result;
};
}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val), false); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
var runBlocks = [], moduleFn;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
function runInvokeQueue(queue) {
var i, ii;
for (i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
/* jshint -W022 */
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName, caller);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals, serviceName) {
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = [],
$inject = createInjector.$$annotate(fn, strictDi, serviceName),
length, i,
key;
for (i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, serviceName)
);
}
if (isArray(fn)) {
fn = fn[length];
}
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
}
function instantiate(Type, locals, serviceName) {
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
// Object creation: http://jsperf.com/create-constructor/2
var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
var returnedValue = invoke(Type, instance, locals, serviceName);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: createInjector.$$annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
/**
* @ngdoc provider
* @name $anchorScrollProvider
*
* @description
* Use `$anchorScrollProvider` to disable automatic scrolling whenever
* {@link ng.$location#hash $location.hash()} changes.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
/**
* @ngdoc method
* @name $anchorScrollProvider#disableAutoScrolling
*
* @description
* By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
* {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
* Use this method to disable automatic scrolling.
*
* If automatic scrolling is disabled, one must explicitly call
* {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
* current hash.
*/
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
/**
* @ngdoc service
* @name $anchorScroll
* @kind function
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
* current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
* in the
* [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
*
* It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
* match any anchor whenever it changes. This can be disabled by calling
* {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
*
* Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
* vertical scroll-offset (either fixed or dynamic).
*
* @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
* {@link ng.$location#hash $location.hash()} will be used.
*
* @property {(number|function|jqLite)} yOffset
* If set, specifies a vertical scroll-offset. This is often useful when there are fixed
* positioned elements at the top of the page, such as navbars, headers etc.
*
* `yOffset` can be specified in various ways:
* - **number**: A fixed number of pixels to be used as offset.<br /><br />
* - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
* a number representing the offset (in pixels).<br /><br />
* - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
* the top of the page to the element's bottom will be used as offset.<br />
* **Note**: The element will be taken into account only as long as its `position` is set to
* `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
* their height and/or positioning according to the viewport's size.
*
* <br />
* <div class="alert alert-warning">
* In order for `yOffset` to work properly, scrolling should take place on the document's root and
* not some child element.
* </div>
*
* @example
<example module="anchorScrollExample">
<file name="index.html">
<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
</file>
<file name="script.js">
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function ($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
</file>
<file name="style.css">
#scrollArea {
height: 280px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
</file>
</example>
*
* <hr />
* The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
* See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
*
* @example
<example module="anchorScrollOffsetExample">
<file name="index.html">
<div class="fixed-header" ng-controller="headerCtrl">
<a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
Go to anchor {{x}}
</a>
</div>
<div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
Anchor {{x}} of 5
</div>
</file>
<file name="script.js">
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function ($anchorScroll, $location, $scope) {
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
}
]);
</file>
<file name="style.css">
body {
padding-top: 50px;
}
.anchor {
border: 2px dashed DarkOrchid;
padding: 10px 10px 200px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 50px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
</file>
</example>
*/
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// Helper function to get first anchor from a NodeList
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
// and working in all supported browsers.)
function getFirstAnchor(list) {
var result = null;
Array.prototype.some.call(list, function(element) {
if (nodeName_(element) === 'a') {
result = element;
return true;
}
});
return result;
}
function getYOffset() {
var offset = scroll.yOffset;
if (isFunction(offset)) {
offset = offset();
} else if (isElement(offset)) {
var elem = offset[0];
var style = $window.getComputedStyle(elem);
if (style.position !== 'fixed') {
offset = 0;
} else {
offset = elem.getBoundingClientRect().bottom;
}
} else if (!isNumber(offset)) {
offset = 0;
}
return offset;
}
function scrollTo(elem) {
if (elem) {
elem.scrollIntoView();
var offset = getYOffset();
if (offset) {
// `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
// This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
// top of the viewport.
//
// IF the number of pixels from the top of `elem` to the end of the page's content is less
// than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
// way down the page.
//
// This is often the case for elements near the bottom of the page.
//
// In such cases we do not need to scroll the whole `offset` up, just the difference between
// the top of the element and the offset, which is enough to align the top of `elem` at the
// desired position.
var elemTop = elem.getBoundingClientRect().top;
$window.scrollBy(0, elemTop - offset);
}
} else {
$window.scrollTo(0, 0);
}
}
function scroll(hash) {
hash = isString(hash) ? hash : $location.hash();
var elm;
// empty hash, scroll to the top of the page
if (!hash) scrollTo(null);
// element with given id
else if ((elm = document.getElementById(hash))) scrollTo(elm);
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') scrollTo(null);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction(newVal, oldVal) {
// skip the initial scroll if $location.hash is empty
if (newVal === oldVal && newVal === '') return;
jqLiteDocumentLoaded(function() {
$rootScope.$evalAsync(scroll);
});
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
var ELEMENT_NODE = 1;
var NG_ANIMATE_CLASSNAME = 'ng-animate';
function mergeClasses(a,b) {
if (!a && !b) return '';
if (!a) return b;
if (!b) return a;
if (isArray(a)) a = a.join(' ');
if (isArray(b)) b = b.join(' ');
return a + ' ' + b;
}
function extractElementNode(element) {
for (var i = 0; i < element.length; i++) {
var elm = element[i];
if (elm.nodeType === ELEMENT_NODE) {
return elm;
}
}
}
function splitClasses(classes) {
if (isString(classes)) {
classes = classes.split(' ');
}
// Use createMap() to prevent class assumptions involving property names in
// Object.prototype
var obj = createMap();
forEach(classes, function(klass) {
// sometimes the split leaves empty string values
// incase extra spaces were applied to the options
if (klass.length) {
obj[klass] = true;
}
});
return obj;
}
// if any other type of options value besides an Object value is
// passed into the $animate.method() animation then this helper code
// will be run which will ignore it. While this patch is not the
// greatest solution to this, a lot of existing plugins depend on
// $animate to either call the callback (< 1.2) or return a promise
// that can be changed. This helper function ensures that the options
// are wiped clean incase a callback function is provided.
function prepareAnimateOptions(options) {
return isObject(options)
? options
: {};
}
var $$CoreAnimateRunnerProvider = function() {
this.$get = ['$q', '$$rAF', function($q, $$rAF) {
function AnimateRunner() {}
AnimateRunner.all = noop;
AnimateRunner.chain = noop;
AnimateRunner.prototype = {
end: noop,
cancel: noop,
resume: noop,
pause: noop,
complete: noop,
then: function(pass, fail) {
return $q(function(resolve) {
$$rAF(function() {
resolve();
});
}).then(pass, fail);
}
};
return AnimateRunner;
}];
};
// this is prefixed with Core since it conflicts with
// the animateQueueProvider defined in ngAnimate/animateQueue.js
var $$CoreAnimateQueueProvider = function() {
var postDigestQueue = new HashMap();
var postDigestElements = [];
this.$get = ['$$AnimateRunner', '$rootScope',
function($$AnimateRunner, $rootScope) {
return {
enabled: noop,
on: noop,
off: noop,
pin: noop,
push: function(element, event, options, domOperation) {
domOperation && domOperation();
options = options || {};
options.from && element.css(options.from);
options.to && element.css(options.to);
if (options.addClass || options.removeClass) {
addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
}
return new $$AnimateRunner(); // jshint ignore:line
}
};
function addRemoveClassesPostDigest(element, add, remove) {
var classVal, data = postDigestQueue.get(element);
if (!data) {
postDigestQueue.put(element, data = {});
postDigestElements.push(element);
}
var updateData = function(classes, value) {
var changed = false;
if (classes) {
classes = isString(classes) ? classes.split(' ') :
isArray(classes) ? classes : [];
forEach(classes, function(className) {
if (className) {
changed = true;
data[className] = value;
}
});
}
return changed;
};
var classesAdded = updateData(add, true);
var classesRemoved = updateData(remove, false);
if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;
$rootScope.$$postDigest(function() {
forEach(postDigestElements, function(element) {
var data = postDigestQueue.get(element);
if (data) {
var existing = splitClasses(element.attr('class'));
var toAdd = '';
var toRemove = '';
forEach(data, function(status, className) {
var hasClass = !!existing[className];
if (status !== hasClass) {
if (status) {
toAdd += (toAdd.length ? ' ' : '') + className;
} else {
toRemove += (toRemove.length ? ' ' : '') + className;
}
}
});
forEach(element, function(elm) {
toAdd && jqLiteAddClass(elm, toAdd);
toRemove && jqLiteRemoveClass(elm, toRemove);
});
postDigestQueue.remove(element);
}
});
postDigestElements.length = 0;
});
}
}];
};
/**
* @ngdoc provider
* @name $animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM updates and resolves the returned runner promise.
*
* In order to enable animations the `ngAnimate` module has to be loaded.
*
* To see the functional implementation check out `src/ngAnimate/animate.js`.
*/
var $AnimateProvider = ['$provide', function($provide) {
var provider = this;
this.$$registeredAnimations = Object.create(null);
/**
* @ngdoc method
* @name $animateProvider#register
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(element, ... , doneFunction, options)`
* The element to animate, the `doneFunction` and the options fed into the animation. Depending
* on the type of animation additional arguments will be injected into the animation function. The
* list below explains the function signatures for the different animation methods:
*
* - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
* - addClass: function(element, addedClasses, doneFunction, options)
* - removeClass: function(element, removedClasses, doneFunction, options)
* - enter, leave, move: function(element, doneFunction, options)
* - animate: function(element, fromStyles, toStyles, doneFunction, options)
*
* Make sure to trigger the `doneFunction` once the animation is fully complete.
*
* ```js
* return {
* //enter, leave, move signature
* eventFn : function(element, done, options) {
* //code to run the animation
* //once complete, then run done()
* return function endFunction(wasCancelled) {
* //code to cancel the animation
* }
* }
* }
* ```
*
* @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
* @param {Function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
if (name && name.charAt(0) !== '.') {
throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
}
var key = name + '-animation';
provider.$$registeredAnimations[name.substr(1)] = key;
$provide.factory(key, factory);
};
/**
* @ngdoc method
* @name $animateProvider#classNameFilter
*
* @description
* Sets and/or returns the CSS class regular expression that is checked when performing
* an animation. Upon bootstrap the classNameFilter value is not set at all and will
* therefore enable $animate to attempt to perform an animation on any element that is triggered.
* When setting the `classNameFilter` value, animations will only be performed on elements
* that successfully match the filter expression. This in turn can boost performance
* for low-powered devices as well as applications containing a lot of structural operations.
* @param {RegExp=} expression The className expression which will be checked against all animations
* @return {RegExp} The current CSS className expression value. If null then there is no expression value
*/
this.classNameFilter = function(expression) {
if (arguments.length === 1) {
this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
if (this.$$classNameFilter) {
var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
if (reservedRegex.test(this.$$classNameFilter.toString())) {
throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
}
}
}
return this.$$classNameFilter;
};
this.$get = ['$$animateQueue', function($$animateQueue) {
function domInsert(element, parentElement, afterElement) {
// if for some reason the previous element was removed
// from the dom sometime before this code runs then let's
// just stick to using the parent element as the anchor
if (afterElement) {
var afterNode = extractElementNode(afterElement);
if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
afterElement = null;
}
}
afterElement ? afterElement.after(element) : parentElement.prepend(element);
}
/**
* @ngdoc service
* @name $animate
* @description The $animate service exposes a series of DOM utility methods that provide support
* for animation hooks. The default behavior is the application of DOM operations, however,
* when an animation is detected (and animations are enabled), $animate will do the heavy lifting
* to ensure that animation runs with the triggered DOM operation.
*
* By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
* included and only when it is active then the animation hooks that `$animate` triggers will be
* functional. Once active then all structural `ng-` directives will trigger animations as they perform
* their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
* `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
*
* It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
*
* To learn more about enabling animation support, click here to visit the
* {@link ngAnimate ngAnimate module page}.
*/
return {
// we don't call it directly since non-existant arguments may
// be interpreted as null within the sub enabled function
/**
*
* @ngdoc method
* @name $animate#on
* @kind function
* @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
* has fired on the given element or among any of its children. Once the listener is fired, the provided callback
* is fired with the following params:
*
* ```js
* $animate.on('enter', container,
* function callback(element, phase) {
* // cool we detected an enter animation within the container
* }
* );
* ```
*
* @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
* as well as among its children
* @param {Function} callback the callback function that will be fired when the listener is triggered
*
* The arguments present in the callback function are:
* * `element` - The captured DOM element that the animation was fired on.
* * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
*/
on: $$animateQueue.on,
/**
*
* @ngdoc method
* @name $animate#off
* @kind function
* @description Deregisters an event listener based on the event which has been associated with the provided element. This method
* can be used in three different ways depending on the arguments:
*
* ```js
* // remove all the animation event listeners listening for `enter`
* $animate.off('enter');
*
* // remove all the animation event listeners listening for `enter` on the given element and its children
* $animate.off('enter', container);
*
* // remove the event listener function provided by `listenerFn` that is set
* // to listen for `enter` on the given `element` as well as its children
* $animate.off('enter', container, callback);
* ```
*
* @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement=} container the container element the event listener was placed on
* @param {Function=} callback the callback function that was registered as the listener
*/
off: $$animateQueue.off,
/**
* @ngdoc method
* @name $animate#pin
* @kind function
* @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
* outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
* element despite being outside the realm of the application or within another application. Say for example if the application
* was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
* as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
* that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
*
* Note that this feature is only active when the `ngAnimate` module is used.
*
* @param {DOMElement} element the external element that will be pinned
* @param {DOMElement} parentElement the host parent element that will be associated with the external element
*/
pin: $$animateQueue.pin,
/**
*
* @ngdoc method
* @name $animate#enabled
* @kind function
* @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
* function can be called in four ways:
*
* ```js
* // returns true or false
* $animate.enabled();
*
* // changes the enabled state for all animations
* $animate.enabled(false);
* $animate.enabled(true);
*
* // returns true or false if animations are enabled for an element
* $animate.enabled(element);
*
* // changes the enabled state for an element and its children
* $animate.enabled(element, true);
* $animate.enabled(element, false);
* ```
*
* @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
* @param {boolean=} enabled whether or not the animations will be enabled for the element
*
* @return {boolean} whether or not animations are enabled
*/
enabled: $$animateQueue.enabled,
/**
* @ngdoc method
* @name $animate#cancel
* @kind function
* @description Cancels the provided animation.
*
* @param {Promise} animationPromise The animation promise that is returned when an animation is started.
*/
cancel: function(runner) {
runner.end && runner.end();
},
/**
*
* @ngdoc method
* @name $animate#enter
* @kind function
* @description Inserts the element into the DOM either after the `after` element (if provided) or
* as the first child within the `parent` element and then triggers an animation.
* A promise is returned that will be resolved during the next digest once the animation
* has completed.
*
* @param {DOMElement} element the element which will be inserted into the DOM
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
enter: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
},
/**
*
* @ngdoc method
* @name $animate#move
* @kind function
* @description Inserts (moves) the element into its new position in the DOM either after
* the `after` element (if provided) or as the first child within the `parent` element
* and then triggers an animation. A promise is returned that will be resolved
* during the next digest once the animation has completed.
*
* @param {DOMElement} element the element which will be moved into the new DOM position
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
move: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
},
/**
* @ngdoc method
* @name $animate#leave
* @kind function
* @description Triggers an animation and then removes the element from the DOM.
* When the function is called a promise is returned that will be resolved during the next
* digest once the animation has completed.
*
* @param {DOMElement} element the element which will be removed from the DOM
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
leave: function(element, options) {
return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
element.remove();
});
},
/**
* @ngdoc method
* @name $animate#addClass
* @kind function
*
* @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
* execution, the addClass operation will only be handled after the next digest and it will not trigger an
* animation if element already contains the CSS class or if the class is removed at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
addClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addclass, className);
return $$animateQueue.push(element, 'addClass', options);
},
/**
* @ngdoc method
* @name $animate#removeClass
* @kind function
*
* @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
* execution, the removeClass operation will only be handled after the next digest and it will not trigger an
* animation if element does not contain the CSS class or if the class is added at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
removeClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.removeClass = mergeClasses(options.removeClass, className);
return $$animateQueue.push(element, 'removeClass', options);
},
/**
* @ngdoc method
* @name $animate#setClass
* @kind function
*
* @description Performs both the addition and removal of a CSS classes on an element and (during the process)
* triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
* `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
* passed. Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
setClass: function(element, add, remove, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addClass, add);
options.removeClass = mergeClasses(options.removeClass, remove);
return $$animateQueue.push(element, 'setClass', options);
},
/**
* @ngdoc method
* @name $animate#animate
* @kind function
*
* @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
* If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
* on the provided styles. For example, if a transition animation is set for the given className then the provided from and
* to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
* will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
*
* @param {DOMElement} element the element which the CSS styles will be applied to
* @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
* @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
* @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
* this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
* (Note that if no animation is detected then this value will not be appplied to the element.)
* @param {object=} options an optional collection of options/styles that will be applied to the element
*
* @return {Promise} the animation callback promise
*/
animate: function(element, from, to, className, options) {
options = prepareAnimateOptions(options);
options.from = options.from ? extend(options.from, from) : from;
options.to = options.to ? extend(options.to, to) : to;
className = className || 'ng-inline-animate';
options.tempClasses = mergeClasses(options.tempClasses, className);
return $$animateQueue.push(element, 'animate', options);
}
};
}];
}];
/**
* @ngdoc service
* @name $animateCss
* @kind object
*
* @description
* This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
* then the `$animateCss` service will actually perform animations.
*
* Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
*/
var $CoreAnimateCssProvider = function() {
this.$get = ['$$rAF', '$q', function($$rAF, $q) {
var RAFPromise = function() {};
RAFPromise.prototype = {
done: function(cancel) {
this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
},
end: function() {
this.done();
},
cancel: function() {
this.done(true);
},
getPromise: function() {
if (!this.defer) {
this.defer = $q.defer();
}
return this.defer.promise;
},
then: function(f1,f2) {
return this.getPromise().then(f1,f2);
},
'catch': function(f1) {
return this.getPromise().catch(f1);
},
'finally': function(f1) {
return this.getPromise().finally(f1);
}
};
return function(element, options) {
if (options.from) {
element.css(options.from);
options.from = null;
}
var closed, runner = new RAFPromise();
return {
start: run,
end: run
};
function run() {
$$rAF(function() {
close();
if (!closed) {
runner.done();
}
closed = true;
});
return runner;
}
function close() {
if (options.addClass) {
element.addClass(options.addClass);
options.addClass = null;
}
if (options.removeClass) {
element.removeClass(options.removeClass);
options.removeClass = null;
}
if (options.to) {
element.css(options.to);
options.to = null;
}
}
};
}];
};
/* global stripHash: true */
/**
* ! This is a private undocumented service !
*
* @name $browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} $log window.console or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while (outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
function getHash(url) {
var index = url.indexOf('#');
return index === -1 ? '' : url.substr(index);
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var cachedState, lastHistoryState,
lastBrowserUrl = location.href,
baseElement = document.find('base'),
reloadLocation = null;
cacheState();
lastHistoryState = cachedState;
/**
* @name $browser#url
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record?
* @param {object=} state object to use with pushState/replaceState
*/
self.url = function(url, replace, state) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (isUndefined(state)) {
state = null;
}
// Android Browser BFCache causes location, history reference to become stale.
if (location !== window.location) location = window.location;
if (history !== window.history) history = window.history;
// setter
if (url) {
var sameState = lastHistoryState === state;
// Don't change anything if previous and current URLs and states match. This also prevents
// IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
// See https://github.com/angular/angular.js/commit/ffb2701
if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
return self;
}
var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
lastBrowserUrl = url;
lastHistoryState = state;
// Don't use history API if only the hash changed
// due to a bug in IE10/IE11 which leads
// to not firing a `hashchange` nor `popstate` event
// in some cases (see #9143).
if ($sniffer.history && (!sameBase || !sameState)) {
history[replace ? 'replaceState' : 'pushState'](state, '', url);
cacheState();
// Do the assignment again so that those two variables are referentially identical.
lastHistoryState = cachedState;
} else {
if (!sameBase || reloadLocation) {
reloadLocation = url;
}
if (replace) {
location.replace(url);
} else if (!sameBase) {
location.href = url;
} else {
location.hash = getHash(url);
}
}
return self;
// getter
} else {
// - reloadLocation is needed as browsers don't allow to read out
// the new location.href if a reload happened.
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return reloadLocation || location.href.replace(/%27/g,"'");
}
};
/**
* @name $browser#state
*
* @description
* This method is a getter.
*
* Return history.state or null if history.state is undefined.
*
* @returns {object} state
*/
self.state = function() {
return cachedState;
};
var urlChangeListeners = [],
urlChangeInit = false;
function cacheStateAndFireUrlChange() {
cacheState();
fireUrlChange();
}
function getCurrentState() {
try {
return history.state;
} catch (e) {
// MSIE can reportedly throw when there is no state (UNCONFIRMED).
}
}
// This variable should be used *only* inside the cacheState function.
var lastCachedState = null;
function cacheState() {
// This should be the only place in $browser where `history.state` is read.
cachedState = getCurrentState();
cachedState = isUndefined(cachedState) ? null : cachedState;
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (equals(cachedState, lastCachedState)) {
cachedState = lastCachedState;
}
lastCachedState = cachedState;
}
function fireUrlChange() {
if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
return;
}
lastBrowserUrl = self.url();
lastHistoryState = cachedState;
forEach(urlChangeListeners, function(listener) {
listener(self.url(), cachedState);
});
}
/**
* @name $browser#onUrlChange
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed from outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
// TODO(vojta): refactor to use node's syntax for events
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
// hashchange event
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
/**
* @private
* Remove popstate and hashchange handler from window.
*
* NOTE: this api is intended for use only by $rootScope.
*/
self.$$applicationDestroyed = function() {
jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
};
/**
* Checks whether the url has changed outside of Angular.
* Needs to be exported to be able to check for changes that have been done in sync,
* as hashchange/popstate events fire in async.
*/
self.$$checkUrlChange = fireUrlChange;
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name $browser#baseHref
*
* @description
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string} The current base href
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
};
/**
* @name $browser#defer
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name $browser#defer.cancel
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document',
function($window, $log, $sniffer, $document) {
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc service
* @name $cacheFactory
*
* @description
* Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
* them.
*
* ```js
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* ```
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
* @example
<example module="cacheExampleApp">
<file name="index.html">
<div ng-controller="CacheController">
<input ng-model="newCacheKey" placeholder="Key">
<input ng-model="newCacheValue" placeholder="Value">
<button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
<p ng-if="keys.length">Cached Values</p>
<div ng-repeat="key in keys">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="cache.get(key)"></b>
</div>
<p>Cache Info</p>
<div ng-repeat="(key, value) in cache.info()">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="value"></b>
</div>
</div>
</file>
<file name="script.js">
angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
$scope.keys = [];
$scope.cache = $cacheFactory('cacheId');
$scope.put = function(key, value) {
if ($scope.cache.get(key) === undefined) {
$scope.keys.push(key);
}
$scope.cache.put(key, value === undefined ? null : value);
};
}]);
</file>
<file name="style.css">
p {
margin: 10px 0 3px;
}
</file>
</example>
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
/**
* @ngdoc type
* @name $cacheFactory.Cache
*
* @description
* A cache object used to store and retrieve data, primarily used by
* {@link $http $http} and the {@link ng.directive:script script} directive to cache
* templates and other data.
*
* ```js
* angular.module('superCache')
* .factory('superCache', ['$cacheFactory', function($cacheFactory) {
* return $cacheFactory('super-cache');
* }]);
* ```
*
* Example test:
*
* ```js
* it('should behave like a cache', inject(function(superCache) {
* superCache.put('key', 'value');
* superCache.put('another key', 'another value');
*
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 2
* });
*
* superCache.remove('another key');
* expect(superCache.get('another key')).toBeUndefined();
*
* superCache.removeAll();
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 0
* });
* }));
* ```
*/
return caches[cacheId] = {
/**
* @ngdoc method
* @name $cacheFactory.Cache#put
* @kind function
*
* @description
* Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
* retrieved later, and incrementing the size of the cache if the key was not already
* present in the cache. If behaving like an LRU cache, it will also remove stale
* entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param {string} key the key under which the cached data is stored.
* @param {*} value the value to store alongside the key. If it is undefined, the key
* will not be stored.
* @returns {*} the value stored.
*/
put: function(key, value) {
if (isUndefined(value)) return;
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
}
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#get
* @kind function
*
* @description
* Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the data to be retrieved
* @returns {*} the value stored.
*/
get: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
}
return data[key];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#remove
* @kind function
*
* @description
* Removes an entry from the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the entry to be removed
*/
remove: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
}
delete data[key];
size--;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#removeAll
* @kind function
*
* @description
* Clears the cache object of any entries.
*/
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#destroy
* @kind function
*
* @description
* Destroys the {@link $cacheFactory.Cache Cache} object entirely,
* removing it from the {@link $cacheFactory $cacheFactory} set.
*/
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#info
* @kind function
*
* @description
* Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
*
* @returns {object} an object with the following properties:
* <ul>
* <li>**id**: the id of the cache instance</li>
* <li>**size**: the number of entries kept in the cache instance</li>
* <li>**...**: any additional properties from the options object when creating the
* cache.</li>
* </ul>
*/
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name $cacheFactory#info
*
* @description
* Get information about all the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name $cacheFactory#get
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc service
* @name $templateCache
*
* @description
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, or by consuming the
* `$templateCache` service directly.
*
* Adding via the `script` tag:
*
* ```html
* <script type="text/ng-template" id="templateId.html">
* <p>This is the content of the template</p>
* </script>
* ```
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
* element with ng-app attribute), otherwise the template will be ignored.
*
* Adding via the `$templateCache` service:
*
* ```js
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* ```
*
* To retrieve the template later, simply use it in your HTML:
* ```html
* <div ng-include=" 'templateId.html' "></div>
* ```
*
* or get it via Javascript:
* ```js
* $templateCache.get('templateId.html')
* ```
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc service
* @name $compile
* @kind function
*
* @description
* Compiles an HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#directive directives}.
*
* <div class="alert alert-warning">
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
* </div>
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a "Directive Definition Object" (see below) that defines the directive properties,
* or just the `postLink` function (all other properties will have the default values).
*
* <div class="alert alert-success">
* **Best Practice:** It's recommended to use the "directive definition object" form.
* </div>
*
* Here's an example directive declared with a Directive Definition Object:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* priority: 0,
* template: '<div></div>', // or // function(tElement, tAttrs) { ... },
* // or
* // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
* transclude: false,
* restrict: 'A',
* templateNamespace: 'html',
* scope: false,
* controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
* controllerAs: 'stringIdentifier',
* bindToController: false,
* require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
* compile: function compile(tElement, tAttrs, transclude) {
* return {
* pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* post: function postLink(scope, iElement, iAttrs, controller) { ... }
* }
* // or
* // return function postLink( ... ) { ... }
* },
* // or
* // link: {
* // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* // post: function postLink(scope, iElement, iAttrs, controller) { ... }
* // }
* // or
* // link: function postLink( ... ) { ... }
* };
* return directiveDefinitionObject;
* });
* ```
*
* <div class="alert alert-warning">
* **Note:** Any unspecified options will use the default value. You can see the default values below.
* </div>
*
* Therefore the above can be simplified as:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* ```
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `multiElement`
* When this property is set to true, the HTML compiler will collect DOM nodes between
* nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
* together as the directive elements. It is recommended that this feature be used on directives
* which are not strictly behavioural (such as {@link ngClick}), and which
* do not manipulate or replace child nodes (such as {@link ngInclude}).
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions
* are also run in priority order, but post-link functions are run in reverse order. The order
* of directives with the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined). Note that expressions
* and other directives used in the directive's template will also be excluded from execution.
*
* #### `scope`
* **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
* same element request a new scope, only one new scope is created. The new scope rule does not
* apply for the root of the template since the root of the template always gets a new scope.
*
* **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
* normal scope in that it does not prototypically inherit from the parent scope. This is useful
* when creating reusable components, which should not accidentally read or modify data in the
* parent scope.
*
* The 'isolate' scope takes an object hash which defines a set of local scope properties
* derived from the parent scope. These local properties are useful for aliasing values for
* templates. Locals definition is a hash of local scope property to its source:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="hello {{name}}">` and widget definition
* of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
* the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
* `localName` property on the widget scope. The `name` is read from the parent scope (not
* component scope).
*
* * `=` or `=attr` - set up bi-directional binding between a local scope property and the
* parent scope property of name defined via the value of the `attr` attribute. If no `attr`
* name is specified then the attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="parentModel">` and widget definition of
* `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
* value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
* in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
* scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
* can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
* you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
* `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
*
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the
* local name. Given `<widget my-attr="count = count + value">` and widget definition of
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
* a function wrapper for the `count = count + value` expression. Often it's desirable to
* pass data from the isolated scope via an expression to the parent scope, this can be
* done by passing a map of local variable names and values into the expression wrapper fn.
* For example, if the expression is `increment(amount)` then we can specify the amount value
* by calling the `localFn` as `localFn({amount: 22})`.
*
*
* #### `bindToController`
* When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
* allow a component to have its properties bound to the controller, rather than to scope. When the controller
* is instantiated, the initial values of the isolate scope bindings are already available.
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and it is shared with other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function([scope], cloneLinkingFn, futureParentElement)`.
* * `scope`: optional argument to override the scope.
* * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
* * `futureParentElement`:
* * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
* * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
* * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
* and when the `cloneLinkinFn` is passed,
* as those elements need to created and cloned in a special way when they are defined outside their
* usual containers (e.g. like `<svg>`).
* * See also the `directive.templateNamespace` property.
*
*
* #### `require`
* Require another directive and inject its controller as the fourth argument to the linking function. The
* `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
* injected argument will be an array in corresponding order. If no such directive can be
* found, or if the directive does not have a controller, then an error is raised (unless no link function
* is specified, in which case error checking is skipped). The name can be prefixed with:
*
* * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
* * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
* * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
* * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
* * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
* `null` to the `link` fn if not found.
* * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
* `null` to the `link` fn if not found.
*
*
* #### `controllerAs`
* Identifier name for a reference to the controller in the directive's scope.
* This allows the controller to be referenced from the directive template. The directive
* needs to define a scope for this configuration to be used. Useful in the case when
* directive is used as component.
*
*
* #### `restrict`
* String of subset of `EACM` which restricts the directive to a specific directive
* declaration style. If omitted, the defaults (elements and attributes) are used.
*
* * `E` - Element name (default): `<my-directive></my-directive>`
* * `A` - Attribute (default): `<div my-directive="exp"></div>`
* * `C` - Class: `<div class="my-directive: exp;"></div>`
* * `M` - Comment: `<!-- directive: my-directive exp -->`
*
*
* #### `templateNamespace`
* String representing the document type used by the markup in the template.
* AngularJS needs this information as those elements need to be created and cloned
* in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
*
* * `html` - All root nodes in the template are HTML. Root nodes may also be
* top-level elements such as `<svg>` or `<math>`.
* * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
* * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
*
* If no `templateNamespace` is specified, then the namespace is considered to be `html`.
*
* #### `template`
* HTML markup that may:
* * Replace the contents of the directive's element (default).
* * Replace the directive's element itself (if `replace` is true - DEPRECATED).
* * Wrap the contents of the directive's element (if `transclude` is true).
*
* Value may be:
*
* * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
* * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
* function api below) and returns a string value.
*
*
* #### `templateUrl`
* This is similar to `template` but the template is loaded from the specified URL, asynchronously.
*
* Because template loading is asynchronous the compiler will suspend compilation of directives on that element
* for later when the template has been resolved. In the meantime it will continue to compile and link
* sibling and parent elements as though this element had not contained any directives.
*
* The compiler does not suspend the entire compilation to wait for templates to be loaded because this
* would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
* case when only one deeply nested directive has `templateUrl`.
*
* Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
*
* You can specify `templateUrl` as a string representing the URL or as a function which takes two
* arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
* a string value representing the url. In either case, the template URL is passed through {@link
* $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
*
*
* #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
* specify what the template should replace. Defaults to `false`.
*
* * `true` - the template will replace the directive's element.
* * `false` - the template will replace the contents of the directive's element.
*
* The replacement process migrates all of the attributes / classes from the old element to the new
* one. See the {@link guide/directive#template-expanding-directive
* Directives Guide} for an example.
*
* There are very few scenarios where element replacement is required for the application function,
* the main one being reusable custom components that are used within SVG contexts
* (because SVG doesn't work with custom elements in the DOM tree).
*
* #### `transclude`
* Extract the contents of the element where the directive appears and make it available to the directive.
* The contents are compiled and provided to the directive as a **transclusion function**. See the
* {@link $compile#transclusion Transclusion} section below.
*
* There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
* directive's element or the entire element:
*
* * `true` - transclude the content (i.e. the child nodes) of the directive's element.
* * `'element'` - transclude the whole of the directive's element including any directives on this
* element that defined at a lower priority than this directive. When used, the `template`
* property is ignored.
*
*
* #### `compile`
*
* ```js
* function compile(tElement, tAttrs, transclude) { ... }
* ```
*
* The compile function deals with transforming the template DOM. Since most directives do not do
* template transformation, it is not used often. The compile function takes the following arguments:
*
* * `tElement` - template element - The element where the directive has been declared. It is
* safe to do template transformation on the element and child elements only.
*
* * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
* between all directive compile functions.
*
* * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
*
* <div class="alert alert-warning">
* **Note:** The template instance and the link instance may be different objects if the template has
* been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
* apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
* should be done in a linking function rather than in a compile function.
* </div>
* <div class="alert alert-warning">
* **Note:** The compile function cannot handle directives that recursively use themselves in their
* own templates or compile functions. Compiling these directives results in an infinite loop and a
* stack overflow errors.
*
* This can be avoided by manually using $compile in the postLink function to imperatively compile
* a directive's template instead of relying on automatic template compilation via `template` or
* `templateUrl` declaration or manual compilation inside the compile function.
* </div>
*
* <div class="alert alert-danger">
* **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
* e.g. does not know about the right outer scope. Please use the transclude function that is passed
* to the link function instead.
* </div>
* A compile function can have a return value which can be either a function or an object.
*
* * returning a (post-link) function - is equivalent to registering the linking function via the
* `link` property of the config object when the compile function is empty.
*
* * returning an object with function(s) registered via `pre` and `post` properties - allows you to
* control when a linking function should be called during the linking phase. See info about
* pre-linking and post-linking functions below.
*
*
* #### `link`
* This property is used only if the `compile` property is not defined.
*
* ```js
* function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
* ```
*
* The link function is responsible for registering DOM listeners as well as updating the DOM. It is
* executed after the template has been cloned. This is where most of the directive logic will be
* put.
*
* * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
* directive for registering {@link ng.$rootScope.Scope#$watch watches}.
*
* * `iElement` - instance element - The element where the directive is to be used. It is safe to
* manipulate the children of the element only in `postLink` function since the children have
* already been linked.
*
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
* between all directive linking functions.
*
* * `controller` - the directive's required controller instance(s) - Instances are shared
* among all directives, which allows the directives to use the controllers as a communication
* channel. The exact value depends on the directive's `require` property:
* * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
* * `string`: the controller instance
* * `array`: array of controller instances
*
* If a required controller cannot be found, and it is optional, the instance is `null`,
* otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
*
* Note that you can also require the directive's own controller - it will be made available like
* any other controller.
*
* * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
* This is the same as the `$transclude`
* parameter of directive controllers, see there for details.
* `function([scope], cloneLinkingFn, futureParentElement)`.
*
* #### Pre-linking function
*
* Executed before the child elements are linked. Not safe to do DOM transformation since the
* compiler linking function will fail to locate the correct elements for linking.
*
* #### Post-linking function
*
* Executed after the child elements are linked.
*
* Note that child elements that contain `templateUrl` directives will not have been compiled
* and linked since they are waiting for their template to load asynchronously and their own
* compilation and linking has been suspended until that occurs.
*
* It is safe to do DOM transformation in the post-linking function on elements that are not waiting
* for their async templates to be resolved.
*
*
* ### Transclusion
*
* Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
* copying them to another part of the DOM, while maintaining their connection to the original AngularJS
* scope from where they were taken.
*
* Transclusion is used (often with {@link ngTransclude}) to insert the
* original contents of a directive's element into a specified place in the template of the directive.
* The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
* content has access to the properties on the scope from which it was taken, even if the directive
* has isolated scope.
* See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
*
* This makes it possible for the widget to have private state for its template, while the transcluded
* content has access to its originating scope.
*
* <div class="alert alert-warning">
* **Note:** When testing an element transclude directive you must not place the directive at the root of the
* DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
* Testing Transclusion Directives}.
* </div>
*
* #### Transclusion Functions
*
* When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
* function** to the directive's `link` function and `controller`. This transclusion function is a special
* **linking function** that will return the compiled contents linked to a new transclusion scope.
*
* <div class="alert alert-info">
* If you are just using {@link ngTransclude} then you don't need to worry about this function, since
* ngTransclude will deal with it for us.
* </div>
*
* If you want to manually control the insertion and removal of the transcluded content in your directive
* then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
* object that contains the compiled DOM, which is linked to the correct transclusion scope.
*
* When you call a transclusion function you can pass in a **clone attach function**. This function accepts
* two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
* content and the `scope` is the newly created transclusion scope, to which the clone is bound.
*
* <div class="alert alert-info">
* **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
* since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
* </div>
*
* It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
* attach function**:
*
* ```js
* var transcludedContent, transclusionScope;
*
* $transclude(function(clone, scope) {
* element.append(clone);
* transcludedContent = clone;
* transclusionScope = scope;
* });
* ```
*
* Later, if you want to remove the transcluded content from your DOM then you should also destroy the
* associated transclusion scope:
*
* ```js
* transcludedContent.remove();
* transclusionScope.$destroy();
* ```
*
* <div class="alert alert-info">
* **Best Practice**: if you intend to add and remove transcluded content manually in your directive
* (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
* then you are also responsible for calling `$destroy` on the transclusion scope.
* </div>
*
* The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
* automatically destroy their transluded clones as necessary so you do not need to worry about this if
* you are simply using {@link ngTransclude} to inject the transclusion into your directive.
*
*
* #### Transclusion Scopes
*
* When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
* scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
* when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
* was taken.
*
* For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
* like this:
*
* ```html
* <div ng-app>
* <div isolate>
* <div transclusion>
* </div>
* </div>
* </div>
* ```
*
* The `$parent` scope hierarchy will look like this:
*
* ```
* - $rootScope
* - isolate
* - transclusion
* ```
*
* but the scopes will inherit prototypically from different scopes to their `$parent`.
*
* ```
* - $rootScope
* - transclusion
* - isolate
* ```
*
*
* ### Attributes
*
* The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
* `link()` or `compile()` functions. It has a variety of uses.
*
* accessing *Normalized attribute names:*
* Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
* the attributes object allows for normalized access to
* the attributes.
*
* * *Directive inter-communication:* All directives share the same instance of the attributes
* object which allows the directives to use the attributes object as inter directive
* communication.
*
* * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
* allowing other directives to read the interpolated value.
*
* * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
* that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
* the only way to easily get the actual value because during the linking phase the interpolation
* hasn't been evaluated yet and so the value is at this time set to `undefined`.
*
* ```js
* function linkingFn(scope, elm, attrs, ctrl) {
* // get the attribute value
* console.log(attrs.ngModel);
*
* // change the attribute
* attrs.$set('ngModel', 'new value');
*
* // observe changes to interpolated attribute
* attrs.$observe('ngModel', function(value) {
* console.log('ngModel has changed value to ' + value);
* });
* }
* ```
*
* ## Example
*
* <div class="alert alert-warning">
* **Note**: Typically directives are registered with `module.directive`. The example below is
* to illustrate how `$compile` works.
* </div>
*
<example module="compileExample">
<file name="index.html">
<script>
angular.module('compileExample', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
})
.controller('GreeterController', ['$scope', function($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}]);
</script>
<div ng-controller="GreeterController">
<input ng-model="name"> <br/>
<textarea ng-model="html"></textarea> <br/>
<div compile="html"></div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should auto compile', function() {
var textarea = $('textarea');
var output = $('div[compile]');
// The initial state reads 'Hello Angular'.
expect(output.getText()).toBe('Hello Angular');
textarea.clear();
textarea.sendKeys('{{name}}!');
expect(output.getText()).toBe('Angular!');
});
</file>
</example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
*
* <div class="alert alert-danger">
* **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
* e.g. will not use the right outer scope. Please pass the transclude function as a
* `parentBoundTranscludeFn` to the link function instead.
* </div>
*
* @param {number} maxPriority only apply directives lower than given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* * `options` - An optional object hash with linking options. If `options` is provided, then the following
* keys may be used to control linking behavior:
*
* * `parentBoundTranscludeFn` - the transclude function made available to
* directives; if given, it will be passed through to the link functions of
* directives found in `element` during compilation.
* * `transcludeControllers` - an object hash with keys that map controller names
* to controller instances; if given, it will make the controllers
* available to directives.
* * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
* the cloned elements; only needed for transcludes that are allowed to contain non html
* elements (e.g. SVG elements). See also the directive.controller property.
*
* Calling the linking function returns the element of the template. It is either the original
* element passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* ```js
* var element = $compile('<p>{{total}}</p>')(scope);
* ```
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* ```js
* var templateElement = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clonedElement`
* ```
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
var $compileMinErr = minErr('$compile');
/**
* @ngdoc provider
* @name $compileProvider
*
* @description
*/
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
function $CompileProvider($provide, $$sanitizeUriProvider) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
// The assumption is that future DOM event attribute names will begin with
// 'on' and be composed of only English letters.
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
function parseIsolateBindings(scope, directiveName, isController) {
var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
var bindings = {};
forEach(scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP);
if (!match) {
throw $compileMinErr('iscp',
"Invalid {3} for directive '{0}'." +
" Definition: {... {1}: '{2}' ...}",
directiveName, scopeName, definition,
(isController ? "controller bindings definition" :
"isolate scope definition"));
}
bindings[scopeName] = {
mode: match[1][0],
collection: match[2] === '*',
optional: match[3] === '?',
attrName: match[4] || scopeName
};
});
return bindings;
}
function parseDirectiveBindings(directive, directiveName) {
var bindings = {
isolateScope: null,
bindToController: null
};
if (isObject(directive.scope)) {
if (directive.bindToController === true) {
bindings.bindToController = parseIsolateBindings(directive.scope,
directiveName, true);
bindings.isolateScope = {};
} else {
bindings.isolateScope = parseIsolateBindings(directive.scope,
directiveName, false);
}
}
if (isObject(directive.bindToController)) {
bindings.bindToController =
parseIsolateBindings(directive.bindToController, directiveName, true);
}
if (isObject(bindings.bindToController)) {
var controller = directive.controller;
var controllerAs = directive.controllerAs;
if (!controller) {
// There is no controller, there may or may not be a controllerAs property
throw $compileMinErr('noctrl',
"Cannot bind to controller without directive '{0}'s controller.",
directiveName);
} else if (!identifierForController(controller, controllerAs)) {
// There is a controller, but no identifier or controllerAs property
throw $compileMinErr('noident',
"Cannot bind to controller without identifier for directive '{0}'.",
directiveName);
}
}
return bindings;
}
function assertValidDirectiveName(name) {
var letter = name.charAt(0);
if (!letter || letter !== lowercase(letter)) {
throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
}
if (name !== name.trim()) {
throw $compileMinErr('baddir',
"Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
name);
}
}
/**
* @ngdoc method
* @name $compileProvider#directive
* @kind function
*
* @description
* Register a new directive with the compiler.
*
* @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
* will match as <code>ng-bind</code>), or an object map of directives where the keys are the
* names and the values are the factories.
* @param {Function|Array} directiveFactory An injectable directive factory function. See
* {@link guide/directive} for more info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
assertNotHasOwnProperty(name, 'directive');
if (isString(name)) {
assertValidDirectiveName(name);
assertArg(directiveFactory, 'directiveFactory');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory, index) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.index = index;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'EA';
var bindings = directive.$$bindings =
parseDirectiveBindings(directive, directive.name);
if (isObject(bindings.isolateScope)) {
directive.$$isolateBindings = bindings.isolateScope;
}
directive.$$moduleName = directiveFactory.$$moduleName;
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc method
* @name $compileProvider#aHrefSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at preventing XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#imgSrcSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#debugInfoEnabled
*
* @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
* current debugInfoEnabled state
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*
* @kind function
*
* @description
* Call this method to enable/disable various debug runtime information in the compiler such as adding
* binding information and a reference to the current scope on to DOM elements.
* If enabled, the compiler will add the following to DOM elements that have been bound to the scope
* * `ng-binding` CSS class
* * `$binding` data property containing an array of the binding expressions
*
* You may want to disable this in production for a significant performance boost. See
* {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
*
* The default value is true.
*/
var debugInfoEnabled = true;
this.debugInfoEnabled = function(enabled) {
if (isDefined(enabled)) {
debugInfoEnabled = enabled;
return this;
}
return debugInfoEnabled;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
'$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
$controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
var Attributes = function(element, attributesToCopy) {
if (attributesToCopy) {
var keys = Object.keys(attributesToCopy);
var i, l, key;
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
this[key] = attributesToCopy[key];
}
} else {
this.$attr = {};
}
this.$$element = element;
};
Attributes.prototype = {
/**
* @ngdoc method
* @name $compile.directive.Attributes#$normalize
* @kind function
*
* @description
* Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
* `data-`) to its normalized, camelCase form.
*
* Also there is special case for Moz prefix starting with upper case letter.
*
* For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
*
* @param {string} name Name to normalize
*/
$normalize: directiveNormalize,
/**
* @ngdoc method
* @name $compile.directive.Attributes#$addClass
* @kind function
*
* @description
* Adds the CSS class value specified by the classVal parameter to the element. If animations
* are enabled then an animation will be triggered for the class addition.
*
* @param {string} classVal The className value that will be added to the element
*/
$addClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.addClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$removeClass
* @kind function
*
* @description
* Removes the CSS class value specified by the classVal parameter from the element. If
* animations are enabled then an animation will be triggered for the class removal.
*
* @param {string} classVal The className value that will be removed from the element
*/
$removeClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.removeClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$updateClass
* @kind function
*
* @description
* Adds and removes the appropriate CSS class values to the element based on the difference
* between the new and old CSS class values (specified as newClasses and oldClasses).
*
* @param {string} newClasses The current CSS className value
* @param {string} oldClasses The former CSS className value
*/
$updateClass: function(newClasses, oldClasses) {
var toAdd = tokenDifference(newClasses, oldClasses);
if (toAdd && toAdd.length) {
$animate.addClass(this.$$element, toAdd);
}
var toRemove = tokenDifference(oldClasses, newClasses);
if (toRemove && toRemove.length) {
$animate.removeClass(this.$$element, toRemove);
}
},
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
// TODO: decide whether or not to throw an error if "class"
//is set through this function since it may cause $updateClass to
//become unstable.
var node = this.$$element[0],
booleanKey = getBooleanAttrName(node, key),
aliasedKey = getAliasedAttrName(node, key),
observer = key,
nodeName;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
} else if (aliasedKey) {
this[aliasedKey] = value;
observer = aliasedKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
nodeName = nodeName_(this.$$element);
if ((nodeName === 'a' && key === 'href') ||
(nodeName === 'img' && key === 'src')) {
// sanitize a[href] and img[src] values
this[key] = value = $$sanitizeUri(value, key === 'src');
} else if (nodeName === 'img' && key === 'srcset') {
// sanitize img[srcset] values
var result = "";
// first check if there are spaces because it's not the same pattern
var trimmedSrcset = trim(value);
// ( 999x ,| 999w ,| ,|, )
var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
// split srcset into tuple of uri and descriptor except for the last item
var rawUris = trimmedSrcset.split(pattern);
// for each tuples
var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
for (var i = 0; i < nbrUrisWith2parts; i++) {
var innerIdx = i * 2;
// sanitize the uri
result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
// add the descriptor
result += (" " + trim(rawUris[innerIdx + 1]));
}
// split the last item into uri and descriptor
var lastTuple = trim(rawUris[i * 2]).split(/\s/);
// sanitize the last uri
result += $$sanitizeUri(trim(lastTuple[0]), true);
// and add the last descriptor if any
if (lastTuple.length === 2) {
result += (" " + trim(lastTuple[1]));
}
this[key] = value = result;
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
var $$observers = this.$$observers;
$$observers && forEach($$observers[observer], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$observe
* @kind function
*
* @description
* Observes an interpolated attribute.
*
* The observer function will be invoked once during the next `$digest` following
* compilation. The observer is then invoked whenever the interpolated value
* changes.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(interpolatedValue)} fn Function that will be called whenever
the interpolated value of the attribute changes.
* See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
* @returns {function()} Returns a deregistration function for this observer.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return function() {
arrayRemove(listeners, fn);
};
}
};
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch (e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
},
NG_ATTR_BINDING = /^ngAttr[A-Z]/;
compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
var bindings = $element.data('$binding') || [];
if (isArray(binding)) {
bindings = bindings.concat(binding);
} else {
bindings.push(binding);
}
$element.data('$binding', bindings);
} : noop;
compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
safeAddClass($element, 'ng-binding');
} : noop;
compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
$element.data(dataName, scope);
} : noop;
compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
} : noop;
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
previousCompileContext) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can
// modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index) {
if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn =
compileNodes($compileNodes, transcludeFn, $compileNodes,
maxPriority, ignoreDirective, previousCompileContext);
compile.$$addScopeClass($compileNodes);
var namespace = null;
return function publicLinkFn(scope, cloneConnectFn, options) {
assertArg(scope, 'scope');
options = options || {};
var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
transcludeControllers = options.transcludeControllers,
futureParentElement = options.futureParentElement;
// When `parentBoundTranscludeFn` is passed, it is a
// `controllersBoundTransclude` function (it was previously passed
// as `transclude` to directive.link) so we must unwrap it to get
// its `boundTranscludeFn`
if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
}
if (!namespace) {
namespace = detectNamespaceForChildElements(futureParentElement);
}
var $linkNode;
if (namespace !== 'html') {
// When using a directive with replace:true and templateUrl the $compileNodes
// (or a child element inside of them)
// might change, so we need to recreate the namespace adapted compileNodes
// for call to the link function.
// Note: This will already clone the nodes...
$linkNode = jqLite(
wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
);
} else if (cloneConnectFn) {
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
$linkNode = JQLitePrototype.clone.call($compileNodes);
} else {
$linkNode = $compileNodes;
}
if (transcludeControllers) {
for (var controllerName in transcludeControllers) {
$linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
}
}
compile.$$addScopeInfo($linkNode, scope);
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
return $linkNode;
};
}
function detectNamespaceForChildElements(parentElement) {
// TODO: Make this detect MathML as well...
var node = parentElement && parentElement[0];
if (!node) {
return 'html';
} else {
return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
* the rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} maxPriority Max directive priority.
* @returns {Function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
previousCompileContext) {
var linkFns = [],
attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
for (var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
null, [], [], previousCompileContext)
: null;
if (nodeLinkFn && nodeLinkFn.scope) {
compile.$$addScopeClass(attrs.$$element);
}
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
!(childNodes = nodeList[i].childNodes) ||
!childNodes.length)
? null
: compileNodes(childNodes,
nodeLinkFn ? (
(nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
&& nodeLinkFn.transclude) : transcludeFn);
if (nodeLinkFn || childLinkFn) {
linkFns.push(i, nodeLinkFn, childLinkFn);
linkFnFound = true;
nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
}
//use the previous context only for the first element in the virtual group
previousCompileContext = null;
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
var stableNodeList;
if (nodeLinkFnFound) {
// copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
// offsets don't get screwed up
var nodeListLength = nodeList.length;
stableNodeList = new Array(nodeListLength);
// create a sparse array by only copying the elements which have a linkFn
for (i = 0; i < linkFns.length; i+=3) {
idx = linkFns[i];
stableNodeList[idx] = nodeList[idx];
}
} else {
stableNodeList = nodeList;
}
for (i = 0, ii = linkFns.length; i < ii;) {
node = stableNodeList[linkFns[i++]];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new();
compile.$$addScopeInfo(jqLite(node), childScope);
var destroyBindings = nodeLinkFn.$$destroyBindings;
if (destroyBindings) {
nodeLinkFn.$$destroyBindings = null;
childScope.$on('$destroyed', destroyBindings);
}
} else {
childScope = scope;
}
if (nodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(
scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
} else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
childBoundTranscludeFn = parentBoundTranscludeFn;
} else if (!parentBoundTranscludeFn && transcludeFn) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
} else {
childBoundTranscludeFn = null;
}
nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
nodeLinkFn);
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
}
}
}
}
function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
if (!transcludedScope) {
transcludedScope = scope.$new(false, containingScope);
transcludedScope.$$transcluded = true;
}
return transcludeFn(transcludedScope, cloneFn, {
parentBoundTranscludeFn: previousBoundTranscludeFn,
transcludeControllers: controllers,
futureParentElement: futureParentElement
});
};
return boundTranscludeFn;
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch (nodeType) {
case NODE_TYPE_ELEMENT: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName = false;
var attrEndName = false;
attr = nAttrs[j];
name = attr.name;
value = trim(attr.value);
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
name = name.replace(PREFIX_REGEXP, '')
.substr(8).replace(/_(.)/g, function(match, letter) {
return letter.toUpperCase();
});
}
var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
if (directiveIsMultiElement(directiveNName)) {
if (ngAttrName === directiveNName + 'Start') {
attrStartName = name;
attrEndName = name.substr(0, name.length - 5) + 'end';
name = name.substr(0, name.length - 6);
}
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
if (isNgAttr || !attrs.hasOwnProperty(nName)) {
attrs[nName] = value;
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
}
addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
attrEndName);
}
// use class as directive
className = node.className;
if (isObject(className)) {
// Maybe SVGAnimatedString
className = className.animVal;
}
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case NODE_TYPE_TEXT: /* Text Node */
if (msie === 11) {
// Workaround for #11781
while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
node.parentNode.removeChild(node.nextSibling);
}
}
addTextInterpolateDirective(directives, node.nodeValue);
break;
case NODE_TYPE_COMMENT: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read
// comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Given a node with an directive-start it collects all of the siblings until it finds
* directive-end.
* @param node
* @param attrStart
* @param attrEnd
* @returns {*}
*/
function groupScan(node, attrStart, attrEnd) {
var nodes = [];
var depth = 0;
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
do {
if (!node) {
throw $compileMinErr('uterdir',
"Unterminated attribute, found '{0}' but no matching '{1}' found.",
attrStart, attrEnd);
}
if (node.nodeType == NODE_TYPE_ELEMENT) {
if (node.hasAttribute(attrStart)) depth++;
if (node.hasAttribute(attrEnd)) depth--;
}
nodes.push(node);
node = node.nextSibling;
} while (depth > 0);
} else {
nodes.push(node);
}
return jqLite(nodes);
}
/**
* Wrapper for linking function which converts normal linking function into a grouped
* linking function.
* @param linkFn
* @param attrStart
* @param attrEnd
* @returns {Function}
*/
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
return function(scope, element, attrs, controllers, transcludeFn) {
element = groupScan(element[0], attrStart, attrEnd);
return linkFn(scope, element, attrs, controllers, transcludeFn);
};
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new
* child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes
* on it.
* @param {Object=} originalReplaceDirective An optional directive that will be ignored when
* compiling the transclusion.
* @param {Array.<Function>} preLinkFns
* @param {Array.<Function>} postLinkFns
* @param {Object} previousCompileContext Context used for previous compilation of the current
* node
* @returns {Function} linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
previousCompileContext) {
previousCompileContext = previousCompileContext || {};
var terminalPriority = -Number.MAX_VALUE,
newScopeDirective = previousCompileContext.newScopeDirective,
controllerDirectives = previousCompileContext.controllerDirectives,
newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
templateDirective = previousCompileContext.templateDirective,
nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
hasTranscludeDirective = false,
hasTemplate = false,
hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
replaceDirective = originalReplaceDirective,
childTranscludeFn = transcludeFn,
linkFn,
directiveValue;
// executes all directives on the current element
for (var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
var attrStart = directive.$$start;
var attrEnd = directive.$$end;
// collect multiblock sections
if (attrStart) {
$compileNode = groupScan(compileNode, attrStart, attrEnd);
}
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
// skip the check for directives with async templates, we'll check the derived sync
// directive when the template arrives
if (!directive.templateUrl) {
if (isObject(directiveValue)) {
// This directive is trying to add an isolated scope.
// Check that there is no scope of any kind already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
directive, $compileNode);
newIsolateScopeDirective = directive;
} else {
// This directive is trying to add a child scope.
// Check that there is no isolated scope already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
$compileNode);
}
}
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (!directive.templateUrl && directive.controller) {
directiveValue = directive.controller;
controllerDirectives = controllerDirectives || createMap();
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
hasTranscludeDirective = true;
// Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
// This option should only be used by directives that know how to safely handle element transclusion,
// where the transcluded nodes are added or replaced after linking.
if (!directive.$$tlb) {
assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
nonTlbTranscludeDirective = directive;
}
if (directiveValue == 'element') {
hasElementTranscludeDirective = true;
terminalPriority = directive.priority;
$template = $compileNode;
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' +
templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, sliceArgs($template), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name, {
// Don't pass in:
// - controllerDirectives - otherwise we'll create duplicates controllers
// - newIsolateScopeDirective or templateDirective - combining templates with
// element transclusion doesn't make sense.
//
// We need only nonTlbTranscludeDirective so that we prevent putting transclusion
// on the same element more than once.
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
} else {
$template = jqLite(jqLiteClone(compileNode)).contents();
$compileNode.empty(); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directive.template) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = (isFunction(directive.template))
? directive.template($compileNode, templateAttrs)
: directive.template;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
replaceDirective = directive;
if (jqLiteIsTextNode(directiveValue)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
// - collect directives from the template and sort them by priority
// - combine directives as: processed + template + unprocessed
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
if (newIsolateScopeDirective) {
markDirectivesAsIsolate(templateDirectives);
}
directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
controllerDirectives: controllerDirectives,
newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
newIsolateScopeDirective: newIsolateScopeDirective,
templateDirective: templateDirective,
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn, attrStart, attrEnd);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
nodeLinkFn.templateOnThisElement = hasTemplate;
nodeLinkFn.transclude = childTranscludeFn;
previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post, attrStart, attrEnd) {
if (pre) {
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
pre.require = directive.require;
pre.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
pre = cloneAndAnnotateFn(pre, {isolateScope: true});
}
preLinkFns.push(pre);
}
if (post) {
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
post.require = directive.require;
post.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
post = cloneAndAnnotateFn(post, {isolateScope: true});
}
postLinkFns.push(post);
}
}
function getControllers(directiveName, require, $element, elementControllers) {
var value;
if (isString(require)) {
var match = require.match(REQUIRE_PREFIX_REGEXP);
var name = require.substring(match[0].length);
var inheritType = match[1] || match[3];
var optional = match[2] === '?';
//If only parents then start at the parent element
if (inheritType === '^^') {
$element = $element.parent();
//Otherwise attempt getting the controller from elementControllers in case
//the element is transcluded (and has no data) and to avoid .data if possible
} else {
value = elementControllers && elementControllers[name];
value = value && value.instance;
}
if (!value) {
var dataName = '$' + name + 'Controller';
value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
}
if (!value && !optional) {
throw $compileMinErr('ctreq',
"Controller '{0}', required by directive '{1}', can't be found!",
name, directiveName);
}
} else if (isArray(require)) {
value = [];
for (var i = 0, ii = require.length; i < ii; i++) {
value[i] = getControllers(directiveName, require[i], $element, elementControllers);
}
}
return value || null;
}
function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
var elementControllers = createMap();
for (var controllerKey in controllerDirectives) {
var directive = controllerDirectives[controllerKey];
var locals = {
$scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
$element: $element,
$attrs: attrs,
$transclude: transcludeFn
};
var controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
// For directives with element transclusion the element is a comment,
// but jQuery .data doesn't support attaching data to comment nodes as it's hard to
// clean up (http://bugs.jquery.com/ticket/8335).
// Instead, we save the controllers for the element in a local hash and attach to .data
// later, once we have the actual element.
elementControllers[directive.name] = controllerInstance;
if (!hasElementTranscludeDirective) {
$element.data('$' + directive.name + 'Controller', controllerInstance.instance);
}
}
return elementControllers;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
thisLinkFn) {
var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
attrs;
if (compileNode === linkNode) {
attrs = templateAttrs;
$element = templateAttrs.$$element;
} else {
$element = jqLite(linkNode);
attrs = new Attributes($element, templateAttrs);
}
if (newIsolateScopeDirective) {
isolateScope = scope.$new(true);
}
if (boundTranscludeFn) {
// track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
// is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
transcludeFn = controllersBoundTransclude;
transcludeFn.$$boundTransclude = boundTranscludeFn;
}
if (controllerDirectives) {
elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
}
if (newIsolateScopeDirective) {
// Initialize isolate scope bindings for new isolate scope directive.
compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
templateDirective === newIsolateScopeDirective.$$originalDirective)));
compile.$$addScopeClass($element, true);
isolateScope.$$isolateBindings =
newIsolateScopeDirective.$$isolateBindings;
initializeDirectiveBindings(scope, attrs, isolateScope,
isolateScope.$$isolateBindings,
newIsolateScopeDirective, isolateScope);
}
if (elementControllers) {
// Initialize bindToController bindings for new/isolate scopes
var scopeDirective = newIsolateScopeDirective || newScopeDirective;
var bindings;
var controllerForBindings;
if (scopeDirective && elementControllers[scopeDirective.name]) {
bindings = scopeDirective.$$bindings.bindToController;
controller = elementControllers[scopeDirective.name];
if (controller && controller.identifier && bindings) {
controllerForBindings = controller;
thisLinkFn.$$destroyBindings =
initializeDirectiveBindings(scope, attrs, controller.instance,
bindings, scopeDirective);
}
}
for (i in elementControllers) {
controller = elementControllers[i];
var controllerResult = controller();
if (controllerResult !== controller.instance) {
// If the controller constructor has a return value, overwrite the instance
// from setupControllers and update the element data
controller.instance = controllerResult;
$element.data('$' + i + 'Controller', controllerResult);
if (controller === controllerForBindings) {
// Remove and re-install bindToController bindings
thisLinkFn.$$destroyBindings();
thisLinkFn.$$destroyBindings =
initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
}
}
}
}
// PRELINKING
for (i = 0, ii = preLinkFns.length; i < ii; i++) {
linkFn = preLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// RECURSION
// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.
var scopeToChild = scope;
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
scopeToChild = isolateScope;
}
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for (i = postLinkFns.length - 1; i >= 0; i--) {
linkFn = postLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// This is the function that is injected as `$transclude`.
// Note: all arguments are optional!
function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
var transcludeControllers;
// No scope passed in:
if (!isScope(scope)) {
futureParentElement = cloneAttachFn;
cloneAttachFn = scope;
scope = undefined;
}
if (hasElementTranscludeDirective) {
transcludeControllers = elementControllers;
}
if (!futureParentElement) {
futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
}
return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
}
}
}
function markDirectivesAsIsolate(directives) {
// mark all directives as needing isolate scope.
for (var j = 0, jj = directives.length; j < jj; j++) {
directives[j] = inherit(directives[j], {$$isolateScope: true});
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns {boolean} true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
endAttrName) {
if (name === ignoreDirective) return null;
var match = null;
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
try {
directive = directives[i];
if ((maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
if (startAttrName) {
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
}
tDirectives.push(directive);
match = directive;
}
} catch (e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* looks up the directive and returns true if it is a multi-element directive,
* and therefore requires DOM nodes between -start and -end markers to be grouped
* together.
*
* @param {string} name name of the directive to look up.
* @returns true if directive was registered as multi-element.
*/
function directiveIsMultiElement(name) {
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
if (directive.multiElement) {
return true;
}
}
}
return false;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key] && src[key] !== value) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
// `dst` will never contain hasOwnProperty as DOM parser won't let it.
// You will get an "InvalidCharacterError: DOM Exception 5" error if you
// have an attribute like "has-own-property" or "data-has-own-property", etc.
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, $compileNode, tAttrs,
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
derivedSyncDirective = inherit(origAsyncDirective, {
templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
}),
templateUrl = (isFunction(origAsyncDirective.templateUrl))
? origAsyncDirective.templateUrl($compileNode, tAttrs)
: origAsyncDirective.templateUrl,
templateNamespace = origAsyncDirective.templateNamespace;
$compileNode.empty();
$templateRequest(templateUrl)
.then(function(content) {
var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
content = denormalizeTemplate(content);
if (origAsyncDirective.replace) {
if (jqLiteIsTextNode(content)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(templateNamespace, trim(content)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
origAsyncDirective.name, templateUrl);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
if (isObject(origAsyncDirective.scope)) {
markDirectivesAsIsolate(templateDirectives);
}
directives = templateDirectives.concat(directives);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
previousCompileContext);
forEach($rootElement, function(node, i) {
if (node == compileNode) {
$rootElement[i] = $compileNode[0];
}
});
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while (linkQueue.length) {
var scope = linkQueue.shift(),
beforeTemplateLinkNode = linkQueue.shift(),
linkRootElement = linkQueue.shift(),
boundTranscludeFn = linkQueue.shift(),
linkNode = $compileNode[0];
if (scope.$$destroyed) continue;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
var oldClasses = beforeTemplateLinkNode.className;
if (!(previousCompileContext.hasElementTranscludeDirective &&
origAsyncDirective.replace)) {
// it was cloned therefore we have to clone as well.
linkNode = jqLiteClone(compileNode);
}
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
// Copy in CSS classes from original node
safeAddClass(jqLite(linkNode), oldClasses);
}
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
} else {
childBoundTranscludeFn = boundTranscludeFn;
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
childBoundTranscludeFn, afterTemplateNodeLinkFn);
}
linkQueue = null;
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
var childBoundTranscludeFn = boundTranscludeFn;
if (scope.$$destroyed) return;
if (linkQueue) {
linkQueue.push(scope,
node,
rootElement,
childBoundTranscludeFn);
} else {
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
afterTemplateNodeLinkFn);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
var diff = b.priority - a.priority;
if (diff !== 0) return diff;
if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
return a.index - b.index;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
function wrapModuleNameIfDefined(moduleName) {
return moduleName ?
(' (module: ' + moduleName + ')') :
'';
}
if (previousDirective) {
throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: function textInterpolateCompileFn(templateNode) {
var templateNodeParent = templateNode.parent(),
hasCompileParent = !!templateNodeParent.length;
// When transcluding a template that has bindings in the root
// we don't have a parent and thus need to add the class during linking fn.
if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
return function textInterpolateLinkFn(scope, node) {
var parent = node.parent();
if (!hasCompileParent) compile.$$addBindingClass(parent);
compile.$$addBindingInfo(parent, interpolateFn.expressions);
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
};
}
});
}
}
function wrapTemplate(type, template) {
type = lowercase(type || 'html');
switch (type) {
case 'svg':
case 'math':
var wrapper = document.createElement('div');
wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
return wrapper.childNodes[0].childNodes;
default:
return template;
}
}
function getTrustedContext(node, attrNormalizedName) {
if (attrNormalizedName == "srcdoc") {
return $sce.HTML;
}
var tag = nodeName_(node);
// maction[xlink:href] can source SVG. It's not limited to <maction>.
if (attrNormalizedName == "xlinkHref" ||
(tag == "form" && attrNormalizedName == "action") ||
(tag != "img" && (attrNormalizedName == "src" ||
attrNormalizedName == "ngSrc"))) {
return $sce.RESOURCE_URL;
}
}
function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
var trustedContext = getTrustedContext(node, name);
allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
// no interpolation found -> ignore
if (!interpolateFn) return;
if (name === "multiple" && nodeName_(node) === "select") {
throw $compileMinErr("selmulti",
"Binding to the 'multiple' attribute is not supported. Element: {0}",
startingTag(node));
}
directives.push({
priority: 100,
compile: function() {
return {
pre: function attrInterpolatePreLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
throw $compileMinErr('nodomevents',
"Interpolations for HTML DOM event attributes are disallowed. Please use the " +
"ng- versions (such as ng-click instead of onclick) instead.");
}
// If the attribute has changed since last $interpolate()ed
var newValue = attr[name];
if (newValue !== value) {
// we need to interpolate again since the attribute value has been updated
// (e.g. by another directive's compile function)
// ensure unset/empty values make interpolateFn falsy
interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
value = newValue;
}
// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
if (!interpolateFn) return;
// initialize attr object so that it's ready in case we need the value for isolate
// scope initialization, otherwise the value would not be available from isolate
// directive's linking fn during linking phase
attr[name] = interpolateFn(scope);
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
//special case for class attribute addition + removal
//so that class changes can tap into the animation
//hooks provided by the $animate service. Be sure to
//skip animations when the first digest occurs (when
//both the new and the old values are the same) since
//the CSS classes are the non-interpolated values
if (name === 'class' && newValue != oldValue) {
attr.$updateClass(newValue, oldValue);
} else {
attr.$set(name, newValue);
}
});
}
};
}
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
* the shell, but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, elementsToRemove, newNode) {
var firstElementToRemove = elementsToRemove[0],
removeCount = elementsToRemove.length,
parent = firstElementToRemove.parentNode,
i, ii;
if ($rootElement) {
for (i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == firstElementToRemove) {
$rootElement[i++] = newNode;
for (var j = i, j2 = j + removeCount - 1,
jj = $rootElement.length;
j < jj; j++, j2++) {
if (j2 < jj) {
$rootElement[j] = $rootElement[j2];
} else {
delete $rootElement[j];
}
}
$rootElement.length -= removeCount - 1;
// If the replaced element is also the jQuery .context then replace it
// .context is a deprecated jQuery api, so we should set it only when jQuery set it
// http://api.jquery.com/context/
if ($rootElement.context === firstElementToRemove) {
$rootElement.context = newNode;
}
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, firstElementToRemove);
}
// TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
var fragment = document.createDocumentFragment();
fragment.appendChild(firstElementToRemove);
if (jqLite.hasData(firstElementToRemove)) {
// Copy over user data (that includes Angular's $scope etc.). Don't copy private
// data here because there's no public interface in jQuery to do that and copying over
// event listeners (which is the main use of private data) wouldn't work anyway.
jqLite(newNode).data(jqLite(firstElementToRemove).data());
// Remove data of the replaced element. We cannot just call .remove()
// on the element it since that would deallocate scope that is needed
// for the new node. Instead, remove the data "manually".
if (!jQuery) {
delete jqLite.cache[firstElementToRemove[jqLite.expando]];
} else {
// jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
// the replaced element. The cleanData version monkey-patched by Angular would cause
// the scope to be trashed and we do need the very same scope to work with the new
// element. However, we cannot just cache the non-patched version and use it here as
// that would break if another library patches the method after Angular does (one
// example is jQuery UI). Instead, set a flag indicating scope destroying should be
// skipped this one time.
skipDestroyOnNextJQueryCleanData = true;
jQuery.cleanData([firstElementToRemove]);
}
}
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
var element = elementsToRemove[k];
jqLite(element).remove(); // must do this way to clean up expando
fragment.appendChild(element);
delete elementsToRemove[k];
}
elementsToRemove[0] = newNode;
elementsToRemove.length = 1;
}
function cloneAndAnnotateFn(fn, annotation) {
return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
}
function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
try {
linkFn(scope, $element, attrs, controllers, transcludeFn);
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// Set up $watches for isolate scope and controller bindings. This process
// only occurs for isolate scopes and new scopes with controllerAs.
function initializeDirectiveBindings(scope, attrs, destination, bindings,
directive, newScope) {
var onNewScopeDestroyed;
forEach(bindings, function(definition, scopeName) {
var attrName = definition.attrName,
optional = definition.optional,
mode = definition.mode, // @, =, or &
lastValue,
parentGet, parentSet, compare;
switch (mode) {
case '@':
if (!optional && !hasOwnProperty.call(attrs, attrName)) {
destination[scopeName] = attrs[attrName] = void 0;
}
attrs.$observe(attrName, function(value) {
if (isString(value)) {
destination[scopeName] = value;
}
});
attrs.$$observers[attrName].$$scope = scope;
if (isString(attrs[attrName])) {
// If the attribute has been provided then we trigger an interpolation to ensure
// the value is there for use in the link fn
destination[scopeName] = $interpolate(attrs[attrName])(scope);
}
break;
case '=':
if (!hasOwnProperty.call(attrs, attrName)) {
if (optional) break;
attrs[attrName] = void 0;
}
if (optional && !attrs[attrName]) break;
parentGet = $parse(attrs[attrName]);
if (parentGet.literal) {
compare = equals;
} else {
compare = function(a, b) { return a === b || (a !== a && b !== b); };
}
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = destination[scopeName] = parentGet(scope);
throw $compileMinErr('nonassign',
"Expression '{0}' used with directive '{1}' is non-assignable!",
attrs[attrName], directive.name);
};
lastValue = destination[scopeName] = parentGet(scope);
var parentValueWatch = function parentValueWatch(parentValue) {
if (!compare(parentValue, destination[scopeName])) {
// we are out of sync and need to copy
if (!compare(parentValue, lastValue)) {
// parent changed and it has precedence
destination[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(scope, parentValue = destination[scopeName]);
}
}
return lastValue = parentValue;
};
parentValueWatch.$stateful = true;
var unwatch;
if (definition.collection) {
unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
} else {
unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
}
onNewScopeDestroyed = (onNewScopeDestroyed || []);
onNewScopeDestroyed.push(unwatch);
break;
case '&':
// Don't assign Object.prototype method to scope
parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
// Don't assign noop to destination if expression is not valid
if (parentGet === noop && optional) break;
destination[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
}
});
var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
onNewScopeDestroyed[i]();
}
} : noop;
if (newScope && destroyBindings !== noop) {
newScope.$on('$destroy', destroyBindings);
return noop;
}
return destroyBindings;
}
}];
}
var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc type
* @name $compile.directive.Attributes
*
* @description
* A shared object between directive compile / linking functions which contains normalized DOM
* element attributes. The values reflect current binding state `{{ }}`. The normalization is
* needed since all of these are treated as equivalent in Angular:
*
* ```
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
* ```
*/
/**
* @ngdoc property
* @name $compile.directive.Attributes#$attr
*
* @description
* A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc method
* @name $compile.directive.Attributes#$set
* @kind function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to. The value can be an interpolated string.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function tokenDifference(str1, str2) {
var values = '',
tokens1 = str1.split(/\s+/),
tokens2 = str2.split(/\s+/);
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values += (values.length > 0 ? ' ' : '') + token;
}
return values;
}
function removeComments(jqNodes) {
jqNodes = jqLite(jqNodes);
var i = jqNodes.length;
if (i <= 1) {
return jqNodes;
}
while (i--) {
var node = jqNodes[i];
if (node.nodeType === NODE_TYPE_COMMENT) {
splice.call(jqNodes, i, 1);
}
}
return jqNodes;
}
var $controllerMinErr = minErr('$controller');
var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
function identifierForController(controller, ident) {
if (ident && isString(ident)) return ident;
if (isString(controller)) {
var match = CNTRL_REG.exec(controller);
if (match) return match[3];
}
}
/**
* @ngdoc provider
* @name $controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {},
globals = false;
/**
* @ngdoc method
* @name $controllerProvider#register
* @param {string|Object} name Controller name, or an object map of controllers where the keys are
* the names and the values are the constructors.
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
assertNotHasOwnProperty(name, 'controller');
if (isObject(name)) {
extend(controllers, name);
} else {
controllers[name] = constructor;
}
};
/**
* @ngdoc method
* @name $controllerProvider#allowGlobals
* @description If called, allows `$controller` to find controller constructors on `window`
*/
this.allowGlobals = function() {
globals = true;
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc service
* @name $controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
* `window` object (not recommended)
*
* The string can use the `controller as property` syntax, where the controller instance is published
* as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
* to work correctly.
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link auto.$injector $injector}, but extracted into
* a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
*/
return function(expression, locals, later, ident) {
// PRIVATE API:
// param `later` --- indicates that the controller's constructor is invoked at a later time.
// If true, $controller will allocate the object with the correct
// prototype chain, but will not invoke the controller until a returned
// callback is invoked.
// param `ident` --- An optional label which overrides the label parsed from the controller
// expression, if any.
var instance, match, constructor, identifier;
later = later === true;
if (ident && isString(ident)) {
identifier = ident;
}
if (isString(expression)) {
match = expression.match(CNTRL_REG);
if (!match) {
throw $controllerMinErr('ctrlfmt',
"Badly formed controller string '{0}'. " +
"Must match `__name__ as __id__` or `__name__`.", expression);
}
constructor = match[1],
identifier = identifier || match[3];
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
assertArgFn(expression, constructor, true);
}
if (later) {
// Instantiate controller later:
// This machinery is used to create an instance of the object before calling the
// controller's constructor itself.
//
// This allows properties to be added to the controller before the constructor is
// invoked. Primarily, this is used for isolate scope bindings in $compile.
//
// This feature is not intended for use by applications, and is thus not documented
// publicly.
// Object creation: http://jsperf.com/create-constructor/2
var controllerPrototype = (isArray(expression) ?
expression[expression.length - 1] : expression).prototype;
instance = Object.create(controllerPrototype || null);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
var instantiate;
return instantiate = extend(function() {
var result = $injector.invoke(expression, instance, locals, constructor);
if (result !== instance && (isObject(result) || isFunction(result))) {
instance = result;
if (identifier) {
// If result changed, re-assign controllerAs value to scope.
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
}
return instance;
}, {
instance: instance,
identifier: identifier
});
}
instance = $injector.instantiate(expression, locals, constructor);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
return instance;
};
function addIdentifier(locals, identifier, instance, name) {
if (!(locals && isObject(locals.$scope))) {
throw minErr('$controller')('noscp',
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
name, identifier);
}
locals.$scope[identifier] = instance;
}
}];
}
/**
* @ngdoc service
* @name $document
* @requires $window
*
* @description
* A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
*
* @example
<example module="documentExample">
<file name="index.html">
<div ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>
</file>
<file name="script.js">
angular.module('documentExample', [])
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
$scope.title = $document[0].title;
$scope.windowTitle = angular.element(window.document)[0].title;
}]);
</file>
</example>
*/
function $DocumentProvider() {
this.$get = ['$window', function(window) {
return jqLite(window.document);
}];
}
/**
* @ngdoc service
* @name $exceptionHandler
* @requires ng.$log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* ## Example:
*
* ```js
* angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
* return function(exception, cause) {
* exception.message += ' (caused by "' + cause + '")';
* throw exception;
* };
* });
* ```
*
* This example will override the normal action of `$exceptionHandler`, to make angular
* exceptions fail hard when they happen, instead of just logging to the console.
*
* <hr />
* Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
* methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
* (unless executed during a digest).
*
* If you wish, you can manually delegate exceptions, e.g.
* `try { ... } catch(e) { $exceptionHandler(e); }`
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
var $$ForceReflowProvider = function() {
this.$get = ['$document', function($document) {
return function(domNode) {
//the line below will force the browser to perform a repaint so
//that all the animated elements within the animation frame will
//be properly updated and drawn on screen. This is required to
//ensure that the preparation animation is properly flushed so that
//the active state picks up from there. DO NOT REMOVE THIS LINE.
//DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
//WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
//WILL TAKE YEARS AWAY FROM YOUR LIFE.
if (domNode) {
if (!domNode.nodeType && domNode instanceof jqLite) {
domNode = domNode[0];
}
} else {
domNode = $document[0].body;
}
return domNode.offsetWidth + 1;
};
}];
};
var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
'[': /]$/,
'{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $httpMinErr = minErr('$http');
var $httpMinErrLegacyFn = function(method) {
return function() {
throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
};
};
function serializeValue(v) {
if (isObject(v)) {
return isDate(v) ? v.toISOString() : toJson(v);
}
return v;
}
function $HttpParamSerializerProvider() {
/**
* @ngdoc service
* @name $httpParamSerializer
* @description
*
* Default {@link $http `$http`} params serializer that converts objects to strings
* according to the following rules:
*
* * `{'foo': 'bar'}` results in `foo=bar`
* * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
* * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
* * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
*
* Note that serializer will sort the request parameters alphabetically.
* */
this.$get = function() {
return function ngParamSerializer(params) {
if (!params) return '';
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (isArray(value)) {
forEach(value, function(v, k) {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
});
} else {
parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
}
});
return parts.join('&');
};
};
}
function $HttpParamSerializerJQLikeProvider() {
/**
* @ngdoc service
* @name $httpParamSerializerJQLike
* @description
*
* Alternative {@link $http `$http`} params serializer that follows
* jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
* The serializer will also sort the params alphabetically.
*
* To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
*
* ```js
* $http({
* url: myUrl,
* method: 'GET',
* params: myParams,
* paramSerializer: '$httpParamSerializerJQLike'
* });
* ```
*
* It is also possible to set it as the default `paramSerializer` in the
* {@link $httpProvider#defaults `$httpProvider`}.
*
* Additionally, you can inject the serializer and use it explicitly, for example to serialize
* form data for submission:
*
* ```js
* .controller(function($http, $httpParamSerializerJQLike) {
* //...
*
* $http({
* url: myUrl,
* method: 'POST',
* data: $httpParamSerializerJQLike(myData),
* headers: {
* 'Content-Type': 'application/x-www-form-urlencoded'
* }
* });
*
* });
* ```
*
* */
this.$get = function() {
return function jQueryLikeParamSerializer(params) {
if (!params) return '';
var parts = [];
serialize(params, '', true);
return parts.join('&');
function serialize(toSerialize, prefix, topLevel) {
if (toSerialize === null || isUndefined(toSerialize)) return;
if (isArray(toSerialize)) {
forEach(toSerialize, function(value, index) {
serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
});
} else if (isObject(toSerialize) && !isDate(toSerialize)) {
forEachSorted(toSerialize, function(value, key) {
serialize(value, prefix +
(topLevel ? '' : '[') +
key +
(topLevel ? '' : ']'));
});
} else {
parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
}
}
};
};
}
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
function isJsonLike(str) {
var jsonStart = str.match(JSON_START);
return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = createMap(), i;
function fillInParsed(key, val) {
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
if (isString(headers)) {
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
});
} else if (isObject(headers)) {
forEach(headers, function(headerVal, headerKey) {
fillInParsed(lowercase(headerKey), trim(headerVal));
});
}
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers HTTP headers getter fn.
* @param {number} status HTTP status code of the response.
* @param {(Function|Array.<Function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, status, fns) {
if (isFunction(fns)) {
return fns(data, headers, status);
}
forEach(fns, function(fn) {
data = fn(data, headers, status);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
/**
* @ngdoc provider
* @name $httpProvider
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
function $HttpProvider() {
/**
* @ngdoc property
* @name $httpProvider#defaults
* @description
*
* Object containing default values for all {@link ng.$http $http} requests.
*
* - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
* that will provide the cache for all requests who set their `cache` property to `true`.
* If you set the `defaults.cache = false` then only requests that specify their own custom
* cache object will be cached. See {@link $http#caching $http Caching} for more information.
*
* - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
* Defaults value is `'XSRF-TOKEN'`.
*
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
* - **`defaults.headers`** - {Object} - Default headers for all $http requests.
* Refer to {@link ng.$http#setting-http-headers $http} for documentation on
* setting default headers.
* - **`defaults.headers.common`**
* - **`defaults.headers.post`**
* - **`defaults.headers.put`**
* - **`defaults.headers.patch`**
*
*
* - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
* used to the prepare string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
* Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
*
**/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
paramSerializer: '$httpParamSerializer'
};
var useApplyAsync = false;
/**
* @ngdoc method
* @name $httpProvider#useApplyAsync
* @description
*
* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests
* concurrently (common during application bootstrap).
*
* Defaults to false. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
* "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
* to load and share the same digest cycle.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
return this;
}
return useApplyAsync;
};
var useLegacyPromise = true;
/**
* @ngdoc method
* @name $httpProvider#useLegacyPromiseExtensions
* @description
*
* Configure `$http` service to return promises without the shorthand methods `success` and `error`.
* This should be used to make sure that applications work without these methods.
*
* Defaults to false. If no value is specified, returns the current configured value.
*
* @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useLegacyPromiseExtensions = function(value) {
if (isDefined(value)) {
useLegacyPromise = !!value;
return this;
}
return useLegacyPromise;
};
/**
* @ngdoc property
* @name $httpProvider#interceptors
* @description
*
* Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
* pre-processing of request or postprocessing of responses.
*
* These service factories are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
var interceptorFactories = this.interceptors = [];
this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Make sure that default param serializer is exposed as a function
*/
defaults.paramSerializer = isString(defaults.paramSerializer) ?
$injector.get(defaults.paramSerializer) : defaults.paramSerializer;
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
/**
* @ngdoc service
* @kind function
* @name $http
* @requires ng.$httpBackend
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
* object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* ## General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}.
*
* ```js
* // Simple GET request example :
* $http.get('/someUrl').
* then(function(response) {
* // this callback will be called asynchronously
* // when the response is available
* }, function(response) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* ```js
* // Simple POST request example (passing data) :
* $http.post('/someUrl', {msg:'hello word!'}).
* then(function(response) {
* // this callback will be called asynchronously
* // when the response is available
* }, function(response) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
* - **statusText** – `{string}` – HTTP status text of the response.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* ## Writing Unit Tests that use $http
* When unit testing (using {@link ngMock ngMock}), it is necessary to call
* {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
* request using trained responses.
*
* ```
* $httpBackend.expectGET(...);
* $http.get(...);
* $httpBackend.flush();
* ```
*
* ## Shortcut methods
*
* Shortcut methods are also available. All shortcut methods require passing in the URL, and
* request data must be passed in for POST/PUT requests.
*
* ```js
* $http.get('/someUrl').then(successCallback);
* $http.post('/someUrl', data).then(successCallback);
* ```
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
* - {@link ng.$http#patch $http.patch}
*
*
* ## Deprecation Notice
* <div class="alert alert-danger">
* The `$http` legacy promise methods `success` and `error` have been deprecated.
* Use the standard `then` method instead.
* If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
* `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
* </div>
*
* ## Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. For example:
*
* ```
* module.run(function($http) {
* $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
* });
* ```
*
* In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
* To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
* Use the `headers` property, setting the desired header to `undefined`. For example:
*
* ```js
* var req = {
* method: 'POST',
* url: 'http://example.com',
* headers: {
* 'Content-Type': undefined
* },
* data: { test: 'test' }
* }
*
* $http(req).then(function(){...}, function(){...});
* ```
*
* ## Transforming Requests and Responses
*
* Both requests and responses can be transformed using transformation functions: `transformRequest`
* and `transformResponse`. These properties can be a single function that returns
* the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
* which allows you to `push` or `unshift` a new transformation function into the transformation chain.
*
* ### Default Transformations
*
* The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
* `defaults.transformResponse` properties. If a request does not provide its own transformations
* then these will be applied.
*
* You can augment or replace the default transformations by modifying these properties by adding to or
* replacing the array.
*
* Angular provides the following default transformations:
*
* Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
*
* ### Overriding the Default Transformations Per Request
*
* If you wish override the request/response transformations only for a single request then provide
* `transformRequest` and/or `transformResponse` properties on the configuration object passed
* into `$http`.
*
* Note that if you provide these properties on the config object the default transformations will be
* overwritten. If you wish to augment the default transformations then you must include them in your
* local transformation array.
*
* The following code demonstrates adding a new response transformation to be run after the default response
* transformations have been run.
*
* ```js
* function appendTransform(defaults, transform) {
*
* // We can't guarantee that the default transformation is an array
* defaults = angular.isArray(defaults) ? defaults : [defaults];
*
* // Append the new transformation to the defaults
* return defaults.concat(transform);
* }
*
* $http({
* url: '...',
* method: 'GET',
* transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
* return doTransform(value);
* })
* });
* ```
*
*
* ## Caching
*
* To enable caching, set the request configuration `cache` property to `true` (to use default
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
* When the cache is enabled, `$http` stores the response from the server in the specified
* cache. The next time the same request is made, the response is served from the cache without
* sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* You can change the default cache to a new object (built with
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the
* {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
* their `cache` property to `true` will now use this cache object.
*
* If you set the default cache to `false` then only requests that specify their own custom
* cache object will be cached.
*
* ## Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with a http `config` object. The function is free to
* modify the `config` object or create a new one. The function needs to return the `config`
* object directly, or a promise containing the `config` or a new `config` object.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` object or create a new one. The function needs to return the `response`
* object directly, or as a promise containing the `response` or a new `response` object.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* ```js
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config;
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response;
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* }
* };
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // alternatively, register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
*
* 'response': function(response) {
* // same as above
* }
* };
* });
* ```
*
* ## Security Considerations
*
* When designing web applications, consider security threats from:
*
* - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ### JSON Vulnerability Protection
*
* A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* allows third party website to turn your JSON resource URL into
* [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* ```js
* ['one','two']
* ```
*
* which is vulnerable to attack, your server can return:
* ```js
* )]}',
* ['one','two']
* ```
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ### Cross Site Request Forgery (XSRF) Protection
*
* [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
*
* In order to prevent collisions in environments where multiple Angular apps share the
* same domain or subdomain, we recommend that each application uses unique cookie name.
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
* with the `paramSerializer` and appended as GET parameters.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent. Functions accept a config object as an argument.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **transformResponse** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default TransformationjqLiks}
* - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
* prepare the string representation of request parameters (specified as an object).
* If specified as string, it is interpreted as function registered with the
* {@link $injector $injector}, which means you can create your own serializer
* by registering it as a {@link auto.$provide#service service}.
* The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
* alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
* for more information.
* - **responseType** - `{string}` - see
* [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
*
* @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
* when the request succeeds or fails.
*
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example module="httpExample">
<file name="index.html">
<div ng-controller="FetchController">
<select ng-model="method" aria-label="Request method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80" aria-label="URL" />
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
if (!angular.isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
}
var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse,
paramSerializer: defaults.paramSerializer
}, requestConfig);
config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
config.paramSerializer = isString(config.paramSerializer) ?
$injector.get(config.paramSerializer) : config.paramSerializer;
var serverRequest = function(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while (chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
if (useLegacyPromise) {
promise.success = function(fn) {
assertArgFn(fn, 'fn');
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
assertArgFn(fn, 'fn');
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
} else {
promise.success = $httpMinErrLegacyFn('success');
promise.error = $httpMinErrLegacyFn('error');
}
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
if (!response.data) {
resp.data = response.data;
} else {
resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
}
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function executeHeaderFns(headers, config) {
var headerContent, processedHeaders = {};
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn(config);
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
});
return processedHeaders;
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
// execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders, shallowCopy(config));
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name $http#get
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#delete
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#head
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#jsonp
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name $http#post
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#put
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#patch
*
* @description
* Shortcut method to perform `PATCH` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put', 'patch');
/**
* @ngdoc property
* @name $http#defaults
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend({}, config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend({}, config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
reqHeaders = config.headers,
url = buildUrl(config.url, config.paramSerializer(config.params));
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
} else {
resolvePromise(cachedResp, 200, {}, 'OK');
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
function resolveHttpPromise() {
resolvePromise(response, status, headersString, statusText);
}
if (useApplyAsync) {
$rootScope.$applyAsync(resolveHttpPromise);
} else {
resolveHttpPromise();
if (!$rootScope.$$phase) $rootScope.$apply();
}
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers, statusText) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config,
statusText: statusText
});
}
function resolvePromiseWithResult(result) {
resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
}
function removePendingReq() {
var idx = $http.pendingRequests.indexOf(config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, serializedParams) {
if (serializedParams.length > 0) {
url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
}
return url;
}
}];
}
function createXhr() {
return new window.XMLHttpRequest();
}
/**
* @ngdoc service
* @name $httpBackend
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
}];
}
function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
callbacks[callbackId].called = true;
};
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
callbackId, function(status, text) {
completeRequest(callback, status, callbacks[callbackId].data, "", text);
callbacks[callbackId] = noop;
});
} else {
var xhr = createXhr();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
xhr.onload = function requestLoaded() {
var statusText = xhr.statusText || '';
// responseText is the old-school way of retrieving response (supported by IE9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
var response = ('response' in xhr) ? xhr.response : xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
completeRequest(callback,
status,
response,
xhr.getAllResponseHeaders(),
statusText);
};
var requestError = function() {
// The response is always empty
// See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
completeRequest(callback, -1, null, null, '');
};
xhr.onerror = requestError;
xhr.onabort = requestError;
if (withCredentials) {
xhr.withCredentials = true;
}
if (responseType) {
try {
xhr.responseType = responseType;
} catch (e) {
// WebKit added support for the json responseType value on 09/03/2013
// https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
// known to throw when setting the value "json" as the response type. Other older
// browsers implementing the responseType
//
// The json response type can be ignored if not supported, because JSON payloads are
// parsed on the client-side regardless.
if (responseType !== 'json') {
throw e;
}
}
}
xhr.send(post);
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (isPromiseLike(timeout)) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
if (timeoutId !== undefined) {
$browserDefer.cancel(timeoutId);
}
jsonpDone = xhr = null;
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, callbackId, done) {
// we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'), callback = null;
script.type = "text/javascript";
script.src = url;
script.async = true;
callback = function(event) {
removeEventListenerFn(script, "load", callback);
removeEventListenerFn(script, "error", callback);
rawDocument.body.removeChild(script);
script = null;
var status = -1;
var text = "unknown";
if (event) {
if (event.type === "load" && !callbacks[callbackId].called) {
event = { type: "error" };
}
text = event.type;
status = event.type === "error" ? 404 : 200;
}
if (done) {
done(status, text);
}
};
addEventListenerFn(script, "load", callback);
addEventListenerFn(script, "error", callback);
rawDocument.body.appendChild(script);
return callback;
}
}
var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
$interpolateMinErr.throwNoconcat = function(text) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
};
$interpolateMinErr.interr = function(text, err) {
return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
};
/**
* @ngdoc provider
* @name $interpolateProvider
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<example module="customInterpolationApp">
<file name="index.html">
<script>
var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
customInterpolationApp.controller('DemoController', function() {
this.label = "This binding is brought you by // interpolation symbols.";
});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
//demo.label//
</div>
</file>
<file name="protractor.js" type="protractor">
it('should interpolate binding with custom symbols', function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
});
</file>
</example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name $interpolateProvider#startSymbol
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value) {
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name $interpolateProvider#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value) {
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length,
escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
function escape(ch) {
return '\\\\\\' + ch;
}
function unescapeText(text) {
return text.replace(escapedStartRegexp, startSymbol).
replace(escapedEndRegexp, endSymbol);
}
function stringify(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
value = toJson(value);
}
return value;
}
/**
* @ngdoc service
* @name $interpolate
* @kind function
*
* @requires $parse
* @requires $sce
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
* ```js
* var $interpolate = ...; // injected
* var exp = $interpolate('Hello {{name | uppercase}}!');
* expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
* ```
*
* `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
* `true`, the interpolation function will return `undefined` unless all embedded expressions
* evaluate to a value other than `undefined`.
*
* ```js
* var $interpolate = ...; // injected
* var context = {greeting: 'Hello', name: undefined };
*
* // default "forgiving" mode
* var exp = $interpolate('{{greeting}} {{name}}!');
* expect(exp(context)).toEqual('Hello !');
*
* // "allOrNothing" mode
* exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
* expect(exp(context)).toBeUndefined();
* context.name = 'Angular';
* expect(exp(context)).toEqual('Hello Angular!');
* ```
*
* `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
*
* ####Escaped Interpolation
* $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
* can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
* It will be rendered as a regular start/end marker, and will not be interpreted as an expression
* or binding.
*
* This enables web-servers to prevent script injection attacks and defacing attacks, to some
* degree, while also enabling code examples to work without relying on the
* {@link ng.directive:ngNonBindable ngNonBindable} directive.
*
* **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
* replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
* interpolation start/end markers with their escaped counterparts.**
*
* Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
* output when the $interpolate service processes the text. So, for HTML elements interpolated
* by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
* set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
* this is typically useful only when user-data is used in rendering a template from the server, or
* when otherwise untrusted data is used by a directive.
*
* <example>
* <file name="index.html">
* <div ng-init="username='A user'">
* <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
* </p>
* <p><strong>{{username}}</strong> attempts to inject code which will deface the
* application, but fails to accomplish their task, because the server has correctly
* escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
* characters.</p>
* <p>Instead, the result of the attempted script injection is visible, and can be removed
* from the database by an administrator.</p>
* </div>
* </file>
* </example>
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @param {string=} trustedContext when provided, the returned function passes the interpolated
* result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
* provides Strict Contextual Escaping for details.
* @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
* unless all embedded expressions evaluate to a value other than `undefined`.
* @returns {function(context)} an interpolation function which is used to compute the
* interpolated string. The function has these parameters:
*
* - `context`: evaluation context for all expressions embedded in the interpolated text
*/
function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
allOrNothing = !!allOrNothing;
var startIndex,
endIndex,
index = 0,
expressions = [],
parseFns = [],
textLength = text.length,
exp,
concat = [],
expressionPositions = [];
while (index < textLength) {
if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
if (index !== startIndex) {
concat.push(unescapeText(text.substring(index, startIndex)));
}
exp = text.substring(startIndex + startSymbolLength, endIndex);
expressions.push(exp);
parseFns.push($parse(exp, parseStringifyInterceptor));
index = endIndex + endSymbolLength;
expressionPositions.push(concat.length);
concat.push('');
} else {
// we did not find an interpolation, so we have to add the remainder to the separators array
if (index !== textLength) {
concat.push(unescapeText(text.substring(index)));
}
break;
}
}
// Concatenating expressions makes it hard to reason about whether some combination of
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
// single expression be used for iframe[src], object[src], etc., we ensure that the value
// that's used is assigned or constructed by some JS code somewhere that is more testable or
// make it obvious that you bound the value to some user controlled value. This helps reduce
// the load when auditing for XSS issues.
if (trustedContext && concat.length > 1) {
$interpolateMinErr.throwNoconcat(text);
}
if (!mustHaveExpression || expressions.length) {
var compute = function(values) {
for (var i = 0, ii = expressions.length; i < ii; i++) {
if (allOrNothing && isUndefined(values[i])) return;
concat[expressionPositions[i]] = values[i];
}
return concat.join('');
};
var getValue = function(value) {
return trustedContext ?
$sce.getTrusted(trustedContext, value) :
$sce.valueOf(value);
};
return extend(function interpolationFn(context) {
var i = 0;
var ii = expressions.length;
var values = new Array(ii);
try {
for (; i < ii; i++) {
values[i] = parseFns[i](context);
}
return compute(values);
} catch (err) {
$exceptionHandler($interpolateMinErr.interr(text, err));
}
}, {
// all of these properties are undocumented for now
exp: text, //just for compatibility with regular watchers created via $watch
expressions: expressions,
$$watchDelegate: function(scope, listener) {
var lastValue;
return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
var currValue = compute(values);
if (isFunction(listener)) {
listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
}
lastValue = currValue;
});
}
});
}
function parseStringifyInterceptor(value) {
try {
value = getValue(value);
return allOrNothing && !isDefined(value) ? value : stringify(value);
} catch (err) {
$exceptionHandler($interpolateMinErr.interr(text, err));
}
}
}
/**
* @ngdoc method
* @name $interpolate#startSymbol
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
};
/**
* @ngdoc method
* @name $interpolate#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
* the symbol.
*
* @returns {string} end symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
};
return $interpolate;
}];
}
function $IntervalProvider() {
this.$get = ['$rootScope', '$window', '$q', '$$q',
function($rootScope, $window, $q, $$q) {
var intervals = {};
/**
* @ngdoc service
* @name $interval
*
* @description
* Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
* milliseconds.
*
* The return value of registering an interval function is a promise. This promise will be
* notified upon each tick of the interval, and will be resolved after `count` iterations, or
* run indefinitely if `count` is not defined. The value of the notification will be the
* number of iterations that have run.
* To cancel an interval, call `$interval.cancel(promise)`.
*
* In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* <div class="alert alert-warning">
* **Note**: Intervals created by this service must be explicitly destroyed when you are finished
* with them. In particular they are not automatically destroyed when a controller's scope or a
* directive's element are destroyed.
* You should take this into consideration and make sure to always cancel the interval at the
* appropriate moment. See the example below for more details on how and when to do this.
* </div>
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @param {...*=} Pass additional parameters to the executed function.
* @returns {promise} A promise which will be notified on each iteration.
*
* @example
* <example module="intervalExample">
* <file name="index.html">
* <script>
* angular.module('intervalExample', [])
* .controller('ExampleController', ['$scope', '$interval',
* function($scope, $interval) {
* $scope.format = 'M/d/yy h:mm:ss a';
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
*
* var stop;
* $scope.fight = function() {
* // Don't start a new fight if we are already fighting
* if ( angular.isDefined(stop) ) return;
*
* stop = $interval(function() {
* if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
* $scope.blood_1 = $scope.blood_1 - 3;
* $scope.blood_2 = $scope.blood_2 - 4;
* } else {
* $scope.stopFight();
* }
* }, 100);
* };
*
* $scope.stopFight = function() {
* if (angular.isDefined(stop)) {
* $interval.cancel(stop);
* stop = undefined;
* }
* };
*
* $scope.resetFight = function() {
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
* };
*
* $scope.$on('$destroy', function() {
* // Make sure that the interval is destroyed too
* $scope.stopFight();
* });
* }])
* // Register the 'myCurrentTime' directive factory method.
* // We inject $interval and dateFilter service since the factory method is DI.
* .directive('myCurrentTime', ['$interval', 'dateFilter',
* function($interval, dateFilter) {
* // return the directive link function. (compile function not needed)
* return function(scope, element, attrs) {
* var format, // date format
* stopTime; // so that we can cancel the time updates
*
* // used to update the UI
* function updateTime() {
* element.text(dateFilter(new Date(), format));
* }
*
* // watch the expression, and update the UI on change.
* scope.$watch(attrs.myCurrentTime, function(value) {
* format = value;
* updateTime();
* });
*
* stopTime = $interval(updateTime, 1000);
*
* // listen on DOM destroy (removal) event, and cancel the next UI update
* // to prevent updating time after the DOM element was removed.
* element.on('$destroy', function() {
* $interval.cancel(stopTime);
* });
* }
* }]);
* </script>
*
* <div>
* <div ng-controller="ExampleController">
* <label>Date format: <input ng-model="format"></label> <hr/>
* Current time is: <span my-current-time="format"></span>
* <hr/>
* Blood 1 : <font color='red'>{{blood_1}}</font>
* Blood 2 : <font color='red'>{{blood_2}}</font>
* <button type="button" data-ng-click="fight()">Fight</button>
* <button type="button" data-ng-click="stopFight()">StopFight</button>
* <button type="button" data-ng-click="resetFight()">resetFight</button>
* </div>
* </div>
*
* </file>
* </example>
*/
function interval(fn, delay, count, invokeApply) {
var hasParams = arguments.length > 4,
args = hasParams ? sliceArgs(arguments, 4) : [],
setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
iteration = 0,
skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise;
count = isDefined(count) ? count : 0;
promise.then(null, null, (!hasParams) ? fn : function() {
fn.apply(null, args);
});
promise.$$intervalId = setInterval(function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
intervals[promise.$$intervalId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $interval#cancel
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {Promise=} promise returned by the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully canceled.
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
intervals[promise.$$intervalId].reject('canceled');
$window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
return true;
}
return false;
};
return interval;
}];
}
/**
* @ngdoc service
* @name $locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function parseAbsoluteUrl(absoluteUrl, locationObj) {
var parsedUrl = urlResolve(absoluteUrl);
locationObj.$$protocol = parsedUrl.protocol;
locationObj.$$host = parsedUrl.hostname;
locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
function parseAppUrl(relativeUrl, locationObj) {
var prefixed = (relativeUrl.charAt(0) !== '/');
if (prefixed) {
relativeUrl = '/' + relativeUrl;
}
var match = urlResolve(relativeUrl);
locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
match.pathname.substring(1) : match.pathname);
locationObj.$$search = parseKeyValue(match.search);
locationObj.$$hash = decodeURIComponent(match.hash);
// make sure path starts with '/';
if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
locationObj.$$path = '/' + locationObj.$$path;
}
}
/**
*
* @param {string} begin
* @param {string} whole
* @returns {string} returns text from whole after begin or undefined if it does not begin with
* expected string.
*/
function beginsWith(begin, whole) {
if (whole.indexOf(begin) === 0) {
return whole.substr(begin.length);
}
}
function stripHash(url) {
var index = url.indexOf('#');
return index == -1 ? url : url.substr(0, index);
}
function trimEmptyHash(url) {
return url.replace(/(#.+)|#$/, '$1');
}
function stripFile(url) {
return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}
/* return the server only (scheme://host:port) */
function serverBase(url) {
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}
/**
* LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} basePrefix url path prefix
*/
function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
this.$$html5 = true;
basePrefix = basePrefix || '';
parseAbsoluteUrl(appBase, this);
/**
* Parse given html5 (regular) url string into properties
* @param {string} url HTML5 url
* @private
*/
this.$$parse = function(url) {
var pathUrl = beginsWith(appBaseNoFile, url);
if (!isString(pathUrl)) {
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
appBaseNoFile);
}
parseAppUrl(pathUrl, this);
if (!this.$$path) {
this.$$path = '/';
}
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var appUrl, prevAppUrl;
var rewrittenUrl;
if ((appUrl = beginsWith(appBase, url)) !== undefined) {
prevAppUrl = appUrl;
if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
rewrittenUrl = appBase + prevAppUrl;
}
} else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
rewrittenUrl = appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when developer doesn't opt into html5 mode.
* It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
parseAbsoluteUrl(appBase, this);
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
var withoutHashUrl;
if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
// The rest of the url starts with a hash so we have
// got either a hashbang path or a plain hash fragment
withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
if (isUndefined(withoutHashUrl)) {
// There was no hashbang prefix so we just have a hash fragment
withoutHashUrl = withoutBaseUrl;
}
} else {
// There was no hashbang path nor hash fragment:
// If we are in HTML5 mode we use what is left as the path;
// Otherwise we ignore what is left
if (this.$$html5) {
withoutHashUrl = withoutBaseUrl;
} else {
withoutHashUrl = '';
if (isUndefined(withoutBaseUrl)) {
appBase = url;
this.replace();
}
}
}
parseAppUrl(withoutHashUrl, this);
this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
this.$$compose();
/*
* In Windows, on an anchor node on documents loaded from
* the filesystem, the browser will return a pathname
* prefixed with the drive name ('/C:/path') when a
* pathname without a drive is set:
* * a.setAttribute('href', '/foo')
* * a.pathname === '/C:/foo' //true
*
* Inside of Angular, we're always using pathnames that
* do not include drive names for routing.
*/
function removeWindowsDriveName(path, url, base) {
/*
Matches paths for file protocol on windows,
such as /C:/foo/bar, and captures only /foo/bar.
*/
var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
var firstPathSegmentMatch;
//Get the relative path from the input URL.
if (url.indexOf(base) === 0) {
url = url.replace(base, '');
}
// The input URL intentionally contains a first path segment that ends with a colon.
if (windowsFilePathExp.exec(url)) {
return path;
}
firstPathSegmentMatch = windowsFilePathExp.exec(path);
return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
}
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
this.$$parseLinkUrl = function(url, relHref) {
if (stripHash(appBase) == stripHash(url)) {
this.$$parse(url);
return true;
}
return false;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is enabled but the browser
* does not support it.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} appBaseNoFile application base URL stripped of any filename
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
this.$$html5 = true;
LocationHashbangUrl.apply(this, arguments);
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var rewrittenUrl;
var appUrl;
if (appBase == stripHash(url)) {
rewrittenUrl = url;
} else if ((appUrl = beginsWith(appBaseNoFile, url))) {
rewrittenUrl = appBase + hashPrefix + appUrl;
} else if (appBaseNoFile === url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
// include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
this.$$absUrl = appBase + hashPrefix + this.$$url;
};
}
var locationPrototype = {
/**
* Are we in html5 mode?
* @private
*/
$$html5: false,
/**
* Has any change been replacing?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name $location#absUrl
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var absUrl = $location.absUrl();
* // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
* ```
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name $location#url
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var url = $location.url();
* // => "/some/path?foo=bar&baz=xoxo"
* ```
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url) {
if (isUndefined(url)) {
return this.$$url;
}
var match = PATH_MATCH.exec(url);
if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
if (match[2] || match[1] || url === '') this.search(match[3] || '');
this.hash(match[5] || '');
return this;
},
/**
* @ngdoc method
* @name $location#protocol
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var protocol = $location.protocol();
* // => "http"
* ```
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name $location#host
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var host = $location.host();
* // => "example.com"
*
* // given url http://user:[email protected]:8080/#/some/path?foo=bar&baz=xoxo
* host = $location.host();
* // => "example.com"
* host = location.host;
* // => "example.com:8080"
* ```
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name $location#port
*
* @description
* This method is getter only.
*
* Return port of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var port = $location.port();
* // => 80
* ```
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name $location#path
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var path = $location.path();
* // => "/some/path"
* ```
*
* @param {(string|number)=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
path = path !== null ? path.toString() : '';
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name $location#search
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var searchObject = $location.search();
* // => {foo: 'bar', baz: 'xoxo'}
*
* // set foo to 'yipee'
* $location.search('foo', 'yipee');
* // $location.search() => {foo: 'yipee', baz: 'xoxo'}
* ```
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
* hash object.
*
* When called with a single argument the method acts as a setter, setting the `search` component
* of `$location` to the specified value.
*
* If the argument is a hash object containing an array of values, these values will be encoded
* as duplicate search parameters in the url.
*
* @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
* will override only a single search property.
*
* If `paramValue` is an array, it will override the property of the `search` component of
* `$location` specified via the first argument.
*
* If `paramValue` is `null`, the property specified via the first argument will be deleted.
*
* If `paramValue` is `true`, the property specified via the first argument will be added with no
* value nor trailing equal sign.
*
* @return {Object} If called with no arguments returns the parsed `search` object. If called with
* one or more arguments returns `$location` object itself.
*/
search: function(search, paramValue) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (isString(search) || isNumber(search)) {
search = search.toString();
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
search = copy(search, {});
// remove object undefined or null properties
forEach(search, function(value, key) {
if (value == null) delete search[key];
});
this.$$search = search;
} else {
throw $locationMinErr('isrcharg',
'The first argument of the `$location#search()` call must be a string or an object.');
}
break;
default:
if (isUndefined(paramValue) || paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name $location#hash
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
* var hash = $location.hash();
* // => "hashValue"
* ```
*
* @param {(string|number)=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', function(hash) {
return hash !== null ? hash.toString() : '';
}),
/**
* @ngdoc method
* @name $location#replace
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
Location.prototype = Object.create(locationPrototype);
/**
* @ngdoc method
* @name $location#state
*
* @description
* This method is getter / setter.
*
* Return the history state object when called without any parameter.
*
* Change the history state object when called with one parameter and return `$location`.
* The state object is later passed to `pushState` or `replaceState`.
*
* NOTE: This method is supported only in HTML5 mode and only in browsers supporting
* the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
* older browsers (like IE9 or Android < 4.0), don't use this method.
*
* @param {object=} state State object for pushState or replaceState
* @return {object} state
*/
Location.prototype.state = function(state) {
if (!arguments.length) {
return this.$$state;
}
if (Location !== LocationHtml5Url || !this.$$html5) {
throw $locationMinErr('nostate', 'History API state support is available only ' +
'in HTML5 mode and only in browsers supporting HTML5 History API');
}
// The user might modify `stateObject` after invoking `$location.state(stateObject)`
// but we're changing the $$state reference to $browser.state() during the $digest
// so the modification window is narrow.
this.$$state = isUndefined(state) ? null : state;
return this;
};
});
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value)) {
return this[property];
}
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc service
* @name $location
*
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/$location Developer Guide: Using $location}
*/
/**
* @ngdoc provider
* @name $locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider() {
var hashPrefix = '',
html5Mode = {
enabled: false,
requireBase: true,
rewriteLinks: true
};
/**
* @ngdoc method
* @name $locationProvider#hashPrefix
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc method
* @name $locationProvider#html5Mode
* @description
* @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
* If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
* properties:
* - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
* change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
* support `pushState`.
* - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
* whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
* true, and a base tag is not present, an error will be thrown when `$location` is injected.
* See the {@link guide/$location $location guide for more information}
* - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
* enables/disables url rewriting for relative links.
*
* @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isBoolean(mode)) {
html5Mode.enabled = mode;
return this;
} else if (isObject(mode)) {
if (isBoolean(mode.enabled)) {
html5Mode.enabled = mode.enabled;
}
if (isBoolean(mode.requireBase)) {
html5Mode.requireBase = mode.requireBase;
}
if (isBoolean(mode.rewriteLinks)) {
html5Mode.rewriteLinks = mode.rewriteLinks;
}
return this;
} else {
return html5Mode;
}
};
/**
* @ngdoc event
* @name $location#$locationChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a URL will change.
*
* This change can be prevented by calling
* `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
* details about event object. Upon successful change
* {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
/**
* @ngdoc event
* @name $location#$locationChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a URL was changed.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
function($rootScope, $browser, $sniffer, $rootElement, $window) {
var $location,
LocationMode,
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
initialUrl = $browser.url(),
appBase;
if (html5Mode.enabled) {
if (!baseHref && html5Mode.requireBase) {
throw $locationMinErr('nobase',
"$location in HTML5 mode requires a <base> tag to be present!");
}
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
var appBaseNoFile = stripFile(appBase);
$location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
$location.$$parseLinkUrl(initialUrl, initialUrl);
$location.$$state = $browser.state();
var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
function setBrowserUrlWithFallback(url, replace, state) {
var oldUrl = $location.url();
var oldState = $location.$$state;
try {
$browser.url(url, replace, state);
// Make sure $location.state() returns referentially identical (not just deeply equal)
// state object; this makes possible quick checking if the state changed in the digest
// loop. Checking deep equality would be too expensive.
$location.$$state = $browser.state();
} catch (e) {
// Restore old values if pushState fails
$location.url(oldUrl);
$location.$$state = oldState;
throw e;
}
}
$rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (nodeName_(elm[0]) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href');
// get the actual href attribute - see
// http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
var relHref = elm.attr('href') || elm.attr('xlink:href');
if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
// SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
// an animation.
absHref = urlResolve(absHref.animVal).href;
}
// Ignore when url is started with javascript: or mailto:
if (IGNORE_URI_REGEXP.test(absHref)) return;
if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
if ($location.$$parseLinkUrl(absHref, relHref)) {
// We do a preventDefault for all urls that are part of the angular application,
// in html5mode and also without, so that we are able to abort navigation without
// getting double entries in the location history.
event.preventDefault();
// update location manually
if ($location.absUrl() != $browser.url()) {
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
$window.angular['ff-684208-preventDefault'] = true;
}
}
}
});
// rewrite hashbang url <> html5 url
if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
$browser.url($location.absUrl(), true);
}
var initializing = true;
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl, newState) {
if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
// If we are navigating outside of the app then force a reload
$window.location.href = newUrl;
return;
}
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
var oldState = $location.$$state;
var defaultPrevented;
$location.$$parse(newUrl);
$location.$$state = newState;
defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
newState, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
setBrowserUrlWithFallback(oldUrl, false, oldState);
} else {
initializing = false;
afterLocationChange(oldUrl, oldState);
}
});
if (!$rootScope.$$phase) $rootScope.$digest();
});
// update browser
$rootScope.$watch(function $locationWatch() {
var oldUrl = trimEmptyHash($browser.url());
var newUrl = trimEmptyHash($location.absUrl());
var oldState = $browser.state();
var currentReplace = $location.$$replace;
var urlOrStateChanged = oldUrl !== newUrl ||
($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
if (initializing || urlOrStateChanged) {
initializing = false;
$rootScope.$evalAsync(function() {
var newUrl = $location.absUrl();
var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
$location.$$state, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
} else {
if (urlOrStateChanged) {
setBrowserUrlWithFallback(newUrl, currentReplace,
oldState === $location.$$state ? null : $location.$$state);
}
afterLocationChange(oldUrl, oldState);
}
});
}
$location.$$replace = false;
// we don't need to return anything because $evalAsync will make the digest loop dirty when
// there is a change
});
return $location;
function afterLocationChange(oldUrl, oldState) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
$location.$$state, oldState);
}
}];
}
/**
* @ngdoc service
* @name $log
* @requires $window
*
* @description
* Simple service for logging. Default implementation safely writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* The default is to log `debug` messages. You can use
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
*
* @example
<example module="logExample">
<file name="script.js">
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}]);
</file>
<file name="index.html">
<div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
<label>Message:
<input type="text" ng-model="message" /></label>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
<button ng-click="$log.debug(message)">debug</button>
</div>
</file>
</example>
*/
/**
* @ngdoc provider
* @name $logProvider
* @description
* Use the `$logProvider` to configure how the application logs messages
*/
function $LogProvider() {
var debug = true,
self = this;
/**
* @ngdoc method
* @name $logProvider#debugEnabled
* @description
* @param {boolean=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
if (isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = ['$window', function($window) {
return {
/**
* @ngdoc method
* @name $log#log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name $log#info
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name $log#warn
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name $log#error
*
* @description
* Write an error message
*/
error: consoleLog('error'),
/**
* @ngdoc method
* @name $log#debug
*
* @description
* Write a debug message
*/
debug: (function() {
var fn = consoleLog('debug');
return function() {
if (debug) {
fn.apply(self, arguments);
}
};
}())
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2 == null ? '' : arg2);
};
}
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security
function ensureSafeMemberName(name, fullExpression) {
if (name === "__defineGetter__" || name === "__defineSetter__"
|| name === "__lookupGetter__" || name === "__lookupSetter__"
|| name === "__proto__") {
throw $parseMinErr('isecfld',
'Attempting to access a disallowed field in Angular expressions! '
+ 'Expression: {0}', fullExpression);
}
return name;
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj.window === obj) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// block Object so that we can't get hold of dangerous Object.* methods
obj === Object) {
throw $parseMinErr('isecobj',
'Referencing Object in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
return obj;
}
var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;
function ensureSafeFunction(obj, fullExpression) {
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (obj === CALL || obj === APPLY || obj === BIND) {
throw $parseMinErr('isecff',
'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
}
var OPERATORS = createMap();
forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function(options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function(text) {
this.text = text;
this.index = 0;
this.tokens = [];
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (ch === '"' || ch === "'") {
this.readString(ch);
} else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdent(ch)) {
this.readIdent();
} else if (this.is(ch, '(){}[].,;:?')) {
this.tokens.push({index: this.index, text: ch});
this.index++;
} else if (this.isWhitespace(ch)) {
this.index++;
} else {
var ch2 = ch + this.peek();
var ch3 = ch2 + this.peek(2);
var op1 = OPERATORS[ch];
var op2 = OPERATORS[ch2];
var op3 = OPERATORS[ch3];
if (op1 || op2 || op3) {
var token = op3 ? ch3 : (op2 ? ch2 : ch);
this.tokens.push({index: this.index, text: token, operator: true});
this.index += token.length;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
}
return this.tokens;
},
is: function(ch, chars) {
return chars.indexOf(ch) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9') && typeof ch === "string";
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdent: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
this.tokens.push({
index: start,
text: number,
constant: true,
value: Number(number)
});
},
readIdent: function() {
var start = this.index;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (!(this.isIdent(ch) || this.isNumber(ch))) {
break;
}
this.index++;
}
this.tokens.push({
index: start,
text: this.text.slice(start, this.index),
identifier: true
});
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i)) {
this.throwError('Invalid unicode escape [\\u' + hex + ']');
}
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
constant: true,
value: string
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
var AST = function(lexer, options) {
this.lexer = lexer;
this.options = options;
};
AST.Program = 'Program';
AST.ExpressionStatement = 'ExpressionStatement';
AST.AssignmentExpression = 'AssignmentExpression';
AST.ConditionalExpression = 'ConditionalExpression';
AST.LogicalExpression = 'LogicalExpression';
AST.BinaryExpression = 'BinaryExpression';
AST.UnaryExpression = 'UnaryExpression';
AST.CallExpression = 'CallExpression';
AST.MemberExpression = 'MemberExpression';
AST.Identifier = 'Identifier';
AST.Literal = 'Literal';
AST.ArrayExpression = 'ArrayExpression';
AST.Property = 'Property';
AST.ObjectExpression = 'ObjectExpression';
AST.ThisExpression = 'ThisExpression';
// Internal use only
AST.NGValueParameter = 'NGValueParameter';
AST.prototype = {
ast: function(text) {
this.text = text;
this.tokens = this.lexer.lex(text);
var value = this.program();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
return value;
},
program: function() {
var body = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
body.push(this.expressionStatement());
if (!this.expect(';')) {
return { type: AST.Program, body: body};
}
}
},
expressionStatement: function() {
return { type: AST.ExpressionStatement, expression: this.filterChain() };
},
filterChain: function() {
var left = this.expression();
var token;
while ((token = this.expect('|'))) {
left = this.filter(left);
}
return left;
},
expression: function() {
return this.assignment();
},
assignment: function() {
var result = this.ternary();
if (this.expect('=')) {
result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
}
return result;
},
ternary: function() {
var test = this.logicalOR();
var alternate;
var consequent;
if (this.expect('?')) {
alternate = this.expression();
if (this.consume(':')) {
consequent = this.expression();
return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
}
}
return test;
},
logicalOR: function() {
var left = this.logicalAND();
while (this.expect('||')) {
left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
}
return left;
},
logicalAND: function() {
var left = this.equality();
while (this.expect('&&')) {
left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
}
return left;
},
equality: function() {
var left = this.relational();
var token;
while ((token = this.expect('==','!=','===','!=='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
}
return left;
},
relational: function() {
var left = this.additive();
var token;
while ((token = this.expect('<', '>', '<=', '>='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
}
return left;
},
unary: function() {
var token;
if ((token = this.expect('+', '-', '!'))) {
return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
} else {
return this.primary();
}
},
primary: function() {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else if (this.constants.hasOwnProperty(this.peek().text)) {
primary = copy(this.constants[this.consume().text]);
} else if (this.peek().identifier) {
primary = this.identifier();
} else if (this.peek().constant) {
primary = this.constant();
} else {
this.throwError('not a primary expression', this.peek());
}
var next;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
this.consume(')');
} else if (next.text === '[') {
primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
this.consume(']');
} else if (next.text === '.') {
primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
filter: function(baseExpression) {
var args = [baseExpression];
var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
while (this.expect(':')) {
args.push(this.expression());
}
return result;
},
parseArguments: function() {
var args = [];
if (this.peekToken().text !== ')') {
do {
args.push(this.expression());
} while (this.expect(','));
}
return args;
},
identifier: function() {
var token = this.consume();
if (!token.identifier) {
this.throwError('is not a valid identifier', token);
}
return { type: AST.Identifier, name: token.text };
},
constant: function() {
// TODO check that it is a constant
return { type: AST.Literal, value: this.consume().value };
},
arrayDeclaration: function() {
var elements = [];
if (this.peekToken().text !== ']') {
do {
if (this.peek(']')) {
// Support trailing commas per ES5.1.
break;
}
elements.push(this.expression());
} while (this.expect(','));
}
this.consume(']');
return { type: AST.ArrayExpression, elements: elements };
},
object: function() {
var properties = [], property;
if (this.peekToken().text !== '}') {
do {
if (this.peek('}')) {
// Support trailing commas per ES5.1.
break;
}
property = {type: AST.Property, kind: 'init'};
if (this.peek().constant) {
property.key = this.constant();
} else if (this.peek().identifier) {
property.key = this.identifier();
} else {
this.throwError("invalid key", this.peek());
}
this.consume(':');
property.value = this.expression();
properties.push(property);
} while (this.expect(','));
}
this.consume('}');
return {type: AST.ObjectExpression, properties: properties };
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
consume: function(e1) {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
var token = this.expect(e1);
if (!token) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
return token;
},
peekToken: function() {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
return this.peekAhead(0, e1, e2, e3, e4);
},
peekAhead: function(i, e1, e2, e3, e4) {
if (this.tokens.length > i) {
var token = this.tokens[i];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4) {
var token = this.peek(e1, e2, e3, e4);
if (token) {
this.tokens.shift();
return token;
}
return false;
},
/* `undefined` is not a constant, it is an identifier,
* but using it as an identifier is not supported
*/
constants: {
'true': { type: AST.Literal, value: true },
'false': { type: AST.Literal, value: false },
'null': { type: AST.Literal, value: null },
'undefined': {type: AST.Literal, value: undefined },
'this': {type: AST.ThisExpression }
}
};
function ifDefined(v, d) {
return typeof v !== 'undefined' ? v : d;
}
function plusFn(l, r) {
if (typeof l === 'undefined') return r;
if (typeof r === 'undefined') return l;
return l + r;
}
function isStateless($filter, filterName) {
var fn = $filter(filterName);
return !fn.$stateful;
}
function findConstantAndWatchExpressions(ast, $filter) {
var allConstants;
var argsToWatch;
switch (ast.type) {
case AST.Program:
allConstants = true;
forEach(ast.body, function(expr) {
findConstantAndWatchExpressions(expr.expression, $filter);
allConstants = allConstants && expr.expression.constant;
});
ast.constant = allConstants;
break;
case AST.Literal:
ast.constant = true;
ast.toWatch = [];
break;
case AST.UnaryExpression:
findConstantAndWatchExpressions(ast.argument, $filter);
ast.constant = ast.argument.constant;
ast.toWatch = ast.argument.toWatch;
break;
case AST.BinaryExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
break;
case AST.LogicalExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.ConditionalExpression:
findConstantAndWatchExpressions(ast.test, $filter);
findConstantAndWatchExpressions(ast.alternate, $filter);
findConstantAndWatchExpressions(ast.consequent, $filter);
ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.Identifier:
ast.constant = false;
ast.toWatch = [ast];
break;
case AST.MemberExpression:
findConstantAndWatchExpressions(ast.object, $filter);
if (ast.computed) {
findConstantAndWatchExpressions(ast.property, $filter);
}
ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
ast.toWatch = [ast];
break;
case AST.CallExpression:
allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
argsToWatch = [];
forEach(ast.arguments, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
break;
case AST.AssignmentExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = [ast];
break;
case AST.ArrayExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.elements, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ObjectExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.properties, function(property) {
findConstantAndWatchExpressions(property.value, $filter);
allConstants = allConstants && property.value.constant;
if (!property.value.constant) {
argsToWatch.push.apply(argsToWatch, property.value.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ThisExpression:
ast.constant = false;
ast.toWatch = [];
break;
}
}
function getInputs(body) {
if (body.length != 1) return;
var lastExpression = body[0].expression;
var candidate = lastExpression.toWatch;
if (candidate.length !== 1) return candidate;
return candidate[0] !== lastExpression ? candidate : undefined;
}
function isAssignable(ast) {
return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
}
function assignableAST(ast) {
if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
}
}
function isLiteral(ast) {
return ast.body.length === 0 ||
ast.body.length === 1 && (
ast.body[0].expression.type === AST.Literal ||
ast.body[0].expression.type === AST.ArrayExpression ||
ast.body[0].expression.type === AST.ObjectExpression);
}
function isConstant(ast) {
return ast.constant;
}
function ASTCompiler(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTCompiler.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.state = {
nextId: 0,
filters: {},
expensiveChecks: expensiveChecks,
fn: {vars: [], body: [], own: {}},
assign: {vars: [], body: [], own: {}},
inputs: []
};
findConstantAndWatchExpressions(ast, self.$filter);
var extra = '';
var assignable;
this.stage = 'assign';
if ((assignable = assignableAST(ast))) {
this.state.computing = 'assign';
var result = this.nextId();
this.recurse(assignable, result);
extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
}
var toWatch = getInputs(ast.body);
self.stage = 'inputs';
forEach(toWatch, function(watch, key) {
var fnKey = 'fn' + key;
self.state[fnKey] = {vars: [], body: [], own: {}};
self.state.computing = fnKey;
var intoId = self.nextId();
self.recurse(watch, intoId);
self.return_(intoId);
self.state.inputs.push(fnKey);
watch.watchId = key;
});
this.state.computing = 'fn';
this.stage = 'main';
this.recurse(ast);
var fnString =
// The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
// This is a workaround for this until we do a better job at only removing the prefix only when we should.
'"' + this.USE + ' ' + this.STRICT + '";\n' +
this.filterPrefix() +
'var fn=' + this.generateFunction('fn', 's,l,a,i') +
extra +
this.watchFns() +
'return fn;';
/* jshint -W054 */
var fn = (new Function('$filter',
'ensureSafeMemberName',
'ensureSafeObject',
'ensureSafeFunction',
'ifDefined',
'plus',
'text',
fnString))(
this.$filter,
ensureSafeMemberName,
ensureSafeObject,
ensureSafeFunction,
ifDefined,
plusFn,
expression);
/* jshint +W054 */
this.state = this.stage = undefined;
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
USE: 'use',
STRICT: 'strict',
watchFns: function() {
var result = [];
var fns = this.state.inputs;
var self = this;
forEach(fns, function(name) {
result.push('var ' + name + '=' + self.generateFunction(name, 's'));
});
if (fns.length) {
result.push('fn.inputs=[' + fns.join(',') + '];');
}
return result.join('');
},
generateFunction: function(name, params) {
return 'function(' + params + '){' +
this.varsPrefix(name) +
this.body(name) +
'};';
},
filterPrefix: function() {
var parts = [];
var self = this;
forEach(this.state.filters, function(id, filter) {
parts.push(id + '=$filter(' + self.escape(filter) + ')');
});
if (parts.length) return 'var ' + parts.join(',') + ';';
return '';
},
varsPrefix: function(section) {
return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
},
body: function(section) {
return this.state[section].body.join('');
},
recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var left, right, self = this, args, expression;
recursionFn = recursionFn || noop;
if (!skipWatchIdCheck && isDefined(ast.watchId)) {
intoId = intoId || this.nextId();
this.if_('i',
this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
);
return;
}
switch (ast.type) {
case AST.Program:
forEach(ast.body, function(expression, pos) {
self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
if (pos !== ast.body.length - 1) {
self.current().body.push(right, ';');
} else {
self.return_(right);
}
});
break;
case AST.Literal:
expression = this.escape(ast.value);
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.UnaryExpression:
this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.BinaryExpression:
this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
if (ast.operator === '+') {
expression = this.plus(left, right);
} else if (ast.operator === '-') {
expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
} else {
expression = '(' + left + ')' + ast.operator + '(' + right + ')';
}
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.LogicalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.left, intoId);
self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
recursionFn(intoId);
break;
case AST.ConditionalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.test, intoId);
self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
recursionFn(intoId);
break;
case AST.Identifier:
intoId = intoId || this.nextId();
if (nameId) {
nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
nameId.computed = false;
nameId.name = ast.name;
}
ensureSafeMemberName(ast.name);
self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
function() {
self.if_(self.stage === 'inputs' || 's', function() {
if (create && create !== 1) {
self.if_(
self.not(self.nonComputedMember('s', ast.name)),
self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
}
self.assign(intoId, self.nonComputedMember('s', ast.name));
});
}, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
self.addEnsureSafeObject(intoId);
}
recursionFn(intoId);
break;
case AST.MemberExpression:
left = nameId && (nameId.context = this.nextId()) || this.nextId();
intoId = intoId || this.nextId();
self.recurse(ast.object, left, undefined, function() {
self.if_(self.notNull(left), function() {
if (ast.computed) {
right = self.nextId();
self.recurse(ast.property, right);
self.addEnsureSafeMemberName(right);
if (create && create !== 1) {
self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
}
expression = self.ensureSafeObject(self.computedMember(left, right));
self.assign(intoId, expression);
if (nameId) {
nameId.computed = true;
nameId.name = right;
}
} else {
ensureSafeMemberName(ast.property.name);
if (create && create !== 1) {
self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
}
expression = self.nonComputedMember(left, ast.property.name);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
expression = self.ensureSafeObject(expression);
}
self.assign(intoId, expression);
if (nameId) {
nameId.computed = false;
nameId.name = ast.property.name;
}
}
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
}, !!create);
break;
case AST.CallExpression:
intoId = intoId || this.nextId();
if (ast.filter) {
right = self.filter(ast.callee.name);
args = [];
forEach(ast.arguments, function(expr) {
var argument = self.nextId();
self.recurse(expr, argument);
args.push(argument);
});
expression = right + '(' + args.join(',') + ')';
self.assign(intoId, expression);
recursionFn(intoId);
} else {
right = self.nextId();
left = {};
args = [];
self.recurse(ast.callee, right, left, function() {
self.if_(self.notNull(right), function() {
self.addEnsureSafeFunction(right);
forEach(ast.arguments, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(self.ensureSafeObject(argument));
});
});
if (left.name) {
if (!self.state.expensiveChecks) {
self.addEnsureSafeObject(left.context);
}
expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
} else {
expression = right + '(' + args.join(',') + ')';
}
expression = self.ensureSafeObject(expression);
self.assign(intoId, expression);
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
});
}
break;
case AST.AssignmentExpression:
right = this.nextId();
left = {};
if (!isAssignable(ast.left)) {
throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
}
this.recurse(ast.left, undefined, left, function() {
self.if_(self.notNull(left.context), function() {
self.recurse(ast.right, right);
self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
self.assign(intoId, expression);
recursionFn(intoId || expression);
});
}, 1);
break;
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(argument);
});
});
expression = '[' + args.join(',') + ']';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
self.recurse(property.value, self.nextId(), undefined, function(expr) {
args.push(self.escape(
property.key.type === AST.Identifier ? property.key.name :
('' + property.key.value)) +
':' + expr);
});
});
expression = '{' + args.join(',') + '}';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ThisExpression:
this.assign(intoId, 's');
recursionFn('s');
break;
case AST.NGValueParameter:
this.assign(intoId, 'v');
recursionFn('v');
break;
}
},
getHasOwnProperty: function(element, property) {
var key = element + '.' + property;
var own = this.current().own;
if (!own.hasOwnProperty(key)) {
own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
}
return own[key];
},
assign: function(id, value) {
if (!id) return;
this.current().body.push(id, '=', value, ';');
return id;
},
filter: function(filterName) {
if (!this.state.filters.hasOwnProperty(filterName)) {
this.state.filters[filterName] = this.nextId(true);
}
return this.state.filters[filterName];
},
ifDefined: function(id, defaultValue) {
return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
},
plus: function(left, right) {
return 'plus(' + left + ',' + right + ')';
},
return_: function(id) {
this.current().body.push('return ', id, ';');
},
if_: function(test, alternate, consequent) {
if (test === true) {
alternate();
} else {
var body = this.current().body;
body.push('if(', test, '){');
alternate();
body.push('}');
if (consequent) {
body.push('else{');
consequent();
body.push('}');
}
}
},
not: function(expression) {
return '!(' + expression + ')';
},
notNull: function(expression) {
return expression + '!=null';
},
nonComputedMember: function(left, right) {
return left + '.' + right;
},
computedMember: function(left, right) {
return left + '[' + right + ']';
},
member: function(left, right, computed) {
if (computed) return this.computedMember(left, right);
return this.nonComputedMember(left, right);
},
addEnsureSafeObject: function(item) {
this.current().body.push(this.ensureSafeObject(item), ';');
},
addEnsureSafeMemberName: function(item) {
this.current().body.push(this.ensureSafeMemberName(item), ';');
},
addEnsureSafeFunction: function(item) {
this.current().body.push(this.ensureSafeFunction(item), ';');
},
ensureSafeObject: function(item) {
return 'ensureSafeObject(' + item + ',text)';
},
ensureSafeMemberName: function(item) {
return 'ensureSafeMemberName(' + item + ',text)';
},
ensureSafeFunction: function(item) {
return 'ensureSafeFunction(' + item + ',text)';
},
lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var self = this;
return function() {
self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
};
},
lazyAssign: function(id, value) {
var self = this;
return function() {
self.assign(id, value);
};
},
stringEscapeRegex: /[^ a-zA-Z0-9]/g,
stringEscapeFn: function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
},
escape: function(value) {
if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
if (isNumber(value)) return value.toString();
if (value === true) return 'true';
if (value === false) return 'false';
if (value === null) return 'null';
if (typeof value === 'undefined') return 'undefined';
throw $parseMinErr('esc', 'IMPOSSIBLE');
},
nextId: function(skip, init) {
var id = 'v' + (this.state.nextId++);
if (!skip) {
this.current().vars.push(id + (init ? '=' + init : ''));
}
return id;
},
current: function() {
return this.state[this.state.computing];
}
};
function ASTInterpreter(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTInterpreter.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.expression = expression;
this.expensiveChecks = expensiveChecks;
findConstantAndWatchExpressions(ast, self.$filter);
var assignable;
var assign;
if ((assignable = assignableAST(ast))) {
assign = this.recurse(assignable);
}
var toWatch = getInputs(ast.body);
var inputs;
if (toWatch) {
inputs = [];
forEach(toWatch, function(watch, key) {
var input = self.recurse(watch);
watch.input = input;
inputs.push(input);
watch.watchId = key;
});
}
var expressions = [];
forEach(ast.body, function(expression) {
expressions.push(self.recurse(expression.expression));
});
var fn = ast.body.length === 0 ? function() {} :
ast.body.length === 1 ? expressions[0] :
function(scope, locals) {
var lastValue;
forEach(expressions, function(exp) {
lastValue = exp(scope, locals);
});
return lastValue;
};
if (assign) {
fn.assign = function(scope, value, locals) {
return assign(scope, locals, value);
};
}
if (inputs) {
fn.inputs = inputs;
}
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
recurse: function(ast, context, create) {
var left, right, self = this, args, expression;
if (ast.input) {
return this.inputs(ast.input, ast.watchId);
}
switch (ast.type) {
case AST.Literal:
return this.value(ast.value, context);
case AST.UnaryExpression:
right = this.recurse(ast.argument);
return this['unary' + ast.operator](right, context);
case AST.BinaryExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.LogicalExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.ConditionalExpression:
return this['ternary?:'](
this.recurse(ast.test),
this.recurse(ast.alternate),
this.recurse(ast.consequent),
context
);
case AST.Identifier:
ensureSafeMemberName(ast.name, self.expression);
return self.identifier(ast.name,
self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
context, create, self.expression);
case AST.MemberExpression:
left = this.recurse(ast.object, false, !!create);
if (!ast.computed) {
ensureSafeMemberName(ast.property.name, self.expression);
right = ast.property.name;
}
if (ast.computed) right = this.recurse(ast.property);
return ast.computed ?
this.computedMember(left, right, context, create, self.expression) :
this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
case AST.CallExpression:
args = [];
forEach(ast.arguments, function(expr) {
args.push(self.recurse(expr));
});
if (ast.filter) right = this.$filter(ast.callee.name);
if (!ast.filter) right = this.recurse(ast.callee, true);
return ast.filter ?
function(scope, locals, assign, inputs) {
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(args[i](scope, locals, assign, inputs));
}
var value = right.apply(undefined, values, inputs);
return context ? {context: undefined, name: undefined, value: value} : value;
} :
function(scope, locals, assign, inputs) {
var rhs = right(scope, locals, assign, inputs);
var value;
if (rhs.value != null) {
ensureSafeObject(rhs.context, self.expression);
ensureSafeFunction(rhs.value, self.expression);
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
}
value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
}
return context ? {value: value} : value;
};
case AST.AssignmentExpression:
left = this.recurse(ast.left, true, 1);
right = this.recurse(ast.right);
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
ensureSafeObject(lhs.value, self.expression);
lhs.context[lhs.name] = rhs;
return context ? {value: rhs} : rhs;
};
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
args.push(self.recurse(expr));
});
return function(scope, locals, assign, inputs) {
var value = [];
for (var i = 0; i < args.length; ++i) {
value.push(args[i](scope, locals, assign, inputs));
}
return context ? {value: value} : value;
};
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
args.push({key: property.key.type === AST.Identifier ?
property.key.name :
('' + property.key.value),
value: self.recurse(property.value)
});
});
return function(scope, locals, assign, inputs) {
var value = {};
for (var i = 0; i < args.length; ++i) {
value[args[i].key] = args[i].value(scope, locals, assign, inputs);
}
return context ? {value: value} : value;
};
case AST.ThisExpression:
return function(scope) {
return context ? {value: scope} : scope;
};
case AST.NGValueParameter:
return function(scope, locals, assign, inputs) {
return context ? {value: assign} : assign;
};
}
},
'unary+': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = +arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary-': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = -arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary!': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = !argument(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary+': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = plusFn(lhs, rhs);
return context ? {value: arg} : arg;
};
},
'binary-': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
return context ? {value: arg} : arg;
};
},
'binary*': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary/': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary%': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary===': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary&&': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary||': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'ternary?:': function(test, alternate, consequent, context) {
return function(scope, locals, assign, inputs) {
var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
value: function(value, context) {
return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
},
identifier: function(name, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var base = locals && (name in locals) ? locals : scope;
if (create && create !== 1 && base && !(base[name])) {
base[name] = {};
}
var value = base ? base[name] : undefined;
if (expensiveChecks) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: base, name: name, value: value};
} else {
return value;
}
};
},
computedMember: function(left, right, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs;
var value;
if (lhs != null) {
rhs = right(scope, locals, assign, inputs);
ensureSafeMemberName(rhs, expression);
if (create && create !== 1 && lhs && !(lhs[rhs])) {
lhs[rhs] = {};
}
value = lhs[rhs];
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: rhs, value: value};
} else {
return value;
}
};
},
nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
if (create && create !== 1 && lhs && !(lhs[right])) {
lhs[right] = {};
}
var value = lhs != null ? lhs[right] : undefined;
if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: right, value: value};
} else {
return value;
}
};
},
inputs: function(input, watchId) {
return function(scope, value, locals, inputs) {
if (inputs) return inputs[watchId];
return input(scope, value, locals);
};
}
};
/**
* @constructor
*/
var Parser = function(lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
this.ast = new AST(this.lexer);
this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
new ASTCompiler(this.ast, $filter);
};
Parser.prototype = {
constructor: Parser,
parse: function(text) {
return this.astCompiler.compile(text, this.options.expensiveChecks);
}
};
var getterFnCacheDefault = createMap();
var getterFnCacheExpensive = createMap();
function isPossiblyDangerousMemberName(name) {
return name == 'constructor';
}
var objectValueOf = Object.prototype.valueOf;
function getValueOf(value) {
return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}
///////////////////////////////////
/**
* @ngdoc service
* @name $parse
* @kind function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* ```js
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* ```
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc provider
* @name $parseProvider
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cacheDefault = createMap();
var cacheExpensive = createMap();
this.$get = ['$filter', function($filter) {
var noUnsafeEval = csp().noUnsafeEval;
var $parseOptions = {
csp: noUnsafeEval,
expensiveChecks: false
},
$parseOptionsExpensive = {
csp: noUnsafeEval,
expensiveChecks: true
};
return function $parse(exp, interceptorFn, expensiveChecks) {
var parsedExpression, oneTime, cacheKey;
switch (typeof exp) {
case 'string':
exp = exp.trim();
cacheKey = exp;
var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
parsedExpression = cache[cacheKey];
if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
}
var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
var lexer = new Lexer(parseOptions);
var parser = new Parser(lexer, $filter, parseOptions);
parsedExpression = parser.parse(exp);
if (parsedExpression.constant) {
parsedExpression.$$watchDelegate = constantWatchDelegate;
} else if (oneTime) {
parsedExpression.$$watchDelegate = parsedExpression.literal ?
oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
} else if (parsedExpression.inputs) {
parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
case 'function':
return addInterceptor(exp, interceptorFn);
default:
return noop;
}
};
function expressionInputDirtyCheck(newValue, oldValueOfValue) {
if (newValue == null || oldValueOfValue == null) { // null/undefined
return newValue === oldValueOfValue;
}
if (typeof newValue === 'object') {
// attempt to convert the value to a primitive type
// TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
// be cheaply dirty-checked
newValue = getValueOf(newValue);
if (typeof newValue === 'object') {
// objects/arrays are not supported - deep-watching them would be too expensive
return false;
}
// fall-through to the primitive equality check
}
//Primitive or NaN
return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
}
function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
var inputExpressions = parsedExpression.inputs;
var lastResult;
if (inputExpressions.length === 1) {
var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
inputExpressions = inputExpressions[0];
return scope.$watch(function expressionInputWatch(scope) {
var newInputValue = inputExpressions(scope);
if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
oldInputValueOf = newInputValue && getValueOf(newInputValue);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
var oldInputValueOfValues = [];
var oldInputValues = [];
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
oldInputValues[i] = null;
}
return scope.$watch(function expressionInputsWatch(scope) {
var changed = false;
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
var newInputValue = inputExpressions[i](scope);
if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
oldInputValues[i] = newInputValue;
oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
}
}
if (changed) {
lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.apply(this, arguments);
}
if (isDefined(value)) {
scope.$$postDigest(function() {
if (isDefined(lastValue)) {
unwatch();
}
});
}
}, objectEquality);
}
function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.call(this, value, old, scope);
}
if (isAllDefined(value)) {
scope.$$postDigest(function() {
if (isAllDefined(lastValue)) unwatch();
});
}
}, objectEquality);
function isAllDefined(value) {
var allDefined = true;
forEach(value, function(val) {
if (!isDefined(val)) allDefined = false;
});
return allDefined;
}
}
function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
return parsedExpression(scope);
}, function constantListener(value, old, scope) {
if (isFunction(listener)) {
listener.apply(this, arguments);
}
unwatch();
}, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
if (!interceptorFn) return parsedExpression;
var watchDelegate = parsedExpression.$$watchDelegate;
var regularWatch =
watchDelegate !== oneTimeLiteralWatchDelegate &&
watchDelegate !== oneTimeWatchDelegate;
var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
return interceptorFn(value, scope, locals);
} : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
var result = interceptorFn(value, scope, locals);
// we only return the interceptor's result if the
// initial value is defined (for bind-once)
return isDefined(value) ? result : value;
};
// Propagate $$watchDelegates other then inputsWatchDelegate
if (parsedExpression.$$watchDelegate &&
parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
} else if (!interceptorFn.$stateful) {
// If there is an interceptor, but no watchDelegate then treat the interceptor like
// we treat filters - it is assumed to be a pure function unless flagged with $stateful
fn.$$watchDelegate = inputsWatchDelegate;
fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
}
return fn;
}
}];
}
/**
* @ngdoc service
* @name $q
* @requires $rootScope
*
* @description
* A service that helps you run functions asynchronously, and use their return values (or exceptions)
* when they are done processing.
*
* This is an implementation of promises/deferred objects inspired by
* [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
* implementations, and the other which resembles ES6 promises to some degree.
*
* # $q constructor
*
* The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
* function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
* see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
*
* While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
* available yet.
*
* It can be used like so:
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* // perform some asynchronous operation, resolve or reject the promise when appropriate.
* return $q(function(resolve, reject) {
* setTimeout(function() {
* if (okToGreet(name)) {
* resolve('Hello, ' + name + '!');
* } else {
* reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
* });
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* ```
*
* Note: progress/notify callbacks are not currently supported via the ES6-style interface.
*
* However, the more traditional CommonJS-style usage is still available, and documented below.
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* deferred.notify('About to greet ' + name + '.');
*
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* }, function(update) {
* alert('Got notification: ' + update);
* });
* ```
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of guarantees that promise and deferred APIs make, see
* https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion, as well as the status
* of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
* - `notify(value)` - provides updates on the status of the promise's execution. This may be called
* multiple times before the promise is either resolved or rejected.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
* will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
* as soon as the result is available. The callbacks are called with a single argument: the result
* or rejection reason. Additionally, the notify callback may be called zero or more times to
* provide a progress indication, before the promise is resolved or rejected.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
* with the value which is resolved in that promise using
* [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
* It also notifies via the return value of the `notifyCallback` method. The promise cannot be
* resolved or rejected from the notifyCallback method.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
*
* - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
* but to do so without modifying the final value. This is useful to release resources or do some
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
* more information.
*
* # Chaining promises
*
* Because calling the `then` method of a promise returns a new derived promise, it is easily
* possible to create a chain of promises:
*
* ```js
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value
* // will be the result of promiseA incremented by 1
* ```
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are two main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* ```js
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* }));
* ```
*
* @param {function(function, function)} resolver Function which is responsible for resolving or
* rejecting the newly created promise. The first parameter is a function which resolves the
* promise, the second parameter is a function which rejects the promise.
*
* @returns {Promise} The newly created promise.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
function $$QProvider() {
this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
return qFactory(function(callback) {
$browser.defer(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
var $qMinErr = minErr('$q', TypeError);
function callOnce(self, resolveFn, rejectFn) {
var called = false;
function wrap(fn) {
return function(value) {
if (called) return;
called = true;
fn.call(self, value);
};
}
return [wrap(resolveFn), wrap(rejectFn)];
}
/**
* @ngdoc method
* @name ng.$q#defer
* @kind function
*
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
return new Deferred();
};
function Promise() {
this.$$state = { status: 0 };
}
extend(Promise.prototype, {
then: function(onFulfilled, onRejected, progressBack) {
if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
return this;
}
var result = new Deferred();
this.$$state.pending = this.$$state.pending || [];
this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
return result.promise;
},
"catch": function(callback) {
return this.then(null, callback);
},
"finally": function(callback, progressBack) {
return this.then(function(value) {
return handleCallback(value, true, callback);
}, function(error) {
return handleCallback(error, false, callback);
}, progressBack);
}
});
//Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
function simpleBind(context, fn) {
return function(value) {
fn.call(context, value);
};
}
function processQueue(state) {
var fn, deferred, pending;
pending = state.pending;
state.processScheduled = false;
state.pending = undefined;
for (var i = 0, ii = pending.length; i < ii; ++i) {
deferred = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
deferred.resolve(fn(state.value));
} else if (state.status === 1) {
deferred.resolve(state.value);
} else {
deferred.reject(state.value);
}
} catch (e) {
deferred.reject(e);
exceptionHandler(e);
}
}
}
function scheduleProcessQueue(state) {
if (state.processScheduled || !state.pending) return;
state.processScheduled = true;
nextTick(function() { processQueue(state); });
}
function Deferred() {
this.promise = new Promise();
//Necessary to support unbound execution :/
this.resolve = simpleBind(this, this.resolve);
this.reject = simpleBind(this, this.reject);
this.notify = simpleBind(this, this.notify);
}
extend(Deferred.prototype, {
resolve: function(val) {
if (this.promise.$$state.status) return;
if (val === this.promise) {
this.$$reject($qMinErr(
'qcycle',
"Expected promise to be resolved with value other than itself '{0}'",
val));
} else {
this.$$resolve(val);
}
},
$$resolve: function(val) {
var then, fns;
fns = callOnce(this, this.$$resolve, this.$$reject);
try {
if ((isObject(val) || isFunction(val))) then = val && val.then;
if (isFunction(then)) {
this.promise.$$state.status = -1;
then.call(val, fns[0], fns[1], this.notify);
} else {
this.promise.$$state.value = val;
this.promise.$$state.status = 1;
scheduleProcessQueue(this.promise.$$state);
}
} catch (e) {
fns[1](e);
exceptionHandler(e);
}
},
reject: function(reason) {
if (this.promise.$$state.status) return;
this.$$reject(reason);
},
$$reject: function(reason) {
this.promise.$$state.value = reason;
this.promise.$$state.status = 2;
scheduleProcessQueue(this.promise.$$state);
},
notify: function(progress) {
var callbacks = this.promise.$$state.pending;
if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
nextTick(function() {
var callback, result;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
result = callbacks[i][0];
callback = callbacks[i][3];
try {
result.notify(isFunction(callback) ? callback(progress) : progress);
} catch (e) {
exceptionHandler(e);
}
}
});
}
}
});
/**
* @ngdoc method
* @name $q#reject
* @kind function
*
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* ```js
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* ```
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
var result = new Deferred();
result.reject(reason);
return result.promise;
};
var makePromise = function makePromise(value, resolved) {
var result = new Deferred();
if (resolved) {
result.resolve(value);
} else {
result.reject(value);
}
return result.promise;
};
var handleCallback = function handleCallback(value, isResolved, callback) {
var callbackOutput = null;
try {
if (isFunction(callback)) callbackOutput = callback();
} catch (e) {
return makePromise(e, false);
}
if (isPromiseLike(callbackOutput)) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
} else {
return makePromise(value, isResolved);
}
};
/**
* @ngdoc method
* @name $q#when
* @kind function
*
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @param {Function=} successCallback
* @param {Function=} errorCallback
* @param {Function=} progressCallback
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback, progressBack) {
var result = new Deferred();
result.resolve(value);
return result.promise.then(callback, errback, progressBack);
};
/**
* @ngdoc method
* @name $q#resolve
* @kind function
*
* @description
* Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
*
* @param {*} value Value or a promise
* @param {Function=} successCallback
* @param {Function=} errorCallback
* @param {Function=} progressCallback
* @returns {Promise} Returns a promise of the passed value or promise
*/
var resolve = when;
/**
* @ngdoc method
* @name $q#all
* @kind function
*
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
* each value corresponding to the promise at the same index/key in the `promises` array/hash.
* If any of the promises is resolved with a rejection, this resulting promise will be rejected
* with the same rejection value.
*/
function all(promises) {
var deferred = new Deferred(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
when(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (results.hasOwnProperty(key)) return;
deferred.reject(reason);
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
var $Q = function Q(resolver) {
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}
if (!(this instanceof Q)) {
// More useful when $Q is the Promise itself.
return new Q(resolver);
}
var deferred = new Deferred();
function resolveFn(value) {
deferred.resolve(value);
}
function rejectFn(reason) {
deferred.reject(reason);
}
resolver(resolveFn, rejectFn);
return deferred.promise;
};
$Q.defer = defer;
$Q.reject = reject;
$Q.when = when;
$Q.resolve = resolve;
$Q.all = all;
return $Q;
}
function $$RAFProvider() { //rAF
this.$get = ['$window', '$timeout', function($window, $timeout) {
var requestAnimationFrame = $window.requestAnimationFrame ||
$window.webkitRequestAnimationFrame;
var cancelAnimationFrame = $window.cancelAnimationFrame ||
$window.webkitCancelAnimationFrame ||
$window.webkitCancelRequestAnimationFrame;
var rafSupported = !!requestAnimationFrame;
var rafFn = rafSupported
? function(fn) {
var id = requestAnimationFrame(fn);
return function() {
cancelAnimationFrame(id);
};
}
: function(fn) {
var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
return function() {
$timeout.cancel(timer);
};
};
queueFn.supported = rafSupported;
var cancelLastRAF;
var taskCount = 0;
var taskQueue = [];
return queueFn;
function flush() {
for (var i = 0; i < taskQueue.length; i++) {
var task = taskQueue[i];
if (task) {
taskQueue[i] = null;
task();
}
}
taskCount = taskQueue.length = 0;
}
function queueFn(asyncFn) {
var index = taskQueue.length;
taskCount++;
taskQueue.push(asyncFn);
if (index === 0) {
cancelLastRAF = rafFn(flush);
}
return function cancelQueueFn() {
if (index >= 0) {
taskQueue[index] = null;
index = null;
if (--taskCount === 0 && cancelLastRAF) {
cancelLastRAF();
cancelLastRAF = null;
taskQueue.length = 0;
}
}
};
}
}];
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (unshift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc provider
* @name $rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc method
* @name $rootScopeProvider#digestTtl
* @description
*
* Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* In complex applications it's possible that the dependencies between `$watch`s will result in
* several digest iterations. However if an application needs more than the default 10 digest
* iterations for its model to stabilize then you should investigate what is causing the model to
* continuously change during the digest.
*
* Increasing the TTL could have performance implications, so you should not change it without
* proper justification.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc service
* @name $rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are descendant scopes of the root scope. Scopes provide separation
* between the model and the view, via a mechanism for watching the model for changes.
* They also provide an event emission/broadcast and subscription facility. See the
* {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider() {
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
var lastDirtyWatch = null;
var applyAsyncId = null;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
function createChildScopeClass(parent) {
function ChildScope() {
this.$$watchers = this.$$nextSibling =
this.$$childHead = this.$$childTail = null;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$id = nextUid();
this.$$ChildScope = null;
}
ChildScope.prototype = parent;
return ChildScope;
}
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
function($injector, $exceptionHandler, $parse, $browser) {
function destroyChildScope($event) {
$event.currentScope.$$destroyed = true;
}
/**
* @ngdoc type
* @name $rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link auto.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
* an in-depth introduction and usage examples.
*
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* ```js
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* ```
*
* When interacting with `Scope` in tests, additional helper methods are available on the
* instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
* details.
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be
* provided for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy
* when unit-testing and having the need to override a default
* service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this.$root = this;
this.$$destroyed = false;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$$isolateBindings = null;
}
/**
* @ngdoc property
* @name $rootScope.Scope#$id
*
* @description
* Unique scope ID (monotonically increasing) useful for debugging.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$parent
*
* @description
* Reference to the parent scope.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$root
*
* @description
* Reference to the root scope.
*/
Scope.prototype = {
constructor: Scope,
/**
* @ngdoc method
* @name $rootScope.Scope#$new
* @kind function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
* The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
* desired for the scope and its child scopes to be permanently detached from the parent and
* thus stop participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate If true, then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets, it is useful for the widget to not accidentally read parent
* state.
*
* @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
* of the newly created scope. Defaults to `this` scope if not provided.
* This is used when creating a transclude scope to correctly place it
* in the scope hierarchy while maintaining the correct prototypical
* inheritance.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate, parent) {
var child;
parent = parent || this;
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
// Only create a child scope class if somebody asks for one,
// but cache it to allow the VM to optimize lookups.
if (!this.$$ChildScope) {
this.$$ChildScope = createChildScopeClass(this);
}
child = new this.$$ChildScope();
}
child.$parent = parent;
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
parent.$$childHead = parent.$$childTail = child;
}
// When the new scope is not isolated or we inherit from `this`, and
// the parent scope is destroyed, the property `$$destroyed` is inherited
// prototypically. In all other cases, this property needs to be set
// when the parent scope is destroyed.
// The listener needs to be added after the parent is set
if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
return child;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watch
* @kind function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
* $digest()} and should return the value that will be watched. (Since
* {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
* `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). Inequality is determined according to reference inequality,
* [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
* via the `!==` Javascript operator, unless `objectEquality == true`
* (see next point)
* - When `objectEquality == true`, inequality of the `watchExpression` is determined
* according to the {@link angular.equals} function. To save the value of the object for
* later comparison, the {@link angular.copy} function is used. This therefore means that
* watching complex objects will have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire.
* This is achieved by rerunning the watchers until no changes are detected. The rerun
* iteration limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Be prepared for
* multiple calls to your `watchExpression` because it will execute multiple times in a
* single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
*
* # Example
* ```js
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
// Using a function as a watchExpression
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
// This function returns the value being watched. It is called for each turn of the $digest loop
function() { return food; },
// This is the change listener, called when the value returned from the above function changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);
// No digest has been run so the counter will be zero
expect(scope.foodCounter).toEqual(0);
// Run the digest but since food has not changed count will still be zero
scope.$digest();
expect(scope.foodCounter).toEqual(0);
// Update food and run digest. Now the counter will increment
food = 'cheeseburger';
scope.$digest();
expect(scope.foodCounter).toEqual(1);
* ```
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
* a call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
* of `watchExpression` changes.
*
* - `newVal` contains the current value of the `watchExpression`
* - `oldVal` contains the previous value of the `watchExpression`
* - `scope` refers to the current scope
* @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
* comparing for reference equality.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
var get = $parse(watchExp);
if (get.$$watchDelegate) {
return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
}
var scope = this,
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: prettyPrintExpression || watchExp,
eq: !!objectEquality
};
lastDirtyWatch = null;
if (!isFunction(listener)) {
watcher.fn = noop;
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
incrementWatchersCount(this, 1);
return function deregisterWatch() {
if (arrayRemove(array, watcher) >= 0) {
incrementWatchersCount(scope, -1);
}
lastDirtyWatch = null;
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchGroup
* @kind function
*
* @description
* A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
* If any one expression in the collection changes the `listener` is executed.
*
* - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
* call to $digest() to see if any items changes.
* - The `listener` is called whenever any expression in the `watchExpressions` array changes.
*
* @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
* watched using {@link ng.$rootScope.Scope#$watch $watch()}
*
* @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
* expression in `watchExpressions` changes
* The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* The `scope` refers to the current scope.
* @returns {function()} Returns a de-registration function for all listeners.
*/
$watchGroup: function(watchExpressions, listener) {
var oldValues = new Array(watchExpressions.length);
var newValues = new Array(watchExpressions.length);
var deregisterFns = [];
var self = this;
var changeReactionScheduled = false;
var firstRun = true;
if (!watchExpressions.length) {
// No expressions means we call the listener ASAP
var shouldCall = true;
self.$evalAsync(function() {
if (shouldCall) listener(newValues, newValues, self);
});
return function deregisterWatchGroup() {
shouldCall = false;
};
}
if (watchExpressions.length === 1) {
// Special case size of one
return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
newValues[0] = value;
oldValues[0] = oldValue;
listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
});
}
forEach(watchExpressions, function(expr, i) {
var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
newValues[i] = value;
oldValues[i] = oldValue;
if (!changeReactionScheduled) {
changeReactionScheduled = true;
self.$evalAsync(watchGroupAction);
}
});
deregisterFns.push(unwatchFn);
});
function watchGroupAction() {
changeReactionScheduled = false;
if (firstRun) {
firstRun = false;
listener(newValues, newValues, self);
} else {
listener(newValues, oldValues, self);
}
}
return function deregisterWatchGroup() {
while (deregisterFns.length) {
deregisterFns.shift()();
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchCollection
* @kind function
*
* @description
* Shallow watches the properties of an object and fires whenever any of the properties change
* (for arrays, this implies watching the array items; for object maps, this implies watching
* the properties). If a change is detected, the `listener` callback is fired.
*
* - The `obj` collection is observed via standard $watch operation and is examined on every
* call to $digest() to see if any items have been added, removed, or moved.
* - The `listener` is called whenever anything within the `obj` has changed. Examples include
* adding, removing, and moving items belonging to an object or array.
*
*
* # Example
* ```js
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
* ```
*
*
* @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
* expression value should evaluate to an object or an array which is observed on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
* collection will trigger a call to the `listener`.
*
* @param {function(newCollection, oldCollection, scope)} listener a callback function called
* when a change is detected.
* - The `newCollection` object is the newly modified data obtained from the `obj` expression
* - The `oldCollection` object is a copy of the former collection data.
* Due to performance considerations, the`oldCollection` value is computed only if the
* `listener` function declares two or more arguments.
* - The `scope` argument refers to the current scope.
*
* @returns {function()} Returns a de-registration function for this listener. When the
* de-registration function is executed, the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
$watchCollectionInterceptor.$stateful = true;
var self = this;
// the current value, updated on each dirty-check run
var newValue;
// a shallow copy of the newValue from the last dirty-check run,
// updated to match newValue during dirty-check run
var oldValue;
// a shallow copy of the newValue from when the last change happened
var veryOldValue;
// only track veryOldValue if the listener is asking for it
var trackVeryOldValue = (listener.length > 1);
var changeDetected = 0;
var changeDetector = $parse(obj, $watchCollectionInterceptor);
var internalArray = [];
var internalObject = {};
var initRun = true;
var oldLength = 0;
function $watchCollectionInterceptor(_value) {
newValue = _value;
var newLength, key, bothNaN, newItem, oldItem;
// If the new value is undefined, then return undefined as the watch may be a one-time watch
if (isUndefined(newValue)) return;
if (!isObject(newValue)) { // if primitive
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
}
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
oldLength = oldValue.length = 0;
changeDetected++;
}
newLength = newValue.length;
if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
oldItem = oldValue[i];
newItem = newValue[i];
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[i] = newItem;
}
}
} else {
if (oldValue !== internalObject) {
// we are transitioning from something which was not an object into object.
oldValue = internalObject = {};
oldLength = 0;
changeDetected++;
}
// copy the items to oldValue and look for changes.
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
newItem = newValue[key];
oldItem = oldValue[key];
if (key in oldValue) {
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[key] = newItem;
}
} else {
oldLength++;
oldValue[key] = newItem;
changeDetected++;
}
}
}
if (oldLength > newLength) {
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for (key in oldValue) {
if (!newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
}
}
}
return changeDetected;
}
function $watchCollectionAction() {
if (initRun) {
initRun = false;
listener(newValue, newValue, self);
} else {
listener(newValue, veryOldValue, self);
}
// make a copy for the next time a collection is changed
if (trackVeryOldValue) {
if (!isObject(newValue)) {
//primitive
veryOldValue = newValue;
} else if (isArrayLike(newValue)) {
veryOldValue = new Array(newValue.length);
for (var i = 0; i < newValue.length; i++) {
veryOldValue[i] = newValue[i];
}
} else { // if object
veryOldValue = {};
for (var key in newValue) {
if (hasOwnProperty.call(newValue, key)) {
veryOldValue[key] = newValue[key];
}
}
}
}
}
return this.$watch(changeDetector, $watchCollectionAction);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$digest
* @kind function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
* its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
* the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
* until no more listeners are firing. This means that it is possible to get into an infinite
* loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
* iterations exceeds 10.
*
* Usually, you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
* a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with
* {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
*
* In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
*
* # Example
* ```js
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
* ```
*
*/
$digest: function() {
var watch, value, last,
watchers,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg, asyncTask;
beginPhase('$digest');
// Check for changes to browser url that happened in sync before the call to $digest
$browser.$$checkUrlChange();
if (this === $rootScope && applyAsyncId !== null) {
// If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
// cancel the scheduled $apply and flush the queue of expressions to be evaluated.
$browser.defer.cancel(applyAsyncId);
flushApplyAsync();
}
lastDirtyWatch = null;
do { // "while dirty" loop
dirty = false;
current = target;
while (asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
} catch (e) {
$exceptionHandler(e);
}
lastDirtyWatch = null;
}
traverseScopesLoop:
do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch) {
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value === 'number' && typeof last === 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
lastDirtyWatch = watch;
watch.last = watch.eq ? copy(value, null) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
watchLog[logIdx].push({
msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
newVal: value,
oldVal: last
});
}
} else if (watch === lastDirtyWatch) {
// If the most recently dirty watcher is now clean, short circuit since the remaining watchers
// have already been tested.
dirty = false;
break traverseScopesLoop;
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = ((current.$$watchersCount && current.$$childHead) ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
// `break traverseScopesLoop;` takes us to here
if ((dirty || asyncQueue.length) && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: {1}',
TTL, watchLog);
}
} while (dirty || asyncQueue.length);
clearPhase();
while (postDigestQueue.length) {
try {
postDigestQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
},
/**
* @ngdoc event
* @name $rootScope.Scope#$destroy
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
/**
* @ngdoc method
* @name $rootScope.Scope#$destroy
* @kind function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it a chance to
* perform any necessary cleanup.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// We can't destroy a scope that has been already destroyed.
if (this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (this === $rootScope) {
//Remove handlers attached to window when $rootScope is removed
$browser.$$applicationDestroyed();
}
incrementWatchersCount(this, -this.$$watchersCount);
for (var eventName in this.$$listenerCount) {
decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
}
// sever all the references to parent scopes (after this cleanup, the current scope should
// not be retained by any of our references and should be eligible for garbage collection)
if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// Disable listeners, watchers and apply/digest methods
this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
this.$on = this.$watch = this.$watchGroup = function() { return noop; };
this.$$listeners = {};
// All of the code below is bogus code that works around V8's memory leak via optimized code
// and inline caches.
//
// see:
// - https://code.google.com/p/v8/issues/detail?id=2073#c26
// - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
// - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = this.$root = this.$$watchers = null;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$eval
* @kind function
*
* @description
* Executes the `expression` on the current scope and returns the result. Any exceptions in
* the expression are propagated (uncaught). This is useful when evaluating Angular
* expressions.
*
* # Example
* ```js
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* ```
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$evalAsync
* @kind function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
* that:
*
* - it will execute after the function that scheduled the evaluation (preferably before DOM
* rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
* will be scheduled. However, it is encouraged to always call code that changes the model
* from within an `$apply` call. That includes code evaluated via `$evalAsync`.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
*/
$evalAsync: function(expr, locals) {
// if we are outside of an $digest loop and this is the first time we are scheduling async
// task also schedule async auto-flush
if (!$rootScope.$$phase && !asyncQueue.length) {
$browser.defer(function() {
if (asyncQueue.length) {
$rootScope.$digest();
}
});
}
asyncQueue.push({scope: this, expression: expr, locals: locals});
},
$$postDigest: function(fn) {
postDigestQueue.push(fn);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$apply
* @kind function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life
* cycle of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* ```js
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* ```
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
* expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
try {
return this.$eval(expr);
} finally {
clearPhase();
}
} catch (e) {
$exceptionHandler(e);
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$applyAsync
* @kind function
*
* @description
* Schedule the invocation of $apply to occur at a later time. The actual time difference
* varies across browsers, but is typically around ~10 milliseconds.
*
* This can be used to queue up multiple expressions which need to be evaluated in the same
* digest.
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*/
$applyAsync: function(expr) {
var scope = this;
expr && applyAsyncQueue.push($applyAsyncExpression);
scheduleApplyAsync();
function $applyAsyncExpression() {
scope.$eval(expr);
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$on
* @kind function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
* discussion of event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
* `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
* event propagates through the scope hierarchy, this property is set to null.
* - `name` - `{string}`: name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
* further event propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
* to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, ...args)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
var current = this;
do {
if (!current.$$listenerCount[name]) {
current.$$listenerCount[name] = 0;
}
current.$$listenerCount[name]++;
} while ((current = current.$parent));
var self = this;
return function() {
var indexOfListener = namedListeners.indexOf(listener);
if (indexOfListener !== -1) {
namedListeners[indexOfListener] = null;
decrementListenerCount(self, 1, name);
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$emit
* @kind function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event traverses upwards toward the root scope and calls all
* registered listeners along the way. The event will stop propagating if one of the listeners
* cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i = 0, length = namedListeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
//allow all listeners attached to the current scope to run
namedListeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
//if any listener on the current scope stops propagation, prevent bubbling
if (stopPropagation) {
event.currentScope = null;
return event;
}
//traverse upwards
scope = scope.$parent;
} while (scope);
event.currentScope = null;
return event;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$broadcast
* @kind function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event propagates to all direct and indirect scopes of the current
* scope and calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
};
if (!target.$$listenerCount[name]) return event;
var listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
while ((current = next)) {
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i = 0, length = listeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
// (though it differs due to having the extra check for $$listenerCount)
if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
}
event.currentScope = null;
return event;
}
};
var $rootScope = new Scope();
//The internal queues. Expose them on the $rootScope for debugging/testing purposes.
var asyncQueue = $rootScope.$$asyncQueue = [];
var postDigestQueue = $rootScope.$$postDigestQueue = [];
var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function incrementWatchersCount(current, count) {
do {
current.$$watchersCount += count;
} while ((current = current.$parent));
}
function decrementListenerCount(current, count, name) {
do {
current.$$listenerCount[name] -= count;
if (current.$$listenerCount[name] === 0) {
delete current.$$listenerCount[name];
}
} while ((current = current.$parent));
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
function flushApplyAsync() {
while (applyAsyncQueue.length) {
try {
applyAsyncQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
applyAsyncId = null;
}
function scheduleApplyAsync() {
if (applyAsyncId === null) {
applyAsyncId = $browser.defer(function() {
$rootScope.$apply(flushApplyAsync);
});
}
}
}];
}
/**
* @description
* Private service to sanitize uris for links and images. Used by $compile and $sanitize.
*/
function $$SanitizeUriProvider() {
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = function() {
return function sanitizeUri(uri, isImage) {
var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
var normalizedVal;
normalizedVal = urlResolve(uri).href;
if (normalizedVal !== '' && !normalizedVal.match(regex)) {
return 'unsafe:' + normalizedVal;
}
return uri;
};
};
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $sceMinErr = minErr('$sce');
var SCE_CONTEXTS = {
HTML: 'html',
CSS: 'css',
URL: 'url',
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
// url. (e.g. ng-include, script src, templateUrl)
RESOURCE_URL: 'resourceUrl',
JS: 'js'
};
// Helper functions follow.
function adjustMatcher(matcher) {
if (matcher === 'self') {
return matcher;
} else if (isString(matcher)) {
// Strings match exactly except for 2 wildcards - '*' and '**'.
// '*' matches any character except those from the set ':/.?&'.
// '**' matches any character (like .* in a RegExp).
// More than 2 *'s raises an error as it's ill defined.
if (matcher.indexOf('***') > -1) {
throw $sceMinErr('iwcard',
'Illegal sequence *** in string matcher. String: {0}', matcher);
}
matcher = escapeForRegexp(matcher).
replace('\\*\\*', '.*').
replace('\\*', '[^:/.?&;]*');
return new RegExp('^' + matcher + '$');
} else if (isRegExp(matcher)) {
// The only other type of matcher allowed is a Regexp.
// Match entire URL / disallow partial matches.
// Flags are reset (i.e. no global, ignoreCase or multiline)
return new RegExp('^' + matcher.source + '$');
} else {
throw $sceMinErr('imatcher',
'Matchers may only be "self", string patterns or RegExp objects');
}
}
function adjustMatchers(matchers) {
var adjustedMatchers = [];
if (isDefined(matchers)) {
forEach(matchers, function(matcher) {
adjustedMatchers.push(adjustMatcher(matcher));
});
}
return adjustedMatchers;
}
/**
* @ngdoc service
* @name $sceDelegate
* @kind function
*
* @description
*
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
* Contextual Escaping (SCE)} services to AngularJS.
*
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
* work because `$sce` delegates to `$sceDelegate` for these operations.
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
*
* The default instance of `$sceDelegate` should work out of the box with little pain. While you
* can override it completely to change the behavior of `$sce`, the common case would
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
* templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
* $sceDelegateProvider.resourceUrlWhitelist} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*/
/**
* @ngdoc provider
* @name $sceDelegateProvider
* @description
*
* The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
* that the URLs used for sourcing Angular templates are safe. Refer {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
* {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*
* For the general details about this service in Angular, read the main page for {@link ng.$sce
* Strict Contextual Escaping (SCE)}.
*
* **Example**: Consider the following case. <a name="example"></a>
*
* - your app is hosted at url `http://myapp.example.com/`
* - but some of your templates are hosted on other domains you control such as
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
*
* Here is what a secure configuration for this scenario might look like:
*
* ```
* angular.module('myApp', []).config(function($sceDelegateProvider) {
* $sceDelegateProvider.resourceUrlWhitelist([
* // Allow same origin resource loads.
* 'self',
* // Allow loading from our assets domain. Notice the difference between * and **.
* 'http://srv*.assets.example.com/**'
* ]);
*
* // The blacklist overrides the whitelist so the open redirect here is blocked.
* $sceDelegateProvider.resourceUrlBlacklist([
* 'http://myapp.example.com/clickThru**'
* ]);
* });
* ```
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
// Resource URLs can also be trusted by policy.
var resourceUrlWhitelist = ['self'],
resourceUrlBlacklist = [];
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlWhitelist
* @kind function
*
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* Note: **an empty whitelist array will block all URLs**!
*
* @return {Array} the currently set whitelist array.
*
* The **default value** when no whitelist has been explicitly set is `['self']` allowing only
* same origin resource requests.
*
* @description
* Sets/Gets the whitelist of trusted resource URLs.
*/
this.resourceUrlWhitelist = function(value) {
if (arguments.length) {
resourceUrlWhitelist = adjustMatchers(value);
}
return resourceUrlWhitelist;
};
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlBlacklist
* @kind function
*
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* The typical usage for the blacklist is to **block
* [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
* these would otherwise be trusted but actually return content from the redirected domain.
*
* Finally, **the blacklist overrides the whitelist** and has the final say.
*
* @return {Array} the currently set blacklist array.
*
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
* is no blacklist.)
*
* @description
* Sets/Gets the blacklist of trusted resource URLs.
*/
this.resourceUrlBlacklist = function(value) {
if (arguments.length) {
resourceUrlBlacklist = adjustMatchers(value);
}
return resourceUrlBlacklist;
};
this.$get = ['$injector', function($injector) {
var htmlSanitizer = function htmlSanitizer(html) {
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
};
if ($injector.has('$sanitize')) {
htmlSanitizer = $injector.get('$sanitize');
}
function matchUrl(matcher, parsedUrl) {
if (matcher === 'self') {
return urlIsSameOrigin(parsedUrl);
} else {
// definitely a regex. See adjustMatchers()
return !!matcher.exec(parsedUrl.href);
}
}
function isResourceUrlAllowedByPolicy(url) {
var parsedUrl = urlResolve(url.toString());
var i, n, allowed = false;
// Ensure that at least one item from the whitelist allows this url.
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
allowed = true;
break;
}
}
if (allowed) {
// Ensure that no item from the blacklist blocked this url.
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
allowed = false;
break;
}
}
}
return allowed;
}
function generateHolderType(Base) {
var holderType = function TrustedValueHolderType(trustedValue) {
this.$$unwrapTrustedValue = function() {
return trustedValue;
};
};
if (Base) {
holderType.prototype = new Base();
}
holderType.prototype.valueOf = function sceValueOf() {
return this.$$unwrapTrustedValue();
};
holderType.prototype.toString = function sceToString() {
return this.$$unwrapTrustedValue().toString();
};
return holderType;
}
var trustedValueHolderBase = generateHolderType(),
byType = {};
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
/**
* @ngdoc method
* @name $sceDelegate#trustAs
*
* @description
* Returns an object that is trusted by angular for use in specified strict
* contextual escaping contexts (such as ng-bind-html, ng-include, any src
* attribute interpolation, any dom event binding attribute interpolation
* such as for onclick, etc.) that uses the provided value.
* See {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
function trustAs(type, trustedValue) {
var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (!Constructor) {
throw $sceMinErr('icontext',
'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
type, trustedValue);
}
if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
return trustedValue;
}
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
// mutable objects, we ensure here that the value passed in is actually a string.
if (typeof trustedValue !== 'string') {
throw $sceMinErr('itype',
'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
type);
}
return new Constructor(trustedValue);
}
/**
* @ngdoc method
* @name $sceDelegate#valueOf
*
* @description
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
*
* If the passed parameter is not a value that had been returned by {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
*
* @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
* call or anything else.
* @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
* `value` unchanged.
*/
function valueOf(maybeTrusted) {
if (maybeTrusted instanceof trustedValueHolderBase) {
return maybeTrusted.$$unwrapTrustedValue();
} else {
return maybeTrusted;
}
}
/**
* @ngdoc method
* @name $sceDelegate#getTrusted
*
* @description
* Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
* returns the originally supplied value if the queried context type is a supertype of the
* created type. If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
*/
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
}
/**
* @ngdoc provider
* @name $sceProvider
* @description
*
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
* - enable/disable Strict Contextual Escaping (SCE) in a module
* - override the default implementation with a custom delegate
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
/* jshint maxlen: false*/
/**
* @ngdoc service
* @name $sce
* @kind function
*
* @description
*
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
*
* # Strict Contextual Escaping
*
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
* contexts to result in a value that is marked as safe to use for that context. One example of
* such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
* to these contexts as privileged or SCE contexts.
*
* As of version 1.2, Angular ships with SCE enabled by default.
*
* Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
* one to execute arbitrary javascript by the use of the expression() syntax. Refer
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
* to the top of your HTML document.
*
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
* ```
* <input ng-model="userHtml" aria-label="User input">
* <div ng-bind-html="userHtml"></div>
* ```
*
* Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
* security vulnerabilities.)
*
* For the case of HTML, you might use a library, either on the client side, or on the server side,
* to sanitize unsafe HTML before binding to the value and rendering it in the document.
*
* How would you ensure that every place that used these types of bindings was bound to a value that
* was sanitized by your library (or returned as safe for rendering by your server?) How can you
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
* properties/fields and forgot to update the binding to the sanitized value?
*
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can
* determine that something explicitly says it's safe to use a value for binding in that
* context. You can then audit your code (a simple grep would do) to ensure that this is only done
* for those values that you can easily tell are safe - because they were received from your server,
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps
* allowing only the files in a specific directory to do this. Ensuring that the internal API
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
*
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
* (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
* obtain values that will be accepted by SCE / privileged contexts.
*
*
* ## How does it work?
*
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
* ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
* {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
* ```
* var ngBindHtmlDirective = ['$sce', function($sce) {
* return function(scope, element, attr) {
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
* element.html(value || '');
* });
* };
* }];
* ```
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
*
* By default, Angular only loads templates from the same domain and protocol as the application
* document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
* protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
* them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
*
* *Please note*:
* The browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy apply in addition to this and may further restrict whether the template is successfully
* loaded. This means that without the right CORS policy, loading templates from a different domain
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some
* browsers.
*
* ## This feels like too much overhead
*
* It's important to remember that SCE only applies to interpolation expressions.
*
* If your expressions are constant literals, they're automatically trusted and you don't need to
* call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
* `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
*
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
* through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
*
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
* templates in `ng-include` from your application's domain without having to even know about SCE.
* It blocks loading templates from other domains or loading templates over http from an https
* served document. You can change these by setting your own custom {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
*
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an
* application that's secure and can be audited to verify that with much more ease than bolting
* security onto an application later.
*
* <a name="contexts"></a>
* ## What trusted context types are supported?
*
* | Context | Notes |
* |---------------------|----------------|
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
*
* ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
*
* Each element in these arrays must be one of the following:
*
* - **'self'**
* - The special **string**, `'self'`, can be used to match against all URLs of the **same
* domain** as the application document using the **same protocol**.
* - **String** (except the special value `'self'`)
* - The string is matched against the full *normalized / absolute URL* of the resource
* being tested (substring matches are not good enough.)
* - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
* match themselves.
* - `*`: matches zero or more occurrences of any character other than one of the following 6
* characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
* in a whitelist.
* - `**`: matches zero or more occurrences of *any* character. As such, it's not
* appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
* http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
* not have been the intention.) Its usage at the very end of the path is ok. (e.g.
* http://foo.example.com/templates/**).
* - **RegExp** (*see caveat below*)
* - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
* (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
* accidentally introduce a bug when one updates a complex expression (imho, all regexes should
* have good test coverage). For instance, the use of `.` in the regex is correct only in a
* small number of cases. A `.` character in the regex used when matching the scheme or a
* subdomain could be matched against a `:` or literal `.` that was likely not intended. It
* is highly recommended to use the string patterns and only fall back to regular expressions
* as a last resort.
* - The regular expression must be an instance of RegExp (i.e. not a string.) It is
* matched against the **entire** *normalized / absolute URL* of the resource being tested
* (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
* present on the RegExp (such as multiline, global, ignoreCase) are ignored.
* - If you are generating your JavaScript from some other templating engine (not
* recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
* remember to escape your regular expression (and be aware that you might need more than
* one level of escaping depending on your templating engine and the way you interpolated
* the value.) Do make use of your platform's escaping mechanism as it might be good
* enough before coding your own. E.g. Ruby has
* [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
* and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
* Javascript lacks a similar built in function for escaping. Take a look at Google
* Closure library's [goog.string.regExpEscape(s)](
* http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
*
* ## Show me an example using SCE.
*
* <example module="mySceApp" deps="angular-sanitize.js">
* <file name="index.html">
* <div ng-controller="AppController as myCtrl">
* <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
* <b>User comments</b><br>
* By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
* $sanitize is available. If $sanitize isn't available, this results in an error instead of an
* exploit.
* <div class="well">
* <div ng-repeat="userComment in myCtrl.userComments">
* <b>{{userComment.name}}</b>:
* <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
* <br>
* </div>
* </div>
* </div>
* </file>
*
* <file name="script.js">
* angular.module('mySceApp', ['ngSanitize'])
* .controller('AppController', ['$http', '$templateCache', '$sce',
* function($http, $templateCache, $sce) {
* var self = this;
* $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
* self.userComments = userComments;
* });
* self.explicitlyTrustedHtml = $sce.trustAsHtml(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* }]);
* </file>
*
* <file name="test_data.json">
* [
* { "name": "Alice",
* "htmlComment":
* "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
* },
* { "name": "Bob",
* "htmlComment": "<i>Yes!</i> Am I the only other one?"
* }
* ]
* </file>
*
* <file name="protractor.js" type="protractor">
* describe('SCE doc demo', function() {
* it('should sanitize untrusted values', function() {
* expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
* .toBe('<span>Is <i>anyone</i> reading this?</span>');
* });
*
* it('should NOT sanitize explicitly trusted values', function() {
* expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* });
* });
* </file>
* </example>
*
*
*
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
* ```
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
* // Completely disable SCE. For demonstration purposes only!
* // Do not use in new projects.
* $sceProvider.enabled(false);
* });
* ```
*
*/
/* jshint maxlen: 100 */
function $SceProvider() {
var enabled = true;
/**
* @ngdoc method
* @name $sceProvider#enabled
* @kind function
*
* @param {boolean=} value If provided, then enables/disables SCE.
* @return {boolean} true if SCE is enabled, false otherwise.
*
* @description
* Enables/disables SCE and returns the current value.
*/
this.enabled = function(value) {
if (arguments.length) {
enabled = !!value;
}
return enabled;
};
/* Design notes on the default implementation for SCE.
*
* The API contract for the SCE delegate
* -------------------------------------
* The SCE delegate object must provide the following 3 methods:
*
* - trustAs(contextEnum, value)
* This method is used to tell the SCE service that the provided value is OK to use in the
* contexts specified by contextEnum. It must return an object that will be accepted by
* getTrusted() for a compatible contextEnum and return this value.
*
* - valueOf(value)
* For values that were not produced by trustAs(), return them as is. For values that were
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if
* trustAs is wrapping the given values into some type, this operation unwraps it when given
* such a value.
*
* - getTrusted(contextEnum, value)
* This function should return the a value that is safe to use in the context specified by
* contextEnum or throw and exception otherwise.
*
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
* opaque or wrapped in some holder object. That happens to be an implementation detail. For
* instance, an implementation could maintain a registry of all trusted objects by context. In
* such a case, trustAs() would return the same object that was passed in. getTrusted() would
* return the same object passed in if it was found in the registry under a compatible context or
* throw an exception otherwise. An implementation might only wrap values some of the time based
* on some criteria. getTrusted() might return a value and not throw an exception for special
* constants or objects even if not wrapped. All such implementations fulfill this contract.
*
*
* A note on the inheritance model for SCE contexts
* ------------------------------------------------
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
* is purely an implementation details.
*
* The contract is simply this:
*
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
* will also succeed.
*
* Inheritance happens to capture this in a natural way. In some future, we
* may not use inheritance anymore. That is OK because no code outside of
* sce.js and sceSpecs.js would need to be aware of this detail.
*/
this.$get = ['$parse', '$sceDelegate', function(
$parse, $sceDelegate) {
// Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
// the "expression(javascript expression)" syntax which is insecure.
if (enabled && msie < 8) {
throw $sceMinErr('iequirks',
'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
}
var sce = shallowCopy(SCE_CONTEXTS);
/**
* @ngdoc method
* @name $sce#isEnabled
* @kind function
*
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
*
* @description
* Returns a boolean indicating if SCE is enabled.
*/
sce.isEnabled = function() {
return enabled;
};
sce.trustAs = $sceDelegate.trustAs;
sce.getTrusted = $sceDelegate.getTrusted;
sce.valueOf = $sceDelegate.valueOf;
if (!enabled) {
sce.trustAs = sce.getTrusted = function(type, value) { return value; };
sce.valueOf = identity;
}
/**
* @ngdoc method
* @name $sce#parseAs
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
* *result*)}
*
* @param {string} type The kind of SCE context in which this result will be used.
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
sce.parseAs = function sceParseAs(type, expr) {
var parsed = $parse(expr);
if (parsed.literal && parsed.constant) {
return parsed;
} else {
return $parse(expr, function(value) {
return sce.getTrusted(type, value);
});
}
};
/**
* @ngdoc method
* @name $sce#trustAs
*
* @description
* Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
* returns an object that is trusted by angular for use in specified strict contextual
* escaping contexts (such as ng-bind-html, ng-include, any src attribute
* interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
* that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
* escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
/**
* @ngdoc method
* @name $sce#trustAsHtml
*
* @description
* Shorthand method. `$sce.trustAsHtml(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsUrl
*
* @description
* Shorthand method. `$sce.trustAsUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsResourceUrl
*
* @description
* Shorthand method. `$sce.trustAsResourceUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the return
* value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsJs
*
* @description
* Shorthand method. `$sce.trustAsJs(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#getTrusted
*
* @description
* Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
* takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
* originally supplied value if the queried context type is a supertype of the created type.
* If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
* call.
* @returns {*} The value the was originally provided to
* {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
* Otherwise, throws an exception.
*/
/**
* @ngdoc method
* @name $sce#getTrustedHtml
*
* @description
* Shorthand method. `$sce.getTrustedHtml(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedCss
*
* @description
* Shorthand method. `$sce.getTrustedCss(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedUrl
*
* @description
* Shorthand method. `$sce.getTrustedUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedResourceUrl
*
* @description
* Shorthand method. `$sce.getTrustedResourceUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to pass to `$sceDelegate.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedJs
*
* @description
* Shorthand method. `$sce.getTrustedJs(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
*/
/**
* @ngdoc method
* @name $sce#parseAsHtml
*
* @description
* Shorthand method. `$sce.parseAsHtml(expression string)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsCss
*
* @description
* Shorthand method. `$sce.parseAsCss(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsUrl
*
* @description
* Shorthand method. `$sce.parseAsUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsResourceUrl
*
* @description
* Shorthand method. `$sce.parseAsResourceUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsJs
*
* @description
* Shorthand method. `$sce.parseAsJs(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
// Shorthand delegations.
var parse = sce.parseAs,
getTrusted = sce.getTrusted,
trustAs = sce.trustAs;
forEach(SCE_CONTEXTS, function(enumValue, name) {
var lName = lowercase(name);
sce[camelCase("parse_as_" + lName)] = function(expr) {
return parse(enumValue, expr);
};
sce[camelCase("get_trusted_" + lName)] = function(value) {
return getTrusted(enumValue, value);
};
sce[camelCase("trust_as_" + lName)] = function(value) {
return trustAs(enumValue, value);
};
});
return sce;
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name $sniffer
* @requires $window
* @requires $document
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} transitions Does the browser support CSS transition events ?
* @property {boolean} animations Does the browser support CSS animation events ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android =
toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
document = $document[0] || {},
vendorPrefix,
vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for (var prop in bodyStyle) {
if (match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
if (!vendorPrefix) {
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions || !animations)) {
transitions = isString(bodyStyle.webkitTransition);
animations = isString(bodyStyle.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
// older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
// so let's not use the history API also
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
// jshint -W018
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
// jshint +W018
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
// IE10+ implements 'input' event but it erroneously fires under various situations,
// e.g. when placeholder changes, or a form is focused.
if (event === 'input' && msie <= 11) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: csp(),
vendorPrefix: vendorPrefix,
transitions: transitions,
animations: animations,
android: android
};
}];
}
var $compileMinErr = minErr('$compile');
/**
* @ngdoc service
* @name $templateRequest
*
* @description
* The `$templateRequest` service runs security checks then downloads the provided template using
* `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
* fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
* exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
* contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
* when `tpl` is of type string and `$templateCache` has the matching entry.
*
* @param {string|TrustedResourceUrl} tpl The HTTP request template URL
* @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
*
* @return {Promise} a promise for the HTTP response data of the given URL.
*
* @property {number} totalPendingRequests total amount of pending template requests being downloaded.
*/
function $TemplateRequestProvider() {
this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
function handleRequestFn(tpl, ignoreRequestError) {
handleRequestFn.totalPendingRequests++;
// We consider the template cache holds only trusted templates, so
// there's no need to go through whitelisting again for keys that already
// are included in there. This also makes Angular accept any script
// directive, no matter its name. However, we still need to unwrap trusted
// types.
if (!isString(tpl) || !$templateCache.get(tpl)) {
tpl = $sce.getTrustedResourceUrl(tpl);
}
var transformResponse = $http.defaults && $http.defaults.transformResponse;
if (isArray(transformResponse)) {
transformResponse = transformResponse.filter(function(transformer) {
return transformer !== defaultHttpResponseTransform;
});
} else if (transformResponse === defaultHttpResponseTransform) {
transformResponse = null;
}
var httpOptions = {
cache: $templateCache,
transformResponse: transformResponse
};
return $http.get(tpl, httpOptions)
['finally'](function() {
handleRequestFn.totalPendingRequests--;
})
.then(function(response) {
$templateCache.put(tpl, response.data);
return response.data;
}, handleError);
function handleError(resp) {
if (!ignoreRequestError) {
throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
tpl, resp.status, resp.statusText);
}
return $q.reject(resp);
}
}
handleRequestFn.totalPendingRequests = 0;
return handleRequestFn;
}];
}
function $$TestabilityProvider() {
this.$get = ['$rootScope', '$browser', '$location',
function($rootScope, $browser, $location) {
/**
* @name $testability
*
* @description
* The private $$testability service provides a collection of methods for use when debugging
* or by automated test and debugging tools.
*/
var testability = {};
/**
* @name $$testability#findBindings
*
* @description
* Returns an array of elements that are bound (via ng-bind or {{}})
* to expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The binding expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression. Filters and whitespace are ignored.
*/
testability.findBindings = function(element, expression, opt_exactMatch) {
var bindings = element.getElementsByClassName('ng-binding');
var matches = [];
forEach(bindings, function(binding) {
var dataBinding = angular.element(binding).data('$binding');
if (dataBinding) {
forEach(dataBinding, function(bindingName) {
if (opt_exactMatch) {
var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
if (matcher.test(bindingName)) {
matches.push(binding);
}
} else {
if (bindingName.indexOf(expression) != -1) {
matches.push(binding);
}
}
});
}
});
return matches;
};
/**
* @name $$testability#findModels
*
* @description
* Returns an array of elements that are two-way found via ng-model to
* expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The model expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression.
*/
testability.findModels = function(element, expression, opt_exactMatch) {
var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
for (var p = 0; p < prefixes.length; ++p) {
var attributeEquals = opt_exactMatch ? '=' : '*=';
var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
var elements = element.querySelectorAll(selector);
if (elements.length) {
return elements;
}
}
};
/**
* @name $$testability#getLocation
*
* @description
* Shortcut for getting the location in a browser agnostic way. Returns
* the path, search, and hash. (e.g. /path?a=b#hash)
*/
testability.getLocation = function() {
return $location.url();
};
/**
* @name $$testability#setLocation
*
* @description
* Shortcut for navigating to a location without doing a full page reload.
*
* @param {string} url The location url (path, search and hash,
* e.g. /path?a=b#hash) to go to.
*/
testability.setLocation = function(url) {
if (url !== $location.url()) {
$location.url(url);
$rootScope.$digest();
}
};
/**
* @name $$testability#whenStable
*
* @description
* Calls the callback when $timeout and $http requests are completed.
*
* @param {function} callback
*/
testability.whenStable = function(callback) {
$browser.notifyWhenNoOutstandingRequests(callback);
};
return testability;
}];
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
function($rootScope, $browser, $q, $$q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc service
* @name $timeout
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of calling `$timeout` is a promise, which will be resolved when
* the delay has passed and the timeout function, if provided, is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* If you only want a promise that will be resolved after some specified delay
* then you can call `$timeout` without the `fn` function.
*
* @param {function()=} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @param {...*=} Pass additional parameters to the executed function.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*
*/
function timeout(fn, delay, invokeApply) {
if (!isFunction(fn)) {
invokeApply = delay;
delay = fn;
fn = noop;
}
var args = sliceArgs(arguments, 3),
skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise,
timeoutId;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn.apply(null, args));
} catch (e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $timeout#cancel
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
delete deferreds[promise.$$timeoutId];
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
// NOTE: The usage of window and document instead of $window and $document here is
// deliberate. This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here. There is little value is mocking these out for this
// service.
var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href);
/**
*
* Implementation Notes for non-IE browsers
* ----------------------------------------
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
* results both in the normalizing and parsing of the URL. Normalizing means that a relative
* URL will be resolved into an absolute URL in the context of the application document.
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
* properties are all populated to reflect the normalized URL. This approach has wide
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
*
* Implementation Notes for IE
* ---------------------------
* IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
* browsers. However, the parsed components will not be set if the URL assigned did not specify
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
* work around that by performing the parsing in a 2nd step by taking a previously normalized
* URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
* properties such as protocol, hostname, port, etc.
*
* References:
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
* http://url.spec.whatwg.org/#urlutils
* https://github.com/angular/angular.js/pull/2902
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @kind function
* @param {string} url The URL to be parsed.
* @description Normalizes and parses a URL.
* @returns {object} Returns the normalized URL as a dictionary.
*
* | member name | Description |
* |---------------|----------------|
* | href | A normalized version of the provided URL if it was not an absolute URL |
* | protocol | The protocol including the trailing colon |
* | host | The host and port (if the port is non-default) of the normalizedUrl |
* | search | The search params, minus the question mark |
* | hash | The hash string, minus the hash symbol
* | hostname | The hostname
* | port | The port, without ":"
* | pathname | The pathname, beginning with "/"
*
*/
function urlResolve(url) {
var href = url;
if (msie) {
// Normalize before parse. Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/')
? urlParsingNode.pathname
: '/' + urlParsingNode.pathname
};
}
/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
* @returns {boolean} Whether the request is for the same origin as the application document.
*/
function urlIsSameOrigin(requestUrl) {
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
/**
* @ngdoc service
* @name $window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overridden, removed or mocked for testing.
*
* Expressions, like the one defined for the `ngClick` directive in the example
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
<example module="windowExample">
<file name="index.html">
<script>
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
$window.alert(greeting);
};
}]);
</script>
<div ng-controller="ExampleController">
<input type="text" ng-model="greeting" aria-label="greeting" />
<button ng-click="doGreeting(greeting)">ALERT</button>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should display the greeting in the input box', function() {
element(by.model('greeting')).sendKeys('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</file>
</example>
*/
function $WindowProvider() {
this.$get = valueFn(window);
}
/**
* @name $$cookieReader
* @requires $document
*
* @description
* This is a private service for reading cookies used by $http and ngCookies
*
* @return {Object} a key/value map of the current cookies
*/
function $$CookieReader($document) {
var rawDocument = $document[0] || {};
var lastCookies = {};
var lastCookieString = '';
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
return function() {
var cookieArray, cookie, i, index, name;
var currentCookieString = rawDocument.cookie || '';
if (currentCookieString !== lastCookieString) {
lastCookieString = currentCookieString;
cookieArray = lastCookieString.split('; ');
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
};
}
$$CookieReader.$inject = ['$document'];
function $$CookieReaderProvider() {
this.$get = $$CookieReader;
}
/* global currencyFilter: true,
dateFilter: true,
filterFilter: true,
jsonFilter: true,
limitToFilter: true,
lowercaseFilter: true,
numberFilter: true,
orderByFilter: true,
uppercaseFilter: true,
*/
/**
* @ngdoc provider
* @name $filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be
* Dependency Injected. To achieve this a filter definition consists of a factory function which is
* annotated with dependencies and is responsible for creating a filter function.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
*
* ```js
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* ```
*
* The filter function is registered with the `$injector` under the filter name suffix with
* `Filter`.
*
* ```js
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* ```
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/filter Filters} in the Angular Developer Guide.
*/
/**
* @ngdoc service
* @name $filter
* @kind function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
* @example
<example name="$filter" module="filterExample">
<file name="index.html">
<div ng-controller="MainCtrl">
<h3>{{ originalText }}</h3>
<h3>{{ filteredText }}</h3>
</div>
</file>
<file name="script.js">
angular.module('filterExample', [])
.controller('MainCtrl', function($scope, $filter) {
$scope.originalText = 'hello';
$scope.filteredText = $filter('uppercase')($scope.originalText);
});
</file>
</example>
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
/**
* @ngdoc method
* @name $filterProvider#register
* @param {string|Object} name Name of the filter function, or an object map of filters where
* the keys are the filter names and the values are the filter factories.
*
* <div class="alert alert-warning">
* **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
* </div>
* @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map
* of the registered filter instances.
*/
function register(name, factory) {
if (isObject(name)) {
var filters = {};
forEach(name, function(filter, key) {
filters[key] = register(key, filter);
});
return filters;
} else {
return $provide.factory(name + suffix, factory);
}
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
};
}];
////////////////////////////////////////
/* global
currencyFilter: false,
dateFilter: false,
filterFilter: false,
jsonFilter: false,
limitToFilter: false,
lowercaseFilter: false,
numberFilter: false,
orderByFilter: false,
uppercaseFilter: false,
*/
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name filter
* @kind function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: The string is used for matching against the contents of the `array`. All strings or
* objects with string properties in `array` that match this string will be returned. This also
* applies to nested object properties.
* The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object or its nested object properties. That's equivalent to the simple
* substring match with a `string` as described above. The predicate can be negated by prefixing
* the string with `!`.
* For example `{name: "!M"}` predicate will return an array of items which have property `name`
* not containing "M".
*
* Note that a named property will match properties on the same level only, while the special
* `$` property will match properties on the same level or deeper. E.g. an array item like
* `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
* **will** be matched by `{$: 'John'}`.
*
* - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
* The function is called for each element of the array, with the element, its index, and
* the entire array itself as arguments.
*
* The final result is an array of those elements that the predicate returned true for.
*
* @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
* the object in the array) should be considered a match.
*
* Can be one of:
*
* - `function(actual, expected)`:
* The function will be given the object value and the predicate value to compare and
* should return true if both values should be considered equal.
*
* - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
* This is essentially strict comparison of expected and actual.
*
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* Primitive values are converted to strings. Objects are not compared against primitives,
* unless they have a custom `toString` method (e.g. `Date` objects).
*
* @example
<example>
<file name="index.html">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
<label>Search: <input ng-model="searchText"></label>
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
<label>Any: <input ng-model="search.$"></label> <br>
<label>Name only <input ng-model="search.name"></label><br>
<label>Phone only <input ng-model="search.phone"></label><br>
<label>Equality <input type="checkbox" ng-model="strict"></label><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in friends | filter:search:strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</file>
<file name="protractor.js" type="protractor">
var expectFriendNames = function(expectedNames, key) {
element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
arr.forEach(function(wd, i) {
expect(wd.getText()).toMatch(expectedNames[i]);
});
});
};
it('should search across all fields when filtering with a string', function() {
var searchText = element(by.model('searchText'));
searchText.clear();
searchText.sendKeys('m');
expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
searchText.clear();
searchText.sendKeys('76');
expectFriendNames(['John', 'Julie'], 'friend');
});
it('should search in specific fields when filtering with a predicate object', function() {
var searchAny = element(by.model('search.$'));
searchAny.clear();
searchAny.sendKeys('i');
expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
});
it('should use a equal comparison when comparator is true', function() {
var searchName = element(by.model('search.name'));
var strict = element(by.model('strict'));
searchName.clear();
searchName.sendKeys('Julie');
strict.click();
expectFriendNames(['Julie'], 'friendObj');
});
</file>
</example>
*/
function filterFilter() {
return function(array, expression, comparator) {
if (!isArrayLike(array)) {
if (array == null) {
return array;
} else {
throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
}
}
var expressionType = getTypeForFilter(expression);
var predicateFn;
var matchAgainstAnyProp;
switch (expressionType) {
case 'function':
predicateFn = expression;
break;
case 'boolean':
case 'null':
case 'number':
case 'string':
matchAgainstAnyProp = true;
//jshint -W086
case 'object':
//jshint +W086
predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
break;
default:
return array;
}
return Array.prototype.filter.call(array, predicateFn);
};
}
// Helper functions for `filterFilter`
function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
var predicateFn;
if (comparator === true) {
comparator = equals;
} else if (!isFunction(comparator)) {
comparator = function(actual, expected) {
if (isUndefined(actual)) {
// No substring matching against `undefined`
return false;
}
if ((actual === null) || (expected === null)) {
// No substring matching against `null`; only match against `null`
return actual === expected;
}
if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
// Should not compare primitives against objects, unless they have custom `toString` method
return false;
}
actual = lowercase('' + actual);
expected = lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function(item) {
if (shouldMatchPrimitives && !isObject(item)) {
return deepCompare(item, expression.$, comparator, false);
}
return deepCompare(item, expression, comparator, matchAgainstAnyProp);
};
return predicateFn;
}
function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
var actualType = getTypeForFilter(actual);
var expectedType = getTypeForFilter(expected);
if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
} else if (isArray(actual)) {
// In case `actual` is an array, consider it a match
// if ANY of it's items matches `expected`
return actual.some(function(item) {
return deepCompare(item, expected, comparator, matchAgainstAnyProp);
});
}
switch (actualType) {
case 'object':
var key;
if (matchAgainstAnyProp) {
for (key in actual) {
if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
return true;
}
}
return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
} else if (expectedType === 'object') {
for (key in expected) {
var expectedVal = expected[key];
if (isFunction(expectedVal) || isUndefined(expectedVal)) {
continue;
}
var matchAnyProperty = key === '$';
var actualVal = matchAnyProperty ? actual : actual[key];
if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
return false;
}
}
return true;
} else {
return comparator(actual, expected);
}
break;
case 'function':
return false;
default:
return comparator(actual, expected);
}
}
// Used for easily differentiating between `null` and actual `object`
function getTypeForFilter(val) {
return (val === null) ? 'null' : typeof val;
}
/**
* @ngdoc filter
* @name currency
* @kind function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
* @returns {string} Formatted number.
*
*
* @example
<example module="currencyExample">
<file name="index.html">
<script>
angular.module('currencyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.amount = 1234.56;
}]);
</script>
<div ng-controller="ExampleController">
<input type="number" ng-model="amount" aria-label="amount"> <br>
default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should init with 1234.56', function() {
expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
});
it('should update', function() {
if (browser.params.browser == 'safari') {
// Safari does not understand the minus key. See
// https://github.com/angular/protractor/issues/481
return;
}
element(by.model('amount')).clear();
element(by.model('amount')).sendKeys('-1234');
expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
});
</file>
</example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol, fractionSize) {
if (isUndefined(currencySymbol)) {
currencySymbol = formats.CURRENCY_SYM;
}
if (isUndefined(fractionSize)) {
fractionSize = formats.PATTERNS[1].maxFrac;
}
// if null or undefined pass it through
return (amount == null)
? amount
: formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name number
* @kind function
*
* @description
* Formats a number as text.
*
* If the input is null or undefined, it will just be returned.
* If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
* If the input is not a number an empty string is returned.
*
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<example module="numberFilterExample">
<file name="index.html">
<script>
angular.module('numberFilterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter number: <input ng-model='val'></label><br>
Default formatting: <span id='number-default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should format numbers', function() {
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
});
it('should update', function() {
element(by.model('val')).clear();
element(by.model('val')).sendKeys('3374.333');
expect(element(by.id('number-default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});
</file>
</example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
// if null or undefined pass it through
return (number == null)
? number
: formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isObject(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var isInfinity = number === Infinity;
if (!isInfinity && !isFinite(number)) return '';
var numStr = number + '',
formatedText = '',
hasExponent = false,
parts = [];
if (isInfinity) formatedText = '\u221e';
if (!isInfinity && numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
number = 0;
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!isInfinity && !hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
// safely round numbers in JS without hitting imprecisions of floating-point arithmetics
// inspired by:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var i, pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (i = 0; i < pos; i++) {
if ((pos - i) % group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i) % lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while (fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number < 1) {
formatedText = number.toFixed(fractionSize);
number = parseFloat(formatedText);
}
}
if (number === 0) {
isNegative = false;
}
parts.push(isNegative ? pattern.negPre : pattern.posPre,
formatedText,
isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim) {
num = num.substr(num.length - digits);
}
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset) {
value += offset;
}
if (value === 0 && offset == -12) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date, formats, offset) {
var zone = -1 * offset;
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function getFirstThursdayOfYear(year) {
// 0 = index of January
var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
// 4 = index of Thursday (+1 to account for 1st = 5)
// 11 = index of *next* Thursday (+1 account for 1st = 12)
return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
}
function getThursdayThisWeek(datetime) {
return new Date(datetime.getFullYear(), datetime.getMonth(),
// 4 = index of Thursday
datetime.getDate() + (4 - datetime.getDay()));
}
function weekGetter(size) {
return function(date) {
var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
thisThurs = getThursdayThisWeek(date);
var diff = +thisThurs - +firstThurs,
result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
return padNumber(result, size);
};
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
function eraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
}
function longEraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter,
ww: weekGetter(2),
w: weekGetter(1),
G: eraGetter,
GG: eraGetter,
GGG: eraGetter,
GGGG: longEraGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
NUMBER_STRING = /^\-?\d+$/;
/**
* @ngdoc filter
* @name date
* @kind function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in AM/PM, padded (01-12)
* * `'h'`: Hour in AM/PM, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'sss'`: Millisecond in second, padded (000-999)
* * `'a'`: AM/PM marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
* * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
* * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
* * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
* * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 PM)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
*
* `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
* `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
* continental US time zone abbreviations, but for general use, use a time zone offset, for
* example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
* If not specified, the timezone of the browser will be used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<example>
<file name="index.html">
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
<span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
</file>
<file name="protractor.js" type="protractor">
it('should format date', function() {
expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
</file>
</example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = toInt(match[9] + match[10]);
tzMin = toInt(match[9] + match[11]);
}
dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
var h = toInt(match[4] || 0) - tzHour;
var m = toInt(match[5] || 0) - tzMin;
var s = toInt(match[6] || 0);
var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format, timezone) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date) || !isFinite(date.getTime())) {
return date;
}
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
var dateTimezoneOffset = date.getTimezoneOffset();
if (timezone) {
dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
date = convertTimezoneToLocal(date, timezone, true);
}
forEach(parts, function(value) {
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name json
* @kind function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
* @returns {string} JSON string.
*
*
* @example
<example>
<file name="index.html">
<pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
<pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
</file>
<file name="protractor.js" type="protractor">
it('should jsonify filtered objects', function() {
expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
});
</file>
</example>
*
*/
function jsonFilter() {
return function(object, spacing) {
if (isUndefined(spacing)) {
spacing = 2;
}
return toJson(object, spacing);
};
}
/**
* @ngdoc filter
* @name lowercase
* @kind function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name uppercase
* @kind function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc filter
* @name limitTo
* @kind function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array, string or number, as specified by
* the value and sign (positive or negative) of `limit`. If a number is used as input, it is
* converted to a string.
*
* @param {Array|string|number} input Source array, string or number to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
* the input will be returned unchanged.
* @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
* indicates an offset from the end of `input`. Defaults to `0`.
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<example module="limitToExample">
<file name="index.html">
<script>
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.longNumber = 2345432342;
$scope.numLimit = 3;
$scope.letterLimit = 3;
$scope.longNumberLimit = 3;
}]);
</script>
<div ng-controller="ExampleController">
<label>
Limit {{numbers}} to:
<input type="number" step="1" ng-model="numLimit">
</label>
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
<label>
Limit {{letters}} to:
<input type="number" step="1" ng-model="letterLimit">
</label>
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
<label>
Limit {{longNumber}} to:
<input type="number" step="1" ng-model="longNumberLimit">
</label>
<p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
</div>
</file>
<file name="protractor.js" type="protractor">
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
// There is a bug in safari and protractor that doesn't like the minus key
// it('should update the output when -3 is entered', function() {
// numLimitInput.clear();
// numLimitInput.sendKeys('-3');
// letterLimitInput.clear();
// letterLimitInput.sendKeys('-3');
// longNumberLimitInput.clear();
// longNumberLimitInput.sendKeys('-3');
// expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
// expect(limitedLetters.getText()).toEqual('Output letters: ghi');
// expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
// });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
});
</file>
</example>
*/
function limitToFilter() {
return function(input, limit, begin) {
if (Math.abs(Number(limit)) === Infinity) {
limit = Number(limit);
} else {
limit = toInt(limit);
}
if (isNaN(limit)) return input;
if (isNumber(input)) input = input.toString();
if (!isArray(input) && !isString(input)) return input;
begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
if (limit >= 0) {
return input.slice(begin, begin + limit);
} else {
if (begin === 0) {
return input.slice(limit, input.length);
} else {
return input.slice(Math.max(0, begin + limit), begin);
}
}
};
}
/**
* @ngdoc filter
* @name orderBy
* @kind function
*
* @description
* Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
* for strings and numerically for numbers. Note: if you notice numbers are not being sorted
* as expected, make sure they are actually being saved as numbers and not strings.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `===`, `>` operator.
* - `string`: An Angular expression. The result of this expression is used to compare elements
* (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
* 3 first characters of a property called `name`). The result of a constant expression
* is interpreted as a property name to be used in comparisons (for example `"special name"`
* to sort object by the value of their `special name` property). An expression can be
* optionally prefixed with `+` or `-` to control ascending or descending sort order
* (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
* element itself is used to compare where sorting.
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* If the predicate is missing or empty then it defaults to `'+'`.
*
* @param {boolean=} reverse Reverse the order of the array.
* @returns {Array} Sorted copy of the source array.
*
*
* @example
* The example below demonstrates a simple ngRepeat, where the data is sorted
* by age in descending order (predicate is set to `'-age'`).
* `reverse` is not set, which means it defaults to `false`.
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
}]);
</script>
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'-age'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* The predicate and reverse parameters can be controlled dynamically through scope properties,
* as shown in the next example.
* @example
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
$scope.predicate = 'age';
$scope.reverse = true;
$scope.order = function(predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
}]);
</script>
<style type="text/css">
.sortorder:after {
content: '\25b2';
}
.sortorder.reverse:after {
content: '\25bc';
}
</style>
<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th>
<a href="" ng-click="order('name')">Name</a>
<span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
</th>
<th>
<a href="" ng-click="order('phone')">Phone Number</a>
<span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
</th>
<th>
<a href="" ng-click="order('age')">Age</a>
<span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
* filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
* desired parameters.
*
* Example:
*
* @example
<example module="orderByExample">
<file name="index.html">
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
(<a href="" ng-click="order('-name',false)">^</a>)</th>
<th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
<th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
</tr>
<tr ng-repeat="friend in friends">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
<file name="script.js">
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
var orderBy = $filter('orderBy');
$scope.friends = [
{ name: 'John', phone: '555-1212', age: 10 },
{ name: 'Mary', phone: '555-9876', age: 19 },
{ name: 'Mike', phone: '555-4321', age: 21 },
{ name: 'Adam', phone: '555-5678', age: 35 },
{ name: 'Julie', phone: '555-8765', age: 29 }
];
$scope.order = function(predicate, reverse) {
$scope.friends = orderBy($scope.friends, predicate, reverse);
};
$scope.order('-age',false);
}]);
</file>
</example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
return function(array, sortPredicate, reverseOrder) {
if (!(isArrayLike(array))) return array;
if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
if (sortPredicate.length === 0) { sortPredicate = ['+']; }
var predicates = processPredicates(sortPredicate, reverseOrder);
// Add a predicate at the end that evaluates to the element index. This makes the
// sort stable as it works as a tie-breaker when all the input predicates cannot
// distinguish between two elements.
predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
// The next three lines are a version of a Swartzian Transform idiom from Perl
// (sometimes called the Decorate-Sort-Undecorate idiom)
// See https://en.wikipedia.org/wiki/Schwartzian_transform
var compareValues = Array.prototype.map.call(array, getComparisonObject);
compareValues.sort(doComparison);
array = compareValues.map(function(item) { return item.value; });
return array;
function getComparisonObject(value, index) {
return {
value: value,
predicateValues: predicates.map(function(predicate) {
return getPredicateValue(predicate.get(value), index);
})
};
}
function doComparison(v1, v2) {
var result = 0;
for (var index=0, length = predicates.length; index < length; ++index) {
result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
if (result) break;
}
return result;
}
};
function processPredicates(sortPredicate, reverseOrder) {
reverseOrder = reverseOrder ? -1 : 1;
return sortPredicate.map(function(predicate) {
var descending = 1, get = identity;
if (isFunction(predicate)) {
get = predicate;
} else if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-' ? -1 : 1;
predicate = predicate.substring(1);
}
if (predicate !== '') {
get = $parse(predicate);
if (get.constant) {
var key = get();
get = function(value) { return value[key]; };
}
}
}
return { get: get, descending: descending * reverseOrder };
});
}
function isPrimitive(value) {
switch (typeof value) {
case 'number': /* falls through */
case 'boolean': /* falls through */
case 'string':
return true;
default:
return false;
}
}
function objectValue(value, index) {
// If `valueOf` is a valid function use that
if (typeof value.valueOf === 'function') {
value = value.valueOf();
if (isPrimitive(value)) return value;
}
// If `toString` is a valid function and not the one from `Object.prototype` use that
if (hasCustomToString(value)) {
value = value.toString();
if (isPrimitive(value)) return value;
}
// We have a basic object so we use the position of the object in the collection
return index;
}
function getPredicateValue(value, index) {
var type = typeof value;
if (value === null) {
type = 'string';
value = 'null';
} else if (type === 'string') {
value = value.toLowerCase();
} else if (type === 'object') {
value = objectValue(value, index);
}
return { value: value, type: type };
}
function compare(v1, v2) {
var result = 0;
if (v1.type === v2.type) {
if (v1.value !== v2.value) {
result = v1.value < v2.value ? -1 : 1;
}
} else {
result = v1.type < v2.type ? -1 : 1;
}
return result;
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
};
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name a
* @restrict E
*
* @description
* Modifies the default behavior of the html A tag so that the default action is prevented when
* the href attribute is empty.
*
* This change permits the easy creation of action links with the `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="list.addItem()">Add Item</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (!attr.href && !attr.xlinkHref) {
return function(scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') return;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
};
}
}
});
/**
* @ngdoc directive
* @name ngHref
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in an href attribute will
* make the link go to the wrong URL if the user clicks it before
* Angular has a chance to replace the `{{hash}}` markup with its
* value. Until Angular replaces the markup the link will be broken
* and will most likely return a 404 error. The `ngHref` directive
* solves this problem.
*
* The wrong way to write it:
* ```html
* <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* The correct way to write it:
* ```html
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
* in links and their different behaviors:
<example>
<file name="index.html">
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</file>
<file name="protractor.js" type="protractor">
it('should execute ng-click but not reload when href without value', function() {
element(by.id('link-1')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('1');
expect(element(by.id('link-1')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when href empty string', function() {
element(by.id('link-2')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('2');
expect(element(by.id('link-2')).getAttribute('href')).toBe('');
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
element(by.id('link-3')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/123$/);
});
}, 5000, 'page should navigate to /123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element(by.id('link-4')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('4');
expect(element(by.id('link-4')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element(by.id('link-5')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('5');
expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
});
it('should only change url when only ng-href', function() {
element(by.model('value')).clear();
element(by.model('value')).sendKeys('6');
expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
element(by.id('link-6')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/6$/);
});
}, 5000, 'page should navigate to /6');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSrc
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
* ```
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngSrcset
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrcset` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
* ```
*
* @element IMG
* @param {template} ngSrcset any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngDisabled
* @restrict A
* @priority 100
*
* @description
*
* This directive sets the `disabled` attribute on the element if the
* {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
*
* A special directive is necessary because we cannot use interpolation inside the `disabled`
* attribute. The following example would make the button enabled on Chrome/Firefox
* but not on older IEs:
*
* ```html
* <!-- See below for an example of ng-disabled being used correctly -->
* <div ng-init="isDisabled = false">
* <button disabled="{{isDisabled}}">Disabled</button>
* </div>
* ```
*
* This is because the HTML specification does not require browsers to preserve the values of
* boolean attributes such as `disabled` (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
*
* @example
<example>
<file name="index.html">
<label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</file>
<file name="protractor.js" type="protractor">
it('should toggle button', function() {
expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
* then the `disabled` attribute will be set on the element
*/
/**
* @ngdoc directive
* @name ngChecked
* @restrict A
* @priority 100
*
* @description
* Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
*
* Note that this directive should not be used together with {@link ngModel `ngModel`},
* as this can lead to unexpected behavior.
*
* ### Why do we need `ngChecked`?
*
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as checked. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngChecked` directive solves this problem for the `checked` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
<input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
</file>
<file name="protractor.js" type="protractor">
it('should check both checkBoxes', function() {
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
element(by.model('master')).click();
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
* then the `checked` attribute will be set on the element
*/
/**
* @ngdoc directive
* @name ngReadonly
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as readonly. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngReadonly` directive solves this problem for the `readonly` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
<input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
</file>
<file name="protractor.js" type="protractor">
it('should toggle readonly attr', function() {
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
* then special attribute "readonly" will be set on the element
*/
/**
* @ngdoc directive
* @name ngSelected
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as selected. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngSelected` directive solves this problem for the `selected` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
*
* @example
<example>
<file name="index.html">
<label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
<select aria-label="ngSelected demo">
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</file>
<file name="protractor.js" type="protractor">
it('should select Greetings!', function() {
expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
element(by.model('selected')).click();
expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
});
</file>
</example>
*
* @element OPTION
* @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
* then special attribute "selected" will be set on the element
*/
/**
* @ngdoc directive
* @name ngOpen
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as open. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngOpen` directive solves this problem for the `open` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
<label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
<details id="details" ng-open="open">
<summary>Show/Hide me</summary>
</details>
</file>
<file name="protractor.js" type="protractor">
it('should toggle open', function() {
expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
element(by.model('open')).click();
expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
});
</file>
</example>
*
* @element DETAILS
* @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
* then special attribute "open" will be set on the element
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;
function defaultLinkFn(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
}
var normalized = directiveNormalize('ng-' + attrName);
var linkFn = defaultLinkFn;
if (propName === 'checked') {
linkFn = function(scope, element, attr) {
// ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
if (attr.ngModel !== attr[normalized]) {
defaultLinkFn(scope, element, attr);
}
};
}
ngAttributeAliasDirectives[normalized] = function() {
return {
restrict: 'A',
priority: 100,
link: linkFn
};
};
});
// aliased input attrs are evaluated
forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
ngAttributeAliasDirectives[ngAttr] = function() {
return {
priority: 100,
link: function(scope, element, attr) {
//special case ngPattern when a literal regular expression value
//is used as the expression (this way we don't have to watch anything).
if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
if (match) {
attr.$set("ngPattern", new RegExp(match[1], match[2]));
return;
}
}
scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
attr.$set(ngAttr, value);
});
}
};
};
});
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
var propName = attrName,
name = attrName;
if (attrName === 'href' &&
toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
name = 'xlinkHref';
attr.$attr[name] = 'xlink:href';
propName = null;
}
attr.$observe(normalized, function(value) {
if (!value) {
if (attrName === 'href') {
attr.$set(name, null);
}
return;
}
attr.$set(name, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie && propName) element.prop(propName, attr[name]);
});
}
};
};
});
/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
*/
var nullFormCtrl = {
$addControl: noop,
$$renameControl: nullFormRenameControl,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop,
$setPristine: noop,
$setSubmitted: noop
},
SUBMITTED_CLASS = 'ng-submitted';
function nullFormRenameControl(control, name) {
control.$name = name;
}
/**
* @ngdoc type
* @name form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
* @property {boolean} $submitted True if user has submitted the form even if its invalid.
*
* @property {Object} $error Is an object hash, containing references to controls or
* forms with failing validators, where:
*
* - keys are validation tokens (error names),
* - values are arrays of controls or forms that have a failing validator for given error name.
*
* Built-in validation tokens:
*
* - `email`
* - `max`
* - `maxlength`
* - `min`
* - `minlength`
* - `number`
* - `pattern`
* - `required`
* - `url`
* - `date`
* - `datetimelocal`
* - `time`
* - `week`
* - `month`
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as the state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
function FormController(element, attrs, $scope, $animate, $interpolate) {
var form = this,
controls = [];
var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
// init state
form.$error = {};
form.$$success = {};
form.$pending = undefined;
form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
form.$submitted = false;
parentForm.$addControl(form);
/**
* @ngdoc method
* @name form.FormController#$rollbackViewValue
*
* @description
* Rollback all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is typically needed by the reset button of
* a form that uses `ng-model-options` to pend updates.
*/
form.$rollbackViewValue = function() {
forEach(controls, function(control) {
control.$rollbackViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$commitViewValue
*
* @description
* Commit all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
form.$commitViewValue = function() {
forEach(controls, function(control) {
control.$commitViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$addControl
*
* @description
* Register a control with the form.
*
* Input elements using ngModelController do this automatically when they are linked.
*/
form.$addControl = function(control) {
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
// and not added to the scope. Now we throw an error.
assertNotHasOwnProperty(control.$name, 'input');
controls.push(control);
if (control.$name) {
form[control.$name] = control;
}
};
// Private API: rename a form control
form.$$renameControl = function(control, newName) {
var oldName = control.$name;
if (form[oldName] === control) {
delete form[oldName];
}
form[newName] = control;
control.$name = newName;
};
/**
* @ngdoc method
* @name form.FormController#$removeControl
*
* @description
* Deregister a control from the form.
*
* Input elements using ngModelController do this automatically when they are destroyed.
*/
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(form.$pending, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$error, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$$success, function(value, name) {
form.$setValidity(name, null, control);
});
arrayRemove(controls, control);
};
/**
* @ngdoc method
* @name form.FormController#$setValidity
*
* @description
* Sets the validity of a form control.
*
* This method will also propagate to parent forms.
*/
addSetValidityMethod({
ctrl: this,
$element: element,
set: function(object, property, controller) {
var list = object[property];
if (!list) {
object[property] = [controller];
} else {
var index = list.indexOf(controller);
if (index === -1) {
list.push(controller);
}
}
},
unset: function(object, property, controller) {
var list = object[property];
if (!list) {
return;
}
arrayRemove(list, controller);
if (list.length === 0) {
delete object[property];
}
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name form.FormController#$setDirty
*
* @description
* Sets the form to a dirty state.
*
* This method can be called to add the 'ng-dirty' class and set the form to a dirty
* state (ng-dirty class). This method will also propagate to parent forms.
*/
form.$setDirty = function() {
$animate.removeClass(element, PRISTINE_CLASS);
$animate.addClass(element, DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name form.FormController#$setPristine
*
* @description
* Sets the form to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine
* state (ng-pristine class). This method will also propagate to all the controls contained
* in this form.
*
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
* saving or resetting it.
*/
form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};
/**
* @ngdoc method
* @name form.FormController#$setUntouched
*
* @description
* Sets the form to its untouched state.
*
* This method can be called to remove the 'ng-touched' class and set the form controls to their
* untouched state (ng-untouched class).
*
* Setting a form controls back to their untouched state is often useful when setting the form
* back to its pristine state.
*/
form.$setUntouched = function() {
forEach(controls, function(control) {
control.$setUntouched();
});
};
/**
* @ngdoc method
* @name form.FormController#$setSubmitted
*
* @description
* Sets the form to its submitted state.
*/
form.$setSubmitted = function() {
$animate.addClass(element, SUBMITTED_CLASS);
form.$submitted = true;
parentForm.$setSubmitted();
};
}
/**
* @ngdoc directive
* @name ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* Note: the purpose of `ngForm` is to group controls,
* but not to be a replacement for the `<form>` tag with all of its capabilities
* (e.g. posting to the server, ...).
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name form
* @restrict E
*
* @description
* Directive that instantiates
* {@link form.FormController FormController}.
*
* If the `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In Angular, forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
* Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
* `<form>` but can be nested. This allows you to have nested forms, which is very useful when
* using Angular validation directives in forms that are dynamically generated using the
* {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
* attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
* `ngForm` directive and nest these in an outer `form` element.
*
*
* # CSS classes
* - `ng-valid` is set if the form is valid.
* - `ng-invalid` is set if the form is invalid.
* - `ng-pristine` is set if the form is pristine.
* - `ng-dirty` is set if the form is dirty.
* - `ng-submitted` is set if the form was submitted.
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
*
* # Submitting a form and preventing the default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in an application-specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
* or {@link ng.directive:ngClick ngClick} directives.
* This is because of the following form submission rules in the HTML specification:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
* submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* ## Animation Hooks
*
* Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
* These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
* other validations that are performed within the form. Animations in ngForm are similar to how
* they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
* as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style a form element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-form {
* transition:0.5s linear all;
* background: white;
* }
* .my-form.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
<example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
<file name="index.html">
<script>
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
</script>
<style>
.my-form {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-form.ng-invalid {
background: red;
}
</style>
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<code>userType = {{userType}}</code><br>
<code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
<code>myForm.input.$error = {{myForm.input.$error}}</code><br>
<code>myForm.$valid = {{myForm.$valid}}</code><br>
<code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should initialize to model', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
expect(userType.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
var userInput = element(by.model('userType'));
userInput.clear();
userInput.sendKeys('');
expect(userType.getText()).toEqual('userType =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', '$parse', function($timeout, $parse) {
var formDirective = {
name: 'form',
restrict: isNgForm ? 'EAC' : 'E',
controller: FormController,
compile: function ngFormCompile(formElement, attr) {
// Setup initial state of the control
formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
return {
pre: function ngFormPreLink(scope, formElement, attr, controller) {
// if `action` attr is not present on the form, prevent the default action (submission)
if (!('action' in attr)) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.on('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
}, 0, false);
});
}
var parentFormCtrl = controller.$$parentForm;
var setter = nameAttr ? getSetter(controller.$name) : noop;
if (nameAttr) {
setter(scope, controller);
attr.$observe(nameAttr, function(newValue) {
if (controller.$name === newValue) return;
setter(scope, undefined);
parentFormCtrl.$$renameControl(controller, newValue);
setter = getSetter(controller.$name);
setter(scope, controller);
});
}
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
setter(scope, undefined);
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
};
}
};
return formDirective;
function getSetter(expression) {
if (expression === '') {
//create an assignable expression, so forms with an empty name can be renamed later
return $parse('this[""]').assign;
}
return $parse(expression).assign || noop;
}
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
/* global VALID_CLASS: false,
INVALID_CLASS: false,
PRISTINE_CLASS: false,
DIRTY_CLASS: false,
UNTOUCHED_CLASS: false,
TOUCHED_CLASS: false,
ngModelMinErr: false,
*/
// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var inputType = {
/**
* @ngdoc input
* @name input[text]
*
* @description
* Standard HTML text input with angular data binding, inherited by most of the `input` elements.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
text: 'guest',
word: /^\s*\w*\s*$/
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Single word:
<input type="text" name="input" ng-model="example.text"
ng-pattern="example.word" required ng-trim="false">
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
</div>
<tt>text = {{example.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('example.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if multi word', function() {
input.clear();
input.sendKeys('hello world');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'text': textInputType,
/**
* @ngdoc input
* @name input[date]
*
* @description
* Input with date validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
* date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO date string (yyyy-MM-dd).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO date string (yyyy-MM-dd).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="date-input-directive" module="dateInputExample">
<file name="index.html">
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 22)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date in 2013:</label>
<input type="date" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.date">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10-22');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'date': createDateInputType('date', DATE_REGEXP,
createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
'yyyy-MM-dd'),
/**
* @ngdoc input
* @name input[datetime-local]
*
* @description
* Input with datetime validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="datetimelocal-input-directive" module="dateExample">
<file name="index.html">
<script>
angular.module('dateExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2010, 11, 28, 14, 57)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a date between in 2013:</label>
<input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.datetimelocal">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2010-12-28T14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01T23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[time]
*
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
* Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="time-input-directive" module="timeExample">
<file name="index.html">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 57, 0)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a between 8am and 5pm:</label>
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'time': createDateInputType('time', TIME_REGEXP,
createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
'HH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[week]
*
* @description
* Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO week format (yyyy-W##).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO week format (yyyy-W##).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="week-input-directive" module="weekExample">
<file name="index.html">
<script>
angular.module('weekExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 0, 3)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label>Pick a date between in 2013:
<input id="exampleInput" type="week" name="input" ng-model="example.value"
placeholder="YYYY-W##" min="2012-W32"
max="2013-W52" required />
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.week">
Not a valid date!</span>
</div>
<tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-W01');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-W01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
/**
* @ngdoc input
* @name input[month]
*
* @description
* Input with month validation and transformation. In browsers that do not yet support
* the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* month format (yyyy-MM), for example: `2009-01`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
* If the model is not set to the first of the month, the next view to model update will set it
* to the first of the month.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
* a valid ISO month format (yyyy-MM).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
* be a valid ISO month format (yyyy-MM).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="month-input-directive" module="monthExample">
<file name="index.html">
<script>
angular.module('monthExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 1)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
<label for="exampleInput">Pick a month in 2013:</label>
<input id="exampleInput" type="month" name="input" ng-model="example.value"
placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.month">
Not a valid month!</span>
</div>
<tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'month': createDateInputType('month', MONTH_REGEXP,
createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
'yyyy-MM'),
/**
* @ngdoc input
* @name input[number]
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* <div class="alert alert-warning">
* The model must always be of type `number` otherwise Angular will throw an error.
* Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
* error docs for more information and an example of how to convert your model if necessary.
* </div>
*
* ## Issues with HTML5 constraint validation
*
* In browsers that follow the
* [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
* `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
* If a non-number is entered in the input, the browser will report the value as an empty string,
* which means the view / model values in `ngModel` and subsequently the scope value
* will also be an empty string.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
value: 12
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Number:
<input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
</div>
<tt>value = {{example.value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
it('should initialize to model', function() {
expect(value.getText()).toContain('12');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if over max', function() {
input.clear();
input.sendKeys('123');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'number': numberInputType,
/**
* @ngdoc input
* @name input[url]
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* <div class="alert alert-warning">
* **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
* used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
* the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.url = {
text: 'http://google.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>URL:
<input type="url" name="input" ng-model="url.text" required>
<label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
</div>
<tt>text = {{url.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('url.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('url.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('http://google.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not url', function() {
input.clear();
input.sendKeys('box');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'url': urlInputType,
/**
* @ngdoc input
* @name input[email]
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* <div class="alert alert-warning">
* **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
* used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
* use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.email = {
text: '[email protected]'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Email:
<input type="email" name="input" ng-model="email.text" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
</div>
<tt>text = {{email.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('email.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('email.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('[email protected]');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not email', function() {
input.clear();
input.sendKeys('xxx');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'email': emailInputType,
/**
* @ngdoc input
* @name input[radio]
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the `ngModel` expression should be set when selected.
* Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
* too. Use `ngValue` if you need complex models (`number`, `object`, ...).
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
* is selected. Should be used instead of the `value` attribute if you need
* a non-string `ngModel` (`boolean`, `array`, ...).
*
* @example
<example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>
<input type="radio" ng-model="color.name" value="red">
Red
</label><br/>
<label>
<input type="radio" ng-model="color.name" ng-value="specialValue">
Green
</label><br/>
<label>
<input type="radio" ng-model="color.name" value="blue">
Blue
</label><br/>
<tt>color = {{color.name | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var color = element(by.binding('color.name'));
expect(color.getText()).toContain('blue');
element.all(by.model('color.name')).get(0).click();
expect(color.getText()).toContain('red');
});
</file>
</example>
*/
'radio': radioInputType,
/**
* @ngdoc input
* @name input[checkbox]
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ngTrueValue The value to which the expression should be set when selected.
* @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.checkboxModel = {
value1 : true,
value2 : 'YES'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<label>Value1:
<input type="checkbox" ng-model="checkboxModel.value1">
</label><br/>
<label>Value2:
<input type="checkbox" ng-model="checkboxModel.value2"
ng-true-value="'YES'" ng-false-value="'NO'">
</label><br/>
<tt>value1 = {{checkboxModel.value1}}</tt><br/>
<tt>value2 = {{checkboxModel.value2}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var value1 = element(by.binding('checkboxModel.value1'));
var value2 = element(by.binding('checkboxModel.value2'));
expect(value1.getText()).toContain('true');
expect(value2.getText()).toContain('YES');
element(by.model('checkboxModel.value1')).click();
element(by.model('checkboxModel.value2')).click();
expect(value1.getText()).toContain('false');
expect(value2.getText()).toContain('NO');
});
</file>
</example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop,
'file': noop
};
function stringBasedInputType(ctrl) {
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? value : value.toString();
});
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
}
function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var type = lowercase(element[0].type);
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
var composing = false;
element.on('compositionstart', function(data) {
composing = true;
});
element.on('compositionend', function() {
composing = false;
listener();
});
}
var listener = function(ev) {
if (timeout) {
$browser.defer.cancel(timeout);
timeout = null;
}
if (composing) return;
var value = element.val(),
event = ev && ev.type;
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// If input type is 'password', the value is never trimmed
if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
// If a control is suffering from bad input (due to native validators), browsers discard its
// value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
// control's value is the same empty value twice in a row.
if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
ctrl.$setViewValue(value, event);
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function(ev, input, origValue) {
if (!timeout) {
timeout = $browser.defer(function() {
timeout = null;
if (!input || input.value !== origValue) {
listener(ev);
}
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event, this, this.value);
});
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
// if user paste into input using mouse on older browser
// or form autocomplete on newer browser, we need "change" event to catch it
element.on('change', listener);
ctrl.$render = function() {
// Workaround for Firefox validation #12102.
var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
if (element.val() !== value) {
element.val(value);
}
};
}
function weekParser(isoWeek, existingDate) {
if (isDate(isoWeek)) {
return isoWeek;
}
if (isString(isoWeek)) {
WEEK_REGEXP.lastIndex = 0;
var parts = WEEK_REGEXP.exec(isoWeek);
if (parts) {
var year = +parts[1],
week = +parts[2],
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
firstThurs = getFirstThursdayOfYear(year),
addDays = (week - 1) * 7;
if (existingDate) {
hours = existingDate.getHours();
minutes = existingDate.getMinutes();
seconds = existingDate.getSeconds();
milliseconds = existingDate.getMilliseconds();
}
return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
}
}
return NaN;
}
function createDateParser(regexp, mapping) {
return function(iso, date) {
var parts, map;
if (isDate(iso)) {
return iso;
}
if (isString(iso)) {
// When a date is JSON'ified to wraps itself inside of an extra
// set of double quotes. This makes the date parsing code unable
// to match the date string and parse it as a date.
if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
iso = iso.substring(1, iso.length - 1);
}
if (ISO_DATE_REGEXP.test(iso)) {
return new Date(iso);
}
regexp.lastIndex = 0;
parts = regexp.exec(iso);
if (parts) {
parts.shift();
if (date) {
map = {
yyyy: date.getFullYear(),
MM: date.getMonth() + 1,
dd: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds(),
sss: date.getMilliseconds() / 1000
};
} else {
map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
}
forEach(parts, function(part, index) {
if (index < mapping.length) {
map[mapping[index]] = +part;
}
});
return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
}
}
return NaN;
};
}
function createDateInputType(type, regexp, parseDate, format) {
return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
var previousDate;
ctrl.$$parserName = type;
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (regexp.test(value)) {
// Note: We cannot read ctrl.$modelValue, as there might be a different
// parser/formatter in the processing chain so that the model
// contains some different data format!
var parsedDate = parseDate(value, previousDate);
if (timezone) {
parsedDate = convertTimezoneToLocal(parsedDate, timezone);
}
return parsedDate;
}
return undefined;
});
ctrl.$formatters.push(function(value) {
if (value && !isDate(value)) {
throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
}
if (isValidDate(value)) {
previousDate = value;
if (previousDate && timezone) {
previousDate = convertTimezoneToLocal(previousDate, timezone, true);
}
return $filter('date')(value, format, timezone);
} else {
previousDate = null;
return '';
}
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
function isValidDate(value) {
// Invalid Date: getTime() returns NaN
return value && !(value.getTime && value.getTime() !== value.getTime());
}
function parseObservedDateValue(val) {
return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
}
};
}
function badInputChecker(scope, element, attr, ctrl) {
var node = element[0];
var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
if (nativeValidation) {
ctrl.$parsers.push(function(value) {
var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
// Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
// - also sets validity.badInput (should only be validity.typeMismatch).
// - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
// - can ignore this case as we can still read out the erroneous email...
return validity.badInput && !validity.typeMismatch ? undefined : value;
});
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (NUMBER_REGEXP.test(value)) return parseFloat(value);
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isNumber(value)) {
throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
}
value = value.toString();
}
return value;
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
attr.$observe('min', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
minVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
attr.$observe('max', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'url';
ctrl.$validators.url = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'email';
ctrl.$validators.email = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
var listener = function(ev) {
if (element[0].checked) {
ctrl.$setViewValue(attr.value, ev && ev.type);
}
};
element.on('click', listener);
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function parseConstantExpr($parse, context, name, expression, fallback) {
var parseFn;
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
}
return fallback;
}
function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
// This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
// it to a boolean.
ctrl.$isEmpty = function(value) {
return value === false;
};
ctrl.$formatters.push(function(value) {
return equals(value, trueValue);
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*/
/**
* @ngdoc directive
* @name input
* @restrict E
*
* @description
* HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
* input state control, and validation.
* Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
*
* <div class="alert alert-warning">
* **Note:** Not every feature offered is available for all input types.
* Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object, then this is used directly.
* If the expression evaluates to a string, then it will be converted to a RegExp
* after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
* `new RegExp('^abc$')`.<br />
* **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
* start at the index of the last search's match, thus not taking the whole input value into
* account.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="input-directive" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
<label>
User name:
<input type="text" name="userName" ng-model="user.name" required>
</label>
<div role="alert">
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span>
</div>
<label>
Last name:
<input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
</label>
<div role="alert">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span>
</div>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
</div>
</file>
<file name="protractor.js" type="protractor">
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
</file>
</example>
*/
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
$browser, $filter, $parse);
}
}
}
};
}];
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ngValue
*
* @description
* Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
* so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
* the bound value.
*
* `ngValue` is useful when dynamically generating lists of radio buttons using
* {@link ngRepeat `ngRepeat`}, as shown below.
*
* Likewise, `ngValue` can be used to generate `<option>` elements for
* the {@link select `select`} element. In that case however, only strings are supported
* for the `value `attribute, so the resulting `ngModel` will always be a string.
* Support for `select` models with non-string values is available via `ngOptions`.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
<example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>
</file>
<file name="protractor.js" type="protractor">
var favorite = element(by.binding('my.favorite'));
it('should initialize to model', function() {
expect(favorite.getText()).toContain('unicorns');
});
it('should bind the values to the inputs', function() {
element.all(by.model('my.favorite')).get(0).click();
expect(favorite.getText()).toContain('pizza');
});
</file>
</example>
*/
var ngValueDirective = function() {
return {
restrict: 'A',
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ngBind
* @restrict AC
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
</script>
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var nameInput = element(by.model('name'));
expect(element(by.binding('name')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('name')).getText()).toBe('world');
});
</file>
</example>
*/
var ngBindDirective = ['$compile', function($compile) {
return {
restrict: 'AC',
compile: function ngBindCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBind);
element = element[0];
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}]);
</script>
<div ng-controller="ExampleController">
<label>Salutation: <input type="text" ng-model="salutation"></label><br>
<label>Name: <input type="text" ng-model="name"></label><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var salutationElem = element(by.binding('salutation'));
var salutationInput = element(by.model('salutation'));
var nameInput = element(by.model('name'));
expect(salutationElem.getText()).toBe('Hello World!');
salutationInput.clear();
salutationInput.sendKeys('Greetings');
nameInput.clear();
nameInput.sendKeys('user');
expect(salutationElem.getText()).toBe('Greetings user!');
});
</file>
</example>
*/
var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
return {
compile: function ngBindTemplateCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindTemplateLink(scope, element, attr) {
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
$compile.$$addBindingInfo(element, interpolateFn.expressions);
element = element[0];
attr.$observe('ngBindTemplate', function(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindHtml
*
* @description
* Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
* the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
* To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
* ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
* in your module's dependencies, you need to include "angular-sanitize.js" in your application.
*
* You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
<example module="bindHtmlExample" deps="angular-sanitize.js">
<file name="index.html">
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</file>
<file name="script.js">
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind-html', function() {
expect(element(by.binding('myHTML')).getText()).toBe(
'I am an HTMLstring with links! and other stuff');
});
</file>
</example>
*/
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBindHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-evaluate the expr because we want a TrustedValueHolderType
// for $sce, not a string
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngChange
*
* @description
* Evaluate the given expression when the user changes the input.
* The expression is evaluated immediately, unlike the JavaScript onchange event
* which only triggers at the end of a change (usually, when the user leaves the
* form element or presses the return key).
*
* The `ngChange` expression is only evaluated when a change in the input value causes
* a new value to be committed to the model.
*
* It will not be evaluated:
* * if the value returned from the `$parsers` transformation pipeline has not changed
* * if the input has continued to be invalid since the model will stay `null`
* * if the model is changed programmatically and not by a change to the input value
*
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
* in input value.
*
* @example
* <example name="ngChange-directive" module="changeExample">
* <file name="index.html">
* <script>
* angular.module('changeExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }]);
* </script>
* <div ng-controller="ExampleController">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* <tt>debug = {{confirmed}}</tt><br/>
* <tt>counter = {{counter}}</tt><br/>
* </div>
* </file>
* <file name="protractor.js" type="protractor">
* var counter = element(by.binding('counter'));
* var debug = element(by.binding('confirmed'));
*
* it('should evaluate the expression if changing from view', function() {
* expect(counter.getText()).toContain('0');
*
* element(by.id('ng-change-example1')).click();
*
* expect(counter.getText()).toContain('1');
* expect(debug.getText()).toContain('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element(by.id('ng-change-example2')).click();
* expect(counter.getText()).toContain('0');
* expect(debug.getText()).toContain('true');
* });
* </file>
* </example>
*/
var ngChangeDirective = valueFn({
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
function classDirective(name, selector) {
name = 'ngClass' + name;
return ['$animate', function($animate) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
ngClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
// jshint bitwise: false
var mod = $index & 1;
if (mod !== (old$index & 1)) {
var classes = arrayClasses(scope.$eval(attr[name]));
mod === selector ?
addClasses(classes) :
removeClasses(classes);
}
});
}
function addClasses(classes) {
var newClasses = digestClassCounts(classes, 1);
attr.$addClass(newClasses);
}
function removeClasses(classes) {
var newClasses = digestClassCounts(classes, -1);
attr.$removeClass(newClasses);
}
function digestClassCounts(classes, count) {
// Use createMap() to prevent class assumptions involving property
// names in Object.prototype
var classCounts = element.data('$classCounts') || createMap();
var classesToUpdate = [];
forEach(classes, function(className) {
if (count > 0 || classCounts[className]) {
classCounts[className] = (classCounts[className] || 0) + count;
if (classCounts[className] === +(count > 0)) {
classesToUpdate.push(className);
}
}
});
element.data('$classCounts', classCounts);
return classesToUpdate.join(' ');
}
function updateClasses(oldClasses, newClasses) {
var toAdd = arrayDifference(newClasses, oldClasses);
var toRemove = arrayDifference(oldClasses, newClasses);
toAdd = digestClassCounts(toAdd, 1);
toRemove = digestClassCounts(toRemove, -1);
if (toAdd && toAdd.length) {
$animate.addClass(element, toAdd);
}
if (toRemove && toRemove.length) {
$animate.removeClass(element, toRemove);
}
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
var newClasses = arrayClasses(newVal || []);
if (!oldVal) {
addClasses(newClasses);
} else if (!equals(newVal,oldVal)) {
var oldClasses = arrayClasses(oldVal);
updateClasses(oldClasses, newClasses);
}
}
oldVal = shallowCopy(newVal);
}
}
};
function arrayDifference(tokens1, tokens2) {
var values = [];
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
}
function arrayClasses(classVal) {
var classes = [];
if (isArray(classVal)) {
forEach(classVal, function(v) {
classes = classes.concat(arrayClasses(v));
});
return classes;
} else if (isString(classVal)) {
return classVal.split(' ');
} else if (isObject(classVal)) {
forEach(classVal, function(v, k) {
if (v) {
classes = classes.concat(k.split(' '));
}
});
return classes;
}
return classVal;
}
}];
}
/**
* @ngdoc directive
* @name ngClass
* @restrict AC
*
* @description
* The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
* an expression that represents all classes to be added.
*
* The directive operates in three different ways, depending on which of three types the expression
* evaluates to:
*
* 1. If the expression evaluates to a string, the string should be one or more space-delimited class
* names.
*
* 2. If the expression evaluates to an object, then for each key-value pair of the
* object with a truthy value the corresponding key is used as a class name.
*
* 3. If the expression evaluates to an array, each element of the array should either be a string as in
* type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
* to give you more control over what CSS classes appear. See the code below for an example of this.
*
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then are the
* new classes added.
*
* @animations
* **add** - happens just before the class is applied to the elements
*
* **remove** - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demonstrates basic bindings via ngClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
<label>
<input type="checkbox" ng-model="deleted">
deleted (apply "strike" class)
</label><br>
<label>
<input type="checkbox" ng-model="important">
important (apply "bold" class)
</label><br>
<label>
<input type="checkbox" ng-model="error">
error (apply "has-error" class)
</label>
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style"
placeholder="Type: bold strike red" aria-label="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
<input ng-model="style2"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
<input ng-model="style3"
placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
<hr>
<p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
<input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
<label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
.has-error {
color: red;
background-color: yellow;
}
.orange {
color: orange;
}
</file>
<file name="protractor.js" type="protractor">
var ps = element.all(by.css('p'));
it('should let you toggle the class', function() {
expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
element(by.model('important')).click();
expect(ps.first().getAttribute('class')).toMatch(/bold/);
element(by.model('error')).click();
expect(ps.first().getAttribute('class')).toMatch(/has-error/);
});
it('should let you toggle string example', function() {
expect(ps.get(1).getAttribute('class')).toBe('');
element(by.model('style')).clear();
element(by.model('style')).sendKeys('red');
expect(ps.get(1).getAttribute('class')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(ps.get(2).getAttribute('class')).toBe('');
element(by.model('style1')).sendKeys('bold');
element(by.model('style2')).sendKeys('strike');
element(by.model('style3')).sendKeys('red');
expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
});
it('array with map example should have 2 classes', function() {
expect(ps.last().getAttribute('class')).toBe('');
element(by.model('style4')).sendKeys('bold');
element(by.model('warning')).click();
expect(ps.last().getAttribute('class')).toBe('bold orange');
});
</file>
</example>
## Animations
The example below demonstrates how to perform animations using ngClass.
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.base-class {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.base-class.my-class {
color: red;
font-size:3em;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class', function() {
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
element(by.id('setbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).
toMatch(/my-class/);
element(by.id('clearbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
});
</file>
</example>
## ngClass and pre-existing CSS3 Transitions/Animations
The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
to view the step by step details of {@link $animate#addClass $animate.addClass} and
{@link $animate#removeClass $animate.removeClass}.
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ngClassOdd
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ngClassEven
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ngCloak
* @restrict AC
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but the preferred usage is to apply
* multiple `ngCloak` directives to small portions of the page to permit progressive rendering
* of the browser view.
*
* `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
* `angular.min.js`.
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```css
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none !important;
* }
* ```
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, making
* the compiled element visible.
*
* For the best result, the `angular.js` script must be loaded in the head section of the html
* document; alternatively, the css rule above must be included in the external stylesheet of the
* application.
*
* @element ANY
*
* @example
<example>
<file name="index.html">
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" class="ng-cloak">{{ 'world' }}</div>
</file>
<file name="protractor.js" type="protractor">
it('should remove the template directive and css class', function() {
expect($('#template1').getAttribute('ng-cloak')).
toBeNull();
expect($('#template2').getAttribute('ng-cloak')).
toBeNull();
});
</file>
</example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ngController
*
* @description
* The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
* are accessed through bindings.
* * View — The template (HTML with data bindings) that is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class contains business
* logic behind the application to decorate the scope with functions and values
*
* Note that you can also attach controllers to the DOM by declaring it in a route definition
* via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
* again using `ng-controller` in the template itself. This will cause the controller to be attached
* and executed twice.
*
* @element ANY
* @scope
* @priority 500
* @param {expression} ngController Name of a constructor function registered with the current
* {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
* that on the current scope evaluates to a constructor function.
*
* The controller instance can be published into a scope property by specifying
* `ng-controller="as propertyName"`.
*
* If the current `$controllerProvider` is configured to use globals (via
* {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
* also be the name of a globally accessible constructor function (not recommended).
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Any changes to the data are automatically reflected
* in the View without the need for a manual update.
*
* Two different declaration styles are included below:
*
* * one binds methods and properties directly onto the controller using `this`:
* `ng-controller="SettingsController1 as settings"`
* * one injects `$scope` into the controller:
* `ng-controller="SettingsController2"`
*
* The second option is more common in the Angular community, and is generally used in boilerplates
* and in this guide. However, there are advantages to binding properties directly to the controller
* and avoiding scope.
*
* * Using `controller as` makes it obvious which controller you are accessing in the template when
* multiple controllers apply to an element.
* * If you are writing your controllers as classes you have easier access to the properties and
* methods, which will appear on the scope, from inside the controller code.
* * Since there is always a `.` in the bindings, you don't have to worry about prototypal
* inheritance masking primitives.
*
* This example demonstrates the `controller as` syntax.
*
* <example name="ngControllerAs" module="controllerAsExample">
* <file name="index.html">
* <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
* <label>Name: <input type="text" ng-model="settings.name"/></label>
* <button ng-click="settings.greet()">greet</button><br/>
* Contact:
* <ul>
* <li ng-repeat="contact in settings.contacts">
* <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
* <button ng-click="settings.clearContact(contact)">clear</button>
* <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
* </li>
* <li><button ng-click="settings.addContact()">add</button></li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerAsExample', [])
* .controller('SettingsController1', SettingsController1);
*
* function SettingsController1() {
* this.name = "John Smith";
* this.contacts = [
* {type: 'phone', value: '408 555 1212'},
* {type: 'email', value: '[email protected]'} ];
* }
*
* SettingsController1.prototype.greet = function() {
* alert(this.name);
* };
*
* SettingsController1.prototype.addContact = function() {
* this.contacts.push({type: 'email', value: '[email protected]'});
* };
*
* SettingsController1.prototype.removeContact = function(contactToRemove) {
* var index = this.contacts.indexOf(contactToRemove);
* this.contacts.splice(index, 1);
* };
*
* SettingsController1.prototype.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller as', function() {
* var container = element(by.id('ctrl-as-exmpl'));
* expect(container.element(by.model('settings.name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in settings.contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in settings.contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
*
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('[email protected]');
*
* firstRepeat.element(by.buttonText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.buttonText('add')).click();
*
* expect(container.element(by.repeater('contact in settings.contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('[email protected]');
* });
* </file>
* </example>
*
* This example demonstrates the "attach to `$scope`" style of controller.
*
* <example name="ngController" module="controllerExample">
* <file name="index.html">
* <div id="ctrl-exmpl" ng-controller="SettingsController2">
* <label>Name: <input type="text" ng-model="name"/></label>
* <button ng-click="greet()">greet</button><br/>
* Contact:
* <ul>
* <li ng-repeat="contact in contacts">
* <select ng-model="contact.type" id="select_{{$index}}">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
* <button ng-click="clearContact(contact)">clear</button>
* <button ng-click="removeContact(contact)">X</button>
* </li>
* <li>[ <button ng-click="addContact()">add</button> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerExample', [])
* .controller('SettingsController2', ['$scope', SettingsController2]);
*
* function SettingsController2($scope) {
* $scope.name = "John Smith";
* $scope.contacts = [
* {type:'phone', value:'408 555 1212'},
* {type:'email', value:'[email protected]'} ];
*
* $scope.greet = function() {
* alert($scope.name);
* };
*
* $scope.addContact = function() {
* $scope.contacts.push({type:'email', value:'[email protected]'});
* };
*
* $scope.removeContact = function(contactToRemove) {
* var index = $scope.contacts.indexOf(contactToRemove);
* $scope.contacts.splice(index, 1);
* };
*
* $scope.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* }
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller', function() {
* var container = element(by.id('ctrl-exmpl'));
*
* expect(container.element(by.model('name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('[email protected]');
*
* firstRepeat.element(by.buttonText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.buttonText('add')).click();
*
* expect(container.element(by.repeater('contact in contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('[email protected]');
* });
* </file>
*</example>
*/
var ngControllerDirective = [function() {
return {
restrict: 'A',
scope: true,
controller: '@',
priority: 500
};
}];
/**
* @ngdoc directive
* @name ngCsp
*
* @element html
* @description
*
* Angular has some features that can break certain
* [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
*
* If you intend to implement these rules then you must tell Angular not to use these features.
*
* This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
*
*
* The following rules affect Angular:
*
* * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
* (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
* increase in the speed of evaluating Angular expressions.
*
* * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
* makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
* To make these directives work when a CSP rule is blocking inline styles, you must link to the
* `angular-csp.css` in your HTML manually.
*
* If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
* and automatically deactivates this feature in the {@link $parse} service. This autodetection,
* however, triggers a CSP error to be logged in the console:
*
* ```
* Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
* script in the following Content Security Policy directive: "default-src 'self'". Note that
* 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
* ```
*
* This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
* directive on an element of the HTML document that appears before the `<script>` tag that loads
* the `angular.js` file.
*
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
*
* You can specify which of the CSP related Angular features should be deactivated by providing
* a value for the `ng-csp` attribute. The options are as follows:
*
* * no-inline-style: this stops Angular from injecting CSS styles into the DOM
*
* * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
*
* You can use these values in the following combinations:
*
*
* * No declaration means that Angular will assume that you can do inline styles, but it will do
* a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
* of Angular.
*
* * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
* styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
* of Angular.
*
* * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
* inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
*
* * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
* run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
*
* * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
* styles nor use eval, which is the same as an empty: ng-csp.
* E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
```
* @example
// Note: the suffix `.csp` in the example name triggers
// csp mode in our http server!
<example name="example.csp" module="cspExample" ng-csp="true">
<file name="index.html">
<div ng-controller="MainController as ctrl">
<div>
<button ng-click="ctrl.inc()" id="inc">Increment</button>
<span id="counter">
{{ctrl.counter}}
</span>
</div>
<div>
<button ng-click="ctrl.evil()" id="evil">Evil</button>
<span id="evilError">
{{ctrl.evilError}}
</span>
</div>
</div>
</file>
<file name="script.js">
angular.module('cspExample', [])
.controller('MainController', function() {
this.counter = 0;
this.inc = function() {
this.counter++;
};
this.evil = function() {
// jshint evil:true
try {
eval('1+2');
} catch (e) {
this.evilError = e.message;
}
};
});
</file>
<file name="protractor.js" type="protractor">
var util, webdriver;
var incBtn = element(by.id('inc'));
var counter = element(by.id('counter'));
var evilBtn = element(by.id('evil'));
var evilError = element(by.id('evilError'));
function getAndClearSevereErrors() {
return browser.manage().logs().get('browser').then(function(browserLog) {
return browserLog.filter(function(logEntry) {
return logEntry.level.value > webdriver.logging.Level.WARNING.value;
});
});
}
function clearErrors() {
getAndClearSevereErrors();
}
function expectNoErrors() {
getAndClearSevereErrors().then(function(filteredLog) {
expect(filteredLog.length).toEqual(0);
if (filteredLog.length) {
console.log('browser console errors: ' + util.inspect(filteredLog));
}
});
}
function expectError(regex) {
getAndClearSevereErrors().then(function(filteredLog) {
var found = false;
filteredLog.forEach(function(log) {
if (log.message.match(regex)) {
found = true;
}
});
if (!found) {
throw new Error('expected an error that matches ' + regex);
}
});
}
beforeEach(function() {
util = require('util');
webdriver = require('protractor/node_modules/selenium-webdriver');
});
// For now, we only test on Chrome,
// as Safari does not load the page with Protractor's injected scripts,
// and Firefox webdriver always disables content security policy (#6358)
if (browser.params.browser !== 'chrome') {
return;
}
it('should not report errors when the page is loaded', function() {
// clear errors so we are not dependent on previous tests
clearErrors();
// Need to reload the page as the page is already loaded when
// we come here
browser.driver.getCurrentUrl().then(function(url) {
browser.get(url);
});
expectNoErrors();
});
it('should evaluate expressions', function() {
expect(counter.getText()).toEqual('0');
incBtn.click();
expect(counter.getText()).toEqual('1');
expectNoErrors();
});
it('should throw and report an error when using "eval"', function() {
evilBtn.click();
expect(evilError.getText()).toMatch(/Content Security Policy/);
expectError(/Content Security Policy/);
});
</file>
</example>
*/
// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
// bootstrap the system (before $parse is instantiated), for this reason we just have
// the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
/**
* @ngdoc directive
* @name ngClick
*
* @description
* The ngClick directive allows you to specify custom behavior when
* an element is clicked.
*
* @element ANY
* @priority 0
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
<span>
count: {{count}}
</span>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-click', function() {
expect(element(by.binding('count')).getText()).toMatch('0');
element(by.css('button')).click();
expect(element(by.binding('count')).getText()).toMatch('1');
});
</file>
</example>
*/
/*
* A collection of directives that allows creation of custom event handlers that are defined as
* angular expressions and are compiled and executed within the current scope.
*/
var ngEventDirectives = {};
// For events that might fire synchronously during DOM manipulation
// we need to execute their event handlers asynchronously using $evalAsync,
// so that they are not executed in an inconsistent state.
var forceAsyncEvents = {
'blur': true,
'focus': true
};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(eventName) {
var directiveName = directiveNormalize('ng-' + eventName);
ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
// We expose the powerful $event object on the scope that provides access to the Window,
// etc. that isn't protected by the fast paths in $parse. We explicitly request better
// checks at the cost of speed since event handler expressions are not executed as
// frequently as regular change detection.
var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
return function ngEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
};
}
};
}];
}
);
/**
* @ngdoc directive
* @name ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
*
* @element ANY
* @priority 0
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* a dblclick. (The Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<button ng-dblclick="count = count + 1" ng-init="count=0">
Increment (on double click)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousedown="count = count + 1" ng-init="count=0">
Increment (on mouse down)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseup="count = count + 1" ng-init="count=0">
Increment (on mouse up)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseover="count = count + 1" ng-init="count=0">
Increment (when mouse is over)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseenter="count = count + 1" ng-init="count=0">
Increment (when mouse enters)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseleave="count = count + 1" ng-init="count=0">
Increment (when mouse leaves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousemove="count = count + 1" ng-init="count=0">
Increment (when mouse moves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeydown
*
* @description
* Specify custom behavior on keydown event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keydown="count = count + 1" ng-init="count=0">
key down count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeyup
*
* @description
* Specify custom behavior on keyup event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<p>Typing in the input box below updates the key count</p>
<input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
<p>Typing in the input box below updates the keycode</p>
<input ng-keyup="event=$event">
<p>event keyCode: {{ event.keyCode }}</p>
<p>event altKey: {{ event.altKey }}</p>
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeypress
*
* @description
* Specify custom behavior on keypress event.
*
* @element ANY
* @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
* keypress. ({@link guide/expression#-event- Event object is available as `$event`}
* and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keypress="count = count + 1" ng-init="count=0">
key press count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page), but only if the form does not contain `action`,
* `data-action`, or `x-action` attributes.
*
* <div class="alert alert-warning">
* **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
* `ngSubmit` handlers together. See the
* {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
* for a detailed discussion of when `ngSubmit` may be triggered.
* </div>
*
* @element form
* @priority 0
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
* ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example module="submitExample">
<file name="index.html">
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-submit', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
expect(element(by.model('text')).getAttribute('value')).toBe('');
});
it('should ignore empty strings', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngFocus
*
* @description
* Specify custom behavior on focus event.
*
* Note: As the `focus` event is executed synchronously when calling `input.focus()`
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
* focus. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngBlur
*
* @description
* Specify custom behavior on blur event.
*
* A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
* an element has lost focus.
*
* Note: As the `blur` event is executed synchronously also during DOM manipulations
* (e.g. removing a focussed input),
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
* blur. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngCopy
*
* @description
* Specify custom behavior on copy event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
* copy. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
copied: {{copied}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngCut
*
* @description
* Specify custom behavior on cut event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
* cut. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
cut: {{cut}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngPaste
*
* @description
* Specify custom behavior on paste event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
* paste. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
pasted: {{paste}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngIf
* @restrict A
* @multiElement
*
* @description
* The `ngIf` directive removes or recreates a portion of the DOM tree based on an
* {expression}. If the expression assigned to `ngIf` evaluates to a false
* value then the element is removed from the DOM, otherwise a clone of the
* element is reinserted into the DOM.
*
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
* is created when the element is restored. The scope created within `ngIf` inherits from
* its parent scope using
* [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
* An important implication of this is if `ngModel` is used within `ngIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `ngIf` recreates elements using their compiled state. An example of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
* and `leave` effects.
*
* @animations
* enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
* leave - happens just before the `ngIf` contents are removed from the DOM
*
* @element ANY
* @scope
* @priority 600
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree. If it is truthy a copy of the compiled
* element is added to the DOM tree.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-leave,
.animate-if.ng-enter.ng-enter-active {
opacity:1;
}
</file>
</example>
*/
var ngIfDirective = ['$animate', function($animate) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
});
}
};
}];
/**
* @ngdoc directive
* @name ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* By default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link $sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
* you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
* {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
* ng.$sce Strict Contextual Escaping}.
*
* In addition, the browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy may further restrict whether the template is successfully loaded.
* For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers.
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example module="includeExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <code>{{template.url}}</code>
<hr/>
<div class="slide-animate-container">
<div class="slide-animate" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
angular.module('includeExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'},
{ name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}]);
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="animations.css">
.slide-animate-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.slide-animate {
padding:10px;
}
.slide-animate.ng-enter, .slide-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
display:block;
padding:10px;
}
.slide-animate.ng-enter {
top:-50px;
}
.slide-animate.ng-enter.ng-enter-active {
top:0;
}
.slide-animate.ng-leave {
top:0;
}
.slide-animate.ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="protractor.js" type="protractor">
var templateSelect = element(by.model('template'));
var includeElem = element(by.css('[ng-include]'));
it('should load template1.html', function() {
expect(includeElem.getText()).toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
// See https://github.com/angular/protractor/issues/480
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(2).click();
expect(includeElem.getText()).toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(0).click();
expect(includeElem.isPresent()).toBe(false);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentRequested
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentLoaded
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentError
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
function($templateRequest, $anchorScroll, $animate) {
return {
restrict: 'ECA',
priority: 400,
terminal: true,
transclude: 'element',
controller: angular.noop,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, $element, $attr, ctrl, $transclude) {
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var afterAnimation = function() {
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
};
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
ctrl.template = response;
// Note: This will also link all children of ng-include that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-include on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, null, $element).then(afterAnimation);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
scope.$eval(onloadExp);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
ctrl.template = null;
}
});
};
}
};
}];
// This directive is called during the $transclude call of the first `ngInclude` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngInclude
// is called.
var ngIncludeFillContentDirective = ['$compile',
function($compile) {
return {
restrict: 'ECA',
priority: -400,
require: 'ngInclude',
link: function(scope, $element, $attr, ctrl) {
if (/SVG/.test($element[0].toString())) {
// WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
// support innerHTML, so detect this here and try to generate the contents
// specially.
$element.empty();
$compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
function namespaceAdaptedClone(clone) {
$element.append(clone);
}, {futureParentElement: $element});
return;
}
$element.html(ctrl.template);
$compile($element.contents())(scope);
}
};
}];
/**
* @ngdoc directive
* @name ngInit
* @restrict AC
*
* @description
* The `ngInit` directive allows you to evaluate an expression in the
* current scope.
*
* <div class="alert alert-danger">
* The only appropriate use of `ngInit` is for aliasing special properties of
* {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
* should use {@link guide/controller controllers} rather than `ngInit`
* to initialize values on a scope.
* </div>
* <div class="alert alert-warning">
* **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
* sure you have parenthesis for correct precedence:
* <pre class="prettyprint">
* `<div ng-init="test1 = (data | orderBy:'name')"></div>`
* </pre>
* </div>
*
* @priority 450
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<example module="initExample">
<file name="index.html">
<script>
angular.module('initExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should alias index positions', function() {
var elements = element.all(by.css('.example-init'));
expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
});
</file>
</example>
*/
var ngInitDirective = ngDirective({
priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});
/**
* @ngdoc directive
* @name ngList
*
* @description
* Text input that converts between a delimited string and an array of strings. The default
* delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
* delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
*
* The behaviour of the directive is affected by the use of the `ngTrim` attribute.
* * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
* list item is respected. This implies that the user of the directive is responsible for
* dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
* tab or newline character.
* * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
* when joining the list items back together) and whitespace around each list item is stripped
* before it is added to the model.
*
* ### Example with Validation
*
* <example name="ngList-directive" module="listExample">
* <file name="app.js">
* angular.module('listExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.names = ['morpheus', 'neo', 'trinity'];
* }]);
* </file>
* <file name="index.html">
* <form name="myForm" ng-controller="ExampleController">
* <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
* <span role="alert">
* <span class="error" ng-show="myForm.namesInput.$error.required">
* Required!</span>
* </span>
* <br>
* <tt>names = {{names}}</tt><br/>
* <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
* <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
* <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
* <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
* </form>
* </file>
* <file name="protractor.js" type="protractor">
* var listInput = element(by.model('names'));
* var names = element(by.exactBinding('names'));
* var valid = element(by.binding('myForm.namesInput.$valid'));
* var error = element(by.css('span.error'));
*
* it('should initialize to model', function() {
* expect(names.getText()).toContain('["morpheus","neo","trinity"]');
* expect(valid.getText()).toContain('true');
* expect(error.getCssValue('display')).toBe('none');
* });
*
* it('should be invalid if empty', function() {
* listInput.clear();
* listInput.sendKeys('');
*
* expect(names.getText()).toContain('');
* expect(valid.getText()).toContain('false');
* expect(error.getCssValue('display')).not.toBe('none');
* });
* </file>
* </example>
*
* ### Example - splitting on whitespace
* <example name="ngList-directive-newlines">
* <file name="index.html">
* <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
* <pre>{{ list | json }}</pre>
* </file>
* <file name="protractor.js" type="protractor">
* it("should split the text by newlines", function() {
* var listInput = element(by.model('list'));
* var output = element(by.binding('list | json'));
* listInput.sendKeys('abc\ndef\nghi');
* expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
* });
* </file>
* </example>
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value.
*/
var ngListDirective = function() {
return {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
};
/* global VALID_CLASS: true,
INVALID_CLASS: true,
PRISTINE_CLASS: true,
DIRTY_CLASS: true,
UNTOUCHED_CLASS: true,
TOUCHED_CLASS: true,
*/
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
TOUCHED_CLASS = 'ng-touched',
PENDING_CLASS = 'ng-pending';
var ngModelMinErr = minErr('ngModel');
/**
* @ngdoc type
* @name ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. The functions are called in array order, each passing
its return value through to the next. The last return value is forwarded to the
{@link ngModel.NgModelController#$validators `$validators`} collection.
Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
`$viewValue`}.
Returning `undefined` from a parser means a parse error occurred. In that case,
no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
is set to `true`. The parse error is stored in `ngModel.$error.parse`.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. The functions are called in reverse array order, each passing the value through to the
next. The last return value is used as the actual DOM value.
Used to format / convert values for display in the control.
* ```js
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* ```
*
* @property {Object.<string, function>} $validators A collection of validators that are applied
* whenever the model value changes. The key value within the object refers to the name of the
* validator while the function refers to the validation operation. The validation operation is
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
* ```js
* ngModel.$validators.validCharacters = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
* return /[0-9]+/.test(value) &&
* /[a-z]+/.test(value) &&
* /[A-Z]+/.test(value) &&
* /\W+/.test(value);
* };
* ```
*
* @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
* perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
* is expected to return a promise when it is run during the model validation process. Once the promise
* is delivered then the validation status will be set to true when fulfilled and false when rejected.
* When the asynchronous validators are triggered, each of the validators will run in parallel and the model
* value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
* is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
* will only run once all synchronous validators have passed.
*
* Please note that if $http is used then it is important that the server returns a success HTTP response code
* in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
*
* ```js
* ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
*
* // Lookup user by username
* return $http.get('/api/users/' + value).
* then(function resolved() {
* //username exists, this means validation fails
* return $q.reject('exists');
* }, function rejected() {
* //username does not exist, therefore this validation passes
* return true;
* });
* };
* ```
*
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
* @property {Object} $error An object hash with all failing validator ids as keys.
* @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
* @property {string} $name The name attribute of the control.
*
* @description
*
* `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
* The controller contains services for data-binding, validation, CSS updates, and value formatting
* and parsing. It purposefully does not contain any logic which deals with DOM rendering or
* listening to DOM events.
* Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding to control elements.
* Angular provides this DOM logic for most {@link input `input`} elements.
* At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
* custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
*
* @example
* ### Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user.
*
* We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
* module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
* However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
* that content using the `$sce` service.
*
* <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if ( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should data-bind and become invalid', function() {
if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
// SafariDriver can't handle contenteditable
// and Firefox driver can't clear contenteditables very well
return;
}
var contentEditable = element(by.css('[contenteditable]'));
var content = 'Change me!';
expect(contentEditable.getText()).toEqual(content);
contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$untouched = true;
this.$touched = false;
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$error = {}; // keep invalid keys here
this.$$success = {}; // keep valid keys here
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
var parsedNgModel = $parse($attr.ngModel),
parsedNgModelAssign = parsedNgModel.assign,
ngModelGet = parsedNgModel,
ngModelSet = parsedNgModelAssign,
pendingDebounce = null,
parserValid,
ctrl = this;
this.$$setOptions = function(options) {
ctrl.$options = options;
if (options && options.getterSetter) {
var invokeModelGetter = $parse($attr.ngModel + '()'),
invokeModelSetter = $parse($attr.ngModel + '($$$p)');
ngModelGet = function($scope) {
var modelValue = parsedNgModel($scope);
if (isFunction(modelValue)) {
modelValue = invokeModelGetter($scope);
}
return modelValue;
};
ngModelSet = function($scope, newValue) {
if (isFunction(parsedNgModel($scope))) {
invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
} else {
parsedNgModelAssign($scope, ctrl.$modelValue);
}
};
} else if (!parsedNgModel.assign) {
throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$render
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*
* The `$render()` method is invoked in the following situations:
*
* * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
* committed value then `$render()` is called to update the input control.
* * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
* the `$viewValue` are different from last time.
*
* Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
* `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
* or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
* invoked if you only change a property on the objects.
*/
this.$render = noop;
/**
* @ngdoc method
* @name ngModel.NgModelController#$isEmpty
*
* @description
* This is called when we need to determine if the value of an input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
*
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different from the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
* @param {*} value The value of the input to check for emptiness.
* @returns {boolean} True if `value` is "empty".
*/
this.$isEmpty = function(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
currentValidationRunId = 0;
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
* Change the validity state, and notify the form.
*
* This method can be called within $parsers/$formatters or a custom validation implementation.
* However, in most cases it should be sufficient to use the `ngModel.$validators` and
* `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
*
* @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
* to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
* (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
* or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
* Skipped is used by Angular when validators do not run because of parse errors and
* when `$asyncValidators` do not run because any of the `$validators` failed.
*/
addSetValidityMethod({
ctrl: this,
$element: $element,
set: function(object, property) {
object[property] = true;
},
unset: function(object, property) {
delete object[property];
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name ngModel.NgModelController#$setPristine
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the `ng-dirty` class and set the control to its pristine
* state (`ng-pristine` class). A model is considered to be pristine when the control
* has not been changed from when first compiled.
*/
this.$setPristine = function() {
ctrl.$dirty = false;
ctrl.$pristine = true;
$animate.removeClass($element, DIRTY_CLASS);
$animate.addClass($element, PRISTINE_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setDirty
*
* @description
* Sets the control to its dirty state.
*
* This method can be called to remove the `ng-pristine` class and set the control to its dirty
* state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
* from when first compiled.
*/
this.$setDirty = function() {
ctrl.$dirty = true;
ctrl.$pristine = false;
$animate.removeClass($element, PRISTINE_CLASS);
$animate.addClass($element, DIRTY_CLASS);
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setUntouched
*
* @description
* Sets the control to its untouched state.
*
* This method can be called to remove the `ng-touched` class and set the control to its
* untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
* by default, however this function can be used to restore that state if the model has
* already been touched by the user.
*/
this.$setUntouched = function() {
ctrl.$touched = false;
ctrl.$untouched = true;
$animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setTouched
*
* @description
* Sets the control to its touched state.
*
* This method can be called to remove the `ng-untouched` class and set the control to its
* touched state (`ng-touched` class). A model is considered to be touched when the user has
* first focused the control element and then shifted focus away from the control (blur event).
*/
this.$setTouched = function() {
ctrl.$touched = true;
ctrl.$untouched = false;
$animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$rollbackViewValue
*
* @description
* Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
* which may be caused by a pending debounced event or because the input is waiting for a some
* future event.
*
* If you have an input that uses `ng-model-options` to set up debounced events or events such
* as blur you can have a situation where there is a period when the `$viewValue`
* is out of synch with the ngModel's `$modelValue`.
*
* In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
* programmatically before these debounced/future events have resolved/occurred, because Angular's
* dirty checking mechanism is not able to tell whether the model has actually changed or not.
*
* The `$rollbackViewValue()` method should be called before programmatically changing the model of an
* input which may have such events pending. This is important in order to make sure that the
* input field will be updated with the new model value and any pending operations are cancelled.
*
* <example name="ng-model-cancel-update" module="cancel-update-example">
* <file name="app.js">
* angular.module('cancel-update-example', [])
*
* .controller('CancelUpdateController', ['$scope', function($scope) {
* $scope.resetWithCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myForm.myInput1.$rollbackViewValue();
* $scope.myValue = '';
* }
* };
* $scope.resetWithoutCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myValue = '';
* }
* };
* }]);
* </file>
* <file name="index.html">
* <div ng-controller="CancelUpdateController">
* <p>Try typing something in each input. See that the model only updates when you
* blur off the input.
* </p>
* <p>Now see what happens if you start typing then press the Escape key</p>
*
* <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
* <p id="inputDescription1">With $rollbackViewValue()</p>
* <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
* ng-keydown="resetWithCancel($event)"><br/>
* myValue: "{{ myValue }}"
*
* <p id="inputDescription2">Without $rollbackViewValue()</p>
* <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
* ng-keydown="resetWithoutCancel($event)"><br/>
* myValue: "{{ myValue }}"
* </form>
* </div>
* </file>
* </example>
*/
this.$rollbackViewValue = function() {
$timeout.cancel(pendingDebounce);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
ctrl.$render();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$validate
*
* @description
* Runs each of the registered validators (first synchronous validators and then
* asynchronous validators).
* If the validity changes to invalid, the model will be set to `undefined`,
* unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
* If the validity changes to valid, it will set the model to the last available valid
* `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
*/
this.$validate = function() {
// ignore $validate before model is initialized
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
var viewValue = ctrl.$$lastCommittedViewValue;
// Note: we use the $$rawModelValue as $modelValue might have been
// set to undefined during a view -> model update that found validation
// errors. We can't parse the view here, since that could change
// the model although neither viewValue nor the model on the scope changed
var modelValue = ctrl.$$rawModelValue;
var prevValid = ctrl.$valid;
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
// If there was no change in validity, don't update the model
// This prevents changing an invalid modelValue to undefined
if (!allowInvalid && prevValid !== allValid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
});
};
this.$$runValidators = function(modelValue, viewValue, doneCallback) {
currentValidationRunId++;
var localValidationRunId = currentValidationRunId;
// check parser error
if (!processParseErrors()) {
validationDone(false);
return;
}
if (!processSyncValidators()) {
validationDone(false);
return;
}
processAsyncValidators();
function processParseErrors() {
var errorKey = ctrl.$$parserName || 'parse';
if (parserValid === undefined) {
setValidity(errorKey, null);
} else {
if (!parserValid) {
forEach(ctrl.$validators, function(v, name) {
setValidity(name, null);
});
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
}
// Set the parse error last, to prevent unsetting it, should a $validators key == parserName
setValidity(errorKey, parserValid);
return parserValid;
}
return true;
}
function processSyncValidators() {
var syncValidatorsValid = true;
forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
if (!syncValidatorsValid) {
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
return true;
}
function processAsyncValidators() {
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw ngModelMinErr("$asyncValidators",
"Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
}
setValidity(name, undefined);
validatorPromises.push(promise.then(function() {
setValidity(name, true);
}, function(error) {
allValid = false;
setValidity(name, false);
}));
});
if (!validatorPromises.length) {
validationDone(true);
} else {
$q.all(validatorPromises).then(function() {
validationDone(allValid);
}, noop);
}
}
function setValidity(name, isValid) {
if (localValidationRunId === currentValidationRunId) {
ctrl.$setValidity(name, isValid);
}
}
function validationDone(allValid) {
if (localValidationRunId === currentValidationRunId) {
doneCallback(allValid);
}
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$commitViewValue
*
* @description
* Commit a pending update to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
// If the view value has not changed then we should just exit, except in the case where there is
// a native validator on the element. In this case the validation state may have changed even though
// the viewValue has stayed empty.
if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
// change to dirty
if (ctrl.$pristine) {
this.$setDirty();
}
this.$$parseAndValidate();
};
this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
parserValid = isUndefined(modelValue) ? undefined : true;
if (parserValid) {
for (var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet($scope);
}
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$rawModelValue = modelValue;
if (allowInvalid) {
ctrl.$modelValue = modelValue;
writeToModelIfNeeded();
}
// Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
// This can happen if e.g. $setViewValue is called from inside a parser
ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
if (!allowInvalid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
writeToModelIfNeeded();
}
});
function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
};
this.$$writeModelToScope = function() {
ngModelSet($scope, ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
$exceptionHandler(e);
}
});
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setViewValue
*
* @description
* Update the view value.
*
* This method should be called when an input directive want to change the view value; typically,
* this is done from within a DOM event handler.
*
* For example {@link ng.directive:input input} calls it when the value of the input changes and
* {@link ng.directive:select select} calls it when an option is selected.
*
* If the new `value` is an object (rather than a string or a number), we should make a copy of the
* object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
* watch of objects, it only looks for a change of identity. If you only change the property of
* the object then ngModel will not realise that the object has changed and will not invoke the
* `$parsers` and `$validators` pipelines.
*
* For this reason, you should not change properties of the copy once it has been passed to
* `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
*
* When this method is called, the new `value` will be staged for committing through the `$parsers`
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute.
*
* Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
* `updateOn` events is triggered on the DOM element.
* All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
* directive is used with a custom debounce for this particular event.
*
* Note that calling this function does not trigger a `$digest`.
*
* @param {string} value Value from the view.
* @param {string} trigger Event that triggered the update.
*/
this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (!ctrl.$options || ctrl.$options.updateOnDefault) {
ctrl.$$debounceViewValueCommit(trigger);
}
};
this.$$debounceViewValueCommit = function(trigger) {
var debounceDelay = 0,
options = ctrl.$options,
debounce;
if (options && isDefined(options.debounce)) {
debounce = options.debounce;
if (isNumber(debounce)) {
debounceDelay = debounce;
} else if (isNumber(debounce[trigger])) {
debounceDelay = debounce[trigger];
} else if (isNumber(debounce['default'])) {
debounceDelay = debounce['default'];
}
}
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
ctrl.$commitViewValue();
}, debounceDelay);
} else if ($rootScope.$$phase) {
ctrl.$commitViewValue();
} else {
$scope.$apply(function() {
ctrl.$commitViewValue();
});
}
};
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
var modelValue = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue &&
// checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
(ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
parserValid = undefined;
var formatters = ctrl.$formatters,
idx = formatters.length;
var viewValue = modelValue;
while (idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
ctrl.$$runValidators(modelValue, viewValue, noop);
}
}
return modelValue;
});
}];
/**
* @ngdoc directive
* @name ngModel
*
* @element input
* @priority 1
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link input[text] text}
* - {@link input[checkbox] checkbox}
* - {@link input[radio] radio}
* - {@link input[number] number}
* - {@link input[email] email}
* - {@link input[url] url}
* - {@link input[date] date}
* - {@link input[datetime-local] datetime-local}
* - {@link input[time] time}
* - {@link input[month] month}
* - {@link input[week] week}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
* # CSS classes
* The following CSS classes are added and removed on the associated input/select/textarea element
* depending on the validity of the model.
*
* - `ng-valid`: the model is valid
* - `ng-invalid`: the model is invalid
* - `ng-valid-[key]`: for each valid key added by `$setValidity`
* - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
* - `ng-pristine`: the control hasn't been interacted with yet
* - `ng-dirty`: the control has been interacted with
* - `ng-touched`: the control has been blurred
* - `ng-untouched`: the control hasn't been blurred
* - `ng-pending`: any `$asyncValidators` are unfulfilled
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
* ## Animation Hooks
*
* Animations within models are triggered when any of the associated CSS classes are added and removed
* on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
* `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
* The animations that are triggered within ngModel are similar to how they work in ngClass and
* animations can be hooked into using CSS transitions, keyframes as well as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style an input element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-input {
* transition:0.5s linear all;
* background: white;
* }
* .my-input.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
* <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
<p id="inputDescription">
Update input to see transitions when valid/invalid.
Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
</form>
</file>
* </example>
*
* ## Binding to a getter/setter
*
* Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
* function that returns a representation of the model when called with zero arguments, and sets
* the internal state of a model when called with an argument. It's sometimes useful to use this
* for models that have an internal representation that's different from what the model exposes
* to the view.
*
* <div class="alert alert-success">
* **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
* frequently than other parts of your code.
* </div>
*
* You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
* has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
* a `<form>`, which will enable this behavior for all `<input>`s within it. See
* {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
*
* The following example shows how to use `ngModel` with a getter/setter:
*
* @example
* <example name="ngModel-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
</file>
* </example>
*/
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
formCtrl.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function(ev) {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
}];
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
/**
* @ngdoc directive
* @name ngModelOptions
*
* @description
* Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
* events that will trigger a model update and/or a debouncing delay so that the actual update only
* takes place when a timer expires; this timer will be reset after another change takes place.
*
* Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
* be different from the value in the actual model. This means that if you update the model you
* should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
* order to make sure it is synchronized with the model and that any debounced action is canceled.
*
* The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
* method is by making sure the input is placed inside a form that has a `name` attribute. This is
* important because `form` controllers are published to the related scope under the name in their
* `name` attribute.
*
* Any pending changes will take place immediately when an enclosing form is submitted via the
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* `ngModelOptions` has an effect on the element it's declared on and its descendants.
*
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should the input be bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
* matches the default events belonging of the control.
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
* `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
* - `allowInvalid`: boolean value which indicates that the model can be set with values that did
* not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
`ngModel` as getters/setters.
* - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
* `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
* continental US time zone abbreviations, but for general use, use a time zone offset, for
* example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
* If not specified, the timezone of the browser will be used.
*
* @example
The following example shows how to override immediate updates. Changes on the inputs within the
form will update the model only when the control loses focus (blur event). If `escape` key is
pressed while the input field is focused, the value is reset to the value in the current model.
<example name="ngModelOptions-directive-blur" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" />
</label><br />
<label>Other data:
<input type="text" ng-model="user.data" />
</label><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say', data: '' };
$scope.cancel = function(e) {
if (e.keyCode == 27) {
$scope.userForm.userName.$rollbackViewValue();
}
};
}]);
</file>
<file name="protractor.js" type="protractor">
var model = element(by.binding('user.name'));
var input = element(by.model('user.name'));
var other = element(by.model('user.data'));
it('should allow custom events', function() {
input.sendKeys(' hello');
input.click();
expect(model.getText()).toEqual('say');
other.click();
expect(model.getText()).toEqual('say hello');
});
it('should $rollbackViewValue when model changes', function() {
input.sendKeys(' hello');
expect(input.getAttribute('value')).toEqual('say hello');
input.sendKeys(protractor.Key.ESCAPE);
expect(input.getAttribute('value')).toEqual('say');
other.click();
expect(model.getText()).toEqual('say');
});
</file>
</example>
This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
<example name="ngModelOptions-directive-debounce" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ debounce: 1000 }" />
</label>
<button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
<br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say' };
}]);
</file>
</example>
This one shows how to bind to getter/setters:
<example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
<label>Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</label>
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
// Note that newName can be undefined for two reasons:
// 1. Because it is called as a getter and thus called with no arguments
// 2. Because the property should actually be set to undefined. This happens e.g. if the
// input is invalid
return arguments.length ? (_name = newName) : _name;
}
};
}]);
</file>
</example>
*/
var ngModelOptionsDirective = function() {
return {
restrict: 'A',
controller: ['$scope', '$attrs', function($scope, $attrs) {
var that = this;
this.$options = copy($scope.$eval($attrs.ngModelOptions));
// Allow adding/overriding bound events
if (this.$options.updateOn !== undefined) {
this.$options.updateOnDefault = false;
// extract "default" pseudo-event from list of events that can trigger a model update
this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
that.$options.updateOnDefault = true;
return ' ';
}));
} else {
this.$options.updateOnDefault = true;
}
}]
};
};
// helper methods
function addSetValidityMethod(context) {
var ctrl = context.ctrl,
$element = context.$element,
classCache = {},
set = context.set,
unset = context.unset,
parentForm = context.parentForm,
$animate = context.$animate;
classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
ctrl.$setValidity = setValidity;
function setValidity(validationErrorKey, state, controller) {
if (state === undefined) {
createAndSet('$pending', validationErrorKey, controller);
} else {
unsetAndCleanup('$pending', validationErrorKey, controller);
}
if (!isBoolean(state)) {
unset(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
} else {
if (state) {
unset(ctrl.$error, validationErrorKey, controller);
set(ctrl.$$success, validationErrorKey, controller);
} else {
set(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
}
}
if (ctrl.$pending) {
cachedToggleClass(PENDING_CLASS, true);
ctrl.$valid = ctrl.$invalid = undefined;
toggleValidationCss('', null);
} else {
cachedToggleClass(PENDING_CLASS, false);
ctrl.$valid = isObjectEmpty(ctrl.$error);
ctrl.$invalid = !ctrl.$valid;
toggleValidationCss('', ctrl.$valid);
}
// re-read the state as the set/unset methods could have
// combined state in ctrl.$error[validationError] (used for forms),
// where setting/unsetting only increments/decrements the value,
// and does not replace it.
var combinedState;
if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
combinedState = undefined;
} else if (ctrl.$error[validationErrorKey]) {
combinedState = false;
} else if (ctrl.$$success[validationErrorKey]) {
combinedState = true;
} else {
combinedState = null;
}
toggleValidationCss(validationErrorKey, combinedState);
parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
}
function createAndSet(name, value, controller) {
if (!ctrl[name]) {
ctrl[name] = {};
}
set(ctrl[name], value, controller);
}
function unsetAndCleanup(name, value, controller) {
if (ctrl[name]) {
unset(ctrl[name], value, controller);
}
if (isObjectEmpty(ctrl[name])) {
ctrl[name] = undefined;
}
}
function cachedToggleClass(className, switchValue) {
if (switchValue && !classCache[className]) {
$animate.addClass($element, className);
classCache[className] = true;
} else if (!switchValue && classCache[className]) {
$animate.removeClass($element, className);
classCache[className] = false;
}
}
function toggleValidationCss(validationErrorKey, isValid) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
}
}
function isObjectEmpty(obj) {
if (obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
return false;
}
}
}
return true;
}
/**
* @ngdoc directive
* @name ngNonBindable
* @restrict AC
* @priority 1000
*
* @description
* The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
* DOM element. This is useful if the element contains what appears to be Angular directives and
* bindings but which should be ignored by Angular. This could be the case if you have a site that
* displays snippets of code, for instance.
*
* @element ANY
*
* @example
* In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
* but the one wrapped in `ngNonBindable` is left alone.
*
* @example
<example>
<file name="index.html">
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-non-bindable', function() {
expect(element(by.binding('1 + 2')).getText()).toContain('3');
expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
});
</file>
</example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/* global jqLiteRemove */
var ngOptionsMinErr = minErr('ngOptions');
/**
* @ngdoc directive
* @name ngOptions
* @restrict A
*
* @description
*
* The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for the `<select>` element using the array or object obtained by evaluating the
* `ngOptions` comprehension expression.
*
* In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
* similar result. However, `ngOptions` provides some benefits such as reducing memory and
* increasing speed by not creating a new scope for each repeated instance, as well as providing
* more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
* comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
* to a non-string value. This is because an option element can only be bound to string values at
* present.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* ## Complex Models (objects or collections)
*
* **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
* binding any input directive to a model that is an object or a collection.
*
* Since this is a common situation for `ngOptions` the directive additionally watches the model using
* `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
* the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
* object/collection has not changed identity but only a property on the object or an item in the collection
* changes.
*
* Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
* if the model is an array). This means that changing a property deeper inside the object/collection that the
* first level will not trigger a re-rendering.
*
*
* ## `select` **`as`**
*
* Using `select` **`as`** will bind the result of the `select` expression to the model, but
* the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
* or property name (for object data sources) of the value within the collection. If a **`track by`** expression
* is used, the result of that expression will be set as the value of the `option` and `select` elements.
*
*
* ### `select` **`as`** and **`track by`**
*
* <div class="alert alert-warning">
* Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
* </div>
*
* Consider the following example:
*
* ```html
* <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"></select>
* ```
*
* ```js
* $scope.values = [{
* id: 1,
* label: 'aLabel',
* subItem: { name: 'aSubItem' }
* }, {
* id: 2,
* label: 'bLabel',
* subItem: { name: 'bSubItem' }
* }];
*
* $scope.selected = { name: 'aSubItem' };
* ```
*
* With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
* of the data source (to `item` in this example). To calculate whether an element is selected, we do the
* following:
*
* 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
* 2. Apply **`track by`** to the already selected value in `ngModel`.
* In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
* value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
* a wrong object, the selected element can't be found, `<select>` is always reset to the "not
* selected" option.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
* (for including a filter with `track by`)
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`disable when`** `disable`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `disable`: The result of this expression will be used to disable the rendered `<option>`
* element. Return `true` to disable.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`). With this the selection is preserved
* even when the options are recreated (e.g. reloaded from the server).
*
* @example
<example module="selectExample">
<file name="index.html">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light', notAnOption: true},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark', notAnOption: true},
{name:'yellow', shade:'light', notAnOption: false}
];
$scope.myColor = $scope.colors[2]; // red
}]);
</script>
<div ng-controller="ExampleController">
<ul>
<li ng-repeat="color in colors">
<label>Name: <input ng-model="color.name"></label>
<label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
<button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
</li>
<li>
<button ng-click="colors.push({})">add</button>
</li>
</ul>
<hr/>
<label>Color (null not allowed):
<select ng-model="myColor" ng-options="color.name for color in colors"></select>
</label><br/>
<label>Color (null allowed):
<span class="nullable">
<select ng-model="myColor" ng-options="color.name for color in colors">
<option value="">-- choose color --</option>
</select>
</span></label><br/>
<label>Color grouped by shade:
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
</select>
</label><br/>
<label>Color grouped by shade, with some disabled:
<select ng-model="myColor"
ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
</select>
</label><br/>
Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
<br/>
<hr/>
Currently selected: {{ {selected_color:myColor} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':myColor.name}">
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-options', function() {
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
element.all(by.model('myColor')).first().click();
element.all(by.css('select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
element(by.css('.nullable select[ng-model="myColor"]')).click();
element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
});
</file>
</example>
*/
// jshint maxlen: false
// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
// 1: value expression (valueFn)
// 2: label expression (displayFn)
// 3: group by expression (groupByFn)
// 4: disable when expression (disableWhenFn)
// 5: array item variable name
// 6: object item key variable name
// 7: object item value variable name
// 8: collection expression
// 9: track by expression
// jshint maxlen: 100
var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
function parseOptionsExpression(optionsExp, selectElement, scope) {
var match = optionsExp.match(NG_OPTIONS_REGEXP);
if (!(match)) {
throw ngOptionsMinErr('iexp',
"Expected expression in form of " +
"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '{0}'. Element: {1}",
optionsExp, startingTag(selectElement));
}
// Extract the parts from the ngOptions expression
// The variable name for the value of the item in the collection
var valueName = match[5] || match[7];
// The variable name for the key of the item in the collection
var keyName = match[6];
// An expression that generates the viewValue for an option if there is a label expression
var selectAs = / as /.test(match[0]) && match[1];
// An expression that is used to track the id of each object in the options collection
var trackBy = match[9];
// An expression that generates the viewValue for an option if there is no label expression
var valueFn = $parse(match[2] ? match[1] : valueName);
var selectAsFn = selectAs && $parse(selectAs);
var viewValueFn = selectAsFn || valueFn;
var trackByFn = trackBy && $parse(trackBy);
// Get the value by which we are going to track the option
// if we have a trackFn then use that (passing scope and locals)
// otherwise just hash the given viewValue
var getTrackByValueFn = trackBy ?
function(value, locals) { return trackByFn(scope, locals); } :
function getHashOfValue(value) { return hashKey(value); };
var getTrackByValue = function(value, key) {
return getTrackByValueFn(value, getLocals(value, key));
};
var displayFn = $parse(match[2] || match[1]);
var groupByFn = $parse(match[3] || '');
var disableWhenFn = $parse(match[4] || '');
var valuesFn = $parse(match[8]);
var locals = {};
var getLocals = keyName ? function(value, key) {
locals[keyName] = key;
locals[valueName] = value;
return locals;
} : function(value) {
locals[valueName] = value;
return locals;
};
function Option(selectValue, viewValue, label, group, disabled) {
this.selectValue = selectValue;
this.viewValue = viewValue;
this.label = label;
this.group = group;
this.disabled = disabled;
}
function getOptionValuesKeys(optionValues) {
var optionValuesKeys;
if (!keyName && isArrayLike(optionValues)) {
optionValuesKeys = optionValues;
} else {
// if object, extract keys, in enumeration order, unsorted
optionValuesKeys = [];
for (var itemKey in optionValues) {
if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
optionValuesKeys.push(itemKey);
}
}
}
return optionValuesKeys;
}
return {
trackBy: trackBy,
getTrackByValue: getTrackByValue,
getWatchables: $parse(valuesFn, function(optionValues) {
// Create a collection of things that we would like to watch (watchedArray)
// so that they can all be watched using a single $watchCollection
// that only runs the handler once if anything changes
var watchedArray = [];
optionValues = optionValues || [];
var optionValuesKeys = getOptionValuesKeys(optionValues);
var optionValuesLength = optionValuesKeys.length;
for (var index = 0; index < optionValuesLength; index++) {
var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
var value = optionValues[key];
var locals = getLocals(optionValues[key], key);
var selectValue = getTrackByValueFn(optionValues[key], locals);
watchedArray.push(selectValue);
// Only need to watch the displayFn if there is a specific label expression
if (match[2] || match[1]) {
var label = displayFn(scope, locals);
watchedArray.push(label);
}
// Only need to watch the disableWhenFn if there is a specific disable expression
if (match[4]) {
var disableWhen = disableWhenFn(scope, locals);
watchedArray.push(disableWhen);
}
}
return watchedArray;
}),
getOptions: function() {
var optionItems = [];
var selectValueMap = {};
// The option values were already computed in the `getWatchables` fn,
// which must have been called to trigger `getOptions`
var optionValues = valuesFn(scope) || [];
var optionValuesKeys = getOptionValuesKeys(optionValues);
var optionValuesLength = optionValuesKeys.length;
for (var index = 0; index < optionValuesLength; index++) {
var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
var value = optionValues[key];
var locals = getLocals(value, key);
var viewValue = viewValueFn(scope, locals);
var selectValue = getTrackByValueFn(viewValue, locals);
var label = displayFn(scope, locals);
var group = groupByFn(scope, locals);
var disabled = disableWhenFn(scope, locals);
var optionItem = new Option(selectValue, viewValue, label, group, disabled);
optionItems.push(optionItem);
selectValueMap[selectValue] = optionItem;
}
return {
items: optionItems,
selectValueMap: selectValueMap,
getOptionFromViewValue: function(value) {
return selectValueMap[getTrackByValue(value)];
},
getViewValueFromOption: function(option) {
// If the viewValue could be an object that may be mutated by the application,
// we need to make a copy and not return the reference to the value on the option.
return trackBy ? angular.copy(option.viewValue) : option.viewValue;
}
};
}
};
}
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
var optionTemplate = document.createElement('option'),
optGroupTemplate = document.createElement('optgroup');
return {
restrict: 'A',
terminal: true,
require: ['select', '?ngModel'],
link: function(scope, selectElement, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
var ngModelCtrl = ctrls[1];
if (!ngModelCtrl) return;
var selectCtrl = ctrls[0];
var multiple = attr.multiple;
// The emptyOption allows the application developer to provide their own custom "empty"
// option when the viewValue does not match any of the option values.
var emptyOption;
for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
if (children[i].value === '') {
emptyOption = children.eq(i);
break;
}
}
var providedEmptyOption = !!emptyOption;
var unknownOption = jqLite(optionTemplate.cloneNode(false));
unknownOption.val('?');
var options;
var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
var renderEmptyOption = function() {
if (!providedEmptyOption) {
selectElement.prepend(emptyOption);
}
selectElement.val('');
emptyOption.prop('selected', true); // needed for IE
emptyOption.attr('selected', true);
};
var removeEmptyOption = function() {
if (!providedEmptyOption) {
emptyOption.remove();
}
};
var renderUnknownOption = function() {
selectElement.prepend(unknownOption);
selectElement.val('?');
unknownOption.prop('selected', true); // needed for IE
unknownOption.attr('selected', true);
};
var removeUnknownOption = function() {
unknownOption.remove();
};
// Update the controller methods for multiple selectable options
if (!multiple) {
selectCtrl.writeValue = function writeNgOptionsValue(value) {
var option = options.getOptionFromViewValue(value);
if (option && !option.disabled) {
if (selectElement[0].value !== option.selectValue) {
removeUnknownOption();
removeEmptyOption();
selectElement[0].value = option.selectValue;
option.element.selected = true;
option.element.setAttribute('selected', 'selected');
}
} else {
if (value === null || providedEmptyOption) {
removeUnknownOption();
renderEmptyOption();
} else {
removeEmptyOption();
renderUnknownOption();
}
}
};
selectCtrl.readValue = function readNgOptionsValue() {
var selectedOption = options.selectValueMap[selectElement.val()];
if (selectedOption && !selectedOption.disabled) {
removeEmptyOption();
removeUnknownOption();
return options.getViewValueFromOption(selectedOption);
}
return null;
};
// If we are using `track by` then we must watch the tracked value on the model
// since ngModel only watches for object identity change
if (ngOptions.trackBy) {
scope.$watch(
function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
function() { ngModelCtrl.$render(); }
);
}
} else {
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};
selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
options.items.forEach(function(option) {
option.element.selected = false;
});
if (value) {
value.forEach(function(item) {
var option = options.getOptionFromViewValue(item);
if (option && !option.disabled) option.element.selected = true;
});
}
};
selectCtrl.readValue = function readNgOptionsMultiple() {
var selectedValues = selectElement.val() || [],
selections = [];
forEach(selectedValues, function(value) {
var option = options.selectValueMap[value];
if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
});
return selections;
};
// If we are using `track by` then we must watch these tracked values on the model
// since ngModel only watches for object identity change
if (ngOptions.trackBy) {
scope.$watchCollection(function() {
if (isArray(ngModelCtrl.$viewValue)) {
return ngModelCtrl.$viewValue.map(function(value) {
return ngOptions.getTrackByValue(value);
});
}
}, function() {
ngModelCtrl.$render();
});
}
}
if (providedEmptyOption) {
// we need to remove it before calling selectElement.empty() because otherwise IE will
// remove the label from the element. wtf?
emptyOption.remove();
// compile the element since there might be bindings in it
$compile(emptyOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
emptyOption.removeClass('ng-scope');
} else {
emptyOption = jqLite(optionTemplate.cloneNode(false));
}
// We need to do this here to ensure that the options object is defined
// when we first hit it in writeNgOptionsValue
updateOptions();
// We will re-render the option elements if the option values or labels change
scope.$watchCollection(ngOptions.getWatchables, updateOptions);
// ------------------------------------------------------------------ //
function updateOptionElement(option, element) {
option.element = element;
element.disabled = option.disabled;
if (option.value !== element.value) element.value = option.selectValue;
if (option.label !== element.label) {
element.label = option.label;
element.textContent = option.label;
}
}
function addOrReuseElement(parent, current, type, templateElement) {
var element;
// Check whether we can reuse the next element
if (current && lowercase(current.nodeName) === type) {
// The next element is the right type so reuse it
element = current;
} else {
// The next element is not the right type so create a new one
element = templateElement.cloneNode(false);
if (!current) {
// There are no more elements so just append it to the select
parent.appendChild(element);
} else {
// The next element is not a group so insert the new one
parent.insertBefore(element, current);
}
}
return element;
}
function removeExcessElements(current) {
var next;
while (current) {
next = current.nextSibling;
jqLiteRemove(current);
current = next;
}
}
function skipEmptyAndUnknownOptions(current) {
var emptyOption_ = emptyOption && emptyOption[0];
var unknownOption_ = unknownOption && unknownOption[0];
if (emptyOption_ || unknownOption_) {
while (current &&
(current === emptyOption_ ||
current === unknownOption_)) {
current = current.nextSibling;
}
}
return current;
}
function updateOptions() {
var previousValue = options && selectCtrl.readValue();
options = ngOptions.getOptions();
var groupMap = {};
var currentElement = selectElement[0].firstChild;
// Ensure that the empty option is always there if it was explicitly provided
if (providedEmptyOption) {
selectElement.prepend(emptyOption);
}
currentElement = skipEmptyAndUnknownOptions(currentElement);
options.items.forEach(function updateOption(option) {
var group;
var groupElement;
var optionElement;
if (option.group) {
// This option is to live in a group
// See if we have already created this group
group = groupMap[option.group];
if (!group) {
// We have not already created this group
groupElement = addOrReuseElement(selectElement[0],
currentElement,
'optgroup',
optGroupTemplate);
// Move to the next element
currentElement = groupElement.nextSibling;
// Update the label on the group element
groupElement.label = option.group;
// Store it for use later
group = groupMap[option.group] = {
groupElement: groupElement,
currentOptionElement: groupElement.firstChild
};
}
// So now we have a group for this option we add the option to the group
optionElement = addOrReuseElement(group.groupElement,
group.currentOptionElement,
'option',
optionTemplate);
updateOptionElement(option, optionElement);
// Move to the next element
group.currentOptionElement = optionElement.nextSibling;
} else {
// This option is not in a group
optionElement = addOrReuseElement(selectElement[0],
currentElement,
'option',
optionTemplate);
updateOptionElement(option, optionElement);
// Move to the next element
currentElement = optionElement.nextSibling;
}
});
// Now remove all excess options and group
Object.keys(groupMap).forEach(function(key) {
removeExcessElements(groupMap[key].currentOptionElement);
});
removeExcessElements(currentElement);
ngModelCtrl.$render();
// Check to see if the value has changed due to the update to the options
if (!ngModelCtrl.$isEmpty(previousValue)) {
var nextValue = selectCtrl.readValue();
if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
ngModelCtrl.$setViewValue(nextValue);
ngModelCtrl.$render();
}
}
}
}
};
}];
/**
* @ngdoc directive
* @name ngPluralize
* @restrict EA
*
* @description
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* in Angular's default en-US locale: "one" and "other".
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. There are examples of plural categories
* and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
* ```html
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*```
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* If no rule is defined for a category, then an empty string is displayed and a warning is generated.
* Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* ```html
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* ```
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bound to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<example module="pluralizeExample">
<file name="index.html">
<script>
angular.module('pluralizeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}]);
</script>
<div ng-controller="ExampleController">
<label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
<label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
<label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should show correct pluralized string', function() {
var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var countInput = element(by.model('personCount'));
expect(withoutOffset.getText()).toEqual('1 person is viewing.');
expect(withOffset.getText()).toEqual('Igor is viewing.');
countInput.clear();
countInput.sendKeys('0');
expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
expect(withOffset.getText()).toEqual('Nobody is viewing.');
countInput.clear();
countInput.sendKeys('2');
expect(withoutOffset.getText()).toEqual('2 people are viewing.');
expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
countInput.clear();
countInput.sendKeys('3');
expect(withoutOffset.getText()).toEqual('3 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
countInput.clear();
countInput.sendKeys('4');
expect(withoutOffset.getText()).toEqual('4 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
});
it('should show data-bound names', function() {
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var personCount = element(by.model('personCount'));
var person1 = element(by.model('person1'));
var person2 = element(by.model('person2'));
personCount.clear();
personCount.sendKeys('4');
person1.clear();
person1.sendKeys('Di');
person2.clear();
person2.sendKeys('Vojta');
expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
});
</file>
</example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
var BRACE = /{}/g,
IS_WHEN = /^when(Minus)?(.+)$/;
return {
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
watchRemover = angular.noop,
lastCount;
forEach(attr, function(expression, attributeName) {
var tmpMatch = IS_WHEN.exec(attributeName);
if (tmpMatch) {
var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
whens[whenKey] = element.attr(attr.$attr[attributeName]);
}
});
forEach(whens, function(expression, key) {
whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
});
scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
var count = parseFloat(newVal);
var countIsNaN = isNaN(count);
if (!countIsNaN && !(count in whens)) {
// If an explicit number rule such as 1, 2, 3... is defined, just use it.
// Otherwise, check it against pluralization rules in $locale service.
count = $locale.pluralCat(count - offset);
}
// If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
// In JS `NaN !== NaN`, so we have to exlicitly check.
if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
watchRemover();
var whenExpFn = whensExpFns[count];
if (isUndefined(whenExpFn)) {
if (newVal != null) {
$log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
}
watchRemover = noop;
updateElementText();
} else {
watchRemover = scope.$watch(whenExpFn, updateElementText);
}
lastCount = count;
}
});
function updateElementText(newText) {
element.text(newText || '');
}
}
};
}];
/**
* @ngdoc directive
* @name ngRepeat
* @multiElement
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
* Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
* This may be useful when, for instance, nesting ngRepeats.
*
*
* # Iterating over object properties
*
* It is possible to get `ngRepeat` to iterate over the properties of an object using the following
* syntax:
*
* ```js
* <div ng-repeat="(key, value) in myObj"> ... </div>
* ```
*
* You need to be aware that the JavaScript specification does not define the order of keys
* returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
* used to sort the keys alphabetically.)
*
* Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
* when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
* keys in the order in which they were defined, although there are exceptions when keys are deleted
* and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
*
* If this is not desired, the recommended workaround is to convert your object into an array
* that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
* do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
* or implement a `$watch` on the object yourself.
*
*
* # Tracking and Duplicates
*
* When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
* there are duplicates, it is not possible to maintain a one-to-one mapping between collection
* items and DOM elements.
*
* If you do need to repeat duplicate items, you can substitute the default tracking behavior
* with your own using the `track by` expression.
*
* For example, you may track items by the index of each item in the collection, using the
* special scope property `$index`:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by $index">
* {{n}}
* </div>
* ```
*
* You may use arbitrary expressions in `track by`, including references to custom functions
* on the scope:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
* {{n}}
* </div>
* ```
*
* If you are working with objects that have an identifier property, you can track
* by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
* will not have to rebuild the DOM elements for items it has already rendered, even if the
* JavaScript objects in the collection have been substituted for new ones:
* ```html
* <div ng-repeat="model in collection track by model.id">
* {{model.name}}
* </div>
* ```
*
* When no `track by` expression is provided, it is equivalent to tracking by the built-in
* `$id` function, which tracks items by their identity:
* ```html
* <div ng-repeat="obj in collection track by $id(obj)">
* {{obj.prop}}
* </div>
* ```
*
* <div class="alert alert-warning">
* **Note:** `track by` must always be the last expression:
* </div>
* ```
* <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
* {{model.name}}
* </div>
* ```
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* ```html
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* ```
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
* ```html
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* ```
*
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* **.enter** - when a new item is added to the list or when an item is revealed after a filter
*
* **.leave** - when an item is removed from the list or when an item is filtered out
*
* **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
* which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
* is specified, ng-repeat associates elements by identity. It is an error to have
* more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.)
*
* Note that the tracking expression must come last, after any filters, and the alias expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way in the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
* intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
* when a filter is active on the repeater, but the filtered result set is empty.
*
* For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
* the items have been processed through the filter.
*
* Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
* (and not as operator, inside an expression).
*
* For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0 10px;
}
.animate-repeat {
line-height:40px;
list-style:none;
box-sizing:border-box;
}
.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
}
.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
opacity:0;
max-height:0;
}
.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
opacity:1;
max-height:40px;
}
</file>
<file name="protractor.js" type="protractor">
var friends = element.all(by.repeater('friend in friends'));
it('should render initial data set', function() {
expect(friends.count()).toBe(10);
expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
expect(element(by.binding('friends.length')).getText())
.toMatch("I have 10 friends. They are:");
});
it('should update repeater when filter predicate changes', function() {
expect(friends.count()).toBe(10);
element(by.model('q')).sendKeys('ma');
expect(friends.count()).toBe(2);
expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
});
</file>
</example>
*/
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
// TODO(perf): generate setters to shave off ~40ms or 1-1.5%
scope[valueIdentifier] = value;
if (keyIdentifier) scope[keyIdentifier] = key;
scope.$index = index;
scope.$first = (index === 0);
scope.$last = (index === (arrayLength - 1));
scope.$middle = !(scope.$first || scope.$last);
// jshint bitwise: false
scope.$odd = !(scope.$even = (index&1) === 0);
// jshint bitwise: true
};
var getBlockStart = function(block) {
return block.clone[0];
};
var getBlockEnd = function(block) {
return block.clone[block.clone.length - 1];
};
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function ngRepeatCompile($element, $attr) {
var expression = $attr.ngRepeat;
var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1];
var rhs = match[2];
var aliasAs = match[3];
var trackByExp = match[4];
match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if (!match) {
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
aliasAs);
}
var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
var hashFnLocals = {$id: hashKey};
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
}
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
//
// We are using no-proto object so that we don't need to guard against inherited props via
// hasOwnProperty.
var lastBlockMap = createMap();
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection) {
var index, length,
previousNode = $element[0], // node that cloned nodes should be inserted after
// initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = createMap(),
collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder,
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, in enumeration order, unsorted
collectionKeys = [];
for (var itemKey in collection) {
if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
collectionKeys.push(itemKey);
}
}
}
collectionLength = collectionKeys.length;
nextBlockOrder = new Array(collectionLength);
// locate existing items
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
if (lastBlockMap[trackById]) {
// found previously seen block
block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap[trackById]) {
// if collision detected. restore lastBlockMap and throw an error
forEach(nextBlockOrder, function(block) {
if (block && block.scope) lastBlockMap[block.id] = block;
});
throw ngRepeatMinErr('dupes',
"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
expression, trackById, value);
} else {
// new never before seen block
nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
nextBlockMap[trackById] = true;
}
}
// remove leftover items
for (var blockKey in lastBlockMap) {
block = lastBlockMap[blockKey];
elementsToRemove = getBlockNodes(block.clone);
$animate.leave(elementsToRemove);
if (elementsToRemove[0].parentNode) {
// if the element was not removed yet because of pending animation, mark it as deleted
// so that we can ignore it later
for (index = 0, length = elementsToRemove.length; index < length; index++) {
elementsToRemove[index][NG_REMOVED] = true;
}
}
block.scope.$destroy();
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
nextNode = previousNode;
// skip nodes that are already pending removal via leave animation
do {
nextNode = nextNode.nextSibling;
} while (nextNode && nextNode[NG_REMOVED]);
if (getBlockStart(block) != nextNode) {
// existing item which got moved
$animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
}
previousNode = getBlockEnd(block);
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
} else {
// new item which we don't know about
$transclude(function ngRepeatTransclude(clone, scope) {
block.scope = scope;
// http://jsperf.com/clone-vs-createcomment
var endNode = ngRepeatEndComment.cloneNode(false);
clone[clone.length++] = endNode;
// TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block.clone = clone;
nextBlockMap[block.id] = block;
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
var NG_HIDE_CLASS = 'ng-hide';
var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
/**
* @ngdoc directive
* @name ngShow
* @multiElement
*
* @description
* The `ngShow` directive shows or hides the given HTML element based on the expression
* provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
* the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* ```
*
* When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
* with extra animation classes that can be added.
*
* ```css
* .ng-hide:not(.ng-hide-animate) {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngShow`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
* you must also include the !important flag to override the display property
* so that you can perform an animation when the element is hidden during the time of the animation.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* /* this is required as of 1.3x to properly
* apply all styling in a show/hide animation */
* transition: 0s linear all;
* }
*
* .my-element.ng-hide-add-active,
* .my-element.ng-hide-remove-active {
* /* the transition is defined in the active class */
* transition: 1s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-show {
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-show.ng-hide-add.ng-hide-add-active,
.animate-show.ng-hide-remove.ng-hide-remove-active {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
}
.animate-show.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngShowDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
// we're adding a temporary, animation-specific class for ng-hide since this way
// we can control when the element is actually displayed on screen without having
// to have a global/greedy CSS selector that breaks when other animations are run.
// Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
$animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngHide
* @multiElement
*
* @description
* The `ngHide` directive shows or hides the given HTML element based on the expression
* provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue" class="ng-hide"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue"></div>
* ```
*
* When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class in CSS:
*
* ```css
* .ng-hide {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngHide`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
* CSS class is added and removed for you instead of your own CSS class.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition: 0.5s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-hide {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-hide.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngHideDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
// The comment inside of the ngShowDirective explains why we add and
// remove a temporary class for the show/hide animation
$animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngStyle
* @restrict AC
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle
*
* {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* Since some CSS style names are not valid keys for an object, they must be quoted.
* See the 'background-color' style in the example below.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="protractor.js" type="protractor">
var colorSpan = element(by.css('span'));
it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
element(by.css('input[value=\'set color\']')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
element(by.css('input[value=clear]')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ngSwitch
* @restrict EA
*
* @description
* The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`on="..."` attribute**
* (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* <div class="alert alert-info">
* Be aware that the attribute values to match against cannot be expressions. They are interpreted
* as literal string values to match against.
* For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
* value of the expression `$scope.someVal`.
* </div>
* @animations
* enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
*
* ```
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
* ```
*
*
* @scope
* @priority 1200
* @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
* On child elements add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `ngSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example module="switchExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="selection" ng-options="item for item in items">
</select>
<code>selection={{selection}}</code>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
angular.module('switchExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}]);
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top:-50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top:0;
}
</file>
<file name="protractor.js" type="protractor">
var switchElem = element(by.css('[ng-switch]'));
var select = element(by.model('selection'));
it('should start in settings', function() {
expect(switchElem.getText()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select.all(by.css('option')).get(1).click();
expect(switchElem.getText()).toMatch(/Home Span/);
});
it('should select default', function() {
select.all(by.css('option')).get(2).click();
expect(switchElem.getText()).toMatch(/default/);
});
</file>
</example>
*/
var ngSwitchDirective = ['$animate', function($animate) {
return {
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ngSwitchController) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes = [],
selectedElements = [],
previousLeaveAnimations = [],
selectedScopes = [];
var spliceFactory = function(array, index) {
return function() { array.splice(index, 1); };
};
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
var i, ii;
for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
$animate.cancel(previousLeaveAnimations[i]);
}
previousLeaveAnimations.length = 0;
for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
var selected = getBlockNodes(selectedElements[i].clone);
selectedScopes[i].$destroy();
var promise = previousLeaveAnimations[i] = $animate.leave(selected);
promise.then(spliceFactory(previousLeaveAnimations, i));
}
selectedElements.length = 0;
selectedScopes.length = 0;
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
var anchor = selectedTransclude.element;
caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
var block = { clone: caseElement };
selectedElements.push(block);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
};
}];
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attrs, ctrl, $transclude) {
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
});
/**
* @ngdoc directive
* @name ngTransclude
* @restrict EAC
*
* @description
* Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
*
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
*
* @element ANY
*
* @example
<example module="transcludeExample">
<file name="index.html">
<script>
angular.module('transcludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<ng-transclude></ng-transclude>' +
'</div>'
};
})
.controller('ExampleController', ['$scope', function($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}]);
</script>
<div ng-controller="ExampleController">
<input ng-model="title" aria-label="title"> <br/>
<textarea ng-model="text" aria-label="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should have transcluded', function() {
var titleElement = element(by.model('title'));
titleElement.clear();
titleElement.sendKeys('TITLE');
var textElement = element(by.model('text'));
textElement.clear();
textElement.sendKeys('TEXT');
expect(element(by.binding('title')).getText()).toEqual('TITLE');
expect(element(by.binding('text')).getText()).toEqual('TEXT');
});
</file>
</example>
*
*/
var ngTranscludeDirective = ngDirective({
restrict: 'EAC',
link: function($scope, $element, $attrs, controller, $transclude) {
if (!$transclude) {
throw minErr('ngTransclude')('orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: {0}',
startingTag($element));
}
$transclude(function(clone) {
$element.empty();
$element.append(clone);
});
}
});
/**
* @ngdoc directive
* @name script
* @restrict E
*
* @description
* Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
* template can be used by {@link ng.directive:ngInclude `ngInclude`},
* {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
* `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
* assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
*
* @param {string} type Must be set to `'text/ng-template'`.
* @param {string} id Cache name of the template.
*
* @example
<example>
<file name="index.html">
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</file>
<file name="protractor.js" type="protractor">
it('should load template defined inside script tag', function() {
element(by.css('#tpl-link')).click();
expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
});
</file>
</example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
var noopNgModelController = { $setViewValue: noop, $render: noop };
/**
* @ngdoc type
* @name select.SelectController
* @description
* The controller for the `<select>` directive. This provides support for reading
* and writing the selected value(s) of the control and also coordinates dynamically
* added `<option>` elements, perhaps by an `ngRepeat` directive.
*/
var SelectController =
['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = new HashMap();
// If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
self.ngModelCtrl = noopNgModelController;
// The "unknown" option is one that is prepended to the list if the viewValue
// does not match any of the options. When it is rendered the value of the unknown
// option is '? XXX ?' where XXX is the hashKey of the value that is not known.
//
// We can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
self.unknownOption = jqLite(document.createElement('option'));
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
self.unknownOption.val(unknownVal);
$element.prepend(self.unknownOption);
$element.val(unknownVal);
};
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
self.removeUnknownOption = function() {
if (self.unknownOption.parent()) self.unknownOption.remove();
};
// Read the value of the select control, the implementation of this changes depending
// upon whether the select can have multiple values and whether ngOptions is at work.
self.readValue = function readSingleValue() {
self.removeUnknownOption();
return $element.val();
};
// Write the value to the select control, the implementation of this changes depending
// upon whether the select can have multiple values and whether ngOptions is at work.
self.writeValue = function writeSingleValue(value) {
if (self.hasOption(value)) {
self.removeUnknownOption();
$element.val(value);
if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (value == null && self.emptyOption) {
self.removeUnknownOption();
$element.val('');
} else {
self.renderUnknownOption(value);
}
}
};
// Tell the select control that an option, with the given value, has been added
self.addOption = function(value, element) {
assertNotHasOwnProperty(value, '"option value"');
if (value === '') {
self.emptyOption = element;
}
var count = optionsMap.get(value) || 0;
optionsMap.put(value, count + 1);
};
// Tell the select control that an option, with the given value, has been removed
self.removeOption = function(value) {
var count = optionsMap.get(value);
if (count) {
if (count === 1) {
optionsMap.remove(value);
if (value === '') {
self.emptyOption = undefined;
}
} else {
optionsMap.put(value, count - 1);
}
}
};
// Check whether the select control has an option matching the given value
self.hasOption = function(value) {
return !!optionsMap.get(value);
};
}];
/**
* @ngdoc directive
* @name select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
* ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
* memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
* more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
* comprehension expression.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* If the viewValue contains a value that doesn't match any of the options then the control
* will automatically add an "unknown" option, which it then removes when this is resolved.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* <div class="alert alert-info">
* The value of a `select` directive used without `ngOptions` is always a string.
* When the model needs to be bound to a non-string value, you must either explictly convert it
* using a directive (see example below) or use `ngOptions` to specify the set of options.
* This is because an option element can only be bound to string values at present.
* </div>
*
* ### Example (binding `select` to a non-string value)
*
* <example name="select-with-non-string-options" module="nonStringSelect">
* <file name="index.html">
* <select ng-model="model.id" convert-to-number>
* <option value="0">Zero</option>
* <option value="1">One</option>
* <option value="2">Two</option>
* </select>
* {{ model }}
* </file>
* <file name="app.js">
* angular.module('nonStringSelect', [])
* .run(function($rootScope) {
* $rootScope.model = { id: 2 };
* })
* .directive('convertToNumber', function() {
* return {
* require: 'ngModel',
* link: function(scope, element, attrs, ngModel) {
* ngModel.$parsers.push(function(val) {
* return parseInt(val, 10);
* });
* ngModel.$formatters.push(function(val) {
* return '' + val;
* });
* }
* };
* });
* </file>
* <file name="protractor.js" type="protractor">
* it('should initialize to model', function() {
* var select = element(by.css('select'));
* expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
* });
* </file>
* </example>
*
*/
var selectDirective = function() {
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: SelectController,
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
var ngModelCtrl = ctrls[1];
if (!ngModelCtrl) return;
var selectCtrl = ctrls[0];
selectCtrl.ngModelCtrl = ngModelCtrl;
// We delegate rendering to the `writeValue` method, which can be changed
// if the select can have multiple selected values or if the options are being
// generated by `ngOptions`
ngModelCtrl.$render = function() {
selectCtrl.writeValue(ngModelCtrl.$viewValue);
};
// When the selected item(s) changes we delegate getting the value of the select control
// to the `readValue` method, which can be changed if the select can have multiple
// selected values or if the options are being generated by `ngOptions`
element.on('change', function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(selectCtrl.readValue());
});
});
// If the select allows multiple values then we need to modify how we read and write
// values from and to the control; also what it means for the value to be empty and
// we have to add an extra watch since ngModel doesn't work well with arrays - it
// doesn't trigger rendering if only an item in the array changes.
if (attr.multiple) {
// Read value now needs to check each option to see if it is selected
selectCtrl.readValue = function readMultipleValue() {
var array = [];
forEach(element.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
return array;
};
// Write value now needs to set the selected property of each matching option
selectCtrl.writeValue = function writeMultipleValue(value) {
var items = new HashMap(value);
forEach(element.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
var lastView, lastViewRef = NaN;
scope.$watch(function selectMultipleWatch() {
if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
lastView = shallowCopy(ngModelCtrl.$viewValue);
ngModelCtrl.$render();
}
lastViewRef = ngModelCtrl.$viewValue;
});
// If we are a multiple select then value is now a collection
// so the meaning of $isEmpty changes
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};
}
}
};
};
// The option directive is purely designed to communicate the existence (or lack of)
// of dynamically created (and destroyed) option elements to their containing select
// directive via its controller.
var optionDirective = ['$interpolate', function($interpolate) {
function chromeHack(optionElement) {
// Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
// Adding an <option selected="selected"> element to a <select required="required"> should
// automatically select the new element
if (optionElement[0].hasAttribute('selected')) {
optionElement[0].selected = true;
}
}
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
// If the value attribute is not defined then we fall back to the
// text content of the option element, which may be interpolated
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function(scope, element, attr) {
// This is an optimization over using ^^ since we don't want to have to search
// all the way to the root of the DOM for every single option element
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
// Only update trigger option updates if this is an option within a `select`
// that also has `ngModel` attached
if (selectCtrl && selectCtrl.ngModelCtrl) {
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (oldVal !== newVal) {
selectCtrl.removeOption(oldVal);
}
selectCtrl.addOption(newVal, element);
selectCtrl.ngModelCtrl.$render();
chromeHack(element);
});
} else {
selectCtrl.addOption(attr.value, element);
selectCtrl.ngModelCtrl.$render();
chromeHack(element);
}
element.on('$destroy', function() {
selectCtrl.removeOption(attr.value);
selectCtrl.ngModelCtrl.$render();
});
}
};
}
};
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: false
});
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(modelValue, viewValue) {
return !attr.required || !ctrl.$isEmpty(viewValue);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};
var patternDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var regexp, patternExp = attr.ngPattern || attr.pattern;
attr.$observe('pattern', function(regex) {
if (isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
if (regex && !regex.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
regex, startingTag(elm));
}
regexp = regex || undefined;
ctrl.$validate();
});
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
};
}
};
};
var maxlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var maxlength = -1;
attr.$observe('maxlength', function(value) {
var intVal = toInt(value);
maxlength = isNaN(intVal) ? -1 : intVal;
ctrl.$validate();
});
ctrl.$validators.maxlength = function(modelValue, viewValue) {
return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
};
}
};
};
var minlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var minlength = 0;
attr.$observe('minlength', function(value) {
minlength = toInt(value) || 0;
ctrl.$validate();
});
ctrl.$validators.minlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
};
}
};
};
if (window.angular.bootstrap) {
//AngularJS is already loaded, so we can return here...
console.log('WARNING: Tried to load angular more than once.');
return;
}
//try to bind to jquery now so that one can write jqLite(document).ready()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-us",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');
},{}],9:[function(require,module,exports){
require('./angular');
module.exports = angular;
},{"./angular":8}],10:[function(require,module,exports){
module.exports = {
debug: false
};
},{}],11:[function(require,module,exports){
module.exports = require('./src/Scheduler');
},{"./src/Scheduler":26}],12:[function(require,module,exports){
'use strict';
var cocktail = require('cocktail');
/**
* @trait Configurable
* A trait/talent which provides configure(options) method into the host class.
*/
cocktail.mix({
'@exports' : module,
'@as' : 'class',
'@static': {
/**
* @factory
* @static
* @method withOptions
* Returns a Configurable Trait.
* The setter for a given key will be resolved by looking on the options map for setter names.
* If key is not in the map it will default to set{Key} method.
* @param options {Object}
*/
withOptions: function (options) {
var Configurable = this,
configurable = {};
options = options || {};
return cocktail.mix(configurable, {
'@talents': [
{
talent: Configurable,
alias: {
_getSetter: '_baseSetter'
}
}
],
_getSetter: function (key) {
return options[key] || this._baseSetter(key);
}
})
}
},
/**
* @public
* @method configure
* Configures the host class by calling setters on each property defined in the given options
* @params options {Object}
*/
configure: function (options) {
var key, option, setter, setterName;
for(key in options) {
option = options[key];
setterName = this._getSetter(key);
setter = this[setterName];
if(setter){
setter.call(this, option);
}
}
},
_getSetter: function (key) {
var camelKey = (key.charAt(0).toUpperCase() + key.slice(1));
return 'set'+camelKey;
}
});
},{"cocktail":13}],13:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('./processor/sequence');
var defaults = require('./processor/defaults');
var ANNOTATION_REG_EXP = /^@/;
var cocktail;
cocktail = {
/**
* @public
* SEQUENCE is used to define an enumeration of priorities for annotations
*/
SEQUENCE: sequence,
/**
* @private
* The processors class list.
*/
_DEFAULT_PROCESSORS: defaults,
/**
* @private
* Stack of _queues
*/
_qStack: [],
/**
* @private
* The queue of processors instances for the given mix
*/
_queue: [],
/**
*@private
* Current processor list map
*/
_processors: {},
/**
* @protected
* Returns the processor list map
*/
getProcessors : function () {
return this._processors;
},
/**
* @protected
* sets the processor object list. It is an Object used as a map
*/
setProcessors: function (processor) {
this._processors = processor;
},
/**
* @protected
* returns the list of default processors
*/
getDefaultProcessors: function () {
return cocktail._DEFAULT_PROCESSORS;
},
/**
* @protected
* registers a processor definition
* @param processorsConfig {Object} a key-value pair of processors
*/
registerProcessors: function (processorsConfig) {
var processors = this.getProcessors(),
key;
for (key in processorsConfig){
if (processorsConfig.hasOwnProperty(key)) {
processors[key] = processorsConfig[key];
}
}
},
/**
* @public
*/
use: function (annotation) {
var name = annotation.name || (annotation.prototype && annotation.prototype.name),
processor = {};
if (name && annotation.prototype) {
processor[name] = annotation;
this.registerProcessors(processor);
}
},
/**
* @private
* returns a processor instance for the given key or a NoOp instance if it is not found.
*/
_getProcessorFor: function (key) {
var processors = this.getProcessors(),
P;
P = (processors[key] || processors['no-op']);
return new P();
},
/**
* @private
* applies default options to the given options parameter.
* As of today, the only default option is the configuration for the merge annotation
*/
_applyDefaultsOptions: function (options) {
if (options && !('@merge' in options)) {
options['@merge'] = 'single';
}
},
/**
* @private
* iterates over options to find annotations and adds processors to the queue.
*/
_configureProcessorsWith: function (options) {
var key, value, processor;
this._cleanQueue();
if (options) {
for (key in options) {
if (options.hasOwnProperty(key) && ANNOTATION_REG_EXP.test(key)) {
value = options[key];
//get the processor instance for this annotation
processor = this._getProcessorFor(key);
//configure the annotation parameter
processor.setParameter(value);
//check if the annotation should be removed
if (!processor.retain) {
delete options[key];
}
//add the processor to the queue
this._addProcessorToQueue(processor);
}
}
}
},
/**
* @private
* stacks current queue
*/
_pushQueue: function () {
this._qStack.push(this._queue);
this._queue = [];
},
/**
* @private
* restore current queue
*/
_popQueue: function () {
this._queue = this._qStack.pop();
},
/**
* @private
* Cleans the processor queue
*/
_cleanQueue: function () {
this._queue.length = 0;
},
/**
* @private
* Adds the given processor to the queue
*/
_addProcessorToQueue: function (processor) {
if (processor && processor.priority !== -1) {
this._queue.push(processor);
}
},
/**
* @private
* Sorts the queue by its processor's priorities
*/
_sortQueueByPriority: function () {
this._queue.sort(function(a, b){
return a.priority - b.priority;
});
},
/**
* @private
* Runs all the processors in the queue over the given subject
*/
_executeProcessorsOn: function (subject, options) {
var processors = this._queue,
l = processors.length,
i;
this._sortQueueByPriority();
for (i = 0; i < l; i++) {
processors[i].process(subject, options);
}
},
/**
* @private
* returns true if the given subject has a pseudo annotation `@as` with the given value.
*/
_isSubjectDefinedAs: function (subject, asType) {
return (subject && subject['@as'] && subject['@as'].toLowerCase() === asType);
},
/**
* @private
* returns true if the given subject is a class definition object.
*/
_isClassDefition: function (subject) {
var isClassDef = this._isSubjectDefinedAs(subject, 'class'),
definitionProps = ['constructor', '@extends', '@traits', '@requires', '@annotation'],
key;
if (!isClassDef) {
for (key in subject) {
if (definitionProps.indexOf(key) > -1) {
isClassDef = true;
break;
}
}
}
return isClassDef;
},
/**
* @private
* returns true if the given subject is a module definition object.
*/
_isModuleDefinition: function (subject) {
return this._isSubjectDefinedAs(subject, 'module');
},
/**
* @private
* If the subject has a property construtor returns it,
* if no constructor on subject but it extends then return a function() calling super constructor,
* or a function definition otherwise.
*/
_getDefaultClassConstructor: function (subject) {
var ctor, parent;
if (this._isPropertyDefinedIn('constructor', subject)) {
ctor = subject.constructor;
} else if (this._isPropertyDefinedIn('@extends', subject)) {
parent = subject['@extends'];
ctor = function(){
parent.prototype.constructor.apply(this, arguments);
};
} else {
ctor = function(){};
}
return ctor;
},
/**
* @private
* checks if the given property is enumerable and defined in the obj
*/
_isPropertyDefinedIn: function (property, obj) {
var k;
for (k in obj) {
if (property === k) {
return true;
}
}
return false;
},
/**
* @private
* returns a call to mix() with the subject constructor and options
*/
_processClassDefition: function (subject) {
var defaultConstructor, options;
defaultConstructor = this._getDefaultClassConstructor(subject);
if (this._isPropertyDefinedIn('constructor', subject)) {
delete subject.constructor;
}
options = subject;
return this.mix(defaultConstructor, options);
},
/**
* @private
* @experimental 0.5.1
* returns a call to mix() with the subject module and options
*/
_processModuleDefinition: function (subject) {
var options = subject;
return this.mix(subject, options);
},
/**
* @public
*/
mix: function (subject, options) {
if (!options) {
if (this._isClassDefition(subject)) {
return this._processClassDefition(subject);
}
if (this._isModuleDefinition(subject)) {
return this._processModuleDefinition(subject);
}
}
if (subject) {
this._pushQueue();
this._applyDefaultsOptions(options);
this._configureProcessorsWith(options);
this._executeProcessorsOn(subject, options);
this._popQueue();
}
return subject;
}
};
//register processors
cocktail.registerProcessors(cocktail._DEFAULT_PROCESSORS);
//export module
module.exports = cocktail;
},{"./processor/defaults":24,"./processor/sequence":25}],14:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('./sequence');
var NoOp = function () {};
NoOp.prototype = {
retain : false,
priority : sequence.NO_OP,
name : 'noOp',
setParameter: function(){},
getParameter: function(){}
};
module.exports = NoOp;
},{"./sequence":25}],15:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Annotation () {}
Annotation.prototype = {
retain : false,
priority : sequence.ANNOTATION,
name : '@annotation',
_value: undefined,
setParameter: function (value) {
this._value = value;
},
getParameter: function () {
return this._value;
},
process: function (subject) {
var name = '@' + this.getParameter();
subject.prototype.name = name;
}
};
module.exports = Annotation;
},{"../sequence":25}],16:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Exports () {}
Exports.prototype = {
retain : false,
priority : sequence.EXPORTS,
name : '@extends',
_parameter: undefined,
setParameter: function (value) {
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject /*, proto*/) {
var value = this.getParameter();
if (value && typeof value === 'object') {
value.exports = subject;
}
}
};
module.exports = Exports;
},{"../sequence":25}],17:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Extends () {}
Extends.prototype = {
retain : false,
priority : sequence.EXTENDS,
name : '@extends',
_parameter: undefined,
setParameter: function (value) {
if (!(value && value.prototype)) {
throw new Error('@extends parameter should have a prototype');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var parent = this.getParameter(),
sp;
subject.prototype = sp = Object.create(parent.prototype);
sp.$super = parent;
sp.callSuper = function(methodName){
var mthd = this.$super.prototype[methodName],
mthdArgs = Array.prototype.slice.call(arguments, 1);
if (!mthd) {
throw new Error('callSuper: There is no method named ' + mthd + ' in parent class.');
}
return mthd.apply(this, mthdArgs);
};
}
};
module.exports = Extends;
},{"../sequence":25}],18:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var _STRATEGIES_ = {
'single' : '_mergeMine',
'mine' : '_mergeMine',
'their' : '_mergeTheir',
'deep-mine' : '_mergeDeepMine',
'deep-their' : '_mergeDeepTheir',
'properties' : '_mergeOnlyProperties'
};
/**
* @constructor
*/
function Merge (options) {
var useProto;
if (options) {
useProto = options.usePrototypeWhenSubjectIsClass;
this._usePrototypeWhenSubjectIsClass = (useProto === false) ? useProto : true;
}
}
Merge.prototype = {
retain : false,
priority : sequence.MERGE,
name : '@merge',
_parameter : undefined,
_usePrototypeWhenSubjectIsClass: true,
setParameter: function (value) {
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
_doMerge : function (mine, their, method) {
var key;
for (key in their) {
if (their.hasOwnProperty(key)) {
method.call(this, key);
}
}
},
/**
* mine merge strategy: mine params over their. If params is already defined it gets overriden.
*/
_mergeMine : function (mine, their) {
this._doMerge(mine, their, function(k){
mine[k] = their[k];
});
return mine;
},
_mergeOnlyProperties : function (mine, their) {
this._doMerge(mine, their, function(k){
if (typeof their[k] !== 'function'){
mine[k] = their[k];
}
});
return mine;
},
/**
* deepMine merge strategy: mine params over their.
* If params is already defined and it is an object it is merged with strategy mine,
* if params is already defined and it is an array it is concatenated,
* otherwise it gets overriden with mine.
*/
_mergeDeepMine : function (mine, their) {
return this._mergeDeep(mine, their, '_mergeMine');
},
/**
* their merge strategy: their params over mine. If params is already defined it doesn't get overriden.
*/
_mergeTheir : function (mine, their) {
this._doMerge(mine, their, function(k){
if (mine[k] === undefined) {
mine[k] = their[k];
}
});
return mine;
},
/**
* deepMine merge strategy: their params over mine.
* If params is already defined and it is an object it is merged with strategy their,
* if params is already defined and it is an array it is concatenated,
* otherwise it gets overriden with mine.
*/
_mergeDeepTheir : function (mine, their) {
return this._mergeDeep(mine, their, '_mergeTheir');
},
/**
* runs the deep merge using the given strategy
*/
_mergeDeep: function (mine, their, strategy) {
this._doMerge(mine, their, function(key){
if (typeof their[key] === 'object') {
if (their[key] instanceof Array) {
mine[key] = [].concat(mine[key], their[key]);
} else {
mine[key] = this[strategy](mine[key], their[key]);
}
}else if (mine[key] === undefined ) {
mine[key] = their[key];
}
});
return mine;
},
_shouldUsePrototypeWhenSubjectIsClass: function () {
return this._usePrototypeWhenSubjectIsClass;
},
process: function (subject, options) {
var their = options,
useProto = this._shouldUsePrototypeWhenSubjectIsClass(),
mine = (useProto && subject.prototype) || subject,
strategy = _STRATEGIES_[this.getParameter()];
this[strategy](mine, their);
}
};
module.exports = Merge;
},{"../sequence":25}],19:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function Properties () {}
Properties.prototype = {
retain : false,
priority : sequence.PROPERTIES,
name : '@properties',
_parameter: undefined,
setParameter: function (value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
throw new Error('@properties parameter should be an Object');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
_capitalizeName: function (name) {
return (name.charAt(0).toUpperCase() + name.slice(1));
},
_getterName: function (property, value) {
return (value !== false && value !== true ? 'get' : 'is') + this._capitalizeName(property);
},
_setterName: function (property) {
return 'set' + this._capitalizeName(property);
},
_createPropertyFor: function (subject, name, value, doNotOverride) {
if (typeof subject[name] === 'undefined' || doNotOverride !== true) {
subject[name] = value;
}
subject[this._getterName(name, value)] = function(){
return this[name];
};
subject[this._setterName(name)] = function(set){
this[name] = set;
};
},
process: function (subject) {
var properties = this.getParameter(),
isObject = !(subject.prototype),
key;
for (key in properties) {
if (properties.hasOwnProperty(key)) {
this._createPropertyFor(subject.prototype || subject, key, properties[key], isObject);
}
}
}
};
module.exports = Properties;
},{"../sequence":25}],20:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
function $$required$$ () {
throw new Error('method is marked as required but it has not been defined');
}
function Requires () {}
Requires.requiredMethod = $$required$$;
Requires.prototype = {
retain : false,
priority : sequence.REQUIRES,
name : '@requires',
_parameter: [],
setParameter: function (value) {
//TODO: validate parameter
this._parameter = [].concat(value);
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var reqs = this.getParameter(), // always an []
l = reqs.length,
i;
for (i = 0; i < l; i++) {
this._createRequiredMethod(subject, reqs[i]);
}
},
_createRequiredMethod: function(sub, methodName){
var subject = (sub.prototype || sub);
if (!subject[methodName]) {
subject[methodName] = Requires.requiredMethod;
}
}
};
module.exports = Requires;
},{"../sequence":25}],21:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var Merge = require('./Merge');
function Static () {}
Static.prototype = {
retain : false,
priority : sequence.POST_MERGE,
name : '@static',
_parameter: undefined,
setParameter: function (value) {
if (Object.prototype.toString.call(value) !== '[object Object]') {
throw new Error('@static parameter should be an Object');
}
this._parameter = value;
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var statics = this.getParameter(),
merger = new Merge({usePrototypeWhenSubjectIsClass: false});
merger.setParameter('mine');
merger.process(subject, statics);
}
};
module.exports = Static;
},{"../sequence":25,"./Merge":18}],22:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var Traits = require('./Traits');
function Talents () {
Traits.call(this);
}
Talents.prototype = Object.create(Traits.prototype);
Talents.prototype._configName = 'talent';
Talents.prototype.process = function (subject) {
var talents = this.getParameter(), // always an []
l = talents.length,
i;
for (i = 0; i < l; i++) {
this._applyTo(subject, talents[i]);
}
};
module.exports = Talents;
},{"./Traits":23}],23:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
var sequence = require('../sequence');
var Requires = require('./Requires');
function Traits () {}
Traits.prototype = {
retain : false,
priority : sequence.TRAITS,
name : '@traits',
_configName: 'trait',
_parameter: [],
setParameter: function (value) {
//TODO: validate parameter
this._parameter = [].concat(value);
},
getParameter: function () {
return this._parameter;
},
process: function (subject) {
var traits = this.getParameter(), // always an []
l = traits.length,
i;
for (i = 0; i < l; i++) {
this._applyTo(subject.prototype || subject, traits[i]);
}
},
_isApplicable: function (option) {
var type = this._configName;
return (typeof option === 'function') || (option && !option[type]);
},
_applyTo: function (subject, options) {
var me = this,
type = me._configName,
o = {},
tp, excluded, aliases, t;
if (me._isApplicable(options)) {
o[type] = options;
return me._applyTo(subject, o);
}
excluded = [].concat(options.excludes);
aliases = options.alias || {};
t = options[type];
tp = t.prototype || t;
Object.getOwnPropertyNames(tp)
.filter(function(key){
return !key.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/);
})
.forEach(function(key){
me._raiseErrorIfItIsState(key, tp);
me._applyIfNotExcluded(key, excluded, aliases, subject, tp);
});
},
_applyIfNotExcluded: function (key, excluded, aliases, subject, tp) {
var alias;
if (excluded.indexOf(key) === -1) {
alias = aliases[key] || key;
this._raiseErrorIfConflict(alias, subject, tp);
if (!subject[alias] || subject[alias] === Requires.requiredMethod) {
Object.defineProperty(subject, alias, Object.getOwnPropertyDescriptor(tp, key));
}
}
},
_raiseErrorIfItIsState: function (key, traitProto) {
if (typeof traitProto[key] !== 'function') {
throw new Error('Trait MUST NOT contain any state. Found: ' + key + ' as state while processing trait');
}
},
_raiseErrorIfConflict: function (methodName, subjectProto, traitProto) {
var requiredMethodName = Requires.requiredMethod.name,
subjectMethod = subjectProto[methodName],
traitMethod = traitProto[methodName],
sameMethodName = (subjectMethod && traitMethod),
methodsAreNotTheSame = sameMethodName && (subjectMethod.toString() !== traitMethod.toString()),
traitMethodIsNotARequired = sameMethodName && (traitMethod.name !== requiredMethodName),
subjecMethodIsNotARequired = sameMethodName && (subjectMethod.name !== requiredMethodName);
if (sameMethodName && methodsAreNotTheSame && traitMethodIsNotARequired && subjecMethodIsNotARequired) {
throw new Error('Same method named: ' + methodName + ' is defined in trait and Class.' );
}
}
};
module.exports = Traits;
},{"../sequence":25,"./Requires":20}],24:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
module.exports = {
'no-op' : require('./NoOp'),
'@as' : undefined, /*pseudo-processor*/
'@merge' : require('./annotation/Merge'),
'@extends' : require('./annotation/Extends'),
'@properties' : require('./annotation/Properties'),
'@traits' : require('./annotation/Traits'),
'@requires' : require('./annotation/Requires'),
'@talents' : require('./annotation/Talents'),
'@annotation' : require('./annotation/Annotation'),
'@exports' : require('./annotation/Exports'),
'@static' : require('./annotation/Static')
};
},{"./NoOp":14,"./annotation/Annotation":15,"./annotation/Exports":16,"./annotation/Extends":17,"./annotation/Merge":18,"./annotation/Properties":19,"./annotation/Requires":20,"./annotation/Static":21,"./annotation/Talents":22,"./annotation/Traits":23}],25:[function(require,module,exports){
/*
*
* Copyright (c) 2013 - 2015 Maximiliano Fierro
* Licensed under the MIT license.
*/
'use strict';
/**
* sequence list
The processors will use one of the defined priorities in this list
The priorities are organized in groups:
[-1] No Op.
[1..99) Object/Class creation.
[99..999) Merge - Traits and talents are considered merge stage since we copy the structure into the subject.
[999..) Miscelaneous - Annotation definition makes no changes over the Subject itself.
*/
module.exports = {
NO_OP : -1,
PRE_EXTENDS : 9,
EXTENDS : 10,
POST_EXTENDS : 11,
PRE_PROPERTIES : 19,
PROPERTIES : 20,
POST_PROPERTIES : 21,
PRE_REQUIRES : 29,
REQUIRES : 30,
POST_REQUIRES : 31,
PRE_MERGE : 99,
MERGE : 100,
POST_MERGE : 101,
PRE_TRAITS : 109,
TRAITS : 110,
POST_TRAITS : 111,
PRE_ANNOTATION : 999,
ANNOTATION : 1000,
POST_ANNOTATION : 1001,
PRE_EXPORTS : 1009,
EXPORTS : 1010,
POST_EXPORTS : 1011
};
},{}],26:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('./annotations/Logger');
var Fifo = require('./algorithms/Fifo');
var Lru = require('./algorithms/Lru');
var Memory = require('./common/Memory');
var Requirement = require('./common/Requirement');
var FixedEvenAssignmentPolicy = require('./assignment_filters/FixedEvenAssignmentPolicy');
var AsyncFlushAssignmentPolicy = require('./assignment_filters/AsyncFlushAssignmentPolicy');
cocktail.use(Logger);
cocktail.mix({
'@exports' : module,
'@as' : 'class',
'@logger' : [console, "Scheduler:"],
constructor: function() {
this._memory = undefined;
this._memorySize = 0;
this._moments = [];
this._algorithm = undefined;
this._rawRequirements = [];
this._requirements = [];
this._assignmentPolicies = [];
this.log("Created.");
},
getAlgorithm: function() {
if ( this._algorithm !== undefined ) {
if (this._algorithm instanceof Lru)
return 'lru';
if (this._algorithm instanceof Fifo)
return 'fifo';
}
return undefined;
},
getMemorySize: function() {
return this._memorySize;
},
getRequirements: function() {
return this._rawRequirements;
},
isFixedEvenAssignmentPolicy: function() {
return this._assignmentPolicies[0] !== undefined;
},
isLocalReplacementPolicy: function() {
if (this._algorithm){
return this._algorithm.isLocalReplacementPolicy();
} else {
return undefined;
}
},
isAsyncFlushPolicy: function() {
return this._assignmentPolicies[1] !== undefined;
},
getSecondChanceReplacementPolicy: function() {
return this._algorithm.isSecondChanceReplacementPolicy();
},
isSecondChanceReplacementPolicy: function() {
if (this._algorithm){
return this._algorithm.isSecondChanceReplacementPolicy();
} else {
return undefined;
}
},
setAlgorithm: function(algorithm) {
if (!algorithm) {
return;
}
switch (algorithm) {
case 'fifo':
this.clearPolicies();
this._algorithm = new Fifo();
break;
case 'lru':
this.clearPolicies();
this._algorithm = new Lru();
break;
default:
return;
}
},
setFixedEvenAssignmentPolicy: function(size) {
if (size === undefined) {
return;
}
if (size) {
this._assignmentPolicies[0] = new FixedEvenAssignmentPolicy(size);
} else {
delete this._assignmentPolicies[0];
}
},
setLocalReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm) {
this._algorithm.setLocalReplacementPolicy(enabled);
}
},
setAsyncFlushReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm && enabled) {
var policy = new AsyncFlushAssignmentPolicy()
this._assignmentPolicies[1] = policy;
this._algorithm.setAsyncFlushReplacementPolicy(true, policy);
} else {
delete this._assignmentPolicies[1];
this._algorithm.setAsyncFlushReplacementPolicy(false);
}
},
setSecondChanceReplacementPolicy: function(enabled) {
if (enabled === undefined) {
return;
}
if (this._algorithm) {
this._algorithm.setSecondChanceReplacementPolicy(enabled);
}
},
clearPolicies: function() {
this._assignmentPolicies = [];
if (this._algorithm) {
this._algorithm.clearPolicies();
}
this.log("All policies cleared.")
},
setMemorySize: function(size) {
if (!size) {
return;
}
this._memory = new Memory(size);
this._memorySize = size;
this._updatePolicies();
},
addRequirements: function(requirements) {
if (!requirements) {
return;
}
this._rawRequirements = requirements;
this._requirements = [];
this.log("---Started generating the requirements queue.---");
this._rawRequirements.forEach(function(elem) {
this._requirements.push(new Requirement(elem));
}, this);
this.log("---Finished generating the requirements queue.---\n");
},
run: function() {
if (!this._memory || !this._algorithm || !this._requirements.length) {
throw new Error("Some initialization is missing!!");
}
this._algorithm.initialize(this._requirements);
this._processRequirements();
/*
* _processRequirements will save all data in _moments.
* We'll need to parse it before sending it back to the client.
*/
var allMoments = this._dataMoments();
//Dispose all arrays.
this._clearBuffers();
return allMoments;
},
_dataMoments: function() {
this.log("---Started generating the output matrix.---");
var allMoments = [];
//Here we use the context to bind the array in which i want the pages to be added.
this._moments.forEach(function(moment) {
var singleMoment = {
requirement: moment.requirement.asDataObject(),
pageFault: moment.pageFault,
frames: [],
victim: (moment.victim)? moment.victim.asVictim() : undefined,
potentialVictims: []
}
//Here too (it's a matrix).
moment.instant.forEach(function(page) {
this.push(page.asDataObject());
}, singleMoment.frames);
moment.potentialVictims.forEach(function(potentialVictim) {
this.push(potentialVictim.asVictim());
}, singleMoment.potentialVictims)
this.push(singleMoment);
}, allMoments);
this.log("---Finished generating the output matrix.---\n");
return allMoments;
},
_clearBuffers: function(arguments) {
if (this._memorySize) {
this._memory = new Memory(this._memorySize);
}
this._moments = [];
//this._requirements = [];
this.log("All buffers cleared.");
},
// To be implemented with FixedEven assignment filter.
_assignmentFiltersAproves: function(requirement) {
var hasSpace = !this._memory.isFull();
var i = 0;
var length = this._assignmentPolicies.length;
for (; i < length; i++) {
if (this._assignmentPolicies[i]) {
hasSpace &= this._assignmentPolicies[i].hasFreeFrameFor(requirement, this._memory, this);
}
}
return hasSpace;
},
_update: function(requirement) {
this._algorithm.update(requirement);
this._updateMemory(requirement);
this._updatePolicies();
},
_updateMemory: function(requirement) {
// Assume that the requirement is already in memory.
var page = this._memory.at(this._memory.getFrameOf(requirement));
page.setReferenced(true);
if (requirement.getMode() === "write") {
page.setModified(true);
}
},
_updatePolicies: function() {
this._assignmentPolicies.forEach(function(policy) {
policy.update(this._memory, this)
}, this);
},
_saveMoment: function(requirement, pageFault, victim) {
this.log("Saving moment " + this._moments.length + ".");
var moment = {
requirement: requirement.clone(),
instant: this._memory.clone(),
pageFault: pageFault,
victim: victim,
potentialVictims: this._algorithm.getVictimsStructure()
};
this._moments.push(moment);
this.log("Moment " + (this._moments.length -1) + " saved.\n");
},
_clearMemoryFlags: function() {
this._memory.forEach(function(page) {
page.clearPageFault();
if (!this.getSecondChanceReplacementPolicy()) {
page.clearReferenced();
}
}, this);
this.log("All page flags cleared.");
},
_processRequirements: function() {
this._requirements.forEach(function(requirement) {
// Start with a clean image of the frames.
this._clearMemoryFlags();
//Declare victim here because it'll be used for update.
var victim = {
frame: undefined,
page: undefined
};
var pageFault = false;
if (this._memory.contains(requirement)) {
this.log("---Memory hit! Updating reference.---\n")
} else {
/*
* This is a pageFault.
* Steps to follow:
* 1) Ask to the assignment policy if the requirement
* needs to replace a page.
* 2a) No need to replace. Ask the memory for a free frame to use.
* 2b) We need to replace. Ask the algorithm for the page to replace,
* then find it in the memory.
* 3) Load the requirement to the memory as a page.
*/
this.log("---Page Fault.---");
pageFault = true;
var frame;
if(this._assignmentFiltersAproves(requirement)) {
this.log("---Free frame available.---\n");
frame = this._memory.getFreeFrame();
} else {
this.log("---Searching for a victim muajajaja!---\n");
victim = this._algorithm.victimFor(requirement);
frame = this._memory.getFrameOf(victim.frame);
}
this._memory.atPut(frame, requirement.asPage());
}
// Even if it's a page fault or not, call to update.
this._update(requirement);
this._saveMoment(requirement, pageFault, victim.page);
}, this);
}
});
},{"./algorithms/Fifo":29,"./algorithms/Lru":30,"./annotations/Logger":31,"./assignment_filters/AsyncFlushAssignmentPolicy":33,"./assignment_filters/FixedEvenAssignmentPolicy":34,"./common/Memory":36,"./common/Requirement":38,"cocktail":13}],27:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var LocalReplacementPolicy = require('../replacement_filters/LocalReplacementPolicy');
var SecondChanceReplacementPolicy = require('../replacement_filters/SecondChanceReplacementPolicy');
var AsyncFlushReplacementPolicy = require('../replacement_filters/AsyncFlushReplacementPolicy');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Base:"],
constructor: function() {
//Should be initialized by some especification of this class.
this._victims = undefined;
this._requirements = undefined;
this._filters = [];
},
getVictimsStructure: function() {
return this._victims.clone();
},
initialize: function(requirements) {
this._requirements = requirements;
},
victimFor: function(requirement) {
this.log("---Started applying replacement filters.---");
var filteredVictims = this._victims.clone();
var i = 0;
var length = this._filters.length;
for (; i < length; i++) {
if (this._filters[i]) {
this._filters[i].apply(filteredVictims, requirement, this);
}
}
this.log("Finished applying replacement filters.---\n");
this.log("The selected victim is: " + filteredVictims.peek() + ".\n");
this._victims.remove(filteredVictims.peek());
// A pedidio de Cristian S.
var position = filteredVictims.first();
var victim = position;
if (position.isReservedForAsyncFlush()) {
victim = this._filters[1]._counterpart._memory.at(this._filters[1]._counterpart._position);
}
var result = {
frame: position,
page: victim
}
return result;
},
addPage: function(requirement) {
throw new Error("Subclass responsibility.")
},
getPage: function(requirement) {
throw new Error("Subclass responsibility.")
},
update: function(requirement) {
throw new Error("Subclass responsibility.")
},
recycle: function(requirement) {
throw new Error("Subclass responsibility.")
},
setLocalReplacementPolicy: function(enabled) {
if (enabled) {
this._filters[0] = new LocalReplacementPolicy();
} else {
delete this._filters[0];
}
},
setAsyncFlushReplacementPolicy: function(enabled, counterpartFilter) {
if (enabled) {
this._filters[1] = new AsyncFlushReplacementPolicy(counterpartFilter);
} else {
delete this._filters[1];
}
},
setSecondChanceReplacementPolicy: function(enabled) {
if (enabled) {
this._filters[2] = new SecondChanceReplacementPolicy();
} else {
delete this._filters[2];
}
},
isLocalReplacementPolicy: function() {
return this._filters[0] !== undefined;
},
isSecondChanceReplacementPolicy: function() {
return this._filters[2] !== undefined;
},
clearPolicies: function() {
this._filters = [];
}
});
},{"../annotations/Logger":31,"../replacement_filters/AsyncFlushReplacementPolicy":42,"../replacement_filters/LocalReplacementPolicy":43,"../replacement_filters/SecondChanceReplacementPolicy":45,"./AlgorithmInterface":28,"cocktail":13}],28:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': [
'victimFor',
'addPage',
'getPage',
'update',
'recycle',
'clearPolicies',
'setLocalReplacementPolicy',
'setAsyncFlushReplacementPolicy',
'setSecondChanceReplacementPolicy',
]
});
},{"cocktail":13}],29:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var Algorithm = require('./Algorithm');
var Queue = require('../common/VictimsStructures/Queue');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@extends': Algorithm,
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Fifo:"],
constructor: function() {
this.callSuper("constructor");
this._victims = new Queue();
this.log("Created.");
},
addPage: function(requirement) {
this._victims.add(requirement.asPage().clearAll());
},
getPage: function(page) {
return this._victims.pageOf(page);
},
update: function(requirement) {
if (this._victims.contains(requirement)) {
this.addPage(requirement);
if (requirement.getMode() === "read") {
this._victims.pageOf(requirement).setReferenced(true);
this.log("Updated victim queue, referenced.");
}
if(requirement.getMode() === "write") {
this._victims.pageOf(requirement).setModified(true);
this.log("Updated victim queue, modified.");
}
return;
}
this.addPage(requirement);
},
//Just recycle the page.
recycle: function(requirement) {
this._victims.recycle(requirement);
},
});
},{"../annotations/Logger":31,"../common/VictimsStructures/Queue":39,"./Algorithm":27,"./AlgorithmInterface":28,"cocktail":13}],30:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AlgorithmInterface = require('./AlgorithmInterface');
var Fifo = require('./Fifo');
var ReQueueQueue = require('../common/VictimsStructures/ReQueueQueue');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@extends': Fifo,
'@traits': [AlgorithmInterface],
'@logger' : [console, "Algorithm Lru:"],
constructor: function() {
this.callSuper("constructor");
this._victims = new ReQueueQueue();
this.log("Created.");
}
});
},{"../annotations/Logger":31,"../common/VictimsStructures/ReQueueQueue":40,"./AlgorithmInterface":28,"./Fifo":29,"cocktail":13}],31:[function(require,module,exports){
var cocktail = require('cocktail');
var config = require('../../config');
cocktail.mix({
//Create logger cocktail annotation and export it as a module.
'@annotation': 'logger',
'@exports': module,
//_logger should implement the log method.
_logger: undefined,
_prefix: undefined,
_debug: undefined,
//Called to initialize when the anotation is used.
//Cocktail enforces this method to recive a single parameter.
setParameter: function(parameter) {
/**********************************************************
* SET THIS VARIABLE TO FALSE WHEN GOING TO PRODUCTION! *
**********************************************************
*/
this._debug = config.debug;
//Check if the object passed has the method that we will use to log.
if(typeof parameter[0].log == "function") {
this._logger = parameter[0];
} else {
//Define a default logger if the one provided by the class was invalid.
this._logger = console;
}
this._prefix = parameter[1];
},
//Here is defined what to do if the annotation is called.
process: function(subject, options) {
//When set to false, logs wont be displayed.
var debug = this._debug;
var logger = this._logger;
var prefix = this._prefix;
host = subject.prototype || subject;
//Host is the object I want to add functionality to.
host.log = function(message){
if(debug && logger) {
logger.log.call(logger, prefix ,message);
}
};
}
});
},{"../../config":10,"cocktail":13}],32:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': ['hasFreeFrameFor, update']
});
},{"cocktail":13}],33:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AssignmentFilterInterface = require('./AssignmentFilterInterface');
var Page = require('../common/Page');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AssignmentFilterInterface],
'@logger' : [console, "AsyncFlushAssignmentPolicy:"],
constructor: function() {
this._reserved = new Page(
{
'process': '',
'pageNumber': 0,
'mode' : 'reserved',
'pageFault' : false,
'referenced': false,
'modified': false,
'reservedForAsyncFlush': true
});
this._position = 0;
this._memory = undefined;
this.log("Created.");
},
hasFreeFrameFor: function(requirement, memory, context) {
//Save a reference to the actual memory.
this._memory = memory;
return true;
},
update: function(memory, context) {
this._updateMemory(memory, context);
},
_updateMemory: function(memory, context) {
memory.atPut(this._position, this._reserved.clone());
this.log("The reserved Async Flush Frame was updated.");
},
updatePosition: function(requirement) {
this._position = this._memory.getFrameOf(requirement);
this.log("The reserved Async Flush reference was updated, " + this._position + ".");
},
getReserved: function() {
return this._reserved.clone();
}
});
},{"../annotations/Logger":31,"../common/Page":37,"./AssignmentFilterInterface":32,"cocktail":13}],34:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var AssignmentFilterInterface = require('./AssignmentFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [AssignmentFilterInterface],
'@logger' : [console, "FixedEvenAssignmentPolicy:"],
constructor: function(localitySize) {
this._size = localitySize;
this.log("Created with " + this._size + ".");
},
hasFreeFrameFor: function(requirement, memory, context) {
var processCount = {
process: requirement.getProcess(),
count: 0
};
memory.forEach(function(frame) {
if (this.process == frame.getProcess()) {
this.count++;
}
}, processCount);
return (this._size > processCount.count);
},
update: function(memory, context) {
//Nothing to do here.
}
});
},{"../annotations/Logger":31,"./AssignmentFilterInterface":32,"cocktail":13}],35:[function(require,module,exports){
var cocktail = require('cocktail');
cocktail.mix({
//Create Behavior cocktail module and export it.
'@exports': module,
'@as': 'module',
/*
* Checks whether the equals method is defined and return a function
* that takes two arguments and returns if they are equal
* using the method it defined for that request.
*/
ComparingMethod: function(value){
if(!value) {
return (function(a, b) {
return b === undefined;
});
}
if (typeof value.equals == "function") {
return (function(a, b) {
return a.equals(b);
});
}
return (function(a, b) {
return a === b;
});
},
/*
* Checks whether the clone method is defined and return a function
* that takes an argument and returns a copy of it
* using the method it defined for that request.
*/
CloningMethod: function(value) {
if(typeof value.clone == "function") {
return (function(a) {
return a.clone();
});
}
return (function(a){
return a;
});
}
});
},{"cocktail":13}],36:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Using Behavior class.
var Behavior = require('./Behavior');
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
//var Configurable = require('cocktail-trait-configurable');
/*
**********************************************************************
* This Memory defines Equals and Clone method. *
* This Memory allows to have the same element twice. *
**********************************************************************
*/
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
//'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Memory:"],
/*
* Instance variables of the class.
* Since we want them to be private, we'll define them in the constructor.
*/
// '@properties': {
// array: undefined,
// size: 0,
// used: 0
// },
/*
* Creates a memory with 'size' ammount of frames.
* The proper initialization of the properties must be here.
*/
constructor: function(size) {
this._size = size;
this._array = [];
this._used = 0;
this.log("Created with " + size + " frames.");
},
/*
* Return whether the memory is full or not.
*/
isFull: function() {
if (this._used === this._size) {
return true;
}
return false;
},
/*
* Short circuit search for a free frame.
* Returns the index of a free frame if there is one.
* Otherwise return -1.
*/
getFreeFrame: function() {
//Ensure there is space before searching for it.
if(this.isFull()) {
return -1;
}
//Move all initializations out of the loop.
var i = 0;
var array = this._array;
var length = this._size;
for (; i < length; i++) {
if (array[i] == undefined) {
return i;
}
}
},
/*
* Look for the frame that contains the element.
* If the element isn't found, return -1.
* This method is identical to Queue.js indexOf.
*/
getFrameOf: function(element) {
//Move all asignations out of the loop.
var i = 0;
var array = this._array;
var length = array.length;
//Ask for the supported comparing method of the element.
var areEquals = Behavior.ComparingMethod(element);
for(; i< length; i++) {
if(areEquals(element, array[i])) {
return i;
}
}
return -1
},
/*
* Returns whether an element is already in the Memory.
*/
contains: function(element) {
if(this.getFrameOf(element) === -1) {
return false;
}
return true;
},
/*
* Returns a reference to the frame in the position of the Memory.
* If the request ask for a frame out of bounds, return undefined.
*
* BEWARE THAT THIS METHOD DOESN'T DIFFERENCE BETWEEN ACCESSING TO
* AN OUT OF BOUND POSITION OR ACCESING TO AN UNDEFINED FRAME.
*
* **Should it return a copy(C++ const.)?**
*/
at: function(position) {
//Check if the position is out of the array.
if(position < 0 || position >= this._size) {
this.log("Access to the position " + position + " out of bounds. Access denied.");
return undefined;
}
return this._array[position];
},
/*
* Add an element to a certain position of the Memory.
* If the position is out of bounds, return false.
* Return true when the operation is completed succesfully.
*/
atPut: function(position, element) {
//Check if the position is out of the array.
if(position < 0 || position >= this._size) {
this.log("Access to the position " + position + " out of bounds. Access denied.");
return false;
}
//Check if the element is not defined or is empty
if(!element || (typeof element === 'object' && !Object.keys(element).length)) {
this.log("Element should be not undefined or empty");
return false;
}
//Check if the position was free and add 1 to the used acumulator.
//Log all replaced elements.
if(this.at(position) === undefined) {
this._used = this._used + 1;
} else {
this.log(this.at(position).toString() + " at frame[" + position + "] being replaced.");
}
//Finally add the element to the Memory and log it.
this._array[position] = element;
this.log(element.toString() + " added to the frame[" + position + "].");
return true;
},
/*
* Determines the comparing method used in the Memory objects.
* This is a deep equivalency comparission.
*/
equals: function(obj) {
//For performance improvement, check if they hold the same reference.
if (!obj) {
return false;
}
if(this === obj) {
return true;
}
/*
* Check that the objects are the same class,
* were instantiated with the same params and
* if the internal state of the objects at this given time is "similar".
*/
if(this.constructor !== obj.constructor || this._size !== obj._size || this._used !== obj._used) {
return false;
}
//Then it's time for a deep check.
//Move all asignations out of the loop.
var i = 0;
var myArray = this._array;
var herArray = obj._array;
var length = myArray.length;
/*
* Don't use a forEach loop beacuse it skips undefined values.
* We want to check for those too.
* Also we want to stop in
*/
for(; i < length; i++) {
var myElement = myArray[i];
var herElement = herArray[i];
/*
* If self holds a reference to obj and
* at the same time obj holds a reference to self,
* That would cause an infinite loop so we skip it.
*/
if(myElement !== obj || herElement !== this) {
/*
* Use Behavior to ask for the comparing method of myElement.
* Then call the function with myElement and herElement.
*/
if(!Behavior.ComparingMethod(myElement)(myElement, herElement)) {
return false;
}
}
}
//After iterating all the elements we know for sure that the objects are equivalents.
return true;
},
/*
* Generate a new object equivalent to this one.
* Tries to do a deep clone.
*/
clone: function() {
this.log("---Start of Clonation.---");
//Using Memory class.
var Memory = require('./Memory');
var aux = new Memory(this._size);
var myArray = this._array;
myArray.forEach(function(element, index) {
//Check that the Memory holds a reference to itself.
//Then add a reference to the new object.
if(element == this) {
aux.atPut(index, aux);
} else {
/*
* Use Behavior to ask for the cloning method of element.
* Then call the function with element and assign it to the new Memory.
*/
aux.atPut(index, Behavior.CloningMethod(element)(element));
}
}, this);
this.log("---End of Clonation.---\n");
return aux;
},
forEach: function(exec, that) {
var myArray = this._array;
if ( typeof exec !== 'function')
throw new Error('First param must be a function')
if(that) {
myArray.forEach(function(element, index) {
//Use the contex passed by the caller in the execution of the function.
exec.call(that, element, index);
},that);
} else {
//If no contex was especified use a simple forEach.
myArray.forEach(function(element, index) {
exec(element, index);
});
}
}
});
},{"../annotations/Logger":31,"./Behavior":35,"./Memory":36,"cocktail":13}],37:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Inheriting from Requirement Class.
var Requirement = require('./Requirement');
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
var Configurable = require('cocktail-trait-configurable');
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
'@extends' : Requirement,
'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Page:"],
//Instance variables of the class.
'@properties': {
pageFault: false,
referenced: false,
modified: false,
reservedForAsyncFlush: false
},
/*
* The constructor accept an object like this:
* {
* 'process': 'A',
* 'pageNumber': 1,
* 'mode' : 'write',
* 'pageFault' : false,
* 'referenced': false,
* 'modified' : false,
* 'reservedForAsyncFlush' : false
* }
* Automaticaly is maped to the corresponding properties
* thanks to the Configurable trait.
*/
//@Override
asDataObject: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
referenced : this.isReferenced(),
modified: this.isModified(),
reservedForAsyncFlush: this.isReservedForAsyncFlush()
}
return obj;
},
asVictim: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
referenced : this.isReferenced(),
modified: this.isModified(),
}
return obj;
},
//@Override
clone : function() {
var Page = require('./Page');
var aux = new Page(this.asDataObject());
return aux;
},
//Clearing Page flags methods.
clearPageFault: function() {
this.setPageFault(false);
return this;
},
clearReferenced: function() {
this.setReferenced(false);
return this;
},
clearModified: function() {
this.setModified(false);
},
clearReservedForAsyncFlush: function() {
this.reservedForAsyncFlush(false);
},
clearAll: function() {
this.clearPageFault();
this.clearReferenced();
this.clearModified();
return this;
},
//@Override
asPage: function() {
return this.clone();
}
});
},{"../annotations/Logger":31,"./Page":37,"./Requirement":38,"cocktail":13,"cocktail-trait-configurable":12}],38:[function(require,module,exports){
var cocktail = require('cocktail');
//Add Logger annotation.
var Logger = require('../annotations/Logger');
cocktail.use(Logger);
//Using Behavior class.
var Behavior = require('./Behavior');
//This class uses Page class, but its requirement is delayed until runtime.
/*
* Adding this trait lets the constructor accept an object as parameter.
* Automaticaly, it will map the properties of the object with
* the properties defined as instance variables.
*/
var Configurable = require('cocktail-trait-configurable');
cocktail.mix({
//Define this file as a single class module exportable.
'@exports' : module,
'@as' : 'class',
'@traits' : [Configurable],
//Set the logger and signature of this class.
'@logger' : [console, "Requirement:"],
//Instance variables of the class.
'@properties': {
process: "",
pageNumber: 0,
mode: "read"
},
/*
* The constructor accept an object like this:
* {
* 'process': 'A',
* 'pageNumber': 1,
* 'mode' : 'write'
* }
* Automaticaly is maped to the corresponding properties
* thanks to the Configurable trait.
*/
constructor: function(options) {
this.configure(options);
//Check that the object was created fine.
if(this.validate) {
this.log("Created.");
} else {
//This warning should be seen even in production.
console.warn("A requirement was created with default values.");
}
},
validate: function() {
var process = this.getProcess();
var pageNumber = this.getPageNumber();
var mode = this.getMode();
if ((process == "") || (typeof pageNumber !== "number") ||
(mode !== "read" && mode !== "write" && mode !== "finish" && mode !== "reserved")) {
return false;
}
return true;
},
equals: function(obj) {
//For performance improvement, check if they hold the same reference.
if (!obj) {
return false;
}
if(this === obj) {
return true;
}
/*
* Check that the objects are the same class,
* were instantiated with the same params and
* if the internal state of the objects at this given time is "similar".
*/
if(this.constructor !== obj.constructor || this.getProcess() !== obj.getProcess() ||
this.getPageNumber() !== obj.getPageNumber()) {
return false;
}
//Seems like they are the same.
return true;
},
asDataObject: function() {
var obj =
{
process : this.getProcess(),
pageNumber : this.getPageNumber(),
mode: this.getMode()
}
return obj;
},
asPage: function() {
var obj = this.asDataObject();
//Set a requirement on page fault by default.
obj.pageFault = true;
obj.referenced = true;
obj.modified = false;
obj.reservedForAsyncFlush = false;
//Using Page class.
var Page = require('./Page');
var aux = new Page(obj);
return aux;
},
clone : function() {
var Requirement = require('./Requirement');
var aux = new Requirement(this.asDataObject());
return aux;
},
toString: function() {
return JSON.stringify(this.asDataObject());
}
});
},{"../annotations/Logger":31,"./Behavior":35,"./Page":37,"./Requirement":38,"cocktail":13,"cocktail-trait-configurable":12}],39:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../../annotations/Logger');
var VictimsStructureInterface = require('./VictimsStructureInterface');
cocktail.use(Logger);
cocktail.mix({
//Define this file as a single class module exportable.
'@exports': module,
'@as': 'class',
'@traits': [VictimsStructureInterface],
'@logger' : [console, "VictimsQueue:"],
constructor: function() {
/*
* According to @elmasse default variable initialization must be done
* in the constructor and not in the @properties declaration.
*/
this._array = [];
this.log("Created.");
},
/*
* Add a page to the Queue.
*/
add: function(page) {
if(!this.contains(page)) {
this._array.push(page);
this.log(page.toString() + " added.");
} else {
this.log(page.toString() + " was already on the Queue.")
}
return this;
},
/*
* Add multiple pages to the Queue using the add method.
* collection must implement the forEach method as it is in Array.
*/
addAll: function(collection) {
this.log("Massive assignment started.");
collection.forEach(function(page) {
this.add(page);
}, this);
this.log("Massive assignment finished.");
return this;
},
/*
* Returns the size of the queue at a given time.
*/
size: function() {
return this._array.length;
},
/*
* Returns a reference to the first page of the Queue.
* The page is conserved in the structure.
*/
peek: function() {
return this._array[0];
},
/*
* Returns the first page of the Queue deleting it from the structure.
*/
first: function() {
var page = this._array.shift();
if (page) {
this.log(page.toString() + " removed.");
}
return page;
},
remove: function(requirement) {
var index = this._indexOf(requirement);
if (index != -1) {
return (this._array.splice(index, 1))[0];
}
return undefined;
},
recycle: function(requirement) {
if(this.remove(requirement)) {
this.add(requirement);
}
},
/*
* Determines if a requirement exists in the queue.
* If its found return the index of the element in the array.
* Otherwise return -1.
*/
_indexOf: function (requirement) {
var i = 0;
var array = this._array;
var length = array.length;
//Use a normal looping to stop when a match is encountered.
for(; i < length; i++) {
// console.log(requirement);
if(requirement.equals(array[i])) {
return i;
}
}
return -1
},
/*
* Returns a reference to the page in the queue
* That matches the asked requirement.
*/
pageOf: function(requirement) {
var index = this._indexOf(requirement);
if( index === -1) {
return undefined;
}
return this._array[index];
},
/*
* Returns whether an element is already in the Queue.
*/
contains: function (element) {
if (this._indexOf(element) === -1) {
return false;
}
return true;
},
clone: function() {
var aux = new this.constructor();
this._array.forEach(function(page) {
aux.add(page.clone());
});
return aux;
},
forEach: function(exec, that) {
var myArray = this._array;
if ( typeof exec !== 'function')
throw new Error('First param must be a function')
if(that) {
myArray.forEach(function(element, index) {
//Use the contex passed by the caller in the execution of the function.
exec.call(that, element, index);
},that);
} else {
//If no contex was especified use a simple forEach.
myArray.forEach(function(element, index) {
exec(element, index);
});
}
},
/*
* Removes all objects from the Queue.
*/
clear: function() {
this._array = [];
this.log("Cleared.");
}
});
},{"../../annotations/Logger":31,"./VictimsStructureInterface":41,"cocktail":13}],40:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../../annotations/Logger');
var VictimsStructureInterface = require('./VictimsStructureInterface');
var Queue = require('./Queue');
cocktail.use(Logger);
/*
**********************************************************************
* This Queue doesn't define Equals nor Clone method. Should it? *
* This Queue doesn't allow to have the same element twice. *
**********************************************************************
*/
cocktail.mix({
//Define this file as a single class module exportable.
'@exports': module,
'@as': 'class',
'@extends': Queue,
'@traits': [VictimsStructureInterface],
'@logger' : [console, "VictimsReQQueue:"],
/*
* Add a page to the Queue.
* If the page is already in the queue, remove it,
* then enqueue it again.
*/
//@Override
add: function(page) {
//Don't use contains method here because
//you would have to search again for the index.
var array = this._array;
var index = this._indexOf(page);
if (index != -1) {
array.splice(index ,1);
this.log(page.toString() + " removed. Waiting to requeue.");
}
this.callSuper("add", page);
return this;
},
clone: function() {
var ReQueueQueue = require('./ReQueueQueue');
var aux = new ReQueueQueue();
this._array.forEach(function(page) {
aux.add(page.clone());
});
return aux;
}
});
},{"../../annotations/Logger":31,"./Queue":39,"./ReQueueQueue":40,"./VictimsStructureInterface":41,"cocktail":13}],41:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': [
'add',
'addAll',
'clone',
'first',
'peek',
'remove',
'recycle',
'contains',
'pageOf',
'size',
'clear'
]
});
},{"cocktail":13}],42:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "AsyncFlushReplacementPolicy:"],
constructor: function(counterpartFilter) {
//This counterpart is the AsyncFlushAssignmentPolicy.
this._counterpart = counterpartFilter;
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
//If the next victim was modified, use the async flush reserved memory field.
if (potentialVictim.isModified()) {
this.log("The victim " + potentialVictim + " was modified, applying async flush.");
this._counterpart.updatePosition(potentialVictim);
context._victims.remove(potentialVictim);
var reservedForAsync = this._counterpart.getReserved();
//Ensure that the only posible victim is the reserved field.
filteredVictims.clear();
filteredVictims.add(reservedForAsync);
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}],43:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "LocalReplacementPolicy:"],
constructor: function() {
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
while(filteredVictims.size() && potentialVictim.getProcess() !== requirement.getProcess()) {
this.log("The victim " + potentialVictim + " was isn't from the same process, Applying Local filter.");
//Remove the page from the filteredVictims structure.
filteredVictims.remove(potentialVictim);
//get a new potentialVictim
potentialVictim = filteredVictims.peek();
}
if (!filteredVictims.size()) {
throw new Error("The new process has no free frames to be assigned!!");
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}],44:[function(require,module,exports){
var cocktail = require('cocktail');
//Using a trait as an interface.
cocktail.mix({
'@exports': module,
'@requires': ['apply']
});
},{"cocktail":13}],45:[function(require,module,exports){
var cocktail = require('cocktail');
var Logger = require('../annotations/Logger');
var ReplacementFilterInterface = require('./ReplacementFilterInterface');
cocktail.use(Logger);
cocktail.mix({
'@exports': module,
'@as': 'class',
'@traits': [ReplacementFilterInterface],
'@logger' : [console, "SecondChanceReplacementPolicy:"],
constructor: function() {
this.log("Created.");
},
apply: function(filteredVictims, requirement, context) {
var potentialVictim = filteredVictims.peek();
while(potentialVictim.isReferenced()) {
this.log("The victim " + potentialVictim + " was referenced, applying 2nd chance.");
//Recycle the page in the filteredVictims structure until we get one not referenced.
//Clear the potentialVictim referenced flag.
potentialVictim.clearReferenced();
filteredVictims.recycle(potentialVictim);
context.recycle(potentialVictim);
//get a new potentialVictim
potentialVictim = filteredVictims.peek();
}
}
});
},{"../annotations/Logger":31,"./ReplacementFilterInterface":44,"cocktail":13}]},{},[1,2,3,4,5]);
| updated sams module
| dist/js/sams.js | updated sams module | <ide><path>ist/js/sams.js
<ide> this.log("All policies cleared.")
<ide> },
<ide>
<add> _clearBuffers: function(arguments) {
<add> if (this._memorySize) {
<add> this._memory = new Memory(this._memorySize);
<add> }
<add> this._moments = [];
<add> this._resetPolicies();
<add> this.log("All buffers cleared.");
<add> },
<add>
<add> _resetPolicies: function() {
<add> if (this.isFixedEvenAssignmentPolicy()) {
<add> this.setFixedEvenAssignmentPolicy(this._assignmentPolicies[0].localSize());
<add> }
<add> if (this.isLocalReplacementPolicy()) {
<add> this.setLocalReplacementPolicy(true);
<add> }
<add> if (this.isAsyncFlushPolicy()) {
<add> this.setAsyncFlushReplacementPolicy(true);
<add> }
<add> if (this.isSecondChanceReplacementPolicy()) {
<add> this.setSecondChanceReplacementPolicy(true);
<add> }
<add> },
<add>
<ide> setMemorySize: function(size) {
<ide> if (!size) {
<ide> return;
<ide> }
<ide> this._memory = new Memory(size);
<ide> this._memorySize = size;
<add> // this._resetPolicies();
<ide> this._updatePolicies();
<ide> },
<ide>
<ide> //Here we use the context to bind the array in which i want the pages to be added.
<ide> this._moments.forEach(function(moment) {
<ide> var singleMoment = {
<del> requirement: moment.requirement.asDataObject(),
<add> requirement: moment.requirement,
<ide> pageFault: moment.pageFault,
<del> frames: [],
<del> victim: (moment.victim)? moment.victim.asVictim() : undefined,
<del> potentialVictims: []
<del> }
<del>
<del> //Here too (it's a matrix).
<del> moment.instant.forEach(function(page) {
<del> this.push(page.asDataObject());
<del> }, singleMoment.frames);
<del>
<del> moment.potentialVictims.forEach(function(potentialVictim) {
<del> this.push(potentialVictim.asVictim());
<del> }, singleMoment.potentialVictims)
<add> frames: moment.instant,
<add> victim: moment.victim,
<add> potentialVictims: moment.potentialVictims
<add> }
<ide>
<ide> this.push(singleMoment);
<ide>
<ide>
<ide> this.log("---Finished generating the output matrix.---\n");
<ide> return allMoments;
<del> },
<del>
<del> _clearBuffers: function(arguments) {
<del> if (this._memorySize) {
<del> this._memory = new Memory(this._memorySize);
<del> }
<del> this._moments = [];
<del> //this._requirements = [];
<del> this.log("All buffers cleared.");
<ide> },
<ide>
<ide> // To be implemented with FixedEven assignment filter.
<ide> return hasSpace;
<ide> },
<ide>
<del> _update: function(requirement) {
<add> _saveMoment: function(requirement, pageFault, victim) {
<add> this.log("Saving moment " + this._moments.length + ".");
<add> var moment = {
<add> requirement: requirement.asDataObject(),
<add> instant: [],
<add> pageFault: pageFault,
<add> victim: victim? victim.asVictim(): undefined,
<add> potentialVictims: []
<add> };
<add>
<add> this._memory.forEach(function(frame) {
<add> this.push(frame.asDataObject());
<add> }, moment.instant);
<add>
<add> this._algorithm.getVictimsStructure().forEach(function(potentialVictim) {
<add> this.push(potentialVictim.asVictim());
<add> }, moment.potentialVictims);
<add>
<add> this._moments.push(moment);
<add> this.log("Moment " + (this._moments.length -1) + " saved.\n");
<add> },
<add>
<add> _update: function(requirement, pageFault, victim) {
<ide> this._algorithm.update(requirement);
<del> this._updateMemory(requirement);
<add> this._updateMemory(requirement, pageFault);
<ide> this._updatePolicies();
<ide> },
<ide>
<del> _updateMemory: function(requirement) {
<add> _updateMemory: function(requirement, pageFault) {
<ide> // Assume that the requirement is already in memory.
<ide> var page = this._memory.at(this._memory.getFrameOf(requirement));
<del> page.setReferenced(true);
<add>
<add> page.setRequired(true);
<add>
<ide> if (requirement.getMode() === "write") {
<ide> page.setModified(true);
<add> }
<add>
<add> if (!pageFault) {
<add> page.setReferenced(true);
<add> } else {
<add> page.setPageFault(true);
<ide> }
<ide> },
<ide>
<ide> }, this);
<ide> },
<ide>
<del> _saveMoment: function(requirement, pageFault, victim) {
<del> this.log("Saving moment " + this._moments.length + ".");
<del> var moment = {
<del> requirement: requirement.clone(),
<del> instant: this._memory.clone(),
<del> pageFault: pageFault,
<del> victim: victim,
<del> potentialVictims: this._algorithm.getVictimsStructure()
<del> };
<del> this._moments.push(moment);
<del> this.log("Moment " + (this._moments.length -1) + " saved.\n");
<del> },
<del>
<del> _clearMemoryFlags: function() {
<add> _clearTemporalFlags: function() {
<ide> this._memory.forEach(function(page) {
<add> page.clearRequired();
<ide> page.clearPageFault();
<del> if (!this.getSecondChanceReplacementPolicy()) {
<del> page.clearReferenced();
<del> }
<ide> }, this);
<del> this.log("All page flags cleared.");
<add> this.log("Temporal page flags cleared.");
<ide> },
<ide>
<ide> _processRequirements: function() {
<ide> this._requirements.forEach(function(requirement) {
<ide> // Start with a clean image of the frames.
<del> this._clearMemoryFlags();
<add> this._clearTemporalFlags();
<ide> //Declare victim here because it'll be used for update.
<ide> var victim = {
<ide> frame: undefined,
<ide> }
<ide> this._memory.atPut(frame, requirement.asPage());
<ide> }
<del> // Even if it's a page fault or not, call to update.
<del> this._update(requirement);
<add> this._update(requirement, pageFault, victim.page);
<ide> this._saveMoment(requirement, pageFault, victim.page);
<ide> }, this);
<ide> }
<ide> },
<ide>
<ide> getVictimsStructure: function() {
<del> return this._victims.clone();
<add> return this._victims;
<ide> },
<ide>
<ide> initialize: function(requirements) {
<ide> if (position.isReservedForAsyncFlush()) {
<ide> victim = this._filters[1]._counterpart._memory.at(this._filters[1]._counterpart._position);
<ide> }
<del>
<add>
<ide> var result = {
<ide> frame: position,
<ide> page: victim
<ide> this.log("Created.");
<ide> },
<ide>
<add> initialize: function(requirements) {
<add> this.callSuper("initialize", requirements);
<add> this._victims = new Queue();
<add> },
<add>
<ide> addPage: function(requirement) {
<ide> this._victims.add(requirement.asPage().clearAll());
<ide> },
<ide> this.log("Updated victim queue, referenced.");
<ide> }
<ide> if(requirement.getMode() === "write") {
<add> this._victims.pageOf(requirement).setReferenced(true);
<ide> this._victims.pageOf(requirement).setModified(true);
<del> this.log("Updated victim queue, modified.");
<add> this.log("Updated victim queue, modified & referenced.");
<ide> }
<ide> return;
<ide> }
<ide> this.callSuper("constructor");
<ide> this._victims = new ReQueueQueue();
<ide> this.log("Created.");
<add> },
<add>
<add> initialize: function(requirements) {
<add> this.callSuper("initialize", requirements);
<add> this._victims = new ReQueueQueue();
<ide> }
<ide> });
<ide>
<ide> 'pageNumber': 0,
<ide> 'mode' : 'reserved',
<ide> 'pageFault' : false,
<add> 'required' : false,
<ide> 'referenced': false,
<ide> 'modified': false,
<ide> 'reservedForAsyncFlush': true
<ide>
<ide> update: function(memory, context) {
<ide> //Nothing to do here.
<add> },
<add>
<add> localSize: function() {
<add> return this._size;
<ide> }
<ide> });
<ide>
<ide> //Instance variables of the class.
<ide> '@properties': {
<ide> pageFault: false,
<add> required : false,
<ide> referenced: false,
<ide> modified: false,
<ide> reservedForAsyncFlush: false
<ide> * 'pageNumber': 1,
<ide> * 'mode' : 'write',
<ide> * 'pageFault' : false,
<add> * 'required' : false,
<ide> * 'referenced': false,
<ide> * 'modified' : false,
<ide> * 'reservedForAsyncFlush' : false
<ide> {
<ide> process : this.getProcess(),
<ide> pageNumber : this.getPageNumber(),
<add> pageFault : this.isPageFault(),
<add> required : this.isRequired(),
<ide> referenced : this.isReferenced(),
<ide> modified: this.isModified(),
<ide> reservedForAsyncFlush: this.isReservedForAsyncFlush()
<ide> }
<ide> return obj;
<ide> },
<del>
<add>
<ide> //@Override
<ide> clone : function() {
<ide> var Page = require('./Page');
<ide> return this;
<ide> },
<ide>
<add> clearRequired: function() {
<add> this.setRequired(false);
<add> return this;
<add> },
<add>
<ide> clearReferenced: function() {
<ide> this.setReferenced(false);
<ide> return this;
<ide> },
<ide>
<ide> clearReservedForAsyncFlush: function() {
<del> this.reservedForAsyncFlush(false);
<add> this.setReservedForAsyncFlush(false);
<ide> },
<ide>
<ide> clearAll: function() {
<ide> this.clearPageFault();
<add> this.clearRequired();
<ide> this.clearReferenced();
<ide> this.clearModified();
<add> this.clearReservedForAsyncFlush();
<ide> return this;
<ide> },
<ide>
<ide> asPage: function() {
<ide> var obj = this.asDataObject();
<ide> //Set a requirement on page fault by default.
<del> obj.pageFault = true;
<del> obj.referenced = true;
<add> obj.pageFault = false;
<add> obj.required = false;
<add> obj.referenced = false;
<ide> obj.modified = false;
<ide> obj.reservedForAsyncFlush = false;
<ide> |
|
Java | apache-2.0 | 6e9d7fbca2205d04c9b7ea7f337ac60d12f59748 | 0 | Zrips/Jobs | package com.gamingmesh.jobs.Gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.CMIGUI.CMIGui;
import com.gamingmesh.jobs.CMIGUI.CMIGuiButton;
import com.gamingmesh.jobs.CMIGUI.GUIManager;
import com.gamingmesh.jobs.CMIGUI.GUIManager.GUIClickType;
import com.gamingmesh.jobs.CMILib.CMIMaterial;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.Boost;
import com.gamingmesh.jobs.container.CurrencyType;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobInfo;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
public class GuiManager {
public void openJobsBrowseGUI(final Player player) {
ArrayList<Job> JobsList = new ArrayList<>();
for (Job job : Jobs.getJobs()) {
if (Jobs.getGCManager().getHideJobsWithoutPermission())
if (!Jobs.getCommandManager().hasJobPermission(player, job))
continue;
JobsList.add(job);
}
CMIGui gui = new CMIGui(player);
gui.setTitle(Jobs.getLanguage().getMessage("command.info.gui.pickjob"));
gui.setFiller(CMIMaterial.get(Jobs.getGCManager().guiFiller));
int GuiSize = Jobs.getGCManager().getJobsGUIRows() * 9;
int neededSlots = JobsList.size() + ((JobsList.size() / Jobs.getGCManager().getJobsGUIGroupAmount()) * Jobs.getGCManager().getJobsGUISkipAmount()) + Jobs.getGCManager().getJobsGUIStartPosition();
int neededRows = (int) Math.ceil(neededSlots / 9D);
// Resizing GUI in case we have more jobs then we could fit in current setup
GuiSize = Jobs.getGCManager().getJobsGUIRows() > neededRows ? GuiSize : neededRows * 9;
// Lets avoid oversized GUI
GuiSize = GuiSize > 54 ? 54 : GuiSize;
gui.setInvSize(GuiSize);
JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
int i = 0;
int pos = Jobs.getGCManager().getJobsGUIStartPosition() - 1;
// Changing start position to 0 in case we have more jobs then we can fit in current setup
pos = JobsList.size() > 28 ? JobsList.size() <= 42 ? 0 : -1 : pos;
int group = 0;
main: for (int z = 0; z < JobsList.size(); z++) {
group++;
if (group > Jobs.getGCManager().getJobsGUIGroupAmount()) {
group = 1;
// Only add skip if we can fit all of them in max sized Gui
if (JobsList.size() <= 42) {
pos += Jobs.getGCManager().getJobsGUISkipAmount();
}
}
pos++;
if (i >= JobsList.size())
break main;
Job job = JobsList.get(i);
ArrayList<String> Lore = new ArrayList<>();
for (JobProgression onePJob : JPlayer.getJobProgression()) {
if (onePJob.getJob().getName().equalsIgnoreCase(job.getName()))
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.working"));
}
int maxlevel = job.getMaxLevel(JPlayer);
if (maxlevel > 0)
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.max") + maxlevel);
if (Jobs.getGCManager().ShowTotalWorkers)
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.totalWorkers", "[amount]", job.getTotalPlayers()));
if (Jobs.getGCManager().useDynamicPayment && Jobs.getGCManager().ShowPenaltyBonus)
if (job.getBonus() < 0)
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.penalty", "[amount]", (int) (job.getBonus() * 100) * -1));
else
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.bonus", "[amount]", (int) (job.getBonus() * 100)));
Lore.addAll(Arrays.asList(job.getDescription().split("/n")));
if (job.getMaxSlots() != null)
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.leftSlots") + ((job.getMaxSlots() - Jobs.getUsedSlots(job)) > 0 ? (job.getMaxSlots() - Jobs
.getUsedSlots(job)) : 0));
if (Jobs.getGCManager().ShowActionNames) {
Lore.add("");
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.actions"));
for (ActionType actionType : ActionType.values()) {
List<JobInfo> info = job.getJobInfo(actionType);
if (info != null && !info.isEmpty()) {
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
}
}
}
Lore.add("");
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.leftClick"));
if (JPlayer.isInJob(job))
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.middleClick"));
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.rightClick"));
ItemStack GuiItem = job.getGuiItem();
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
gui.addButton(new CMIGuiButton(pos, GuiItem) {
@Override
public void click(GUIClickType type) {
switch (type) {
case Left:
case LeftShift:
if (Jobs.getGCManager().JobsGUISwitcheButtons) {
if (!Jobs.getGCManager().DisableJoiningJobThroughGui) {
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "join", job.getName() });
} else {
player.sendMessage(Jobs.getLanguage().getMessage("command.info.gui.cantJoin"));
}
openJobsBrowseGUI(player);
} else {
openJobsBrowseGUI(player, job);
}
break;
case MiddleMouse:
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "leave", job.getName() });
openJobsBrowseGUI(player);
break;
case Right:
case RightShift:
if (Jobs.getGCManager().JobsGUISwitcheButtons) {
openJobsBrowseGUI(player, job);
} else {
if (!Jobs.getGCManager().DisableJoiningJobThroughGui) {
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "join", job.getName() });
} else {
player.sendMessage(Jobs.getLanguage().getMessage("command.info.gui.cantJoin"));
}
openJobsBrowseGUI(player);
}
break;
default:
break;
}
}
});
i++;
}
gui.fillEmptyButtons();
gui.open();
}
public void openJobsBrowseGUI(Player player, Job job) {
openJobsBrowseGUI(player, job, false);
}
public void openJobsBrowseGUI(Player player, Job job, boolean fromCommand) {
Inventory tempInv = Bukkit.createInventory(player, 54, "");
JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
Boost boost = Jobs.getPlayerManager().getFinalBonus(JPlayer, job);
int level = 1;
JobProgression prog = JPlayer.getJobProgression(job);
if (prog != null)
level = prog.getLevel();
ItemStack GuiItem = job.getGuiItem();
int numjobs = JPlayer.getJobProgression().size();
int i = 0;
for (ActionType actionType : ActionType.values()) {
List<JobInfo> info = job.getJobInfo(actionType);
if (info == null || info.isEmpty())
continue;
ArrayList<String> Lore = new ArrayList<>();
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
int y = 1;
for (int z = 0; z < info.size(); z++) {
JobInfo jInfo = info.get(z);
if (jInfo == null) {
continue;
}
double income = jInfo.getIncome(level, numjobs);
income = boost.getFinalAmount(CurrencyType.MONEY, income) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
.get(CurrencyType.MONEY)) + 1);
String incomeColor = income >= 0 ? "" : ChatColor.DARK_RED.toString();
double xp = jInfo.getExperience(level, numjobs);
xp = boost.getFinalAmount(CurrencyType.EXP, xp) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
.get(CurrencyType.EXP)) + 1);
String xpColor = xp >= 0 ? "" : ChatColor.GRAY.toString();
double points = jInfo.getPoints(level, numjobs);
points = boost.getFinalAmount(CurrencyType.POINTS, points) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
.get(CurrencyType.POINTS)) + 1);
String pointsColor = xp >= 0 ? "" : ChatColor.RED.toString();
if (income == 0D && points == 0D && xp == 0D)
continue;
String itemName = jInfo.getRealisticName();
String val = "";
if (income != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.money", "%money%", incomeColor +
String.format(Jobs.getGCManager().getDecimalPlacesMoney(), income));
if (points != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.points", "%points%", pointsColor
+ String.format(Jobs.getGCManager().getDecimalPlacesPoints(), points));
if (xp != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.exp", "%exp%", xpColor
+ String.format(Jobs.getGCManager().getDecimalPlacesExp(), xp));
Lore.add(Jobs.getLanguage().getMessage("command.info.help.material", "%material%", itemName) + val);
if (y >= 10) {
y = 1;
if (z == info.size() - 1)
continue;
if (i >= 54) {
break;
}
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
tempInv.setItem(i, GuiItem.clone());
GuiItem = job.getGuiItem();
Lore = new ArrayList<>();
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
i++;
}
y++;
}
// TODO: Make new page when the gui size is bigger than 54
if (i >= 54) {
break;
}
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
tempInv.setItem(i, GuiItem.clone());
i++;
}
List<ItemStack> items = new ArrayList<>();
for (ItemStack one : tempInv.getContents()) {
if (one != null)
items.add(one);
}
int GuiSize = GUIManager.isOpenedGui(player) && GUIManager.getGui(player) != null ?
GUIManager.getGui(player).getInvSize().getFields() : Jobs.getGCManager().getJobsGUIRows() * 9;
int backButton = Jobs.getGCManager().getJobsGUIBackButton();
CMIGui gui = new CMIGui(player);
gui.setTitle(Jobs.getLanguage().getMessage("command.info.gui.jobinfo", "[jobname]", job.getName()));
gui.setFiller(CMIMaterial.get(Jobs.getGCManager().guiFiller));
gui.setInvSize(GuiSize);
for (int i1 = 0; i1 < items.size(); i1++) {
gui.addButton(new CMIGuiButton(i1, items.get(i1)));
}
if (fromCommand) {
return;
}
ItemStack skull = Jobs.getGCManager().guiBackButton;
ItemMeta skullMeta = skull.getItemMeta();
skullMeta.setDisplayName(Jobs.getLanguage().getMessage("command.info.gui.back"));
skull.setItemMeta(skullMeta);
gui.addButton(new CMIGuiButton(backButton, skull) {
@Override
public void click(GUIClickType type) {
openJobsBrowseGUI(player);
}
});
gui.fillEmptyButtons();
gui.open();
}
}
| src/main/java/com/gamingmesh/jobs/Gui/GuiManager.java | package com.gamingmesh.jobs.Gui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import com.gamingmesh.jobs.Jobs;
import com.gamingmesh.jobs.CMIGUI.CMIGui;
import com.gamingmesh.jobs.CMIGUI.CMIGuiButton;
import com.gamingmesh.jobs.CMIGUI.GUIManager;
import com.gamingmesh.jobs.CMIGUI.GUIManager.GUIClickType;
import com.gamingmesh.jobs.CMILib.CMIMaterial;
import com.gamingmesh.jobs.container.ActionType;
import com.gamingmesh.jobs.container.Boost;
import com.gamingmesh.jobs.container.CurrencyType;
import com.gamingmesh.jobs.container.Job;
import com.gamingmesh.jobs.container.JobInfo;
import com.gamingmesh.jobs.container.JobProgression;
import com.gamingmesh.jobs.container.JobsPlayer;
public class GuiManager {
public void openJobsBrowseGUI(final Player player) {
ArrayList<Job> JobsList = new ArrayList<>();
for (Job job : Jobs.getJobs()) {
if (Jobs.getGCManager().getHideJobsWithoutPermission())
if (!Jobs.getCommandManager().hasJobPermission(player, job))
continue;
JobsList.add(job);
}
CMIGui gui = new CMIGui(player);
gui.setTitle(Jobs.getLanguage().getMessage("command.info.gui.pickjob"));
gui.setFiller(CMIMaterial.get(Jobs.getGCManager().guiFiller));
int GuiSize = Jobs.getGCManager().getJobsGUIRows() * 9;
int neededSlots = JobsList.size() + ((JobsList.size() / Jobs.getGCManager().getJobsGUIGroupAmount()) * Jobs.getGCManager().getJobsGUISkipAmount()) + Jobs.getGCManager().getJobsGUIStartPosition();
int neededRows = (int) Math.ceil(neededSlots / 9D);
// Resizing GUI in case we have more jobs then we could fit in current setup
GuiSize = Jobs.getGCManager().getJobsGUIRows() > neededRows ? GuiSize : neededRows * 9;
// Lets avoid oversized GUI
GuiSize = GuiSize > 54 ? 54 : GuiSize;
gui.setInvSize(GuiSize);
JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
int i = 0;
int pos = Jobs.getGCManager().getJobsGUIStartPosition() - 1;
// Changing start position to 0 in case we have more jobs then we can fit in current setup
pos = JobsList.size() > 28 ? JobsList.size() <= 42 ? 0 : -1 : pos;
int group = 0;
main: for (int z = 0; z < JobsList.size(); z++) {
group++;
if (group > Jobs.getGCManager().getJobsGUIGroupAmount()) {
group = 1;
// Only add skip if we can fit all of them in max sized Gui
if (JobsList.size() <= 42) {
pos += Jobs.getGCManager().getJobsGUISkipAmount();
}
}
pos++;
if (i >= JobsList.size())
break main;
Job job = JobsList.get(i);
ArrayList<String> Lore = new ArrayList<>();
for (JobProgression onePJob : JPlayer.getJobProgression()) {
if (onePJob.getJob().getName().equalsIgnoreCase(job.getName()))
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.working"));
}
int maxlevel = job.getMaxLevel(JPlayer);
if (maxlevel > 0)
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.max") + maxlevel);
if (Jobs.getGCManager().ShowTotalWorkers)
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.totalWorkers", "[amount]", job.getTotalPlayers()));
if (Jobs.getGCManager().useDynamicPayment && Jobs.getGCManager().ShowPenaltyBonus)
if (job.getBonus() < 0)
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.penalty", "[amount]", (int) (job.getBonus() * 100) * -1));
else
Lore.add(Jobs.getLanguage().getMessage("command.browse.output.bonus", "[amount]", (int) (job.getBonus() * 100)));
Lore.addAll(Arrays.asList(job.getDescription().split("/n")));
if (job.getMaxSlots() != null)
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.leftSlots") + ((job.getMaxSlots() - Jobs.getUsedSlots(job)) > 0 ? (job.getMaxSlots() - Jobs
.getUsedSlots(job)) : 0));
if (Jobs.getGCManager().ShowActionNames) {
Lore.add("");
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.actions"));
for (ActionType actionType : ActionType.values()) {
List<JobInfo> info = job.getJobInfo(actionType);
if (info != null && !info.isEmpty()) {
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
}
}
}
Lore.add("");
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.leftClick"));
if (JPlayer.isInJob(job))
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.middleClick"));
Lore.add(Jobs.getLanguage().getMessage("command.info.gui.rightClick"));
ItemStack GuiItem = job.getGuiItem();
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
gui.addButton(new CMIGuiButton(pos, GuiItem) {
@Override
public void click(GUIClickType type) {
switch (type) {
case Left:
case LeftShift:
if (Jobs.getGCManager().JobsGUISwitcheButtons) {
if (!Jobs.getGCManager().DisableJoiningJobThroughGui) {
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "join", job.getName() });
} else {
player.sendMessage(Jobs.getLanguage().getMessage("command.info.gui.cantJoin"));
}
openJobsBrowseGUI(player);
} else {
openJobsBrowseGUI(player, job);
}
break;
case MiddleMouse:
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "leave", job.getName() });
openJobsBrowseGUI(player);
break;
case Right:
case RightShift:
if (Jobs.getGCManager().JobsGUISwitcheButtons) {
openJobsBrowseGUI(player, job);
} else {
if (!Jobs.getGCManager().DisableJoiningJobThroughGui) {
Jobs.getCommandManager().onCommand(player, null, "jobs", new String[] { "join", job.getName() });
} else {
player.sendMessage(Jobs.getLanguage().getMessage("command.info.gui.cantJoin"));
}
openJobsBrowseGUI(player);
}
break;
default:
break;
}
}
});
i++;
}
gui.fillEmptyButtons();
gui.open();
}
public void openJobsBrowseGUI(Player player, Job job) {
openJobsBrowseGUI(player, job, false);
}
public void openJobsBrowseGUI(Player player, Job job, boolean fromCommand) {
Inventory tempInv = Bukkit.createInventory(player, 54, "");
JobsPlayer JPlayer = Jobs.getPlayerManager().getJobsPlayer(player);
Boost boost = Jobs.getPlayerManager().getFinalBonus(JPlayer, job);
int level = 1;
JobProgression prog = JPlayer.getJobProgression(job);
if (prog != null)
level = prog.getLevel();
ItemStack GuiItem = job.getGuiItem();
int numjobs = JPlayer.getJobProgression().size();
int i = 0;
for (ActionType actionType : ActionType.values()) {
List<JobInfo> info = job.getJobInfo(actionType);
if (info == null || info.isEmpty())
continue;
ArrayList<String> Lore = new ArrayList<>();
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
int y = 1;
for (int z = 0; z < info.size(); z++) {
JobInfo jInfo = info.get(z);
if (jInfo == null) {
continue;
}
double income = jInfo.getIncome(level, numjobs);
income = boost.getFinalAmount(CurrencyType.MONEY, income);
String incomeColor = income >= 0 ? "" : ChatColor.DARK_RED.toString();
double xp = jInfo.getExperience(level, numjobs);
xp = boost.getFinalAmount(CurrencyType.EXP, xp);
String xpColor = xp >= 0 ? "" : ChatColor.GRAY.toString();
double points = jInfo.getPoints(level, numjobs);
points = boost.getFinalAmount(CurrencyType.POINTS, points);
String pointsColor = xp >= 0 ? "" : ChatColor.RED.toString();
if (income == 0D && points == 0D && xp == 0D)
continue;
String itemName = jInfo.getRealisticName();
String val = "";
if (income != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.money", "%money%", incomeColor +
String.format(Jobs.getGCManager().getDecimalPlacesMoney(), income));
if (points != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.points", "%points%", pointsColor
+ String.format(Jobs.getGCManager().getDecimalPlacesPoints(), points));
if (xp != 0.0)
val += Jobs.getLanguage().getMessage("command.info.help.exp", "%exp%", xpColor
+ String.format(Jobs.getGCManager().getDecimalPlacesExp(), xp));
Lore.add(Jobs.getLanguage().getMessage("command.info.help.material", "%material%", itemName) + val);
if (y >= 10) {
y = 1;
if (z == info.size() - 1)
continue;
if (i >= 54) {
break;
}
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
tempInv.setItem(i, GuiItem.clone());
GuiItem = job.getGuiItem();
Lore = new ArrayList<>();
Lore.add(Jobs.getLanguage().getMessage("command.info.output." + actionType.getName().toLowerCase() + ".info"));
i++;
}
y++;
}
// TODO: Make new page when the gui size is bigger than 54
if (i >= 54) {
break;
}
ItemMeta meta = GuiItem.getItemMeta();
meta.setDisplayName(job.getChatColor() + job.getName());
meta.setLore(Lore);
GuiItem.setItemMeta(meta);
tempInv.setItem(i, GuiItem.clone());
i++;
}
List<ItemStack> items = new ArrayList<>();
for (ItemStack one : tempInv.getContents()) {
if (one != null)
items.add(one);
}
int GuiSize = GUIManager.isOpenedGui(player) && GUIManager.getGui(player) != null ?
GUIManager.getGui(player).getInvSize().getFields() : Jobs.getGCManager().getJobsGUIRows() * 9;
int backButton = Jobs.getGCManager().getJobsGUIBackButton();
CMIGui gui = new CMIGui(player);
gui.setTitle(Jobs.getLanguage().getMessage("command.info.gui.jobinfo", "[jobname]", job.getName()));
gui.setFiller(CMIMaterial.get(Jobs.getGCManager().guiFiller));
gui.setInvSize(GuiSize);
for (int i1 = 0; i1 < items.size(); i1++) {
gui.addButton(new CMIGuiButton(i1, items.get(i1)));
}
if (fromCommand) {
return;
}
ItemStack skull = Jobs.getGCManager().guiBackButton;
ItemMeta skullMeta = skull.getItemMeta();
skullMeta.setDisplayName(Jobs.getLanguage().getMessage("command.info.gui.back"));
skull.setItemMeta(skullMeta);
gui.addButton(new CMIGuiButton(backButton, skull) {
@Override
public void click(GUIClickType type) {
openJobsBrowseGUI(player);
}
});
gui.fillEmptyButtons();
gui.open();
}
}
| Fix when boosted items amount not calculates the correct boosts from inventory
| src/main/java/com/gamingmesh/jobs/Gui/GuiManager.java | Fix when boosted items amount not calculates the correct boosts from inventory | <ide><path>rc/main/java/com/gamingmesh/jobs/Gui/GuiManager.java
<ide> }
<ide>
<ide> double income = jInfo.getIncome(level, numjobs);
<del> income = boost.getFinalAmount(CurrencyType.MONEY, income);
<add> income = boost.getFinalAmount(CurrencyType.MONEY, income) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
<add> .get(CurrencyType.MONEY)) + 1);
<ide> String incomeColor = income >= 0 ? "" : ChatColor.DARK_RED.toString();
<ide>
<ide> double xp = jInfo.getExperience(level, numjobs);
<del> xp = boost.getFinalAmount(CurrencyType.EXP, xp);
<add> xp = boost.getFinalAmount(CurrencyType.EXP, xp) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
<add> .get(CurrencyType.EXP)) + 1);
<ide> String xpColor = xp >= 0 ? "" : ChatColor.GRAY.toString();
<ide>
<ide> double points = jInfo.getPoints(level, numjobs);
<del> points = boost.getFinalAmount(CurrencyType.POINTS, points);
<add> points = boost.getFinalAmount(CurrencyType.POINTS, points) + ((Jobs.getPlayerManager().getInventoryBoost(player, job)
<add> .get(CurrencyType.POINTS)) + 1);
<ide> String pointsColor = xp >= 0 ? "" : ChatColor.RED.toString();
<ide>
<ide> if (income == 0D && points == 0D && xp == 0D) |
|
Java | apache-2.0 | 0a975d549673ed96a9e099d989b178ee1bf757fe | 0 | sudhirkhanger/go-ubiquitous | package com.example.android.sunshine.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.WindowInsets;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataItemBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class SunshineWatchFaceService extends CanvasWatchFaceService {
public static final String LOG_TAG = SunshineWatchFaceService.class.getSimpleName();
@Override
public Engine onCreateEngine() {
return new WatchFaceEngine();
}
private class WatchFaceEngine extends Engine implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient;
private Typeface WATCH_TEXT_TYPEFACE = Typeface.create(Typeface.SERIF, Typeface.NORMAL);
private static final int MSG_UPDATE_TIME_ID = 42;
private static final long DEFAULT_UPDATE_RATE_MS = 1000;
private long mUpdateRateMs = 1000;
private Time mDisplayTime;
private Paint mBackgroundColorPaint;
private Paint mTextColorPaint;
private boolean mHasTimeZoneReceiverBeenRegistered = false;
private boolean mIsInMuteMode;
private boolean mIsLowBitAmbient;
private float mXOffset;
private float mYOffset;
private int mBackgroundColorAmbient = Color.parseColor("black");
private int mBackgroundInteractiveColor = Color.parseColor("#0288D1");
private int mTextColor = Color.parseColor("white");
private static final String PATH = "/simple_watch_face";
private static final String KEY_HIGH_TEMP = "HIGH_TEMP";
private static final String KEY_LOW_TEMP = "LOW_TEMP";
private static final String KEY_WEATHER_ID = "WEATHER_ID";
private String highTemp;
private String lowTemp;
private int weatherIcon = -1;
final BroadcastReceiver mTimeZoneBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mDisplayTime.clear(intent.getStringExtra("time-zone"));
mDisplayTime.setToNow();
}
};
private final Handler mTimeHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_TIME_ID: {
invalidate();
if (isVisible() && !isInAmbientMode()) {
long currentTimeMillis = System.currentTimeMillis();
long delay = mUpdateRateMs - (currentTimeMillis % mUpdateRateMs);
mTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME_ID, delay);
}
break;
}
}
}
};
//Overridden methods
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(SunshineWatchFaceService.this)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setShowSystemUiTime(false)
.build()
);
googleApiClient = new GoogleApiClient.Builder(SunshineWatchFaceService.this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
initBackground();
initDisplayText();
mDisplayTime = new Time();
}
@Override
public void onDestroy() {
mTimeHandler.removeMessages(MSG_UPDATE_TIME_ID);
releaseGoogleApiClient();
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
if (!mHasTimeZoneReceiverBeenRegistered) {
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
SunshineWatchFaceService.this.registerReceiver(mTimeZoneBroadcastReceiver, filter);
mHasTimeZoneReceiverBeenRegistered = true;
}
mDisplayTime.clear(TimeZone.getDefault().getID());
mDisplayTime.setToNow();
googleApiClient.connect();
} else {
if (mHasTimeZoneReceiverBeenRegistered) {
SunshineWatchFaceService.this.unregisterReceiver(mTimeZoneBroadcastReceiver);
mHasTimeZoneReceiverBeenRegistered = false;
}
releaseGoogleApiClient();
}
updateTimer();
}
private void releaseGoogleApiClient() {
Log.d(LOG_TAG, "releaseGoogleApiClient");
if (googleApiClient != null && googleApiClient.isConnected()) {
Log.d(LOG_TAG, "releaseGoogleApiClient disconnect");
googleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
Log.d(LOG_TAG, "connected GoogleAPI");
Wearable.DataApi.addListener(googleApiClient, onDataChangedListener);
Wearable.DataApi.getDataItems(googleApiClient).setResultCallback(onConnectedResultCallback);
}
private final DataApi.DataListener onDataChangedListener = new DataApi.DataListener() {
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.d(LOG_TAG, "onDataChanged");
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = event.getDataItem();
processConfigurationFor(item);
}
}
dataEvents.release();
invalidateIfNecessary();
}
};
private void processConfigurationFor(DataItem item) {
Log.d(LOG_TAG, "processConfigurationFor");
if (PATH.equals(item.getUri().getPath())) {
Log.d(LOG_TAG, "processConfigurationFor path matched");
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
if (dataMap.containsKey(KEY_HIGH_TEMP)) {
highTemp = dataMap.getString(KEY_HIGH_TEMP);
Log.d(LOG_TAG, "high temp is " + highTemp);
}
if (dataMap.containsKey(KEY_LOW_TEMP)) {
lowTemp = dataMap.getString(KEY_LOW_TEMP);
Log.d(LOG_TAG, "low temp is " + lowTemp);
}
if (dataMap.containsKey(KEY_WEATHER_ID)) {
weatherIcon = getArtResourceForWeatherCondition(
dataMap.getInt(KEY_WEATHER_ID));
Log.d(LOG_TAG, "weather id is " + weatherIcon);
}
}
}
/**
* Helper method to provide the art resource id according to the weather condition id returned
* by the OpenWeatherMap call.
*
* @param weatherId from OpenWeatherMap API response
* @return resource id for the corresponding image. -1 if no relation is found.
*/
public int getArtResourceForWeatherCondition(int weatherId) {
// Based on weather code data found at:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (weatherId >= 200 && weatherId <= 232) {
return R.drawable.art_storm;
} else if (weatherId >= 300 && weatherId <= 321) {
return R.drawable.art_light_rain;
} else if (weatherId >= 500 && weatherId <= 504) {
return R.drawable.art_rain;
} else if (weatherId == 511) {
return R.drawable.art_snow;
} else if (weatherId >= 520 && weatherId <= 531) {
return R.drawable.art_rain;
} else if (weatherId >= 600 && weatherId <= 622) {
return R.drawable.art_rain;
} else if (weatherId >= 701 && weatherId <= 761) {
return R.drawable.art_fog;
} else if (weatherId == 761 || weatherId == 781) {
return R.drawable.art_storm;
} else if (weatherId == 800) {
return R.drawable.art_clear;
} else if (weatherId == 801) {
return R.drawable.art_light_clouds;
} else if (weatherId >= 802 && weatherId <= 804) {
return R.drawable.art_clouds;
}
return -1;
}
private final ResultCallback<DataItemBuffer> onConnectedResultCallback = new ResultCallback<DataItemBuffer>() {
@Override
public void onResult(DataItemBuffer dataItems) {
Log.d(LOG_TAG, "onResult");
for (DataItem item : dataItems) {
Log.d(LOG_TAG, "onResult 229");
processConfigurationFor(item);
}
dataItems.release();
invalidateIfNecessary();
}
};
private void invalidateIfNecessary() {
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
@Override
public void onConnectionSuspended(int i) {
Log.e(LOG_TAG, "suspended GoogleAPI");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(LOG_TAG, "connectionFailed GoogleAPI");
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
Resources resources = SunshineWatchFaceService.this.getResources();
boolean isRound = insets.isRound();
mYOffset = resources.getDimension(R.dimen.digital_y_offset);
mXOffset = resources.getDimension(isRound
? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
if (properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false)) {
mIsLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (inAmbientMode) {
// mTextColorPaint.setColor(mTextColor);
mBackgroundColorPaint.setColor(mBackgroundColorAmbient);
} else {
// mTextColorPaint.setColor(mTextColor);
mBackgroundColorPaint.setColor(mBackgroundInteractiveColor);
}
if (mIsLowBitAmbient) {
mTextColorPaint.setAntiAlias(!inAmbientMode);
}
invalidate();
updateTimer();
}
@Override
public void onInterruptionFilterChanged(int interruptionFilter) {
super.onInterruptionFilterChanged(interruptionFilter);
boolean isDeviceMuted = (interruptionFilter == android.support.wearable.watchface.WatchFaceService.INTERRUPTION_FILTER_NONE);
if (isDeviceMuted) {
mUpdateRateMs = TimeUnit.MINUTES.toMillis(1);
} else {
mUpdateRateMs = DEFAULT_UPDATE_RATE_MS;
}
if (mIsInMuteMode != isDeviceMuted) {
mIsInMuteMode = isDeviceMuted;
int alpha = (isDeviceMuted) ? 100 : 255;
mTextColorPaint.setAlpha(alpha);
invalidate();
}
updateTimer();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
super.onDraw(canvas, bounds);
mDisplayTime.setToNow();
drawBackground(canvas, bounds);
drawTimeText(canvas);
drawDate(canvas);
if (weatherIcon != -1)
drawWeatherIcon(canvas);
if (!TextUtils.isEmpty(highTemp))
drawHighTemp(canvas);
if (!TextUtils.isEmpty(lowTemp))
drawLowTemp(canvas);
}
private void initBackground() {
mBackgroundColorPaint = new Paint();
mBackgroundColorPaint.setColor(mBackgroundInteractiveColor);
}
private void initDisplayText() {
mTextColorPaint = new Paint();
mTextColorPaint.setColor(mTextColor);
mTextColorPaint.setTypeface(WATCH_TEXT_TYPEFACE);
mTextColorPaint.setAntiAlias(true);
mTextColorPaint.setTextSize(getResources().getDimension(R.dimen.digital_text_size));
}
private void updateTimer() {
mTimeHandler.removeMessages(MSG_UPDATE_TIME_ID);
if (isVisible() && !isInAmbientMode()) {
mTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME_ID);
}
}
private void drawBackground(Canvas canvas, Rect bounds) {
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundColorPaint);
}
private void drawTimeText(Canvas canvas) {
String timeText = getHourString() + ":" + String.format("%02d", mDisplayTime.minute);
// if (isInAmbientMode() || mIsInMuteMode) {
// timeText += (mDisplayTime.hour < 12) ? "AM" : "PM";
// } else {
// timeText += String.format(":%02d", mDisplayTime.second);
// }
canvas.drawText(timeText, mXOffset, mYOffset, mTextColorPaint);
}
private String getHourString() {
if (mDisplayTime.hour % 12 == 0)
return "12";
else if (mDisplayTime.hour <= 12)
return String.valueOf(mDisplayTime.hour);
else
return String.valueOf(mDisplayTime.hour - 12);
}
private void drawDate(Canvas canvas) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d yyyy");
String strDate = sdf.format(calendar.getTime());
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(strDate, mXOffset, mYOffset + 40.0f, mTextColorPaint);
}
private void drawHighTemp(Canvas canvas) {
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(highTemp, mXOffset + 20.0f, mYOffset + 60.0f, mTextColorPaint);
}
private void drawLowTemp(Canvas canvas) {
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(lowTemp, mXOffset + 40.0f, mYOffset + 60.0f, mTextColorPaint);
}
private void drawWeatherIcon(Canvas canvas) {
Bitmap origBitmap = BitmapFactory.decodeResource(getResources(), weatherIcon);
float scale = ((float) 50) / (float) origBitmap.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap
(origBitmap, (int) (origBitmap.getWidth() * scale),
(int) (origBitmap.getHeight() * scale), true);
canvas.drawBitmap(scaledBitmap, mXOffset, mYOffset + 60.0f, null);
}
}
}
| wear/src/main/java/com/example/android/sunshine/app/SunshineWatchFaceService.java | package com.example.android.sunshine.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.support.wearable.watchface.WatchFaceStyle;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.WindowInsets;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataItemBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class SunshineWatchFaceService extends CanvasWatchFaceService {
public static final String LOG_TAG = SunshineWatchFaceService.class.getSimpleName();
@Override
public Engine onCreateEngine() {
return new WatchFaceEngine();
}
private class WatchFaceEngine extends Engine implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient googleApiClient;
private Typeface WATCH_TEXT_TYPEFACE = Typeface.create(Typeface.SERIF, Typeface.NORMAL);
private static final int MSG_UPDATE_TIME_ID = 42;
private static final long DEFAULT_UPDATE_RATE_MS = 1000;
private long mUpdateRateMs = 1000;
private Time mDisplayTime;
private Paint mBackgroundColorPaint;
private Paint mTextColorPaint;
private boolean mHasTimeZoneReceiverBeenRegistered = false;
private boolean mIsInMuteMode;
private boolean mIsLowBitAmbient;
private float mXOffset;
private float mYOffset;
private int mBackgroundColorAmbient = Color.parseColor("black");
private int mBackgroundInteractiveColor = Color.parseColor("#0288D1");
private int mTextColor = Color.parseColor("white");
private static final String PATH = "/simple_watch_face";
private static final String KEY_HIGH_TEMP = "HIGH_TEMP";
private static final String KEY_LOW_TEMP = "LOW_TEMP";
private static final String KEY_WEATHER_ID = "WEATHER_ID";
private String highTemp;
private String lowTemp;
private int weatherIcon = -1;
final BroadcastReceiver mTimeZoneBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mDisplayTime.clear(intent.getStringExtra("time-zone"));
mDisplayTime.setToNow();
}
};
private final Handler mTimeHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_TIME_ID: {
invalidate();
if (isVisible() && !isInAmbientMode()) {
long currentTimeMillis = System.currentTimeMillis();
long delay = mUpdateRateMs - (currentTimeMillis % mUpdateRateMs);
mTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME_ID, delay);
}
break;
}
}
}
};
//Overridden methods
@Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
setWatchFaceStyle(new WatchFaceStyle.Builder(SunshineWatchFaceService.this)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setShowSystemUiTime(false)
.build()
);
googleApiClient = new GoogleApiClient.Builder(SunshineWatchFaceService.this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
initBackground();
initDisplayText();
mDisplayTime = new Time();
}
@Override
public void onDestroy() {
mTimeHandler.removeMessages(MSG_UPDATE_TIME_ID);
releaseGoogleApiClient();
super.onDestroy();
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (visible) {
if (!mHasTimeZoneReceiverBeenRegistered) {
IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
SunshineWatchFaceService.this.registerReceiver(mTimeZoneBroadcastReceiver, filter);
mHasTimeZoneReceiverBeenRegistered = true;
}
mDisplayTime.clear(TimeZone.getDefault().getID());
mDisplayTime.setToNow();
googleApiClient.connect();
} else {
if (mHasTimeZoneReceiverBeenRegistered) {
SunshineWatchFaceService.this.unregisterReceiver(mTimeZoneBroadcastReceiver);
mHasTimeZoneReceiverBeenRegistered = false;
}
releaseGoogleApiClient();
}
updateTimer();
}
private void releaseGoogleApiClient() {
Log.d(LOG_TAG, "releaseGoogleApiClient");
if (googleApiClient != null && googleApiClient.isConnected()) {
Log.d(LOG_TAG, "releaseGoogleApiClient disconnect");
googleApiClient.disconnect();
}
}
@Override
public void onConnected(Bundle bundle) {
Log.d(LOG_TAG, "connected GoogleAPI");
Wearable.DataApi.addListener(googleApiClient, onDataChangedListener);
Wearable.DataApi.getDataItems(googleApiClient).setResultCallback(onConnectedResultCallback);
}
private final DataApi.DataListener onDataChangedListener = new DataApi.DataListener() {
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.d(LOG_TAG, "onDataChanged");
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem item = event.getDataItem();
processConfigurationFor(item);
}
}
dataEvents.release();
invalidateIfNecessary();
}
};
private void processConfigurationFor(DataItem item) {
Log.d(LOG_TAG, "processConfigurationFor");
if (PATH.equals(item.getUri().getPath())) {
Log.d(LOG_TAG, "processConfigurationFor path matched");
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
if (dataMap.containsKey(KEY_HIGH_TEMP)) {
highTemp = dataMap.getString(KEY_HIGH_TEMP);
Log.d(LOG_TAG, "high temp is " + highTemp);
}
if (dataMap.containsKey(KEY_LOW_TEMP)) {
lowTemp = dataMap.getString(KEY_LOW_TEMP);
Log.d(LOG_TAG, "low temp is " + lowTemp);
}
if (dataMap.containsKey(KEY_WEATHER_ID)) {
weatherIcon = getArtResourceForWeatherCondition(
dataMap.getInt(KEY_WEATHER_ID));
Log.d(LOG_TAG, "weather id is " + weatherIcon);
}
}
}
/**
* Helper method to provide the art resource id according to the weather condition id returned
* by the OpenWeatherMap call.
*
* @param weatherId from OpenWeatherMap API response
* @return resource id for the corresponding image. -1 if no relation is found.
*/
public int getArtResourceForWeatherCondition(int weatherId) {
// Based on weather code data found at:
// http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
if (weatherId >= 200 && weatherId <= 232) {
return R.drawable.art_storm;
} else if (weatherId >= 300 && weatherId <= 321) {
return R.drawable.art_light_rain;
} else if (weatherId >= 500 && weatherId <= 504) {
return R.drawable.art_rain;
} else if (weatherId == 511) {
return R.drawable.art_snow;
} else if (weatherId >= 520 && weatherId <= 531) {
return R.drawable.art_rain;
} else if (weatherId >= 600 && weatherId <= 622) {
return R.drawable.art_rain;
} else if (weatherId >= 701 && weatherId <= 761) {
return R.drawable.art_fog;
} else if (weatherId == 761 || weatherId == 781) {
return R.drawable.art_storm;
} else if (weatherId == 800) {
return R.drawable.art_clear;
} else if (weatherId == 801) {
return R.drawable.art_light_clouds;
} else if (weatherId >= 802 && weatherId <= 804) {
return R.drawable.art_clouds;
}
return -1;
}
private final ResultCallback<DataItemBuffer> onConnectedResultCallback = new ResultCallback<DataItemBuffer>() {
@Override
public void onResult(DataItemBuffer dataItems) {
Log.d(LOG_TAG, "onResult");
for (DataItem item : dataItems) {
Log.d(LOG_TAG, "onResult 229");
processConfigurationFor(item);
}
dataItems.release();
invalidateIfNecessary();
}
};
private void invalidateIfNecessary() {
if (isVisible() && !isInAmbientMode()) {
invalidate();
}
}
@Override
public void onConnectionSuspended(int i) {
Log.e(LOG_TAG, "suspended GoogleAPI");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(LOG_TAG, "connectionFailed GoogleAPI");
}
@Override
public void onApplyWindowInsets(WindowInsets insets) {
super.onApplyWindowInsets(insets);
mYOffset = getResources().getDimension(R.dimen.digital_y_offset);
mXOffset = insets.isRound() ? getResources().getDimension(R.dimen.digital_x_offset_round) :
getResources().getDimension(R.dimen.digital_x_offset);
}
@Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
if (properties.getBoolean(PROPERTY_BURN_IN_PROTECTION, false)) {
mIsLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false);
}
}
@Override
public void onTimeTick() {
super.onTimeTick();
invalidate();
}
@Override
public void onAmbientModeChanged(boolean inAmbientMode) {
super.onAmbientModeChanged(inAmbientMode);
if (inAmbientMode) {
// mTextColorPaint.setColor(mTextColor);
mBackgroundColorPaint.setColor(mBackgroundColorAmbient);
} else {
// mTextColorPaint.setColor(mTextColor);
mBackgroundColorPaint.setColor(mBackgroundInteractiveColor);
}
if (mIsLowBitAmbient) {
mTextColorPaint.setAntiAlias(!inAmbientMode);
}
invalidate();
updateTimer();
}
@Override
public void onInterruptionFilterChanged(int interruptionFilter) {
super.onInterruptionFilterChanged(interruptionFilter);
boolean isDeviceMuted = (interruptionFilter == android.support.wearable.watchface.WatchFaceService.INTERRUPTION_FILTER_NONE);
if (isDeviceMuted) {
mUpdateRateMs = TimeUnit.MINUTES.toMillis(1);
} else {
mUpdateRateMs = DEFAULT_UPDATE_RATE_MS;
}
if (mIsInMuteMode != isDeviceMuted) {
mIsInMuteMode = isDeviceMuted;
int alpha = (isDeviceMuted) ? 100 : 255;
mTextColorPaint.setAlpha(alpha);
invalidate();
}
updateTimer();
}
@Override
public void onDraw(Canvas canvas, Rect bounds) {
super.onDraw(canvas, bounds);
mDisplayTime.setToNow();
drawBackground(canvas, bounds);
drawTimeText(canvas);
drawDate(canvas);
if (weatherIcon != -1)
drawWeatherIcon(canvas);
if (!TextUtils.isEmpty(highTemp))
drawHighTemp(canvas);
if (!TextUtils.isEmpty(lowTemp))
drawLowTemp(canvas);
}
private void initBackground() {
mBackgroundColorPaint = new Paint();
mBackgroundColorPaint.setColor(mBackgroundInteractiveColor);
}
private void initDisplayText() {
mTextColorPaint = new Paint();
mTextColorPaint.setColor(mTextColor);
mTextColorPaint.setTypeface(WATCH_TEXT_TYPEFACE);
mTextColorPaint.setAntiAlias(true);
mTextColorPaint.setTextSize(getResources().getDimension(R.dimen.digital_text_size));
}
private void updateTimer() {
mTimeHandler.removeMessages(MSG_UPDATE_TIME_ID);
if (isVisible() && !isInAmbientMode()) {
mTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME_ID);
}
}
private void drawBackground(Canvas canvas, Rect bounds) {
canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundColorPaint);
}
private void drawTimeText(Canvas canvas) {
String timeText = getHourString() + ":" + String.format("%02d", mDisplayTime.minute);
// if (isInAmbientMode() || mIsInMuteMode) {
// timeText += (mDisplayTime.hour < 12) ? "AM" : "PM";
// } else {
// timeText += String.format(":%02d", mDisplayTime.second);
// }
canvas.drawText(timeText, mXOffset, mYOffset, mTextColorPaint);
}
private String getHourString() {
if (mDisplayTime.hour % 12 == 0)
return "12";
else if (mDisplayTime.hour <= 12)
return String.valueOf(mDisplayTime.hour);
else
return String.valueOf(mDisplayTime.hour - 12);
}
private void drawDate(Canvas canvas) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d yyyy");
String strDate = sdf.format(calendar.getTime());
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(strDate, mXOffset, mYOffset + 40.0f, mTextColorPaint);
}
private void drawHighTemp(Canvas canvas) {
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(highTemp, mXOffset + 20.0f, mYOffset + 60.0f, mTextColorPaint);
}
private void drawLowTemp(Canvas canvas) {
// mTextColorPaint.setTextSize(20.0f);
canvas.drawText(lowTemp, mXOffset + 40.0f, mYOffset + 60.0f, mTextColorPaint);
}
private void drawWeatherIcon(Canvas canvas) {
Bitmap origBitmap = BitmapFactory.decodeResource(getResources(), weatherIcon);
float scale = ((float) 50) / (float) origBitmap.getWidth();
Bitmap scaledBitmap = Bitmap.createScaledBitmap
(origBitmap, (int) (origBitmap.getWidth() * scale),
(int) (origBitmap.getHeight() * scale), true);
canvas.drawBitmap(scaledBitmap, mXOffset, mYOffset + 60.0f, null);
}
}
}
| refactor
| wear/src/main/java/com/example/android/sunshine/app/SunshineWatchFaceService.java | refactor | <ide><path>ear/src/main/java/com/example/android/sunshine/app/SunshineWatchFaceService.java
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.content.IntentFilter;
<add>import android.content.res.Resources;
<ide> import android.graphics.Bitmap;
<ide> import android.graphics.BitmapFactory;
<ide> import android.graphics.Canvas;
<ide> public void onApplyWindowInsets(WindowInsets insets) {
<ide> super.onApplyWindowInsets(insets);
<ide>
<del> mYOffset = getResources().getDimension(R.dimen.digital_y_offset);
<del> mXOffset = insets.isRound() ? getResources().getDimension(R.dimen.digital_x_offset_round) :
<del> getResources().getDimension(R.dimen.digital_x_offset);
<add> Resources resources = SunshineWatchFaceService.this.getResources();
<add> boolean isRound = insets.isRound();
<add>
<add> mYOffset = resources.getDimension(R.dimen.digital_y_offset);
<add> mXOffset = resources.getDimension(isRound
<add> ? R.dimen.digital_x_offset_round : R.dimen.digital_x_offset);
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | f92264d2dbe7a03cadbb643879972ba80867c293 | 0 | benjymous/MWM-for-Android |
/*****************************************************************************
* Copyright (c) 2011 Meta Watch Ltd. *
* www.MetaWatch.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. *
* *
*****************************************************************************/
/*****************************************************************************
* Protocol.java *
* Protocol *
* Basic low level protocol commands *
* *
* *
*****************************************************************************/
package org.metawatch.manager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.NotificationBuilder.FontSize;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.format.DateFormat;
import android.util.Log;
public class Protocol {
public static final byte REPLAY = 30;
private static volatile BlockingQueue<byte[]> sendQueue = new LinkedBlockingQueue<byte[]>();
private static volatile boolean protocolSenderRunning = false;
private static Runnable protocolSender = new Runnable() {
public void run() {
while (protocolSenderRunning) {
try {
byte[] message = sendQueue.take();
send(message);
Thread.sleep(Preferences.packetWait);
} catch (InterruptedException ie) {
/* If we've been interrupted, exit gracefully. */
Log.d(MetaWatch.TAG,
"ProtocolSender was interrupted waiting for next message, exiting.");
break;
} catch (IOException e) {
Log.e(MetaWatch.TAG,
"ProtocolSender encountered an I/O error sending message!");
sendQueue.clear();
break;
}
}
}
};
private static Thread protocolSenderThread = null;
public static synchronized void startProtocolSender() {
if (protocolSenderRunning == false) {
protocolSenderRunning = true;
protocolSenderThread = new Thread(protocolSender, "ProtocolSender");
protocolSenderThread.setDaemon(true);
protocolSenderThread.start();
}
}
public static synchronized void stopProtocolSender() {
if (protocolSenderRunning == true) {
/* Stops thread gracefully */
protocolSenderRunning = false;
/* Wakes up thread if it's sleeping on the queue */
protocolSenderThread.interrupt();
/* Thread is dead, we can mark it for garbage collection. */
protocolSenderThread = null;
}
}
public static void sendLcdBitmap(Bitmap bitmap, int bufferType) {
int pixelArray[] = new int[96 * 96];
bitmap.getPixels(pixelArray, 0, 96, 0, 0, 96, 96);
sendLcdArray(pixelArray, bufferType);
}
static void sendLcdArray(int[] pixelArray, int bufferType) {
byte send[] = new byte[1152];
for (int i = 0; i < 1152; i++) {
int p[] = new int[8];
for (int j = 0; j < 8; j++) {
if (pixelArray[i * 8 + j] == Color.WHITE)
/*
* if (Preferences.invertLCD) p[j] = 1; else
*/
p[j] = 0;
else
/*
* if (Preferences.invertLCD) p[j] = 0; else
*/
p[j] = 1;
}
send[i] = (byte) (p[7] * 128 + p[6] * 64 + p[5] * 32 + p[4] * 16
+ p[3] * 8 + p[2] * 4 + p[1] * 2 + p[0] * 1);
}
sendLcdBuffer(send, bufferType);
}
static void sendLcdBuffer(byte[] buffer, int bufferType) {
if (MetaWatchService.connectionState != MetaWatchService.ConnectionState.CONNECTED)
return;
int i = 0;
if (bufferType == MetaWatchService.WatchBuffers.IDLE)
i = 30;
for (; i < 96; i += 2) {
byte[] bytes = new byte[30];
bytes[0] = 0x01;
bytes[1] = (byte) (bytes.length+2); // packet length
bytes[2] = eMessageType.WriteBuffer.msg;
bytes[3] = (byte) bufferType;
bytes[4] = (byte) i; // row A
for (int j = 0; j < 12; j++)
bytes[j + 5] = buffer[i * 12 + j];
bytes[4 + 13] = (byte) (i + 1); // row B
for (int j = 0; j < 12; j++)
bytes[j + 5 + 13] = buffer[i * 12 + j + 12];
sendQueue.add(bytes);
}
}
public static void send(byte[] bytes) throws IOException {
if (bytes == null)
return;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(bytes);
byteArrayOutputStream.write(crc(bytes));
String str = "sending: ";
byte[] b = byteArrayOutputStream.toByteArray();
for (int i = 0; i < b.length; i++) {
// str+= Byte.toString(b[i]) + ", ";
str += "0x"
+ Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)
+ ", ";
}
Log.d(MetaWatch.TAG, str);
if (MetaWatchService.outputStream == null)
throw new IOException("OutputStream is null");
MetaWatchService.outputStream
.write(byteArrayOutputStream.toByteArray());
MetaWatchService.outputStream.flush();
}
public static void sendAdvanceHands() {
try {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = 9; // length
bytes[2] = eMessageType.AdvanceWatchHandsMsg.msg; // advance watch hands
bytes[3] = 0x04; // complete
bytes[4] = (byte) hour;
bytes[5] = (byte) minute;
bytes[6] = (byte) second;
// send(bytes);
} catch (Exception x) {
}
}
public static void sendRtcNow(Context context) {
try {
boolean isMMDD = true;
char[] ch = DateFormat.getDateFormatOrder(context);
for (int i = 0; i < ch.length; i++) {
if (ch[i] == DateFormat.DATE) {
isMMDD = false;
break;
}
if (ch[i] == DateFormat.MONTH) {
isMMDD = true;
break;
}
}
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
byte[] bytes = new byte[14];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.SetRealTimeClock.msg; // set rtc
bytes[3] = 0x00; // not used
bytes[4] = (byte) (year/256);
bytes[5] = (byte) (year%256);
bytes[6] = (byte) (calendar.get(Calendar.MONTH) + 1);
bytes[7] = (byte) calendar.get(Calendar.DAY_OF_MONTH);
bytes[8] = (byte) (calendar.get(Calendar.DAY_OF_WEEK) - 1);
bytes[9] = (byte) calendar.get(Calendar.HOUR_OF_DAY);
bytes[10] = (byte) calendar.get(Calendar.MINUTE);
bytes[11] = (byte) calendar.get(Calendar.SECOND);
if (DateFormat.is24HourFormat(context))
bytes[12] = (byte) 1; // 24hr
else
bytes[12] = (byte) 0; // 12hr
if (isMMDD)
bytes[13] = (byte) 0; // mm/dd
else
bytes[13] = (byte) 1; // dd/mm
//send(bytes);
sendQueue.add(bytes);
//processSendQueue();
} catch (Exception x) {
}
}
public static byte[] crc(byte[] bytes) {
byte[] result = new byte[2];
short crc = (short) 0xFFFF;
for (int j = 0; j < bytes.length; j++) {
byte c = bytes[j];
for (int i = 7; i >= 0; i--) {
boolean c15 = ((crc >> 15 & 1) == 1);
boolean bit = ((c >> (7 - i) & 1) == 1);
crc <<= 1;
if (c15 ^ bit)
crc ^= 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
}
}
int crc2 = crc - 0xffff0000;
result[0] = (byte) (crc2 % 256);
result[1] = (byte) (crc2 / 256);
return result;
}
public static Bitmap createTextBitmap(Context context, String text) {
String font = null;
int size = 8;
switch (Preferences.fontSize) {
case FontSize.SMALL:
font = "metawatch_8pt_5pxl_CAPS.ttf";
break;
case FontSize.MEDIUM:
font = "metawatch_8pt_7pxl_CAPS.ttf";
break;
case FontSize.LARGE:
font = "metawatch_16pt_11pxl.ttf";
size = 16;
break;
}
Bitmap bitmap = Bitmap.createBitmap(96, 96, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(size);
Typeface typeface = Typeface.createFromAsset(context.getAssets(), font);
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas = breakText(canvas, text, paint, 0, 0);
/*
* FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
* image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close();
* Log.d("ow", "bmp ok");
*/
return bitmap;
}
public static Canvas breakText(Canvas canvas, String text, Paint pen,
int x, int y) {
TextPaint textPaint = new TextPaint(pen);
StaticLayout staticLayout = new StaticLayout(text, textPaint, 98,
android.text.Layout.Alignment.ALIGN_NORMAL, 1.3f, 0, false);
canvas.translate(x, y); // position the text
staticLayout.draw(canvas);
return canvas;
}
public static void loadTemplate(int mode) {
byte[] bytes = new byte[5];
bytes[0] = 0x01;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.LoadTemplate.msg; // load template
bytes[3] = (byte) mode;
bytes[4] = (byte) 0; // write all "0"
sendQueue.add(bytes);
}
public static void activateBuffer(int mode) {
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ConfigureIdleBufferSize.msg; // activate buffer
bytes[3] = (byte) mode;
sendQueue.add(bytes);
}
public static void updateDisplay(int bufferType) {
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.UpdateDisplay.msg; // update display
bytes[3] = (byte) (bufferType + 16);
sendQueue.add(bytes);
}
public static void vibrate(int on, int off, int cycles) {
byte[] bytes = new byte[10];
bytes[0] = eMessageType.start;
bytes[1] = 12; // delka
bytes[2] = eMessageType.SetVibrateMode.msg; // set vibrate
bytes[3] = 0x00; // unused
bytes[4] = 0x01; // enabled
bytes[5] = (byte) (on % 256);
bytes[6] = (byte) (on / 256);
bytes[7] = (byte) (off % 256);
bytes[8] = (byte) (off / 256);
bytes[9] = (byte) cycles;
sendQueue.add(bytes);
}
public static void writeBuffer() {
//for (int j = 0; j < 96; j = j+2) {
byte[] bytes = new byte[17];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.WriteBuffer.msg; // write lcd buffer
//bytes[3] = 0x02; // notif, two lines
//bytes[3] = 18;
bytes[3] = 0;
//bytes[3] = 16;
bytes[4] = 31;
bytes[5] = 15;
bytes[6] = 15;
bytes[7] = 15;
bytes[8] = 15;
bytes[9] = 15;
bytes[10] = 15;
bytes[11] = 15;
bytes[12] = 15;
bytes[13] = 15;
bytes[14] = 15;
bytes[15] = 15;
bytes[16] = 15;
sendQueue.add(bytes);
//processSendQueue();
//}
}
public static void enableButton(int button, int type, int code) {
byte[] bytes = new byte[9];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.EnableButtonMsg.msg; // enable button
bytes[3] = 0; // not used
bytes[4] = 0; // idle
bytes[5] = (byte) button;
bytes[6] = (byte) type; // immediate
bytes[7] = 0x34;
bytes[8] = (byte) code;
sendQueue.add(bytes);
}
public static void disableButton(int button, int type) {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.DisableButtonMsg.msg; // disable button
bytes[3] = 0; // not used
bytes[4] = 0; // idle
bytes[5] = (byte) button;
bytes[6] = (byte) type; // immediate
sendQueue.add(bytes);
}
public static void enableReplayButton() {
enableButton(1, 0, REPLAY);
}
public static void disableReplayButton() {
disableButton(1, 0);
}
public static void enableMediaButtons() {
// enableMediaButton(0); // right top
// enableMediaButton(1); // right middle
// enableMediaButton(2); // right bottom
enableButton(3, 0, 0); // left bottom
enableButton(3, 1, MediaControl.VOLUME_DOWN); // left bottom
enableButton(3, 2, MediaControl.PREVIOUS); // left bottom
// enableMediaButton(5, 0, 0); // left middle
enableButton(5, 0, MediaControl.TOGGLE); // left middle
enableButton(6, 0, 0); // left top
enableButton(6, 1, MediaControl.VOLUME_UP); // left top
enableButton(6, 2, MediaControl.NEXT); // left top
}
public static void disableMediaButtons() {
disableButton(3, 0);
disableButton(3, 1);
disableButton(3, 2);
disableButton(5, 0);
disableButton(6, 0);
disableButton(6, 1);
disableButton(6, 2);
}
public static void readButtonConfiguration() {
byte[] bytes = new byte[9];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ReadButtonConfigMsg.msg; //
bytes[3] = 0; // not used
bytes[4] = 0;
bytes[5] = 1;
bytes[6] = 2; // press type
bytes[7] = 0x34;
bytes[8] = 0;
sendQueue.add(bytes);
}
public static void configureMode() {
byte[] bytes = new byte[6];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ConfigureMode.msg; //
bytes[3] = 0;
bytes[4] = 10;
bytes[5] = (byte) (MetaWatchService.Preferences.invertLCD ? 1 : 0); // invert
sendQueue.add(bytes);
}
public static void getDeviceType() {
Log.d(MetaWatch.TAG, "Asking watch what kind it is.");
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.GetDeviceType.msg;
bytes[3] = 0;
sendQueue.add(bytes);
}
public static void queryNvalTime() {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.NvalOperationMsg.msg; // nval operations
bytes[3] = 0x01; // read
bytes[4] = 0x09;
bytes[5] = 0x20;
bytes[6] = 0x01; // size
sendQueue.add(bytes);
}
public static void setNvalTime(boolean militaryTime) {
byte[] bytes = new byte[8];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.NvalOperationMsg.msg; // nval operations
bytes[3] = 0x02; // write
bytes[4] = 0x09;
bytes[5] = 0x20;
bytes[6] = 0x01; // size
if (militaryTime)
bytes[7] = 0x01; // 24 hour mode
else
bytes[7] = 0x00; // 12 hour mode
sendQueue.add(bytes);
}
public static void test(Context context) {
sendOledDisplay(createOled1line(context, null, "test abc 123"), true,
false);
sendOledDisplay(
createOled2lines(context, "second display", "second line 123"),
false, true);
byte[] display = new byte[800];
createOled2linesLong(context,
"long test text, long test text, long test text...", display);
sendOledBufferPart(display, 0, 80, true, true);
}
public static byte[] createOled1line(Context context, String icon,
String line) {
int offset = 0;
if (icon != null)
offset += 17;
Bitmap image = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(16);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_16pt_11pxl.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line, offset, 14, paint);
if (icon != null) {
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, icon), 0, 0,
null);
}
int poleInt[] = new int[16 * 80];
image.getPixels(poleInt, 0, 80, 0, 0, 80, 16);
byte[] display = new byte[160];
for (int i = 0; i < 160; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (i < 80) {
if (poleInt[80 * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
} else {
if (poleInt[80 * 8 + 80 * j + i - 80] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
return display;
}
public static byte[] createOled2lines(Context context, String line1,
String line2) {
int offset = 0;
/*
* if (logo) offset += 17;
*/
/* Convert newlines to spaces */
line1 = line1.replace('\n', ' ');
line2 = line2.replace('\n', ' ');
Bitmap image = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(8);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_8pt_5pxl_CAPS.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line1, offset, 7, paint);
canvas.drawText(line2, offset, 15, paint);
/*
* if (logo) { Bitmap imageImmutable =
* BitmapFactory.decodeResource(context.getResources(), iconType);
* Bitmap imageIcon = imageImmutable.copy(Bitmap.Config.RGB_565, true);
* canvas.drawBitmap(imageIcon, 0, 0, null); }
*/
int poleInt[] = new int[16 * 80];
image.getPixels(poleInt, 0, 80, 0, 0, 80, 16);
byte[] display = new byte[160];
for (int i = 0; i < 160; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (i < 80) {
if (poleInt[80 * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
} else {
if (poleInt[80 * 8 + 80 * j + i - 80] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
return display;
}
public static int createOled2linesLong(Context context, String line,
byte[] display) {
int offset = 0 - 79;
/*
* if (logo) offset += 17;
*/
/* Replace newlines with spaces */
line = line.replace('\n', ' ');
final int width = 800;
Bitmap image = Bitmap.createBitmap(width, 8, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(8);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_8pt_5pxl_CAPS.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line, offset, 7, paint);
/*
* if (logo) { Bitmap imageImmutable =
* BitmapFactory.decodeResource(context.getResources(), iconType);
* Bitmap imageIcon = imageImmutable.copy(Bitmap.Config.RGB_565, true);
* canvas.drawBitmap(imageIcon, 0, 0, null); }
*/
int poleInt[] = new int[8 * width];
image.getPixels(poleInt, 0, width, 0, 0, width, 8);
for (int i = 0; i < width; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (poleInt[width * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
// int len = (int) paint.measureText(line);
return (int) paint.measureText(line) - 79;
}
public static void sendOledDisplay(byte[] display, boolean top,
boolean scroll) {
try {
byte[] bytes;
for (int a = 0; a < 160; a += 20) {
bytes = new byte[27];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteBufferMsg.msg; // oled write
if (scroll)
bytes[3] = (byte) 0x82; // notification + scroll
else
bytes[3] = 0x02; // notification
if (top)
bytes[4] = 0x00; // top page
else
bytes[4] = 0x01; // bottom page
bytes[5] = (byte) a; // row
bytes[6] = 0x14; // size
System.arraycopy(display, a, bytes, 7, 20);
sendQueue.add(bytes);
}
updateOledNotification(top, scroll);
} catch (Exception x) {
}
}
public static void updateOledNotification(boolean top, boolean scroll) {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteBufferMsg.msg; // oled write
if (scroll)
bytes[3] = (byte) 0xC2; // notification, activate, scroll
else
bytes[3] = 0x42; // notification, activate
if (top)
bytes[4] = 0x00; // top page
else
bytes[4] = 0x01; // bottom page
bytes[5] = 0x00; // row
bytes[6] = 0x00; // size
sendQueue.add(bytes);
}
public static void updateOledsNotification() {
updateOledNotification(true, false);
updateOledNotification(false, false);
}
public static void sendOledBuffer(boolean startScroll) {
byte[] bytes = new byte[25];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteScrollBufferMsg.msg; // write oled buffer
if (startScroll)
bytes[3] = 0x02; // not last, start
else
bytes[3] = 0x00; // not last
bytes[4] = 20; // size
for (int i = 0; i < 20; i++)
bytes[5 + i] = (byte) 0xAA;
sendQueue.add(bytes);
}
public static void sendOledBufferPart(byte[] display, int start,
int length, boolean startScroll, boolean last) {
Log.d(MetaWatch.TAG, "sending oled buffer part, start: " + start
+ ", length: " + length);
for (int j = start; j < start + length; j += 20) {
byte[] bytes = new byte[25];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteScrollBufferMsg.msg; // write oled buffer
bytes[3] = 0x00; // not last
if (j + 20 >= start + length) { // is last packet
if (startScroll)
bytes[3] = 0x02; // not last, start
if (last)
bytes[3] = 0x01; // last
if (startScroll && last)
bytes[3] = 0x03; // last, start
}
bytes[4] = 20; // size
for (int i = 0; i < 20; i++)
bytes[5 + i] = display[j + i];
sendQueue.add(bytes);
}
}
}
| src/org/metawatch/manager/Protocol.java |
/*****************************************************************************
* Copyright (c) 2011 Meta Watch Ltd. *
* www.MetaWatch.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. *
* *
*****************************************************************************/
/*****************************************************************************
* Protocol.java *
* Protocol *
* Basic low level protocol commands *
* *
* *
*****************************************************************************/
package org.metawatch.manager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.metawatch.manager.MetaWatchService.Preferences;
import org.metawatch.manager.NotificationBuilder.FontSize;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.format.DateFormat;
import android.util.Log;
public class Protocol {
public static final byte REPLAY = 30;
private static volatile BlockingQueue<byte[]> sendQueue = new LinkedBlockingQueue<byte[]>();
private static volatile boolean protocolSenderRunning = false;
private static Runnable protocolSender = new Runnable() {
public void run() {
while (protocolSenderRunning) {
try {
byte[] message = sendQueue.take();
send(message);
Thread.sleep(Preferences.packetWait);
} catch (InterruptedException ie) {
/* If we've been interrupted, exit gracefully. */
Log.d(MetaWatch.TAG,
"ProtocolSender was interrupted waiting for next message, exiting.");
break;
} catch (IOException e) {
Log.e(MetaWatch.TAG,
"ProtocolSender encountered an I/O error sending message!");
sendQueue.clear();
break;
}
}
}
};
private static Thread protocolSenderThread = null;
public static synchronized void startProtocolSender() {
if (protocolSenderRunning == false) {
protocolSenderRunning = true;
protocolSenderThread = new Thread(protocolSender, "ProtocolSender");
protocolSenderThread.setDaemon(true);
protocolSenderThread.start();
}
}
public static synchronized void stopProtocolSender() {
if (protocolSenderRunning == true) {
/* Stops thread gracefully */
protocolSenderRunning = false;
/* Wakes up thread if it's sleeping on the queue */
protocolSenderThread.interrupt();
/* Thread is dead, we can mark it for garbage collection. */
protocolSenderThread = null;
}
}
public static void sendLcdBitmap(Bitmap bitmap, int bufferType) {
int pixelArray[] = new int[96 * 96];
bitmap.getPixels(pixelArray, 0, 96, 0, 0, 96, 96);
sendLcdArray(pixelArray, bufferType);
}
static void sendLcdArray(int[] pixelArray, int bufferType) {
byte send[] = new byte[1152];
for (int i = 0; i < 1152; i++) {
int p[] = new int[8];
for (int j = 0; j < 8; j++) {
if (pixelArray[i * 8 + j] == Color.WHITE)
/*
* if (Preferences.invertLCD) p[j] = 1; else
*/
p[j] = 0;
else
/*
* if (Preferences.invertLCD) p[j] = 0; else
*/
p[j] = 1;
}
send[i] = (byte) (p[7] * 128 + p[6] * 64 + p[5] * 32 + p[4] * 16
+ p[3] * 8 + p[2] * 4 + p[1] * 2 + p[0] * 1);
}
sendLcdBuffer(send, bufferType);
}
static void sendLcdBuffer(byte[] buffer, int bufferType) {
if (MetaWatchService.connectionState != MetaWatchService.ConnectionState.CONNECTED)
return;
int i = 0;
if (bufferType == MetaWatchService.WatchBuffers.IDLE)
i = 30;
for (; i < 96; i += 2) {
byte[] bytes = new byte[30];
bytes[0] = 0x01;
bytes[1] = (byte) (bytes.length+2); // packet length
bytes[2] = eMessageType.WriteBuffer.msg;
bytes[3] = (byte) bufferType;
bytes[4] = (byte) i; // row A
for (int j = 0; j < 12; j++)
bytes[j + 5] = buffer[i * 12 + j];
bytes[4 + 13] = (byte) (i + 1); // row B
for (int j = 0; j < 12; j++)
bytes[j + 5 + 13] = buffer[i * 12 + j + 12];
sendQueue.add(bytes);
}
}
public static void send(byte[] bytes) throws IOException {
if (bytes == null)
return;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(bytes);
byteArrayOutputStream.write(crc(bytes));
String str = "sending: ";
byte[] b = byteArrayOutputStream.toByteArray();
for (int i = 0; i < b.length; i++) {
// str+= Byte.toString(b[i]) + ", ";
str += "0x"
+ Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1)
+ ", ";
}
Log.d(MetaWatch.TAG, str);
if (MetaWatchService.outputStream == null)
throw new IOException("OutputStream is null");
MetaWatchService.outputStream
.write(byteArrayOutputStream.toByteArray());
MetaWatchService.outputStream.flush();
}
public static void sendAdvanceHands() {
try {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = 9; // length
bytes[2] = eMessageType.AdvanceWatchHandsMsg.msg; // advance watch hands
bytes[3] = 0x04; // complete
bytes[4] = (byte) hour;
bytes[5] = (byte) minute;
bytes[6] = (byte) second;
// send(bytes);
} catch (Exception x) {
}
}
public static void sendRtcNow(Context context) {
Log.d(MetaWatch.TAG, "Setting time of watch");
boolean isMMDD = true;
char[] ch = DateFormat.getDateFormatOrder(context);
<<<<<<< HEAD
for (int i = 0; i < ch.length; i++) {
if (ch[i] == DateFormat.DATE) {
isMMDD = false;
break;
}
if (ch[i] == DateFormat.MONTH) {
isMMDD = true;
break;
}
=======
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.SetRealTimeClock.msg; // set rtc
bytes[3] = 0x00; // not used
bytes[4] = (byte) (year/256);
bytes[5] = (byte) (year%256);
bytes[6] = (byte) (calendar.get(Calendar.MONTH) + 1);
bytes[7] = (byte) calendar.get(Calendar.DAY_OF_MONTH);
bytes[8] = (byte) (calendar.get(Calendar.DAY_OF_WEEK) - 1);
bytes[9] = (byte) calendar.get(Calendar.HOUR_OF_DAY);
bytes[10] = (byte) calendar.get(Calendar.MINUTE);
bytes[11] = (byte) calendar.get(Calendar.SECOND);
if (DateFormat.is24HourFormat(context))
bytes[12] = (byte) 1; // 24hr
else
bytes[12] = (byte) 0; // 12hr
if (isMMDD)
bytes[13] = (byte) 0; // mm/dd
else
bytes[13] = (byte) 1; // dd/mm
//send(bytes);
sendQueue.add(bytes);
processSendQueue();
} catch (Exception x) {
>>>>>>> 89574c66b9a231b8886b33a0d8a6f24d8834b27b
}
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
byte[] bytes = new byte[14];
bytes[0] = 0x01;
bytes[1] = (byte) (bytes.length + 2); // length
bytes[2] = 0x26; // set rtc
bytes[3] = 0x00; // not used
bytes[4] = (byte) (year / 256);
bytes[5] = (byte) (year % 256);
bytes[6] = (byte) (calendar.get(Calendar.MONTH) + 1);
bytes[7] = (byte) calendar.get(Calendar.DAY_OF_MONTH);
bytes[8] = (byte) (calendar.get(Calendar.DAY_OF_WEEK) - 1);
bytes[9] = (byte) calendar.get(Calendar.HOUR_OF_DAY);
bytes[10] = (byte) calendar.get(Calendar.MINUTE);
bytes[11] = (byte) calendar.get(Calendar.SECOND);
if (DateFormat.is24HourFormat(context))
bytes[12] = (byte) 1; // 24hr
else
bytes[12] = (byte) 0; // 12hr
if (isMMDD)
bytes[13] = (byte) 0; // mm/dd
else
bytes[13] = (byte) 1; // dd/mm
// send(bytes);
sendQueue.add(bytes);
}
public static byte[] crc(byte[] bytes) {
byte[] result = new byte[2];
short crc = (short) 0xFFFF;
for (int j = 0; j < bytes.length; j++) {
byte c = bytes[j];
for (int i = 7; i >= 0; i--) {
boolean c15 = ((crc >> 15 & 1) == 1);
boolean bit = ((c >> (7 - i) & 1) == 1);
crc <<= 1;
if (c15 ^ bit)
crc ^= 0x1021; // 0001 0000 0010 0001 (0, 5, 12)
}
}
int crc2 = crc - 0xffff0000;
result[0] = (byte) (crc2 % 256);
result[1] = (byte) (crc2 / 256);
return result;
}
public static Bitmap createTextBitmap(Context context, String text) {
String font = null;
int size = 8;
switch (Preferences.fontSize) {
case FontSize.SMALL:
font = "metawatch_8pt_5pxl_CAPS.ttf";
break;
case FontSize.MEDIUM:
font = "metawatch_8pt_7pxl_CAPS.ttf";
break;
case FontSize.LARGE:
font = "metawatch_16pt_11pxl.ttf";
size = 16;
break;
}
Bitmap bitmap = Bitmap.createBitmap(96, 96, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(size);
Typeface typeface = Typeface.createFromAsset(context.getAssets(), font);
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas = breakText(canvas, text, paint, 0, 0);
/*
* FileOutputStream fos = new FileOutputStream("/sdcard/test.png");
* image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close();
* Log.d("ow", "bmp ok");
*/
return bitmap;
}
public static Canvas breakText(Canvas canvas, String text, Paint pen,
int x, int y) {
TextPaint textPaint = new TextPaint(pen);
StaticLayout staticLayout = new StaticLayout(text, textPaint, 98,
android.text.Layout.Alignment.ALIGN_NORMAL, 1.3f, 0, false);
canvas.translate(x, y); // position the text
staticLayout.draw(canvas);
return canvas;
}
public static void loadTemplate(int mode) {
byte[] bytes = new byte[5];
bytes[0] = 0x01;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.LoadTemplate.msg; // load template
bytes[3] = (byte) mode;
bytes[4] = (byte) 0; // write all "0"
sendQueue.add(bytes);
}
public static void activateBuffer(int mode) {
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ConfigureIdleBufferSize.msg; // activate buffer
bytes[3] = (byte) mode;
sendQueue.add(bytes);
}
public static void updateDisplay(int bufferType) {
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.UpdateDisplay.msg; // update display
bytes[3] = (byte) (bufferType + 16);
sendQueue.add(bytes);
}
public static void vibrate(int on, int off, int cycles) {
byte[] bytes = new byte[10];
bytes[0] = eMessageType.start;
bytes[1] = 12; // delka
bytes[2] = eMessageType.SetVibrateMode.msg; // set vibrate
bytes[3] = 0x00; // unused
bytes[4] = 0x01; // enabled
bytes[5] = (byte) (on % 256);
bytes[6] = (byte) (on / 256);
bytes[7] = (byte) (off % 256);
bytes[8] = (byte) (off / 256);
bytes[9] = (byte) cycles;
sendQueue.add(bytes);
}
public static void writeBuffer() {
//for (int j = 0; j < 96; j = j+2) {
byte[] bytes = new byte[17];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.WriteBuffer.msg; // write lcd buffer
//bytes[3] = 0x02; // notif, two lines
//bytes[3] = 18;
bytes[3] = 0;
//bytes[3] = 16;
bytes[4] = 31;
bytes[5] = 15;
bytes[6] = 15;
bytes[7] = 15;
bytes[8] = 15;
bytes[9] = 15;
bytes[10] = 15;
bytes[11] = 15;
bytes[12] = 15;
bytes[13] = 15;
bytes[14] = 15;
bytes[15] = 15;
bytes[16] = 15;
sendQueue.add(bytes);
processSendQueue();
//}
}
public static void enableButton(int button, int type, int code) {
byte[] bytes = new byte[9];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.EnableButtonMsg.msg; // enable button
bytes[3] = 0; // not used
bytes[4] = 0; // idle
bytes[5] = (byte) button;
bytes[6] = (byte) type; // immediate
bytes[7] = 0x34;
bytes[8] = (byte) code;
sendQueue.add(bytes);
}
public static void disableButton(int button, int type) {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.DisableButtonMsg.msg; // disable button
bytes[3] = 0; // not used
bytes[4] = 0; // idle
bytes[5] = (byte) button;
bytes[6] = (byte) type; // immediate
sendQueue.add(bytes);
}
public static void enableReplayButton() {
enableButton(1, 0, REPLAY);
}
public static void disableReplayButton() {
disableButton(1, 0);
}
public static void enableMediaButtons() {
// enableMediaButton(0); // right top
// enableMediaButton(1); // right middle
// enableMediaButton(2); // right bottom
enableButton(3, 0, 0); // left bottom
enableButton(3, 1, MediaControl.VOLUME_DOWN); // left bottom
enableButton(3, 2, MediaControl.PREVIOUS); // left bottom
// enableMediaButton(5, 0, 0); // left middle
enableButton(5, 0, MediaControl.TOGGLE); // left middle
enableButton(6, 0, 0); // left top
enableButton(6, 1, MediaControl.VOLUME_UP); // left top
enableButton(6, 2, MediaControl.NEXT); // left top
}
public static void disableMediaButtons() {
disableButton(3, 0);
disableButton(3, 1);
disableButton(3, 2);
disableButton(5, 0);
disableButton(6, 0);
disableButton(6, 1);
disableButton(6, 2);
}
public static void readButtonConfiguration() {
byte[] bytes = new byte[9];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ReadButtonConfigMsg.msg; //
bytes[3] = 0; // not used
bytes[4] = 0;
bytes[5] = 1;
bytes[6] = 2; // press type
bytes[7] = 0x34;
bytes[8] = 0;
sendQueue.add(bytes);
}
public static void configureMode() {
byte[] bytes = new byte[6];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.ConfigureMode.msg; //
bytes[3] = 0;
bytes[4] = 10;
bytes[5] = (byte) (MetaWatchService.Preferences.invertLCD ? 1 : 0); // invert
sendQueue.add(bytes);
}
public static void getDeviceType() {
Log.d(MetaWatch.TAG, "Asking watch what kind it is.");
byte[] bytes = new byte[4];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.GetDeviceType.msg;
bytes[3] = 0;
sendQueue.add(bytes);
}
public static void queryNvalTime() {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.NvalOperationMsg.msg; // nval operations
bytes[3] = 0x01; // read
bytes[4] = 0x09;
bytes[5] = 0x20;
bytes[6] = 0x01; // size
sendQueue.add(bytes);
}
public static void setNvalTime(boolean militaryTime) {
byte[] bytes = new byte[8];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.NvalOperationMsg.msg; // nval operations
bytes[3] = 0x02; // write
bytes[4] = 0x09;
bytes[5] = 0x20;
bytes[6] = 0x01; // size
if (militaryTime)
bytes[7] = 0x01; // 24 hour mode
else
bytes[7] = 0x00; // 12 hour mode
sendQueue.add(bytes);
}
public static void test(Context context) {
sendOledDisplay(createOled1line(context, null, "test abc 123"), true,
false);
sendOledDisplay(
createOled2lines(context, "second display", "second line 123"),
false, true);
byte[] display = new byte[800];
createOled2linesLong(context,
"long test text, long test text, long test text...", display);
sendOledBufferPart(display, 0, 80, true, true);
}
public static byte[] createOled1line(Context context, String icon,
String line) {
int offset = 0;
if (icon != null)
offset += 17;
Bitmap image = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(16);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_16pt_11pxl.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line, offset, 14, paint);
if (icon != null) {
canvas.drawBitmap(Utils.loadBitmapFromAssets(context, icon), 0, 0,
null);
}
int poleInt[] = new int[16 * 80];
image.getPixels(poleInt, 0, 80, 0, 0, 80, 16);
byte[] display = new byte[160];
for (int i = 0; i < 160; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (i < 80) {
if (poleInt[80 * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
} else {
if (poleInt[80 * 8 + 80 * j + i - 80] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
return display;
}
public static byte[] createOled2lines(Context context, String line1,
String line2) {
int offset = 0;
/*
* if (logo) offset += 17;
*/
/* Convert newlines to spaces */
line1 = line1.replace('\n', ' ');
line2 = line2.replace('\n', ' ');
Bitmap image = Bitmap.createBitmap(80, 16, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(8);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_8pt_5pxl_CAPS.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line1, offset, 7, paint);
canvas.drawText(line2, offset, 15, paint);
/*
* if (logo) { Bitmap imageImmutable =
* BitmapFactory.decodeResource(context.getResources(), iconType);
* Bitmap imageIcon = imageImmutable.copy(Bitmap.Config.RGB_565, true);
* canvas.drawBitmap(imageIcon, 0, 0, null); }
*/
int poleInt[] = new int[16 * 80];
image.getPixels(poleInt, 0, 80, 0, 0, 80, 16);
byte[] display = new byte[160];
for (int i = 0; i < 160; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (i < 80) {
if (poleInt[80 * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
} else {
if (poleInt[80 * 8 + 80 * j + i - 80] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
return display;
}
public static int createOled2linesLong(Context context, String line,
byte[] display) {
int offset = 0 - 79;
/*
* if (logo) offset += 17;
*/
/* Replace newlines with spaces */
line = line.replace('\n', ' ');
final int width = 800;
Bitmap image = Bitmap.createBitmap(width, 8, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(image);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setTextSize(8);
Typeface typeface = Typeface.createFromAsset(context.getAssets(),
"metawatch_8pt_5pxl_CAPS.ttf");
paint.setTypeface(typeface);
canvas.drawColor(Color.WHITE);
canvas.drawText(line, offset, 7, paint);
/*
* if (logo) { Bitmap imageImmutable =
* BitmapFactory.decodeResource(context.getResources(), iconType);
* Bitmap imageIcon = imageImmutable.copy(Bitmap.Config.RGB_565, true);
* canvas.drawBitmap(imageIcon, 0, 0, null); }
*/
int poleInt[] = new int[8 * width];
image.getPixels(poleInt, 0, width, 0, 0, width, 8);
for (int i = 0; i < width; i++) {
boolean[] column = new boolean[8];
for (int j = 0; j < 8; j++) {
if (poleInt[width * j + i] == Color.WHITE)
column[j] = false;
else
column[j] = true;
}
for (int j = 0; j < 8; j++) {
if (column[j])
display[i] += Math.pow(2, j);
}
}
// int len = (int) paint.measureText(line);
return (int) paint.measureText(line) - 79;
}
public static void sendOledDisplay(byte[] display, boolean top,
boolean scroll) {
try {
byte[] bytes;
for (int a = 0; a < 160; a += 20) {
bytes = new byte[27];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteBufferMsg.msg; // oled write
if (scroll)
bytes[3] = (byte) 0x82; // notification + scroll
else
bytes[3] = 0x02; // notification
if (top)
bytes[4] = 0x00; // top page
else
bytes[4] = 0x01; // bottom page
bytes[5] = (byte) a; // row
bytes[6] = 0x14; // size
System.arraycopy(display, a, bytes, 7, 20);
sendQueue.add(bytes);
}
updateOledNotification(top, scroll);
} catch (Exception x) {
}
}
public static void updateOledNotification(boolean top, boolean scroll) {
byte[] bytes = new byte[7];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteBufferMsg.msg; // oled write
if (scroll)
bytes[3] = (byte) 0xC2; // notification, activate, scroll
else
bytes[3] = 0x42; // notification, activate
if (top)
bytes[4] = 0x00; // top page
else
bytes[4] = 0x01; // bottom page
bytes[5] = 0x00; // row
bytes[6] = 0x00; // size
sendQueue.add(bytes);
}
public static void updateOledsNotification() {
updateOledNotification(true, false);
updateOledNotification(false, false);
}
public static void sendOledBuffer(boolean startScroll) {
byte[] bytes = new byte[25];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteScrollBufferMsg.msg; // write oled buffer
if (startScroll)
bytes[3] = 0x02; // not last, start
else
bytes[3] = 0x00; // not last
bytes[4] = 20; // size
for (int i = 0; i < 20; i++)
bytes[5 + i] = (byte) 0xAA;
sendQueue.add(bytes);
}
public static void sendOledBufferPart(byte[] display, int start,
int length, boolean startScroll, boolean last) {
Log.d(MetaWatch.TAG, "sending oled buffer part, start: " + start
+ ", length: " + length);
for (int j = start; j < start + length; j += 20) {
byte[] bytes = new byte[25];
bytes[0] = eMessageType.start;
bytes[1] = (byte) (bytes.length+2); // length
bytes[2] = eMessageType.OledWriteScrollBufferMsg.msg; // write oled buffer
bytes[3] = 0x00; // not last
if (j + 20 >= start + length) { // is last packet
if (startScroll)
bytes[3] = 0x02; // not last, start
if (last)
bytes[3] = 0x01; // last
if (startScroll && last)
bytes[3] = 0x03; // last, start
}
bytes[4] = 20; // size
for (int i = 0; i < 20; i++)
bytes[5 + i] = display[j + i];
sendQueue.add(bytes);
}
}
}
| Fixes to the build
| src/org/metawatch/manager/Protocol.java | Fixes to the build | <ide><path>rc/org/metawatch/manager/Protocol.java
<ide> }
<ide>
<ide> public static void sendRtcNow(Context context) {
<del> Log.d(MetaWatch.TAG, "Setting time of watch");
<del>
<del> boolean isMMDD = true;
<del> char[] ch = DateFormat.getDateFormatOrder(context);
<del>
<del><<<<<<< HEAD
<del> for (int i = 0; i < ch.length; i++) {
<del> if (ch[i] == DateFormat.DATE) {
<del> isMMDD = false;
<del> break;
<del> }
<del> if (ch[i] == DateFormat.MONTH) {
<del> isMMDD = true;
<del> break;
<del> }
<del>=======
<add> try {
<add> boolean isMMDD = true;
<add> char[] ch = DateFormat.getDateFormatOrder(context);
<add>
<add> for (int i = 0; i < ch.length; i++) {
<add> if (ch[i] == DateFormat.DATE) {
<add> isMMDD = false;
<add> break;
<add> }
<add> if (ch[i] == DateFormat.MONTH) {
<add> isMMDD = true;
<add> break;
<add> }
<add> }
<add>
<add> Date date = new Date();
<add> Calendar calendar = Calendar.getInstance();
<add> calendar.setTime(date);
<add> int year = calendar.get(Calendar.YEAR);
<add>
<add> byte[] bytes = new byte[14];
<add>
<ide> bytes[0] = eMessageType.start;
<ide> bytes[1] = (byte) (bytes.length+2); // length
<ide> bytes[2] = eMessageType.SetRealTimeClock.msg; // set rtc
<ide>
<ide> //send(bytes);
<ide> sendQueue.add(bytes);
<del> processSendQueue();
<del>
<add> //processSendQueue();
<add>
<ide> } catch (Exception x) {
<del>>>>>>>> 89574c66b9a231b8886b33a0d8a6f24d8834b27b
<del> }
<del>
<del> Date date = new Date();
<del> Calendar calendar = Calendar.getInstance();
<del> calendar.setTime(date);
<del> int year = calendar.get(Calendar.YEAR);
<del>
<del> byte[] bytes = new byte[14];
<del>
<del> bytes[0] = 0x01;
<del> bytes[1] = (byte) (bytes.length + 2); // length
<del> bytes[2] = 0x26; // set rtc
<del> bytes[3] = 0x00; // not used
<del>
<del> bytes[4] = (byte) (year / 256);
<del> bytes[5] = (byte) (year % 256);
<del> bytes[6] = (byte) (calendar.get(Calendar.MONTH) + 1);
<del> bytes[7] = (byte) calendar.get(Calendar.DAY_OF_MONTH);
<del> bytes[8] = (byte) (calendar.get(Calendar.DAY_OF_WEEK) - 1);
<del> bytes[9] = (byte) calendar.get(Calendar.HOUR_OF_DAY);
<del> bytes[10] = (byte) calendar.get(Calendar.MINUTE);
<del> bytes[11] = (byte) calendar.get(Calendar.SECOND);
<del> if (DateFormat.is24HourFormat(context))
<del> bytes[12] = (byte) 1; // 24hr
<del> else
<del> bytes[12] = (byte) 0; // 12hr
<del> if (isMMDD)
<del> bytes[13] = (byte) 0; // mm/dd
<del> else
<del> bytes[13] = (byte) 1; // dd/mm
<del>
<del> // send(bytes);
<del> sendQueue.add(bytes);
<del>
<add> }
<ide> }
<ide>
<ide> public static byte[] crc(byte[] bytes) {
<ide> bytes[16] = 15;
<ide>
<ide> sendQueue.add(bytes);
<del> processSendQueue();
<add> //processSendQueue();
<ide> //}
<ide> }
<ide> |
|
Java | bsd-3-clause | 7b70f8480b359a699d1f2e936299c1d35967947d | 0 | muloem/xins,muloem/xins,muloem/xins | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.URIResolver;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.io.FastStringWriter;
import org.xins.common.manageable.InitializationException;
/**
* XSLT calling convention.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*/
class XSLTCallingConvention extends StandardCallingConvention {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The runtime property name that defines if the templates should be cached.
*/
public final static String TEMPLATES_CACHE_PROPERTY = "templates.cache";
/**
* The runtime property name that defines the base directory of the XSLT
* templates.
*/
public final static String TEMPLATES_LOCATION_PROPERTY = "templates.callingconvention.source";
/**
* The input parameter that specifies the location of the XSLT template to
* use.
*/
public final static String TEMPLATE_PARAMETER = "_template";
/**
* The input parameter used to clear the template cache.
*/
public final static String CLEAR_TEMPLATE_CACHE_PARAMETER = "_cleartemplatecache";
/**
* Cache for the templates.
*/
private final static Map TEMPLATE_CACHE = new HashMap();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>XSLTCallingConvention</code> object.
*/
XSLTCallingConvention() {
// Creates the transformer factory
_factory = TransformerFactory.newInstance();
_factory.setURIResolver(new XsltURIResolver());
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Flag that indicates whether the templates should be cached.
*/
private boolean _cacheTemplates = true;
/**
* Location of the XSLT transformation Style Sheet.
*/
private String _baseXSLTDir;
/**
* The XSLT transformer.
*/
private final TransformerFactory _factory;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected void initImpl(PropertyReader runtimeProperties)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException {
// FIXME: Throw an InvalidPropertyValueException if the value is not
// either 'true' or 'false'
_cacheTemplates = "false".equals(
runtimeProperties.get(TEMPLATES_CACHE_PROPERTY));
// Get the base directory of the Style Sheet
// e.g. http://xslt.mycompany.com/myapi/
// then the XSLT file must have the function names.
_baseXSLTDir = runtimeProperties.get(TEMPLATES_LOCATION_PROPERTY);
// Relative URLs use the user directory as base dir.
if (_baseXSLTDir == null) {
try {
_baseXSLTDir = new File(System.getProperty("user.dir")).toURL().toString();
} catch (IOException ioe) {
// Ignore
}
} else if (_baseXSLTDir.indexOf("://") == -1) {
try {
String userDir = new File(System.getProperty("user.dir")).toURL().toString();
_baseXSLTDir = userDir + _baseXSLTDir;
} catch (IOException ioe) {
// Ignore
}
}
}
protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
// Send the XML output to the stream and flush
FastStringWriter xmlOutput = new FastStringWriter();
CallResultOutputter.output(xmlOutput, xinsResult, false);
xmlOutput.close();
String xsltLocation = httpRequest.getParameter(TEMPLATE_PARAMETER);
if (xsltLocation == null) {
xsltLocation = _baseXSLTDir + httpRequest.getParameter("_function") + ".xslt";
}
try {
Templates t = null;
if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) {
TEMPLATE_CACHE.clear();
PrintWriter out = httpResponse.getWriter();
out.write("Done.");
out.close();
return;
}
if (!_cacheTemplates && TEMPLATE_CACHE.containsKey(xsltLocation)) {
t = (Templates) TEMPLATE_CACHE.get(xsltLocation);
} else {
t = _factory.newTemplates(_factory.getURIResolver().resolve(xsltLocation, _baseXSLTDir));
if (_cacheTemplates) {
TEMPLATE_CACHE.put(xsltLocation, t);
}
}
Transformer xformer = t.newTransformer();
Source source = new StreamSource(new StringReader(xmlOutput.toString()));
Writer buffer = new FastStringWriter(1024);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
PrintWriter out = httpResponse.getWriter();
// Determine the MIME type for the output.
String mimeType = t.getOutputProperties().getProperty("media-type");
if (mimeType == null) {
String method = t.getOutputProperties().getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = t.getOutputProperties().getProperty("encoding");
if (mimeType != null && encoding != null) {
mimeType += ";charset=" + encoding;
}
if (mimeType != null) {
httpResponse.setContentType(mimeType);
}
httpResponse.setStatus(HttpServletResponse.SC_OK);
out.print(buffer.toString());
out.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/**
* Class used to revolved URL locations when an SLT file refers to another XSLT file using a relative URL.
*/
class XsltURIResolver implements URIResolver {
/**
* The previous base URL if any.
*/
private String _base;
/**
* Revolve a hyperlink reference.
*
* @param href
* The hyperlink to resolve.
* @param base
* The base URI in effect when the href attribute was encountered.
*
* @return
* A Source object, or <code>null</code> if the href cannot be resolved,
* and the processor should try to resolve the URI itself.
*
* @throws TransformerException
* If an error occurs when trying to resolve the URI.
*/
public Source resolve(String href, String base) throws TransformerException {
if (base == null) {
base = _base;
} else if (!base.endsWith("/")) {
base += '/';
}
_base = base;
String url = null;
if (href.indexOf(":/") == -1) {
url = base + href;
} else {
url = href;
_base = href.substring(0, href.lastIndexOf('/') + 1);
}
try {
return new StreamSource(new URL(url).openStream());
} catch (IOException ioe) {
ioe.printStackTrace();
throw new TransformerException(ioe);
}
}
}
}
| src/java-server-framework/org/xins/server/XSLTCallingConvention.java | /*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.server;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.URIResolver;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.xins.common.collections.InvalidPropertyValueException;
import org.xins.common.collections.MissingRequiredPropertyException;
import org.xins.common.collections.PropertyReader;
import org.xins.common.io.FastStringWriter;
import org.xins.common.manageable.InitializationException;
/**
* XSLT calling convention.
*
* @version $Revision$ $Date$
* @author Anthony Goubard (<a href="mailto:[email protected]">[email protected]</a>)
*/
class XSLTCallingConvention extends StandardCallingConvention {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The runtime property name that defines if the templates should be cached.
*/
public final static String TEMPLATES_CACHE_PROPERTY = "templates.cache";
/**
* The runtime property name that defines the base directory of the XSLT
* templates.
*/
public final static String TEMPLATES_LOCATION_PROPERTY = "templates.callingconvention.source";
/**
* The input parameter that specifies the location of the XSLT template to
* use.
*/
public final static String TEMPLATE_PARAMETER = "_template";
/**
* The input parameter used to clear the template cache.
*/
public final static String CLEAR_TEMPLATE_CACHE_PARAMETER = "_cleartemplatecache";
/**
* Cache for the templates.
*/
private final static Map TEMPLATE_CACHE = new HashMap();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Constructs a new <code>XSLTCallingConvention</code> object.
*/
XSLTCallingConvention() {
// Creates the transformer factory
_factory = TransformerFactory.newInstance();
_factory.setURIResolver(new XsltURIResolver());
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Flag that indicates whether the templates should be cached.
*/
private boolean _cacheTemplates = true;
/**
* Location of the XSLT transformation Style Sheet.
*/
private String _baseXSLTDir;
/**
* The XSLT transformer.
*/
private final TransformerFactory _factory;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected void initImpl(PropertyReader runtimeProperties)
throws MissingRequiredPropertyException,
InvalidPropertyValueException,
InitializationException {
_cacheTemplates = "false".equals(
runtimeProperties.get(TEMPLATES_CACHE_PROPERTY));
// Get the base directory of the Style Sheet
// e.g. http://xslt.mycompany.com/myapi/
// then the XSLT file must have the function names.
_baseXSLTDir = runtimeProperties.get(TEMPLATES_LOCATION_PROPERTY);
// Relative URLs use the user directory as base dir.
if (_baseXSLTDir == null) {
try {
_baseXSLTDir = new File(System.getProperty("user.dir")).toURL().toString();
} catch (IOException ioe) {
// Ignore
}
} else if (_baseXSLTDir.indexOf("://") == -1) {
try {
String userDir = new File(System.getProperty("user.dir")).toURL().toString();
_baseXSLTDir = userDir + _baseXSLTDir;
} catch (IOException ioe) {
// Ignore
}
}
}
protected void convertResultImpl(FunctionResult xinsResult,
HttpServletResponse httpResponse,
HttpServletRequest httpRequest)
throws IOException {
// Send the XML output to the stream and flush
FastStringWriter xmlOutput = new FastStringWriter();
CallResultOutputter.output(xmlOutput, xinsResult, false);
xmlOutput.close();
String xsltLocation = httpRequest.getParameter(TEMPLATE_PARAMETER);
if (xsltLocation == null) {
xsltLocation = _baseXSLTDir + httpRequest.getParameter("_function") + ".xslt";
}
try {
Templates t = null;
if ("true".equals(httpRequest.getParameter(CLEAR_TEMPLATE_CACHE_PARAMETER))) {
TEMPLATE_CACHE.clear();
PrintWriter out = httpResponse.getWriter();
out.write("Done.");
out.close();
return;
}
if (!_cacheTemplates && TEMPLATE_CACHE.containsKey(xsltLocation)) {
t = (Templates) TEMPLATE_CACHE.get(xsltLocation);
} else {
t = _factory.newTemplates(_factory.getURIResolver().resolve(xsltLocation, _baseXSLTDir));
if (_cacheTemplates) {
TEMPLATE_CACHE.put(xsltLocation, t);
}
}
Transformer xformer = t.newTransformer();
Source source = new StreamSource(new StringReader(xmlOutput.toString()));
Writer buffer = new FastStringWriter(1024);
Result result = new StreamResult(buffer);
xformer.transform(source, result);
PrintWriter out = httpResponse.getWriter();
// Determine the MIME type for the output.
String mimeType = t.getOutputProperties().getProperty("media-type");
if (mimeType == null) {
String method = t.getOutputProperties().getProperty("method");
if ("xml".equals(method)) {
mimeType = "text/xml";
} else if ("html".equals(method)) {
mimeType = "text/html";
} else if ("text".equals(method)) {
mimeType = "text/plain";
}
}
String encoding = t.getOutputProperties().getProperty("encoding");
if (mimeType != null && encoding != null) {
mimeType += ";charset=" + encoding;
}
if (mimeType != null) {
httpResponse.setContentType(mimeType);
}
httpResponse.setStatus(HttpServletResponse.SC_OK);
out.print(buffer.toString());
out.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
/**
* Class used to revolved URL locations when an SLT file refers to another XSLT file using a relative URL.
*/
class XsltURIResolver implements URIResolver {
/**
* The previous base URL if any.
*/
private String _base;
/**
* Revolve a hyperlink reference.
*
* @param href
* The hyperlink to resolve.
* @param base
* The base URI in effect when the href attribute was encountered.
*
* @return
* A Source object, or <code>null</code> if the href cannot be resolved,
* and the processor should try to resolve the URI itself.
*
* @throws TransformerException
* If an error occurs when trying to resolve the URI.
*/
public Source resolve(String href, String base) throws TransformerException {
if (base == null) {
base = _base;
} else if (!base.endsWith("/")) {
base += '/';
}
_base = base;
String url = null;
if (href.indexOf(":/") == -1) {
url = base + href;
} else {
url = href;
_base = href.substring(0, href.lastIndexOf('/') + 1);
}
try {
return new StreamSource(new URL(url).openStream());
} catch (IOException ioe) {
ioe.printStackTrace();
throw new TransformerException(ioe);
}
}
}
}
| Added FIXME comment.
| src/java-server-framework/org/xins/server/XSLTCallingConvention.java | Added FIXME comment. | <ide><path>rc/java-server-framework/org/xins/server/XSLTCallingConvention.java
<ide> InvalidPropertyValueException,
<ide> InitializationException {
<ide>
<add> // FIXME: Throw an InvalidPropertyValueException if the value is not
<add> // either 'true' or 'false'
<ide> _cacheTemplates = "false".equals(
<ide> runtimeProperties.get(TEMPLATES_CACHE_PROPERTY));
<ide> |
|
Java | mit | 8dd2a1237522b072570512e33e1179bc89764db1 | 0 | EpicEricEE/ShopChest,EpicEricEE/ShopChest | package de.epiceric.shopchest.nms;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.utils.Utils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonBuilder {
public static class Part {
private String value;
public Part() {
this("", true);
}
public Part(Object value) {
this(value, value instanceof CharSequence);
}
public Part(Object value, boolean appendQuotes) {
if (appendQuotes) {
this.value = "\"" + value + "\"";
} else {
this.value = String.valueOf(value);
}
}
@Override
public String toString() {
return value;
}
public PartArray toArray() {
return new PartArray(this);
}
public PartMap toMap() {
PartMap map = new PartMap();
map.setValue("text", new Part());
map.setValue("extra", toArray());
return map;
}
}
public static class PartMap extends Part {
private Map<String, Part> values = new HashMap<>();
public PartMap() {
}
public PartMap(Map<String, Part> values) {
this.values.putAll(values);
}
public void setValue(String key, Part value) {
values.put(key, value);
}
public void removeValue(String key) {
values.remove(key);
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(",", "{", "}");
values.forEach((key, value) -> joiner.add("\"" + key + "\":" + value.toString()));
return joiner.toString();
}
@Override
public PartMap toMap() {
return this;
}
}
public static class PartArray extends Part {
private List<Part> parts = new ArrayList<>();
public PartArray(Part... parts) {
this.parts.addAll(Arrays.asList(parts));
}
public void addPart(Part part) {
parts.add(part);
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(",", "[", "]");
parts.forEach(part -> joiner.add(part.toString()));
return joiner.toString();
}
@Override
public PartArray toArray() {
return this;
}
}
private static final Pattern PART_PATTERN = Pattern.compile("(([§][a-fA-Fl-oL-OkK0-9])+)([^§]*)");
private Part rootPart;
private ShopChest plugin;
private Class<?> iChatBaseComponentClass = Utils.getNMSClass("IChatBaseComponent");
private Class<?> packetPlayOutChatClass = Utils.getNMSClass("PacketPlayOutChat");
private Class<?> chatSerializerClass;
public JsonBuilder(ShopChest plugin) {
this.plugin = plugin;
if (Utils.getServerVersion().equals("v1_8_R1")) {
chatSerializerClass = Utils.getNMSClass("ChatSerializer");
} else {
chatSerializerClass = Utils.getNMSClass("IChatBaseComponent$ChatSerializer");
}
Class<?>[] requiredClasses = new Class<?>[] {
iChatBaseComponentClass, packetPlayOutChatClass, chatSerializerClass
};
for (Class<?> c : requiredClasses) {
if (c == null) {
plugin.debug("Failed to instantiate JsonBuilder: Could not find all required classes");
return;
}
}
}
public static Part parse(String text) {
Matcher matcher = PART_PATTERN.matcher(text);
if (!matcher.find()) {
return new Part(text);
}
matcher.reset();
PartArray array = new PartArray();
int lastEndIndex = 0;
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
if (lastEndIndex != startIndex) {
String betweenMatches = text.substring(lastEndIndex, startIndex);
array.addPart(new Part(betweenMatches));
}
String format = matcher.group(1);
String value = matcher.group(3);
PartMap part = new PartMap();
part.setValue("text", new Part(value));
String[] formats = format.split("§");
for (String f : formats) {
switch (f.toLowerCase()) {
case "":
break;
case "k":
part.setValue("obuscated", new Part(true));
break;
case "l":
part.setValue("bold", new Part(true));
break;
case "m":
part.setValue("strikethrough", new Part(true));
break;
case "n":
part.setValue("underlined", new Part(true));
break;
case "o":
part.setValue("italic", new Part(true));
break;
case "r":
part.removeValue("obfuscated");
part.removeValue("bold");
part.removeValue("strikethrough");
part.removeValue("underlined");
part.removeValue("italic");
part.removeValue("color");
break;
default:
part.setValue("color", new Part(ChatColor.getByChar(f).name().toLowerCase()));
}
}
array.addPart(part);
lastEndIndex = endIndex;
}
return array;
}
@Override
public String toString() {
return rootPart.toString();
}
public Part getRootPart() {
return rootPart;
}
public void setRootPart(Part rootPart) {
this.rootPart = rootPart;
}
public void sendJson(Player p) {
try {
Object iChatBaseComponent = chatSerializerClass.getMethod("a", String.class).invoke(null, toString());
Object packetPlayOutChat = packetPlayOutChatClass.getConstructor(iChatBaseComponentClass).newInstance(iChatBaseComponent);
Utils.sendPacket(plugin, packetPlayOutChat, p);
plugin.debug("Sent JSON: " + toString());
} catch (InstantiationException | InvocationTargetException |
IllegalAccessException | NoSuchMethodException e) {
plugin.getLogger().severe("Failed to send JSON with reflection");
plugin.debug("Failed to send JSON with reflection: " + toString());
plugin.debug(e);
}
}
}
| src/main/java/de/epiceric/shopchest/nms/JsonBuilder.java | package de.epiceric.shopchest.nms;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.utils.Utils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonBuilder {
public static class Part {
private String value;
public Part() {
this("");
}
public Part(Object value) {
if (value instanceof CharSequence) {
this.value = "\"" + value + "\"";
} else {
this.value = String.valueOf(value);
}
}
@Override
public String toString() {
return value;
}
public PartArray toArray() {
return new PartArray(this);
}
public PartMap toMap() {
PartMap map = new PartMap();
map.setValue("text", new Part());
map.setValue("extra", toArray());
return map;
}
}
public static class PartMap extends Part {
private Map<String, Part> values = new HashMap<>();
public PartMap() {
}
public PartMap(Map<String, Part> values) {
this.values.putAll(values);
}
public void setValue(String key, Part value) {
values.put(key, value);
}
public void removeValue(String key) {
values.remove(key);
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(",", "{", "}");
values.forEach((key, value) -> joiner.add("\"" + key + "\":" + value.toString()));
return joiner.toString();
}
@Override
public PartMap toMap() {
return this;
}
}
public static class PartArray extends Part {
private List<Part> parts = new ArrayList<>();
public PartArray(Part... parts) {
this.parts.addAll(Arrays.asList(parts));
}
public void addPart(Part part) {
parts.add(part);
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(",", "[", "]");
parts.forEach(part -> joiner.add(part.toString()));
return joiner.toString();
}
@Override
public PartArray toArray() {
return this;
}
}
private static final Pattern PART_PATTERN = Pattern.compile("(([§][a-fA-Fl-oL-OkK0-9])+)([^§]*)");
private Part rootPart;
private ShopChest plugin;
private Class<?> iChatBaseComponentClass = Utils.getNMSClass("IChatBaseComponent");
private Class<?> packetPlayOutChatClass = Utils.getNMSClass("PacketPlayOutChat");
private Class<?> chatSerializerClass;
public JsonBuilder(ShopChest plugin) {
this.plugin = plugin;
if (Utils.getServerVersion().equals("v1_8_R1")) {
chatSerializerClass = Utils.getNMSClass("ChatSerializer");
} else {
chatSerializerClass = Utils.getNMSClass("IChatBaseComponent$ChatSerializer");
}
Class<?>[] requiredClasses = new Class<?>[] {
iChatBaseComponentClass, packetPlayOutChatClass, chatSerializerClass
};
for (Class<?> c : requiredClasses) {
if (c == null) {
plugin.debug("Failed to instantiate JsonBuilder: Could not find all required classes");
return;
}
}
}
public static Part parse(String text) {
Matcher matcher = PART_PATTERN.matcher(text);
if (!matcher.find()) {
return new Part(text);
}
matcher.reset();
PartArray array = new PartArray();
int lastEndIndex = 0;
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
if (lastEndIndex != startIndex) {
String betweenMatches = text.substring(lastEndIndex, startIndex);
array.addPart(new Part(betweenMatches));
}
String format = matcher.group(1);
String value = matcher.group(3);
PartMap part = new PartMap();
part.setValue("text", new Part(value));
String[] formats = format.split("§");
for (String f : formats) {
switch (f.toLowerCase()) {
case "":
break;
case "k":
part.setValue("obuscated", new Part(true));
break;
case "l":
part.setValue("bold", new Part(true));
break;
case "m":
part.setValue("strikethrough", new Part(true));
break;
case "n":
part.setValue("underlined", new Part(true));
break;
case "o":
part.setValue("italic", new Part(true));
break;
case "r":
part.removeValue("obfuscated");
part.removeValue("bold");
part.removeValue("strikethrough");
part.removeValue("underlined");
part.removeValue("italic");
part.removeValue("color");
break;
default:
part.setValue("color", new Part(ChatColor.getByChar(f).name().toLowerCase()));
}
}
array.addPart(part);
lastEndIndex = endIndex;
}
return array;
}
@Override
public String toString() {
return rootPart.toString();
}
public Part getRootPart() {
return rootPart;
}
public void setRootPart(Part rootPart) {
this.rootPart = rootPart;
}
public void sendJson(Player p) {
try {
Object iChatBaseComponent = chatSerializerClass.getMethod("a", String.class).invoke(null, toString());
Object packetPlayOutChat = packetPlayOutChatClass.getConstructor(iChatBaseComponentClass).newInstance(iChatBaseComponent);
Utils.sendPacket(plugin, packetPlayOutChat, p);
} catch (InstantiationException | InvocationTargetException |
IllegalAccessException | NoSuchMethodException e) {
plugin.getLogger().severe("Failed to send JSON with reflection");
plugin.debug("Failed to send JSON with reflection: " + toString());
plugin.debug(e);
}
}
}
| Final updates for JsonBuilder
| src/main/java/de/epiceric/shopchest/nms/JsonBuilder.java | Final updates for JsonBuilder | <ide><path>rc/main/java/de/epiceric/shopchest/nms/JsonBuilder.java
<ide> private String value;
<ide>
<ide> public Part() {
<del> this("");
<add> this("", true);
<ide> }
<ide>
<ide> public Part(Object value) {
<del> if (value instanceof CharSequence) {
<add> this(value, value instanceof CharSequence);
<add> }
<add>
<add> public Part(Object value, boolean appendQuotes) {
<add> if (appendQuotes) {
<ide> this.value = "\"" + value + "\"";
<ide> } else {
<ide> this.value = String.valueOf(value);
<ide> Object packetPlayOutChat = packetPlayOutChatClass.getConstructor(iChatBaseComponentClass).newInstance(iChatBaseComponent);
<ide>
<ide> Utils.sendPacket(plugin, packetPlayOutChat, p);
<add> plugin.debug("Sent JSON: " + toString());
<ide> } catch (InstantiationException | InvocationTargetException |
<ide> IllegalAccessException | NoSuchMethodException e) {
<ide> plugin.getLogger().severe("Failed to send JSON with reflection"); |
|
Java | mit | 5c8805f6d63a651eecba0be71afea60a6a2ac1da | 0 | sdsmdg/Cognizance | package in.co.sdslabs.cognizance;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainNavDrawerActivity extends ActionBarActivity {
int mPosition = -1;
String mTitle = "";
// Array of strings storing Event Category names
String[] mEventCategories;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private LinearLayout mDrawer;
private List<HashMap<String, String>> mList;
private SimpleAdapter mAdapter;
final private String EVENTCATEGORY = "eventcategory";
final private String IMAGE = "image";
private HomeFragment hFragment;
FragmentManager fragmentManager;
FragmentTransaction ft;
public static String initialTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addHomeFragment();
// Getting an array of country names
mEventCategories = getResources().getStringArray(
R.array.eventCategories);
// Title of the activity
mTitle = (String) getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = (LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < mEventCategories.length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(EVENTCATEGORY, mEventCategories[i]);
hm.put(IMAGE, Integer.toString(Drawables.navDrawerImages[i]));
mList.add(hm);
}
// Keys used in Hashmap
String[] from = { IMAGE, EVENTCATEGORY };
// Ids of views in listview_layout
int[] to = { R.id.image, R.id.eventcategory };
// Instantiating an adapter to store each items
// R.layout.drawer_layout defines the layout of each item
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from,
to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Creating a ToggleButton for NavigationDrawer with drawer event
// listener
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedEventCategory();
// getSupportActionBar().setTitle("Cognizance 2014");
getSupportActionBar().setTitle(initialTitle);
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
initialTitle = (String) getSupportActionBar().getTitle();
getSupportActionBar().setTitle("Select a Category");
supportInvalidateOptionsMenu();
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
// ItemClick event handler for the drawer items
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// Show fragment for eventCategories
showFragment(position);
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawer);
}
});
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Changing the background of the color drawable
// getSupportActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.rgb(234, 234, 234)));
// Setting the adapter to the listView
mDrawerList.setAdapter(mAdapter);
}
private void addHomeFragment() {
// initialize the HomeFragment
hFragment = new HomeFragment();
// Getting reference to the FragmentManager
fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, hFragment);
// Committing the transaction
ft.commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@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_navdrawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// super.onOptionsItemSelected(item);
if(mDrawerToggle.onOptionsItemSelected(item)){
}
switch (item.getItemId()) {
case R.id.filter:
Intent intent = new Intent(this, MainTabActivity.class);
startActivity(intent);
break;
case R.id.map:
// TODO : Fire intent for full map and not the zoomed in view
Intent goToMap = new Intent(this, MapTest.class);
startActivity(goToMap);
break;
case R.id.contact:
// TODO : Fire intent for contacts activity
Intent gotocontacts = new Intent(this, ContactListActivity.class);
startActivity(gotocontacts);
break;
case R.id.about_us:
break;
}
return true;
}
public void showFragment(int position) {
// Currently selected eventCategory
mTitle = mEventCategories[position];
// Creating a fragment object
EventCategoryFragment eFragment = new EventCategoryFragment();
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putInt("position", position);
// Setting the position to the fragment
eFragment.setArguments(data);
// Getting reference to the FragmentManager
fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, eFragment);
ft.addToBackStack(null);
// Committing the transaction
ft.commit();
}
// Highlight the selected eventCategory
public void highlightSelectedEventCategory() {
mDrawerList.setItemChecked(mPosition, true);
if (mPosition != -1)
getSupportActionBar().setTitle(mEventCategories[mPosition]);
}
@Override
public void onBackPressed() {
super.onBackPressed();
getSupportActionBar().setTitle("Cognizance");
fragmentManager.popBackStack();
}
}
| Cognizance/src/in/co/sdslabs/cognizance/MainNavDrawerActivity.java | package in.co.sdslabs.cognizance;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainNavDrawerActivity extends ActionBarActivity {
int mPosition = -1;
String mTitle = "";
// Array of strings storing Event Category names
String[] mEventCategories;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private LinearLayout mDrawer;
private List<HashMap<String, String>> mList;
private SimpleAdapter mAdapter;
final private String EVENTCATEGORY = "eventcategory";
final private String IMAGE = "image";
private HomeFragment hFragment;
FragmentManager fragmentManager;
FragmentTransaction ft;
public static String initialTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addHomeFragment();
// Getting an array of country names
mEventCategories = getResources().getStringArray(
R.array.eventCategories);
// Title of the activity
mTitle = (String) getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = (LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < mEventCategories.length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(EVENTCATEGORY, mEventCategories[i]);
hm.put(IMAGE, Integer.toString(Drawables.navDrawerImages[i]));
mList.add(hm);
}
// Keys used in Hashmap
String[] from = { IMAGE, EVENTCATEGORY };
// Ids of views in listview_layout
int[] to = { R.id.image, R.id.eventcategory };
// Instantiating an adapter to store each items
// R.layout.drawer_layout defines the layout of each item
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from,
to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Creating a ToggleButton for NavigationDrawer with drawer event
// listener
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedEventCategory();
// getSupportActionBar().setTitle("Cognizance 2014");
getSupportActionBar().setTitle(initialTitle);
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
initialTitle = (String) getSupportActionBar().getTitle();
getSupportActionBar().setTitle("Select a Category");
supportInvalidateOptionsMenu();
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
// ItemClick event handler for the drawer items
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// Show fragment for eventCategories
showFragment(position);
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawer);
}
});
// Enabling Up navigation
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Changing the background of the color drawable
// getSupportActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.rgb(234, 234, 234)));
// Setting the adapter to the listView
mDrawerList.setAdapter(mAdapter);
}
private void addHomeFragment() {
// initialize the HomeFragment
hFragment = new HomeFragment();
// Getting reference to the FragmentManager
fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, hFragment);
// Committing the transaction
ft.commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@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_navdrawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.filter:
Intent intent = new Intent(this, MainTabActivity.class);
startActivity(intent);
break;
case R.id.map:
// TODO : Fire intent for full map and not the zoomed in view
Intent goToMap = new Intent(this, MapTest.class);
startActivity(goToMap);
break;
case R.id.contact:
// TODO : Fire intent for contacts activity
Intent gotocontacts = new Intent(this, ContactListActivity.class);
startActivity(gotocontacts);
break;
case R.id.about_us:
break;
}
return true;
}
public void showFragment(int position) {
// Currently selected eventCategory
mTitle = mEventCategories[position];
// Creating a fragment object
EventCategoryFragment eFragment = new EventCategoryFragment();
// Creating a Bundle object
Bundle data = new Bundle();
// Setting the index of the currently selected item of mDrawerList
data.putInt("position", position);
// Setting the position to the fragment
eFragment.setArguments(data);
// Getting reference to the FragmentManager
fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.content_frame, eFragment);
ft.addToBackStack(null);
// Committing the transaction
ft.commit();
}
// Highlight the selected eventCategory
public void highlightSelectedEventCategory() {
mDrawerList.setItemChecked(mPosition, true);
if (mPosition != -1)
getSupportActionBar().setTitle(mEventCategories[mPosition]);
}
@Override
public void onBackPressed() {
super.onBackPressed();
getSupportActionBar().setTitle("Cognizance");
fragmentManager.popBackStack();
}
}
| Fix Navigation Drawer Bug
| Cognizance/src/in/co/sdslabs/cognizance/MainNavDrawerActivity.java | Fix Navigation Drawer Bug | <ide><path>ognizance/src/in/co/sdslabs/cognizance/MainNavDrawerActivity.java
<ide>
<ide> @Override
<ide> public boolean onOptionsItemSelected(MenuItem item) {
<del> super.onOptionsItemSelected(item);
<del>
<add>// super.onOptionsItemSelected(item);
<add>
<add> if(mDrawerToggle.onOptionsItemSelected(item)){
<add>
<add> }
<ide> switch (item.getItemId()) {
<ide>
<ide> case R.id.filter: |
|
Java | apache-2.0 | 91c23a3b9383cdaff32e97a7dcca07e13532e032 | 0 | apache/kafka,guozhangwang/kafka,apache/kafka,guozhangwang/kafka,guozhangwang/kafka,apache/kafka,guozhangwang/kafka,apache/kafka | /*
* 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.kafka.common.network;
import org.apache.kafka.common.memory.MemoryPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ScatteringByteChannel;
/**
* A size delimited Receive that consists of a 4 byte network-ordered size N followed by N bytes of content
*/
public class NetworkReceive implements Receive {
public static final String UNKNOWN_SOURCE = "";
public static final int UNLIMITED = -1;
private static final Logger log = LoggerFactory.getLogger(NetworkReceive.class);
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
private final String source;
private final ByteBuffer size;
private final int maxSize;
private final MemoryPool memoryPool;
private int requestedBufferSize = -1;
private ByteBuffer buffer;
public NetworkReceive(String source, ByteBuffer buffer) {
this(UNLIMITED, source);
this.buffer = buffer;
}
public NetworkReceive(String source) {
this(UNLIMITED, source);
}
public NetworkReceive(int maxSize, String source) {
this(maxSize, source, MemoryPool.NONE);
}
public NetworkReceive(int maxSize, String source, MemoryPool memoryPool) {
this.source = source;
this.size = ByteBuffer.allocate(4);
this.buffer = null;
this.maxSize = maxSize;
this.memoryPool = memoryPool;
}
public NetworkReceive() {
this(UNKNOWN_SOURCE);
}
@Override
public String source() {
return source;
}
@Override
public boolean complete() {
return !size.hasRemaining() && buffer != null && !buffer.hasRemaining();
}
public long readFrom(ScatteringByteChannel channel) throws IOException {
int read = 0;
if (size.hasRemaining()) {
int bytesRead = channel.read(size);
if (bytesRead < 0)
throw new EOFException();
read += bytesRead;
if (!size.hasRemaining()) {
size.rewind();
int receiveSize = size.getInt();
if (receiveSize < 0)
throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + ")");
if (maxSize != UNLIMITED && receiveSize > maxSize)
throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + " larger than " + maxSize + ")");
requestedBufferSize = receiveSize; //may be 0 for some payloads (SASL)
if (receiveSize == 0) {
buffer = EMPTY_BUFFER;
}
}
}
if (buffer == null && requestedBufferSize != -1) { //we know the size we want but havent been able to allocate it yet
buffer = memoryPool.tryAllocate(requestedBufferSize);
if (buffer == null)
log.trace("Broker low on memory - could not allocate buffer of size {} for source {}", requestedBufferSize, source);
}
if (buffer != null) {
int bytesRead = channel.read(buffer);
if (bytesRead < 0)
throw new EOFException();
read += bytesRead;
}
return read;
}
@Override
public boolean requiredMemoryAmountKnown() {
return requestedBufferSize != -1;
}
@Override
public boolean memoryAllocated() {
return buffer != null;
}
@Override
public void close() throws IOException {
if (buffer != null && buffer != EMPTY_BUFFER) {
memoryPool.release(buffer);
buffer = null;
}
}
public ByteBuffer payload() {
return this.buffer;
}
public int bytesRead() {
if (buffer == null)
return size.position();
return buffer.position() + size.position();
}
/**
* Returns the total size of the receive including payload and size buffer
* for use in metrics. This is consistent with {@link NetworkSend#size()}
*/
public int size() {
return payload().limit() + size.limit();
}
}
| clients/src/main/java/org/apache/kafka/common/network/NetworkReceive.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.kafka.common.network;
import org.apache.kafka.common.memory.MemoryPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ScatteringByteChannel;
/**
* A size delimited Receive that consists of a 4 byte network-ordered size N followed by N bytes of content
*/
public class NetworkReceive implements Receive {
public final static String UNKNOWN_SOURCE = "";
public final static int UNLIMITED = -1;
private static final Logger log = LoggerFactory.getLogger(NetworkReceive.class);
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
private final String source;
private final ByteBuffer size;
private final int maxSize;
private final MemoryPool memoryPool;
private int requestedBufferSize = -1;
private ByteBuffer buffer;
public NetworkReceive(String source, ByteBuffer buffer) {
this.source = source;
this.buffer = buffer;
this.size = null;
this.maxSize = UNLIMITED;
this.memoryPool = MemoryPool.NONE;
}
public NetworkReceive(String source) {
this.source = source;
this.size = ByteBuffer.allocate(4);
this.buffer = null;
this.maxSize = UNLIMITED;
this.memoryPool = MemoryPool.NONE;
}
public NetworkReceive(int maxSize, String source) {
this.source = source;
this.size = ByteBuffer.allocate(4);
this.buffer = null;
this.maxSize = maxSize;
this.memoryPool = MemoryPool.NONE;
}
public NetworkReceive(int maxSize, String source, MemoryPool memoryPool) {
this.source = source;
this.size = ByteBuffer.allocate(4);
this.buffer = null;
this.maxSize = maxSize;
this.memoryPool = memoryPool;
}
public NetworkReceive() {
this(UNKNOWN_SOURCE);
}
@Override
public String source() {
return source;
}
@Override
public boolean complete() {
return !size.hasRemaining() && buffer != null && !buffer.hasRemaining();
}
public long readFrom(ScatteringByteChannel channel) throws IOException {
int read = 0;
if (size.hasRemaining()) {
int bytesRead = channel.read(size);
if (bytesRead < 0)
throw new EOFException();
read += bytesRead;
if (!size.hasRemaining()) {
size.rewind();
int receiveSize = size.getInt();
if (receiveSize < 0)
throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + ")");
if (maxSize != UNLIMITED && receiveSize > maxSize)
throw new InvalidReceiveException("Invalid receive (size = " + receiveSize + " larger than " + maxSize + ")");
requestedBufferSize = receiveSize; //may be 0 for some payloads (SASL)
if (receiveSize == 0) {
buffer = EMPTY_BUFFER;
}
}
}
if (buffer == null && requestedBufferSize != -1) { //we know the size we want but havent been able to allocate it yet
buffer = memoryPool.tryAllocate(requestedBufferSize);
if (buffer == null)
log.trace("Broker low on memory - could not allocate buffer of size {} for source {}", requestedBufferSize, source);
}
if (buffer != null) {
int bytesRead = channel.read(buffer);
if (bytesRead < 0)
throw new EOFException();
read += bytesRead;
}
return read;
}
@Override
public boolean requiredMemoryAmountKnown() {
return requestedBufferSize != -1;
}
@Override
public boolean memoryAllocated() {
return buffer != null;
}
@Override
public void close() throws IOException {
if (buffer != null && buffer != EMPTY_BUFFER) {
memoryPool.release(buffer);
buffer = null;
}
}
public ByteBuffer payload() {
return this.buffer;
}
public int bytesRead() {
if (buffer == null)
return size.position();
return buffer.position() + size.position();
}
/**
* Returns the total size of the receive including payload and size buffer
* for use in metrics. This is consistent with {@link NetworkSend#size()}
*/
public int size() {
return payload().limit() + size.limit();
}
}
| MINOR: Cleanup NetworkReceive constructors (#12511)
There was unnecessary duplication and one of the overloads
did not set the size field for no good reason.
Reviewers: Luke Chen <[email protected]> | clients/src/main/java/org/apache/kafka/common/network/NetworkReceive.java | MINOR: Cleanup NetworkReceive constructors (#12511) | <ide><path>lients/src/main/java/org/apache/kafka/common/network/NetworkReceive.java
<ide> */
<ide> public class NetworkReceive implements Receive {
<ide>
<del> public final static String UNKNOWN_SOURCE = "";
<del> public final static int UNLIMITED = -1;
<add> public static final String UNKNOWN_SOURCE = "";
<add> public static final int UNLIMITED = -1;
<ide> private static final Logger log = LoggerFactory.getLogger(NetworkReceive.class);
<ide> private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
<ide>
<ide>
<ide>
<ide> public NetworkReceive(String source, ByteBuffer buffer) {
<del> this.source = source;
<add> this(UNLIMITED, source);
<ide> this.buffer = buffer;
<del> this.size = null;
<del> this.maxSize = UNLIMITED;
<del> this.memoryPool = MemoryPool.NONE;
<ide> }
<ide>
<ide> public NetworkReceive(String source) {
<del> this.source = source;
<del> this.size = ByteBuffer.allocate(4);
<del> this.buffer = null;
<del> this.maxSize = UNLIMITED;
<del> this.memoryPool = MemoryPool.NONE;
<add> this(UNLIMITED, source);
<ide> }
<ide>
<ide> public NetworkReceive(int maxSize, String source) {
<del> this.source = source;
<del> this.size = ByteBuffer.allocate(4);
<del> this.buffer = null;
<del> this.maxSize = maxSize;
<del> this.memoryPool = MemoryPool.NONE;
<add> this(maxSize, source, MemoryPool.NONE);
<ide> }
<ide>
<ide> public NetworkReceive(int maxSize, String source, MemoryPool memoryPool) { |
|
Java | mit | f6f22df20b7084ca61f1bc178fe35a9b6d4dd124 | 0 | tsmacdonald/simulator,tsmacdonald/simulator | package edu.wheaton.simulator.gui;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JLabel;
public class EditTriggerScreen extends Screen {
/**
*
*/
private static final long serialVersionUID = 3261558461232576081L;
private JButton addConditional;
private JButton addBehavior;
private JLabel title;
public EditTriggerScreen(Manager sm) {
super(sm);
addConditional = new JButton();
addBehavior = new JButton();
title = new JLabel("Edit Trigger");
title.setPreferredSize(new Dimension(300, 100));
}
@Override
public void load() {
// TODO Auto-generated method stub
}
}
| src/edu/wheaton/simulator/gui/EditTriggerScreen.java | package edu.wheaton.simulator.gui;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JLabel;
public class EditTriggerScreen extends Screen {
private JButton addConditional;
private JButton addBehavior;
private JLabel title;
public EditTriggerScreen(Manager sm) {
super(sm);
addConditional = new JButton();
addBehavior = new JButton();
title = new JLabel("Edit Trigger");
title.setPreferredSize(new Dimension(300, 100));
}
@Override
public void load() {
// TODO Auto-generated method stub
}
}
| warning fixes
| src/edu/wheaton/simulator/gui/EditTriggerScreen.java | warning fixes | <ide><path>rc/edu/wheaton/simulator/gui/EditTriggerScreen.java
<ide> import javax.swing.JLabel;
<ide>
<ide> public class EditTriggerScreen extends Screen {
<add>
<add> /**
<add> *
<add> */
<add> private static final long serialVersionUID = 3261558461232576081L;
<ide>
<ide> private JButton addConditional;
<ide> |
|
JavaScript | mit | 17a6f631350a86e2989dbb70d694b88a8f9bf907 | 0 | theappbusiness/tab-hq,theappbusiness/tab-hq,lukemarsh/tab-hq-react,lukemarsh/tab-hq-react,lukemarsh/tab-hq-react,theappbusiness/tab-hq | 'use strict';
var Reflux = require('reflux');
var CurrentUserActions = require('../actions/CurrentUserActions');
var AuthAPI = require('../utils/AuthAPI');
var CurrentTrackStore = Reflux.createStore({
init: function() {
this.user = null;
this.hasBeenChecked = false;
this.listenTo(CurrentUserActions.checkLoginStatus, this.checkLoginStatus);
this.listenTo(CurrentUserActions.login, this.loginUser);
this.listenTo(CurrentUserActions.logout, this.logoutUser);
},
setUser: function(user, cb) {
this.user = user;
cb(null, this.user);
this.trigger(null, this.user);
},
throwError: function(err, cb) {
cb(err);
this.trigger(err);
},
checkLoginStatus: function(cb) {
cb = cb || function() {};
if ( this.user ) {
this.setUser(this.user, cb);
} else {
AuthAPI.checkLoginStatus().then(function(user) {
this.hasBeenChecked = true;
this.setUser(user, cb);
}.bind(this)).catch(function(err) {
this.hasBeenChecked = true;
this.throwError(err, cb);
}.bind(this));
}
},
loginUser: function(user, cb) {
cb = cb || function() {};
AuthAPI.login(user).then(function(user) {
this.setUser(user, cb);
}.bind(this)).catch(function(err) {
this.throwError(err, cb);
}.bind(this));
},
logoutUser: function(cb) {
cb = cb || function() {};
AuthAPI.logout(this.user).then(function() {
this.setUser(null, cb);
}.bind(this));
}
});
module.exports = CurrentTrackStore; | app/js/stores/CurrentUserStore.js | 'use strict';
var Reflux = require('reflux');
var CurrentUserActions = require('../actions/CurrentUserActions');
var AuthAPI = require('../utils/AuthAPI');
var CurrentTrackStore = Reflux.createStore({
init: function() {
this.user = null;
this.hasBeenChecked = false;
this.listenTo(CurrentUserActions.checkLoginStatus, this.checkLoginStatus);
this.listenTo(CurrentUserActions.login, this.loginUser);
this.listenTo(CurrentUserActions.logout, this.logoutUser);
},
setUser: function(user, cb) {
this.user = user;
cb(null, this.user);
this.trigger(null, this.user);
},
throwError: function(err, cb) {
cb(err);
this.trigger(err);
},
checkLoginStatus: function(cb) {
cb = cb || function() {};
if ( this.user ) {
this.setUser(this.user, cb);
} else {
AuthAPI.checkLoginStatus().then(function(user) {
this.hasBeenChecked = true;
this.setuser(user, cb);
}.bind(this)).catch(function(err) {
this.hasBeenChecked = true;
this.throwError(err, cb);
}.bind(this));
}
},
loginUser: function(user, cb) {
cb = cb || function() {};
AuthAPI.login(user).then(function(user) {
this.setUser(user, cb);
}.bind(this)).catch(function(err) {
this.throwError(err, cb);
}.bind(this));
},
logoutUser: function(cb) {
cb = cb || function() {};
AuthAPI.logout(this.user).then(function() {
this.setUser(null, cb);
}.bind(this));
}
});
module.exports = CurrentTrackStore; | fix typo
| app/js/stores/CurrentUserStore.js | fix typo | <ide><path>pp/js/stores/CurrentUserStore.js
<ide> } else {
<ide> AuthAPI.checkLoginStatus().then(function(user) {
<ide> this.hasBeenChecked = true;
<del> this.setuser(user, cb);
<add> this.setUser(user, cb);
<ide> }.bind(this)).catch(function(err) {
<ide> this.hasBeenChecked = true;
<ide> this.throwError(err, cb); |
|
JavaScript | mit | 24b24ab77462a1f6016f3ebaf24fc7dfd9956f05 | 0 | luislobo/waterline,balderdashy/waterline | /**
* Module Dependencies
*/
var util = require('util');
var async = require('async');
var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
var Deferred = require('../utils/query/deferred');
var forgeStageTwoQuery = require('../utils/query/forge-stage-two-query');
var forgeStageThreeQuery = require('../utils/query/forge-stage-three-query');
var processAllRecords = require('../utils/records/process-all-records');
/**
* Create a new record
*
* @param {Object || Array} values for single model or array of multiple values
* @param {Function} callback
* @return Deferred object if no callback
*/
module.exports = function create(values, cb, metaContainer) {
var self = this;
var query = {
method: 'create',
using: this.identity,
newRecord: values,
meta: metaContainer
};
// Return Deferred or pass to adapter
if (typeof cb !== 'function') {
return new Deferred(this, this.create, query);
}
// ╔═╗╔═╗╦═╗╔═╗╔═╗ ┌─┐┌┬┐┌─┐┌─┐┌─┐ ┌┬┐┬ ┬┌─┐ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
// ╠╣ ║ ║╠╦╝║ ╦║╣ └─┐ │ ├─┤│ ┬├┤ │ ││││ │ │─┼┐│ │├┤ ├┬┘└┬┘
// ╚ ╚═╝╩╚═╚═╝╚═╝ └─┘ ┴ ┴ ┴└─┘└─┘ ┴ └┴┘└─┘ └─┘└└─┘└─┘┴└─ ┴
//
// Forge a stage 2 query (aka logical protostatement)
// This ensures a normalized format.
try {
forgeStageTwoQuery(query, this.waterline);
} catch (e) {
switch (e.code) {
case 'E_INVALID_NEW_RECORD':
return cb(
flaverr(
{ name: 'UsageError' },
new Error(
'Invalid new record(s).\n'+
'Details:\n'+
' '+e.details+'\n'
)
)
);
default:
return cb(e);
}
}
// ╔╗ ╔═╗╔═╗╔═╗╦═╗╔═╗ ┌─┐┬─┐┌─┐┌─┐┌┬┐┌─┐ ┬ ┬┌─┐┌─┐┌─┐┬ ┬┌─┐┬ ┌─┐ ┌─┐┌─┐┬ ┬ ┌┐ ┌─┐┌─┐┬┌─
// ╠╩╗║╣ ╠╣ ║ ║╠╦╝║╣ │ ├┬┘├┤ ├─┤ │ ├┤ │ │├┤ ├┤ │ └┬┘│ │ ├┤ │ ├─┤│ │ ├┴┐├─┤│ ├┴┐
// ╚═╝╚═╝╚ ╚═╝╩╚═╚═╝ └─┘┴└─└─┘┴ ┴ ┴ └─┘ ┴─┘┴└ └─┘└─┘ ┴ └─┘┴─┘└─┘ └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴
// Determine what to do about running "before" lifecycle callbacks
(function(proceed) {
// If there is no relevant "before" lifecycle callback, then just proceed.
if (!_.has(self._callbacks, 'beforeCreate')) {
return proceed();
}//-•
// Now check if the `skipAllLifecycleCallbacks` meta flag was set.
// If so, don't run this lifecycle callback.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed();
}//-•
// IWMIH, run the "before" lifecycle callback.
self._callbacks.beforeCreate(query.newRecord, function(err){
if (err) { return proceed(err); }
return proceed();
});
})(function(err) {
if (err) {
return cb(err);
}
// ╔═╗╦ ╦╔═╗╔═╗╦╔═ ┌─┐┌─┐┬─┐ ┌─┐┌┐┌┬ ┬
// ║ ╠═╣║╣ ║ ╠╩╗ ├┤ │ │├┬┘ ├─┤│││└┬┘
// ╚═╝╩ ╩╚═╝╚═╝╩ ╩ └ └─┘┴└─ ┴ ┴┘└┘ ┴
// ┌─┐┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌ ┬─┐┌─┐┌─┐┌─┐┌┬┐┌─┐
// │ │ ││ │ ├┤ │ │ ││ ││││ ├┬┘├┤ └─┐├┤ │ └─┐
// └─┘└─┘┴─┘┴─┘└─┘└─┘ ┴ ┴└─┘┘└┘ ┴└─└─┘└─┘└─┘ ┴ └─┘
// Also removes them from the newRecord before sending to the adapter.
var collectionResets = {};
_.each(self.attributes, function checkForCollection(attributeVal, attributeName) {
if (_.has(attributeVal, 'collection')) {
// Only create a reset if the value isn't an empty array. If the value
// is an empty array there isn't any resetting to do.
if (query.newRecord[attributeName].length) {
collectionResets[attributeName] = query.newRecord[attributeName];
}
// Remove the collection value from the newRecord because the adapter
// doesn't need to do anything during the initial create.
delete query.newRecord[attributeName];
}
});
// If any collection resets were specified, force `fetch: true` (meta key)
// so that we can use it below. (+ if we force it to `true`, remember that
// so we can adjust accordingly before we send the result back.)
var didForceFetchTrue;
if (_.keys(collectionResets).length > 0) {
didForceFetchTrue = (!query.meta || !query.meta.fetch);
query.meta = query.meta || {};
query.meta.fetch = true;
}//>-
// ╔═╗╔═╗╦═╗╔═╗╔═╗ ┌─┐┌┬┐┌─┐┌─┐┌─┐ ┌┬┐┬ ┬┬─┐┌─┐┌─┐ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
// ╠╣ ║ ║╠╦╝║ ╦║╣ └─┐ │ ├─┤│ ┬├┤ │ ├─┤├┬┘├┤ ├┤ │─┼┐│ │├┤ ├┬┘└┬┘
// ╚ ╚═╝╩╚═╚═╝╚═╝ └─┘ ┴ ┴ ┴└─┘└─┘ ┴ ┴ ┴┴└─└─┘└─┘ └─┘└└─┘└─┘┴└─ ┴
var stageThreeQuery;
// TODO: do `query = forgeStageThreeQuery({ ...` instead of this
// (just need to verify that we aren't relying on the old way anywhere)
try {
stageThreeQuery = forgeStageThreeQuery({
stageTwoQuery: query,
identity: self.identity,
transformer: self._transformer,
originalModels: self.waterline.collections
});
} catch (e) {
return cb(e);
}
// ╔═╗╔═╗╔╗╔╔╦╗ ┌┬┐┌─┐ ┌─┐┌┬┐┌─┐┌─┐┌┬┐┌─┐┬─┐
// ╚═╗║╣ ║║║ ║║ │ │ │ ├─┤ ││├─┤├─┘ │ ├┤ ├┬┘
// ╚═╝╚═╝╝╚╝═╩╝ ┴ └─┘ ┴ ┴─┴┘┴ ┴┴ ┴ └─┘┴└─
// Grab the adapter to perform the query on
var datastoreName = self.adapterDictionary.create;
var adapter = self.datastores[datastoreName].adapter;
// Run the operation
adapter.create(datastoreName, stageThreeQuery, function createCb(err, rawAdapterResult) {
if (err) {
// Attach the identity of this model (for convenience).
err.model = self.identity;
return cb(err);
}//-•
// ╔╦╗╔═╗╔╦╗╔═╗╦═╗╔╦╗╦╔╗╔╔═╗ ┬ ┬┬ ┬┬┌─┐┬ ┬ ┬ ┬┌─┐┬ ┬ ┬┌─┐┌─┐
// ║║║╣ ║ ║╣ ╠╦╝║║║║║║║║╣ │││├─┤││ ├─┤ └┐┌┘├─┤│ │ │├┤ └─┐
// ═╩╝╚═╝ ╩ ╚═╝╩╚═╩ ╩╩╝╚╝╚═╝ └┴┘┴ ┴┴└─┘┴ ┴ └┘ ┴ ┴┴─┘└─┘└─┘└─┘
// ┌┬┐┌─┐ ┬─┐┌─┐┌┬┐┬ ┬┬─┐┌┐┌
// │ │ │ ├┬┘├┤ │ │ │├┬┘│││
// ┴ └─┘ ┴└─└─┘ ┴ └─┘┴└─┘└┘
// If `fetch` was not enabled, return.
if (!_.has(stageThreeQuery.meta, 'fetch') || stageThreeQuery.meta.fetch === false) {
if (!_.isUndefined(rawAdapterResult)) {
console.warn('\n'+
'Warning: Unexpected behavior in database adapter:\n'+
'Since `fetch` is NOT enabled, this adapter (for datastore `'+datastoreName+'`)\n'+
'should NOT have sent back anything as the 2nd argument when triggering the callback\n'+
'from its `create` method. But it did -- which is why this warning is being displayed:\n'+
'to help avoid confusion and draw attention to the bug. Specifically, got:\n'+
util.inspect(rawAdapterResult, {depth:5})+'\n'+
'(Ignoring it and proceeding anyway...)'+'\n'
);
}//>-
return cb();
}//-•
// IWMIH then we know that `fetch: true` meta key was set, and so the
// adapter should have sent back an array.
// Sanity check:
if (!_.isObject(rawAdapterResult) || _.isArray(rawAdapterResult) || _.isFunction(rawAdapterResult)) {
return cb(new Error('Consistency violation: expected `create` adapter method to send back the created record. But instead, got: ' + util.inspect(rawAdapterResult, {depth:5})+''));
}
// Attempt to convert the record's column names to attribute names.
var transformedRecord;
try {
transformedRecord = self._transformer.unserialize(rawAdapterResult);
} catch (e) { return cb(e); }
// Check the record to verify compliance with the adapter spec,
// as well as any issues related to stale data that might not have been
// been migrated to keep up with the logical schema (`type`, etc. in
// attribute definitions).
try {
processAllRecords([ transformedRecord ], undefined, query.meta, self.identity, self.waterline);
} catch (e) { return cb(e); }
// ╔═╗╦═╗╔═╗╔═╗╔═╗╔═╗╔═╗ ┌─┐┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌ ┬─┐┌─┐┌─┐┌─┐┌┬┐┌─┐
// ╠═╝╠╦╝║ ║║ ║╣ ╚═╗╚═╗ │ │ ││ │ ├┤ │ │ ││ ││││ ├┬┘├┤ └─┐├┤ │ └─┐
// ╩ ╩╚═╚═╝╚═╝╚═╝╚═╝╚═╝ └─┘└─┘┴─┘┴─┘└─┘└─┘ ┴ ┴└─┘┘└┘ ┴└─└─┘└─┘└─┘ ┴ └─┘
var targetId = transformedRecord[self.primaryKey];
async.each(_.keys(collectionResets), function resetCollection(collectionAttribute, next) {
self.replaceCollection(targetId, collectionAttribute, collectionResets[collectionAttribute], next, query.meta);
}, function(err) {
if (err) {
return cb(err);
}
// ╔═╗╔═╗╔╦╗╔═╗╦═╗ ┌─┐┬─┐┌─┐┌─┐┌┬┐┌─┐ ┌─┐┌─┐┬ ┬ ┌┐ ┌─┐┌─┐┬┌─
// ╠═╣╠╣ ║ ║╣ ╠╦╝ │ ├┬┘├┤ ├─┤ │ ├┤ │ ├─┤│ │ ├┴┐├─┤│ ├┴┐
// ╩ ╩╚ ╩ ╚═╝╩╚═ └─┘┴└─└─┘┴ ┴ ┴ └─┘ └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴
(function(proceed) {
// If the `skipAllLifecycleCallbacks` meta flag was set, don't run any of
// the methods.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed();
}
// Run afterCreate callback, if defined.
if (_.has(self._callbacks, 'afterCreate')) {
return self._callbacks.afterCreate(transformedRecord, proceed);
}
// Otherwise just proceed
return proceed();
})(function(err) {
if (err) {
return cb(err);
}
// If we forced `fetch: true`, send back nothing.
if (didForceFetchTrue) {
return cb();
}
// Else return the new records.
return cb(undefined, transformedRecord);
});
}, metaContainer);
});//</ adapter.create() >
});//</ handled "before" lifecycle callbacks >
};
| lib/waterline/methods/create.js | /**
* Module Dependencies
*/
var util = require('util');
var async = require('async');
var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
var Deferred = require('../utils/query/deferred');
var forgeStageTwoQuery = require('../utils/query/forge-stage-two-query');
var forgeStageThreeQuery = require('../utils/query/forge-stage-three-query');
var processAllRecords = require('../utils/records/process-all-records');
/**
* Create a new record
*
* @param {Object || Array} values for single model or array of multiple values
* @param {Function} callback
* @return Deferred object if no callback
*/
module.exports = function create(values, cb, metaContainer) {
var self = this;
var query = {
method: 'create',
using: this.identity,
newRecord: values,
meta: metaContainer
};
// Return Deferred or pass to adapter
if (typeof cb !== 'function') {
return new Deferred(this, this.create, query);
}
// ╔═╗╔═╗╦═╗╔═╗╔═╗ ┌─┐┌┬┐┌─┐┌─┐┌─┐ ┌┬┐┬ ┬┌─┐ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
// ╠╣ ║ ║╠╦╝║ ╦║╣ └─┐ │ ├─┤│ ┬├┤ │ ││││ │ │─┼┐│ │├┤ ├┬┘└┬┘
// ╚ ╚═╝╩╚═╚═╝╚═╝ └─┘ ┴ ┴ ┴└─┘└─┘ ┴ └┴┘└─┘ └─┘└└─┘└─┘┴└─ ┴
//
// Forge a stage 2 query (aka logical protostatement)
// This ensures a normalized format.
try {
forgeStageTwoQuery(query, this.waterline);
} catch (e) {
switch (e.code) {
case 'E_INVALID_NEW_RECORD':
return cb(
flaverr(
{ name: 'UsageError' },
new Error(
'Invalid new record(s).\n'+
'Details:\n'+
' '+e.details+'\n'
)
)
);
default:
return cb(e);
}
}
// ╔╗ ╔═╗╔═╗╔═╗╦═╗╔═╗ ┌─┐┬─┐┌─┐┌─┐┌┬┐┌─┐ ┬ ┬┌─┐┌─┐┌─┐┬ ┬┌─┐┬ ┌─┐ ┌─┐┌─┐┬ ┬ ┌┐ ┌─┐┌─┐┬┌─
// ╠╩╗║╣ ╠╣ ║ ║╠╦╝║╣ │ ├┬┘├┤ ├─┤ │ ├┤ │ │├┤ ├┤ │ └┬┘│ │ ├┤ │ ├─┤│ │ ├┴┐├─┤│ ├┴┐
// ╚═╝╚═╝╚ ╚═╝╩╚═╚═╝ └─┘┴└─└─┘┴ ┴ ┴ └─┘ ┴─┘┴└ └─┘└─┘ ┴ └─┘┴─┘└─┘ └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴
// Determine what to do about running "before" lifecycle callbacks
(function(proceed) {
// If there is no relevant "before" lifecycle callback, then just proceed.
if (!_.has(self._callbacks, 'beforeCreate')) {
return proceed();
}//-•
// Now check if the `skipAllLifecycleCallbacks` meta flag was set.
// If so, don't run this lifecycle callback.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed();
}//-•
// IWMIH, run the "before" lifecycle callback.
self._callbacks.beforeCreate(query.newRecord, function(err){
if (err) { return proceed(err); }
return proceed();
});
})(function(err) {
if (err) {
return cb(err);
}
// ╔═╗╦ ╦╔═╗╔═╗╦╔═ ┌─┐┌─┐┬─┐ ┌─┐┌┐┌┬ ┬
// ║ ╠═╣║╣ ║ ╠╩╗ ├┤ │ │├┬┘ ├─┤│││└┬┘
// ╚═╝╩ ╩╚═╝╚═╝╩ ╩ └ └─┘┴└─ ┴ ┴┘└┘ ┴
// ┌─┐┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌ ┬─┐┌─┐┌─┐┌─┐┌┬┐┌─┐
// │ │ ││ │ ├┤ │ │ ││ ││││ ├┬┘├┤ └─┐├┤ │ └─┐
// └─┘└─┘┴─┘┴─┘└─┘└─┘ ┴ ┴└─┘┘└┘ ┴└─└─┘└─┘└─┘ ┴ └─┘
// Also removes them from the newRecord before sending to the adapter.
var collectionResets = {};
_.each(self.attributes, function checkForCollection(attributeVal, attributeName) {
if (_.has(attributeVal, 'collection')) {
// Only create a reset if the value isn't an empty array. If the value
// is an empty array there isn't any resetting to do.
if (query.newRecord[attributeName].length) {
collectionResets[attributeName] = query.newRecord[attributeName];
}
// Remove the collection value from the newRecord because the adapter
// doesn't need to do anything during the initial create.
delete query.newRecord[attributeName];
}
});
// If any collection resets were specified, force `fetch: true` (meta key)
// so that we can use it below.
if (_.keys(collectionResets).length > 0) {
query.meta = query.meta || {};
query.meta.fetch = true;
}//>-
// ╔═╗╔═╗╦═╗╔═╗╔═╗ ┌─┐┌┬┐┌─┐┌─┐┌─┐ ┌┬┐┬ ┬┬─┐┌─┐┌─┐ ┌─┐ ┬ ┬┌─┐┬─┐┬ ┬
// ╠╣ ║ ║╠╦╝║ ╦║╣ └─┐ │ ├─┤│ ┬├┤ │ ├─┤├┬┘├┤ ├┤ │─┼┐│ │├┤ ├┬┘└┬┘
// ╚ ╚═╝╩╚═╚═╝╚═╝ └─┘ ┴ ┴ ┴└─┘└─┘ ┴ ┴ ┴┴└─└─┘└─┘ └─┘└└─┘└─┘┴└─ ┴
var stageThreeQuery;
// TODO: do `query = forgeStageThreeQuery({ ...` instead of this
// (just need to verify that we aren't relying on the old way anywhere)
try {
stageThreeQuery = forgeStageThreeQuery({
stageTwoQuery: query,
identity: self.identity,
transformer: self._transformer,
originalModels: self.waterline.collections
});
} catch (e) {
return cb(e);
}
// ╔═╗╔═╗╔╗╔╔╦╗ ┌┬┐┌─┐ ┌─┐┌┬┐┌─┐┌─┐┌┬┐┌─┐┬─┐
// ╚═╗║╣ ║║║ ║║ │ │ │ ├─┤ ││├─┤├─┘ │ ├┤ ├┬┘
// ╚═╝╚═╝╝╚╝═╩╝ ┴ └─┘ ┴ ┴─┴┘┴ ┴┴ ┴ └─┘┴└─
// Grab the adapter to perform the query on
var datastoreName = self.adapterDictionary.create;
var adapter = self.datastores[datastoreName].adapter;
// Run the operation
adapter.create(datastoreName, stageThreeQuery, function createCb(err, rawAdapterResult) {
if (err) {
// Attach the identity of this model (for convenience).
err.model = self.identity;
return cb(err);
}//-•
// ╔╦╗╔═╗╔╦╗╔═╗╦═╗╔╦╗╦╔╗╔╔═╗ ┬ ┬┬ ┬┬┌─┐┬ ┬ ┬ ┬┌─┐┬ ┬ ┬┌─┐┌─┐
// ║║║╣ ║ ║╣ ╠╦╝║║║║║║║║╣ │││├─┤││ ├─┤ └┐┌┘├─┤│ │ │├┤ └─┐
// ═╩╝╚═╝ ╩ ╚═╝╩╚═╩ ╩╩╝╚╝╚═╝ └┴┘┴ ┴┴└─┘┴ ┴ └┘ ┴ ┴┴─┘└─┘└─┘└─┘
// ┌┬┐┌─┐ ┬─┐┌─┐┌┬┐┬ ┬┬─┐┌┐┌
// │ │ │ ├┬┘├┤ │ │ │├┬┘│││
// ┴ └─┘ ┴└─└─┘ ┴ └─┘┴└─┘└┘
// If `fetch` was not enabled, return.
if (!_.has(stageThreeQuery.meta, 'fetch') || stageThreeQuery.meta.fetch === false) {
if (!_.isUndefined(rawAdapterResult)) {
console.warn('\n'+
'Warning: Unexpected behavior in database adapter:\n'+
'Since `fetch` is NOT enabled, this adapter (for datastore `'+datastoreName+'`)\n'+
'should NOT have sent back anything as the 2nd argument when triggering the callback\n'+
'from its `create` method. But it did -- which is why this warning is being displayed:\n'+
'to help avoid confusion and draw attention to the bug. Specifically, got:\n'+
util.inspect(rawAdapterResult, {depth:5})+'\n'+
'(Ignoring it and proceeding anyway...)'+'\n'
);
}//>-
return cb();
}//-•
// IWMIH then we know that `fetch: true` meta key was set, and so the
// adapter should have sent back an array.
// Sanity check:
if (!_.isObject(rawAdapterResult) || _.isArray(rawAdapterResult) || _.isFunction(rawAdapterResult)) {
return cb(new Error('Consistency violation: expected `create` adapter method to send back the created record. But instead, got: ' + util.inspect(rawAdapterResult, {depth:5})+''));
}
// Attempt to convert the record's column names to attribute names.
var transformedRecords;
try {
transformedRecords = self._transformer.unserialize(rawAdapterResult);
} catch (e) { return cb(e); }
// Check the record to verify compliance with the adapter spec,
// as well as any issues related to stale data that might not have been
// been migrated to keep up with the logical schema (`type`, etc. in
// attribute definitions).
try {
processAllRecords([transformedRecords], undefined, query.meta, self.identity, self.waterline);
} catch (e) { return cb(e); }
// ╔═╗╦═╗╔═╗╔═╗╔═╗╔═╗╔═╗ ┌─┐┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌ ┬─┐┌─┐┌─┐┌─┐┌┬┐┌─┐
// ╠═╝╠╦╝║ ║║ ║╣ ╚═╗╚═╗ │ │ ││ │ ├┤ │ │ ││ ││││ ├┬┘├┤ └─┐├┤ │ └─┐
// ╩ ╩╚═╚═╝╚═╝╚═╝╚═╝╚═╝ └─┘└─┘┴─┘┴─┘└─┘└─┘ ┴ ┴└─┘┘└┘ ┴└─└─┘└─┘└─┘ ┴ └─┘
var targetIds = [transformedRecords[self.primaryKey]];
async.each(_.keys(collectionResets), function resetCollection(collectionAttribute, next) {
self.replaceCollection(targetIds, collectionAttribute, collectionResets[collectionAttribute], next, query.meta);
}, function(err) {
if (err) {
return cb(err);
}
// ╔═╗╔═╗╔╦╗╔═╗╦═╗ ┌─┐┬─┐┌─┐┌─┐┌┬┐┌─┐ ┌─┐┌─┐┬ ┬ ┌┐ ┌─┐┌─┐┬┌─
// ╠═╣╠╣ ║ ║╣ ╠╦╝ │ ├┬┘├┤ ├─┤ │ ├┤ │ ├─┤│ │ ├┴┐├─┤│ ├┴┐
// ╩ ╩╚ ╩ ╚═╝╩╚═ └─┘┴└─└─┘┴ ┴ ┴ └─┘ └─┘┴ ┴┴─┘┴─┘└─┘┴ ┴└─┘┴ ┴
(function(proceed) {
// If the `skipAllLifecycleCallbacks` meta flag was set, don't run any of
// the methods.
if (_.has(query.meta, 'skipAllLifecycleCallbacks') && query.meta.skipAllLifecycleCallbacks) {
return proceed();
}
// Run After Create Callbacks if defined
if (_.has(self._callbacks, 'afterCreate')) {
return self._callbacks.afterCreate(transformedRecords, proceed);
}
// Otherwise just proceed
return proceed();
})(function(err) {
if (err) {
return cb(err);
}
// Return the new record
cb(undefined, transformedRecords);
});
}, metaContainer);
});//</ adapter.create() >
});//</ handled "before" lifecycle callbacks >
};
| Fix typos in .create() (and add use didForceFetchTrue flag to properly discard result data if it was not requested -- but actually, I'm about to remove that in the following commit, because it just makes the situation with lifecycle callbacks confusing. Better to just force fetch: true when there are collection resets.)
| lib/waterline/methods/create.js | Fix typos in .create() (and add use didForceFetchTrue flag to properly discard result data if it was not requested -- but actually, I'm about to remove that in the following commit, because it just makes the situation with lifecycle callbacks confusing. Better to just force fetch: true when there are collection resets.) | <ide><path>ib/waterline/methods/create.js
<ide> });
<ide>
<ide> // If any collection resets were specified, force `fetch: true` (meta key)
<del> // so that we can use it below.
<add> // so that we can use it below. (+ if we force it to `true`, remember that
<add> // so we can adjust accordingly before we send the result back.)
<add> var didForceFetchTrue;
<ide> if (_.keys(collectionResets).length > 0) {
<add> didForceFetchTrue = (!query.meta || !query.meta.fetch);
<ide> query.meta = query.meta || {};
<ide> query.meta.fetch = true;
<ide> }//>-
<ide> }
<ide>
<ide> // Attempt to convert the record's column names to attribute names.
<del> var transformedRecords;
<add> var transformedRecord;
<ide> try {
<del> transformedRecords = self._transformer.unserialize(rawAdapterResult);
<add> transformedRecord = self._transformer.unserialize(rawAdapterResult);
<ide> } catch (e) { return cb(e); }
<ide>
<ide> // Check the record to verify compliance with the adapter spec,
<ide> // been migrated to keep up with the logical schema (`type`, etc. in
<ide> // attribute definitions).
<ide> try {
<del> processAllRecords([transformedRecords], undefined, query.meta, self.identity, self.waterline);
<add> processAllRecords([ transformedRecord ], undefined, query.meta, self.identity, self.waterline);
<ide> } catch (e) { return cb(e); }
<ide>
<ide> // ╔═╗╦═╗╔═╗╔═╗╔═╗╔═╗╔═╗ ┌─┐┌─┐┬ ┬ ┌─┐┌─┐┌┬┐┬┌─┐┌┐┌ ┬─┐┌─┐┌─┐┌─┐┌┬┐┌─┐
<ide> // ╠═╝╠╦╝║ ║║ ║╣ ╚═╗╚═╗ │ │ ││ │ ├┤ │ │ ││ ││││ ├┬┘├┤ └─┐├┤ │ └─┐
<ide> // ╩ ╩╚═╚═╝╚═╝╚═╝╚═╝╚═╝ └─┘└─┘┴─┘┴─┘└─┘└─┘ ┴ ┴└─┘┘└┘ ┴└─└─┘└─┘└─┘ ┴ └─┘
<del> var targetIds = [transformedRecords[self.primaryKey]];
<add> var targetId = transformedRecord[self.primaryKey];
<ide> async.each(_.keys(collectionResets), function resetCollection(collectionAttribute, next) {
<del> self.replaceCollection(targetIds, collectionAttribute, collectionResets[collectionAttribute], next, query.meta);
<add> self.replaceCollection(targetId, collectionAttribute, collectionResets[collectionAttribute], next, query.meta);
<ide> }, function(err) {
<ide> if (err) {
<ide> return cb(err);
<ide> return proceed();
<ide> }
<ide>
<del> // Run After Create Callbacks if defined
<add> // Run afterCreate callback, if defined.
<ide> if (_.has(self._callbacks, 'afterCreate')) {
<del> return self._callbacks.afterCreate(transformedRecords, proceed);
<add> return self._callbacks.afterCreate(transformedRecord, proceed);
<ide> }
<ide>
<ide> // Otherwise just proceed
<ide> return cb(err);
<ide> }
<ide>
<del> // Return the new record
<del> cb(undefined, transformedRecords);
<add> // If we forced `fetch: true`, send back nothing.
<add> if (didForceFetchTrue) {
<add> return cb();
<add> }
<add>
<add> // Else return the new records.
<add> return cb(undefined, transformedRecord);
<add>
<ide> });
<ide> }, metaContainer);
<ide> });//</ adapter.create() > |
|
Java | epl-1.0 | 30001f4abb5f3025255ef9fe453d486c3c5f26d4 | 0 | lewie/openhab2,tavalin/openhab2-addons,pgfeller/openhab2-addons,trokohl/openhab2-addons,lewie/openhab2,Mr-Eskildsen/openhab2-addons,dimalo/openhab2-addons,Mr-Eskildsen/openhab2-addons,tavalin/openhab2-addons,gerrieg/openhab2,Mr-Eskildsen/openhab2-addons,tavalin/openhab2-addons,dimalo/openhab2-addons,Snickermicker/openhab2,Jamstah/openhab2-addons,Jamstah/openhab2-addons,aogorek/openhab2-addons,johannrichard/openhab2-addons,theoweiss/openhab2,pgfeller/openhab2-addons,jarlebh/openhab2-addons,jarlebh/openhab2-addons,jarlebh/openhab2-addons,pail23/openhab2-addons,Snickermicker/openhab2,johannrichard/openhab2-addons,trokohl/openhab2-addons,tavalin/openhab2-addons,Mr-Eskildsen/openhab2-addons,johannrichard/openhab2-addons,aogorek/openhab2-addons,Mr-Eskildsen/openhab2-addons,clinique/openhab2,Jamstah/openhab2-addons,pail23/openhab2-addons,tavalin/openhab2-addons,aogorek/openhab2-addons,clinique/openhab2,digitaldan/openhab2,trokohl/openhab2-addons,trokohl/openhab2-addons,trokohl/openhab2-addons,Snickermicker/openhab2,afuechsel/openhab2,theoweiss/openhab2,aogorek/openhab2-addons,afuechsel/openhab2,dimalo/openhab2-addons,theoweiss/openhab2,trokohl/openhab2-addons,Snickermicker/openhab2,digitaldan/openhab2,digitaldan/openhab2,jarlebh/openhab2-addons,aogorek/openhab2-addons,pail23/openhab2-addons,johannrichard/openhab2-addons,jarlebh/openhab2-addons,pail23/openhab2-addons,aogorek/openhab2-addons,theoweiss/openhab2,gerrieg/openhab2,afuechsel/openhab2,tavalin/openhab2-addons,gerrieg/openhab2,pail23/openhab2-addons,clinique/openhab2,lewie/openhab2,clinique/openhab2,jarlebh/openhab2-addons,johannrichard/openhab2-addons,pgfeller/openhab2-addons,dimalo/openhab2-addons,pgfeller/openhab2-addons,pgfeller/openhab2-addons,dimalo/openhab2-addons,gerrieg/openhab2,digitaldan/openhab2 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.homematic.internal.type;
import static org.openhab.binding.homematic.HomematicBindingConstants.*;
import static org.openhab.binding.homematic.internal.misc.HomematicConstants.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.eclipse.smarthome.config.core.ConfigDescription;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.core.thing.DefaultSystemChannelTypeProvider;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.type.ChannelDefinition;
import org.eclipse.smarthome.core.thing.type.ChannelGroupDefinition;
import org.eclipse.smarthome.core.thing.type.ChannelGroupType;
import org.eclipse.smarthome.core.thing.type.ChannelGroupTypeUID;
import org.eclipse.smarthome.core.thing.type.ChannelKind;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeBuilder;
import org.eclipse.smarthome.core.types.EventDescription;
import org.eclipse.smarthome.core.types.EventOption;
import org.eclipse.smarthome.core.types.StateDescription;
import org.eclipse.smarthome.core.types.StateOption;
import org.openhab.binding.homematic.internal.model.HmChannel;
import org.openhab.binding.homematic.internal.model.HmDatapoint;
import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.internal.model.HmParamsetType;
import org.openhab.binding.homematic.internal.type.MetadataUtils.OptionsBuilder;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generates ThingTypes based on metadata from a Homematic gateway.
*
* @author Gerhard Riegler - Initial contribution
*/
@Component(immediate = true)
public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator {
private final Logger logger = LoggerFactory.getLogger(HomematicTypeGeneratorImpl.class);
private static URI configDescriptionUriChannel;
private HomematicThingTypeProvider thingTypeProvider;
private HomematicChannelTypeProvider channelTypeProvider;
private HomematicConfigDescriptionProvider configDescriptionProvider;
private Map<String, Set<String>> firmwaresByType = new HashMap<String, Set<String>>();
private static final String[] STATUS_DATAPOINT_NAMES = new String[] { DATAPOINT_NAME_UNREACH,
DATAPOINT_NAME_CONFIG_PENDING, DATAPOINT_NAME_DEVICE_IN_BOOTLOADER, DATAPOINT_NAME_UPDATE_PENDING };
private static final String[] IGNORE_DATAPOINT_NAMES = new String[] { DATAPOINT_NAME_AES_KEY,
VIRTUAL_DATAPOINT_NAME_RELOAD_FROM_GATEWAY };
public HomematicTypeGeneratorImpl() {
try {
configDescriptionUriChannel = new URI(CONFIG_DESCRIPTION_URI_CHANNEL);
} catch (Exception ex) {
logger.warn("Can't create ConfigDescription URI '{}', ConfigDescription for channels not avilable!",
CONFIG_DESCRIPTION_URI_CHANNEL);
}
}
@Reference
protected void setThingTypeProvider(HomematicThingTypeProvider thingTypeProvider) {
this.thingTypeProvider = thingTypeProvider;
}
protected void unsetThingTypeProvider(HomematicThingTypeProvider thingTypeProvider) {
this.thingTypeProvider = null;
}
@Reference
protected void setChannelTypeProvider(HomematicChannelTypeProvider channelTypeProvider) {
this.channelTypeProvider = channelTypeProvider;
}
protected void unsetChannelTypeProvider(HomematicChannelTypeProvider channelTypeProvider) {
this.channelTypeProvider = null;
}
@Reference
protected void setConfigDescriptionProvider(HomematicConfigDescriptionProvider configDescriptionProvider) {
this.configDescriptionProvider = configDescriptionProvider;
}
protected void unsetConfigDescriptionProvider(HomematicConfigDescriptionProvider configDescriptionProvider) {
this.configDescriptionProvider = null;
}
@Override
@Activate
public void initialize() {
MetadataUtils.initialize();
}
@Override
public void generate(HmDevice device) {
if (thingTypeProvider != null) {
ThingTypeUID thingTypeUID = UidUtils.generateThingTypeUID(device);
ThingType tt = thingTypeProvider.getThingType(thingTypeUID, Locale.getDefault());
if (tt == null || device.isGatewayExtras()) {
logger.debug("Generating ThingType for device '{}' with {} datapoints", device.getType(),
device.getDatapointCount());
List<ChannelGroupType> groupTypes = new ArrayList<ChannelGroupType>();
for (HmChannel channel : device.getChannels()) {
List<ChannelDefinition> channelDefinitions = new ArrayList<ChannelDefinition>();
// Omit thing channel definitions for reconfigurable channels;
// those will be populated dynamically during thing initialization
if (!channel.isReconfigurable()) {
// generate channel
for (HmDatapoint dp : channel.getDatapoints()) {
if (!isIgnoredDatapoint(dp) && dp.getParamsetType() == HmParamsetType.VALUES) {
ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
ChannelType channelType = channelTypeProvider.getChannelType(channelTypeUID,
Locale.getDefault());
if (channelType == null) {
channelType = createChannelType(dp, channelTypeUID);
channelTypeProvider.addChannelType(channelType);
}
ChannelDefinition channelDef = new ChannelDefinition(dp.getName(),
channelType.getUID());
channelDefinitions.add(channelDef);
}
}
}
// generate group
ChannelGroupTypeUID groupTypeUID = UidUtils.generateChannelGroupTypeUID(channel);
ChannelGroupType groupType = channelTypeProvider.getChannelGroupType(groupTypeUID,
Locale.getDefault());
if (groupType == null || device.isGatewayExtras()) {
String groupLabel = String.format("%s",
WordUtils.capitalizeFully(StringUtils.replace(channel.getType(), "_", " ")));
groupType = new ChannelGroupType(groupTypeUID, false, groupLabel, null, null,
channelDefinitions);
channelTypeProvider.addChannelGroupType(groupType);
groupTypes.add(groupType);
}
}
tt = createThingType(device, groupTypes);
thingTypeProvider.addThingType(tt);
}
addFirmware(device);
}
}
@Override
public void validateFirmwares() {
for (String deviceType : firmwaresByType.keySet()) {
Set<String> firmwares = firmwaresByType.get(deviceType);
if (firmwares.size() > 1) {
logger.info(
"Multiple firmware versions for device type '{}' found ({}). "
+ "Make sure, all devices of the same type have the same firmware version, "
+ "otherwise you MAY have channel and/or datapoint errors in the logfile",
deviceType, StringUtils.join(firmwares, ", "));
}
}
}
/**
* Adds the firmware version for validation.
*/
private void addFirmware(HmDevice device) {
if (!StringUtils.equals(device.getFirmware(), "?") && !DEVICE_TYPE_VIRTUAL.equals(device.getType())
&& !DEVICE_TYPE_VIRTUAL_WIRED.equals(device.getType())) {
Set<String> firmwares = firmwaresByType.get(device.getType());
if (firmwares == null) {
firmwares = new HashSet<String>();
firmwaresByType.put(device.getType(), firmwares);
}
firmwares.add(device.getFirmware());
}
}
/**
* Creates the ThingType for the given device.
*/
private ThingType createThingType(HmDevice device, List<ChannelGroupType> groupTypes) {
String label = MetadataUtils.getDeviceName(device);
String description = String.format("%s (%s)", label, device.getType());
List<String> supportedBridgeTypeUids = new ArrayList<String>();
supportedBridgeTypeUids.add(THING_TYPE_BRIDGE.toString());
ThingTypeUID thingTypeUID = UidUtils.generateThingTypeUID(device);
Map<String, String> properties = new HashMap<String, String>();
properties.put(Thing.PROPERTY_VENDOR, PROPERTY_VENDOR_NAME);
properties.put(Thing.PROPERTY_MODEL_ID, device.getType());
URI configDescriptionURI = getConfigDescriptionURI(device);
if (configDescriptionProvider.getConfigDescription(configDescriptionURI, null) == null) {
generateConfigDescription(device, configDescriptionURI);
}
List<ChannelGroupDefinition> groupDefinitions = new ArrayList<ChannelGroupDefinition>();
for (ChannelGroupType groupType : groupTypes) {
String id = StringUtils.substringAfterLast(groupType.getUID().getId(), "_");
groupDefinitions.add(new ChannelGroupDefinition(id, groupType.getUID()));
}
return ThingTypeBuilder.instance(thingTypeUID, label).withSupportedBridgeTypeUIDs(supportedBridgeTypeUids)
.withDescription(description).withChannelGroupDefinitions(groupDefinitions).withProperties(properties)
.withConfigDescriptionURI(configDescriptionURI).build();
}
/**
* Creates the ChannelType for the given datapoint.
*/
private ChannelType createChannelType(HmDatapoint dp, ChannelTypeUID channelTypeUID) {
ChannelType channelType;
if (dp.getName().equals(DATAPOINT_NAME_LOWBAT) || dp.getName().equals(DATAPOINT_NAME_LOWBAT_IP)) {
channelType = DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_LOW_BATTERY;
} else if (dp.getName().equals(VIRTUAL_DATAPOINT_NAME_SIGNAL_STRENGTH)) {
channelType = DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_SIGNAL_STRENGTH;
} else {
String itemType = MetadataUtils.getItemType(dp);
String category = MetadataUtils.getCategory(dp, itemType);
String label = MetadataUtils.getLabel(dp);
String description = MetadataUtils.getDatapointDescription(dp);
List<StateOption> options = null;
if (dp.isEnumType()) {
options = MetadataUtils.generateOptions(dp, new OptionsBuilder<StateOption>() {
@Override
public StateOption createOption(String value, String description) {
return new StateOption(value, description);
}
});
}
StateDescription state = null;
if (dp.isNumberType()) {
BigDecimal min = MetadataUtils.createBigDecimal(dp.getMinValue());
BigDecimal max = MetadataUtils.createBigDecimal(dp.getMaxValue());
BigDecimal step = MetadataUtils.createBigDecimal(dp.getStep());
if (step == null) {
step = MetadataUtils.createBigDecimal(dp.isFloatType() ? new Float(0.1) : 1L);
}
state = new StateDescription(min, max, step, MetadataUtils.getStatePattern(dp), dp.isReadOnly(),
options);
} else {
state = new StateDescription(null, null, null, MetadataUtils.getStatePattern(dp), dp.isReadOnly(),
options);
}
ChannelKind channelKind = ChannelKind.STATE;
EventDescription eventDescription = null;
if (dp.isTrigger()) {
itemType = null;
channelKind = ChannelKind.TRIGGER;
eventDescription = new EventDescription(
MetadataUtils.generateOptions(dp, new OptionsBuilder<EventOption>() {
@Override
public EventOption createOption(String value, String description) {
return new EventOption(value, description);
}
}));
}
channelType = new ChannelType(channelTypeUID, !MetadataUtils.isStandard(dp), itemType, channelKind, label,
description, category, null, state, eventDescription, configDescriptionUriChannel);
}
return channelType;
}
private void generateConfigDescription(HmDevice device, URI configDescriptionURI) {
List<ConfigDescriptionParameter> parms = new ArrayList<ConfigDescriptionParameter>();
List<ConfigDescriptionParameterGroup> groups = new ArrayList<ConfigDescriptionParameterGroup>();
for (HmChannel channel : device.getChannels()) {
String groupName = "HMG_" + channel.getNumber();
String groupLabel = MetadataUtils.getDescription("CHANNEL_NAME") + " " + channel.getNumber();
groups.add(new ConfigDescriptionParameterGroup(groupName, null, false, groupLabel, null));
for (HmDatapoint dp : channel.getDatapoints()) {
if (dp.getParamsetType() == HmParamsetType.MASTER) {
ConfigDescriptionParameterBuilder builder = ConfigDescriptionParameterBuilder.create(
MetadataUtils.getParameterName(dp), MetadataUtils.getConfigDescriptionParameterType(dp));
builder.withLabel(MetadataUtils.getLabel(dp));
builder.withDefault(ObjectUtils.toString(dp.getDefaultValue()));
builder.withDescription(MetadataUtils.getDatapointDescription(dp));
if (dp.isEnumType()) {
builder.withLimitToOptions(dp.isEnumType());
List<ParameterOption> options = MetadataUtils.generateOptions(dp,
new OptionsBuilder<ParameterOption>() {
@Override
public ParameterOption createOption(String value, String description) {
return new ParameterOption(value, description);
}
});
builder.withOptions(options);
}
if (dp.isNumberType()) {
builder.withMinimum(MetadataUtils.createBigDecimal(dp.getMinValue()));
builder.withMaximum(MetadataUtils.createBigDecimal(dp.getMaxValue()));
builder.withStepSize(MetadataUtils.createBigDecimal(dp.isFloatType() ? new Float(0.1) : 1L));
builder.withUnitLabel(MetadataUtils.getUnit(dp));
}
builder.withGroupName(groupName);
parms.add(builder.build());
}
}
}
configDescriptionProvider.addConfigDescription(new ConfigDescription(configDescriptionURI, parms, groups));
}
private URI getConfigDescriptionURI(HmDevice device) {
try {
return new URI(String.format("%s:%s", CONFIG_DESCRIPTION_URI_THING, UidUtils.generateThingTypeUID(device)));
} catch (URISyntaxException ex) {
logger.warn("Can't create configDescriptionURI for device type {}", device.getType());
return null;
}
}
/**
* Returns true, if the given datapoint is a Thing status.
*/
public static boolean isStatusDatapoint(HmDatapoint dp) {
return StringUtils.indexOfAny(dp.getName(), STATUS_DATAPOINT_NAMES) != -1;
}
/**
* Returns true, if the given datapoint can be ignored for metadata generation.
*/
public static boolean isIgnoredDatapoint(HmDatapoint dp) {
return StringUtils.indexOfAny(dp.getName(), IGNORE_DATAPOINT_NAMES) != -1;
}
}
| addons/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.homematic.internal.type;
import static org.openhab.binding.homematic.HomematicBindingConstants.*;
import static org.openhab.binding.homematic.internal.misc.HomematicConstants.*;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.eclipse.smarthome.config.core.ConfigDescription;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.core.thing.DefaultSystemChannelTypeProvider;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.type.ChannelDefinition;
import org.eclipse.smarthome.core.thing.type.ChannelGroupDefinition;
import org.eclipse.smarthome.core.thing.type.ChannelGroupType;
import org.eclipse.smarthome.core.thing.type.ChannelGroupTypeUID;
import org.eclipse.smarthome.core.thing.type.ChannelKind;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeBuilder;
import org.eclipse.smarthome.core.types.EventDescription;
import org.eclipse.smarthome.core.types.EventOption;
import org.eclipse.smarthome.core.types.StateDescription;
import org.eclipse.smarthome.core.types.StateOption;
import org.openhab.binding.homematic.internal.model.HmChannel;
import org.openhab.binding.homematic.internal.model.HmDatapoint;
import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.internal.model.HmParamsetType;
import org.openhab.binding.homematic.internal.type.MetadataUtils.OptionsBuilder;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generates ThingTypes based on metadata from a Homematic gateway.
*
* @author Gerhard Riegler - Initial contribution
*/
@Component(immediate = true)
public class HomematicTypeGeneratorImpl implements HomematicTypeGenerator {
private final Logger logger = LoggerFactory.getLogger(HomematicTypeGeneratorImpl.class);
private static URI configDescriptionUriChannel;
private HomematicThingTypeProvider thingTypeProvider;
private HomematicChannelTypeProvider channelTypeProvider;
private HomematicConfigDescriptionProvider configDescriptionProvider;
private Map<String, Set<String>> firmwaresByType = new HashMap<String, Set<String>>();
private static final String[] STATUS_DATAPOINT_NAMES = new String[] { DATAPOINT_NAME_UNREACH,
DATAPOINT_NAME_CONFIG_PENDING, DATAPOINT_NAME_DEVICE_IN_BOOTLOADER, DATAPOINT_NAME_UPDATE_PENDING };
private static final String[] IGNORE_DATAPOINT_NAMES = new String[] { DATAPOINT_NAME_AES_KEY,
VIRTUAL_DATAPOINT_NAME_RELOAD_FROM_GATEWAY };
public HomematicTypeGeneratorImpl() {
try {
configDescriptionUriChannel = new URI(CONFIG_DESCRIPTION_URI_CHANNEL);
} catch (Exception ex) {
logger.warn("Can't create ConfigDescription URI '{}', ConfigDescription for channels not avilable!",
CONFIG_DESCRIPTION_URI_CHANNEL);
}
}
@Reference
protected void setThingTypeProvider(HomematicThingTypeProvider thingTypeProvider) {
this.thingTypeProvider = thingTypeProvider;
}
protected void unsetThingTypeProvider(HomematicThingTypeProvider thingTypeProvider) {
this.thingTypeProvider = null;
}
@Reference
protected void setChannelTypeProvider(HomematicChannelTypeProvider channelTypeProvider) {
this.channelTypeProvider = channelTypeProvider;
}
protected void unsetChannelTypeProvider(HomematicChannelTypeProvider channelTypeProvider) {
this.channelTypeProvider = null;
}
@Reference
protected void setConfigDescriptionProvider(HomematicConfigDescriptionProvider configDescriptionProvider) {
this.configDescriptionProvider = configDescriptionProvider;
}
protected void unsetConfigDescriptionProvider(HomematicConfigDescriptionProvider configDescriptionProvider) {
this.configDescriptionProvider = null;
}
@Override
@Activate
public void initialize() {
MetadataUtils.initialize();
}
@Override
public void generate(HmDevice device) {
if (thingTypeProvider != null) {
ThingTypeUID thingTypeUID = UidUtils.generateThingTypeUID(device);
ThingType tt = thingTypeProvider.getThingType(thingTypeUID, Locale.getDefault());
if (tt == null || device.isGatewayExtras()) {
logger.debug("Generating ThingType for device '{}' with {} datapoints", device.getType(),
device.getDatapointCount());
List<ChannelGroupType> groupTypes = new ArrayList<ChannelGroupType>();
for (HmChannel channel : device.getChannels()) {
List<ChannelDefinition> channelDefinitions = new ArrayList<ChannelDefinition>();
// Omit thing channel definitions for reconfigurable channels;
// those will be populated dynamically during thing initialization
if (!channel.isReconfigurable()) {
// generate channel
for (HmDatapoint dp : channel.getDatapoints()) {
if (!isIgnoredDatapoint(dp) && dp.getParamsetType() == HmParamsetType.VALUES) {
ChannelTypeUID channelTypeUID = UidUtils.generateChannelTypeUID(dp);
ChannelType channelType = channelTypeProvider.getChannelType(channelTypeUID,
Locale.getDefault());
if (channelType == null) {
channelType = createChannelType(dp, channelTypeUID);
channelTypeProvider.addChannelType(channelType);
}
ChannelDefinition channelDef = new ChannelDefinition(dp.getName(),
channelType.getUID());
channelDefinitions.add(channelDef);
}
}
}
// generate group
ChannelGroupTypeUID groupTypeUID = UidUtils.generateChannelGroupTypeUID(channel);
ChannelGroupType groupType = channelTypeProvider.getChannelGroupType(groupTypeUID,
Locale.getDefault());
if (groupType == null || device.isGatewayExtras()) {
String groupLabel = String.format("%s",
WordUtils.capitalizeFully(StringUtils.replace(channel.getType(), "_", " ")));
groupType = new ChannelGroupType(groupTypeUID, false, groupLabel, null, null,
channelDefinitions);
channelTypeProvider.addChannelGroupType(groupType);
groupTypes.add(groupType);
}
}
tt = createThingType(device, groupTypes);
thingTypeProvider.addThingType(tt);
}
addFirmware(device);
}
}
@Override
public void validateFirmwares() {
for (String deviceType : firmwaresByType.keySet()) {
Set<String> firmwares = firmwaresByType.get(deviceType);
if (firmwares.size() > 1) {
logger.info(
"Multiple firmware versions for device type '{}' found ({}). "
+ "Make sure, all devices of the same type have the same firmware version, "
+ "otherwise you MAY have channel and/or datapoint errors in the logfile",
deviceType, StringUtils.join(firmwares, ", "));
}
}
}
/**
* Adds the firmware version for validation.
*/
private void addFirmware(HmDevice device) {
if (!StringUtils.equals(device.getFirmware(), "?") && !DEVICE_TYPE_VIRTUAL.equals(device.getType())
&& !DEVICE_TYPE_VIRTUAL_WIRED.equals(device.getType())) {
Set<String> firmwares = firmwaresByType.get(device.getType());
if (firmwares == null) {
firmwares = new HashSet<String>();
firmwaresByType.put(device.getType(), firmwares);
}
firmwares.add(device.getFirmware());
}
}
/**
* Creates the ThingType for the given device.
*/
private ThingType createThingType(HmDevice device, List<ChannelGroupType> groupTypes) {
String label = MetadataUtils.getDeviceName(device);
String description = String.format("%s (%s)", label, device.getType());
List<String> supportedBridgeTypeUids = new ArrayList<String>();
supportedBridgeTypeUids.add(THING_TYPE_BRIDGE.toString());
ThingTypeUID thingTypeUID = UidUtils.generateThingTypeUID(device);
Map<String, String> properties = new HashMap<String, String>();
properties.put(Thing.PROPERTY_VENDOR, PROPERTY_VENDOR_NAME);
properties.put(Thing.PROPERTY_MODEL_ID, device.getType());
URI configDescriptionURI = getConfigDescriptionURI(device);
if (configDescriptionProvider.getConfigDescription(configDescriptionURI, null) == null) {
generateConfigDescription(device, configDescriptionURI);
}
List<ChannelGroupDefinition> groupDefinitions = new ArrayList<ChannelGroupDefinition>();
for (ChannelGroupType groupType : groupTypes) {
String id = StringUtils.substringAfterLast(groupType.getUID().getId(), "_");
groupDefinitions.add(new ChannelGroupDefinition(id, groupType.getUID()));
}
return ThingTypeBuilder.instance(thingTypeUID, label).withSupportedBridgeTypeUIDs(supportedBridgeTypeUids)
.withDescription(description).withChannelGroupDefinitions(groupDefinitions).withProperties(properties)
.withConfigDescriptionURI(configDescriptionURI).build();
}
/**
* Creates the ChannelType for the given datapoint.
*/
private ChannelType createChannelType(HmDatapoint dp, ChannelTypeUID channelTypeUID) {
ChannelType channelType;
if (dp.getName().equals(DATAPOINT_NAME_LOWBAT) || dp.getName().equals(DATAPOINT_NAME_LOWBAT_IP)) {
channelType = DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_LOW_BATTERY;
} else if (dp.getName().equals(VIRTUAL_DATAPOINT_NAME_SIGNAL_STRENGTH)) {
channelType = DefaultSystemChannelTypeProvider.SYSTEM_CHANNEL_SIGNAL_STRENGTH;
} else {
String itemType = MetadataUtils.getItemType(dp);
String category = MetadataUtils.getCategory(dp, itemType);
String label = MetadataUtils.getLabel(dp);
String description = MetadataUtils.getDatapointDescription(dp);
List<StateOption> options = null;
if (dp.isEnumType()) {
options = MetadataUtils.generateOptions(dp, new OptionsBuilder<StateOption>() {
@Override
public StateOption createOption(String value, String description) {
return new StateOption(value, description);
}
});
}
StateDescription state = null;
if (dp.isNumberType()) {
BigDecimal min = MetadataUtils.createBigDecimal(dp.getMinValue());
BigDecimal max = MetadataUtils.createBigDecimal(dp.getMaxValue());
BigDecimal step = MetadataUtils.createBigDecimal(dp.getStep());
if (step == null) {
step = MetadataUtils.createBigDecimal(dp.isFloatType() ? new Float(0.1) : 1L);
}
state = new StateDescription(min, max, step, MetadataUtils.getStatePattern(dp), dp.isReadOnly(),
options);
} else {
state = new StateDescription(null, null, null, MetadataUtils.getStatePattern(dp), dp.isReadOnly(),
options);
}
ChannelKind channelKind = ChannelKind.STATE;
EventDescription eventDescription = null;
if (dp.isTrigger()) {
itemType = null;
channelKind = ChannelKind.TRIGGER;
eventDescription = new EventDescription(
MetadataUtils.generateOptions(dp, new OptionsBuilder<EventOption>() {
@Override
public EventOption createOption(String value, String description) {
return new EventOption(value, description);
}
}));
}
channelType = new ChannelType(channelTypeUID, !MetadataUtils.isStandard(dp), itemType, channelKind, label,
description, category, null, state, eventDescription, configDescriptionUriChannel);
}
return channelType;
}
private void generateConfigDescription(HmDevice device, URI configDescriptionURI) {
List<ConfigDescriptionParameter> parms = new ArrayList<ConfigDescriptionParameter>();
List<ConfigDescriptionParameterGroup> groups = new ArrayList<ConfigDescriptionParameterGroup>();
for (HmChannel channel : device.getChannels()) {
String groupName = "HMG_" + channel.getNumber();
String groupLabel = MetadataUtils.getDescription("CHANNEL_NAME") + " " + channel.getNumber();
groups.add(new ConfigDescriptionParameterGroup(groupName, null, false, groupLabel, null));
for (HmDatapoint dp : channel.getDatapoints()) {
if (dp.getParamsetType() == HmParamsetType.MASTER) {
ConfigDescriptionParameterBuilder builder = ConfigDescriptionParameterBuilder.create(
MetadataUtils.getParameterName(dp), MetadataUtils.getConfigDescriptionParameterType(dp));
builder.withLabel(MetadataUtils.getLabel(dp));
builder.withDefault(ObjectUtils.toString(dp.getDefaultValue()));
builder.withDescription(MetadataUtils.getDatapointDescription(dp));
if (dp.isEnumType()) {
builder.withLimitToOptions(dp.isEnumType());
List<ParameterOption> options = MetadataUtils.generateOptions(dp,
new OptionsBuilder<ParameterOption>() {
@Override
public ParameterOption createOption(String value, String description) {
return new ParameterOption(value, description);
}
});
builder.withOptions(options);
}
if (dp.isNumberType()) {
builder.withMinimum(MetadataUtils.createBigDecimal(dp.getMinValue()));
builder.withMaximum(MetadataUtils.createBigDecimal(dp.getMaxValue()));
builder.withStepSize(MetadataUtils.createBigDecimal(dp.isFloatType() ? new Float(0.1) : 1L));
builder.withUnitLabel(MetadataUtils.getUnit(dp));
}
builder.withGroupName(groupName);
parms.add(builder.build());
}
}
}
if (!parms.isEmpty()) {
configDescriptionProvider.addConfigDescription(new ConfigDescription(configDescriptionURI, parms, groups));
}
}
private URI getConfigDescriptionURI(HmDevice device) {
try {
return new URI(String.format("%s:%s", CONFIG_DESCRIPTION_URI_THING, UidUtils.generateThingTypeUID(device)));
} catch (URISyntaxException ex) {
logger.warn("Can't create configDescriptionURI for device type {}", device.getType());
return null;
}
}
/**
* Returns true, if the given datapoint is a Thing status.
*/
public static boolean isStatusDatapoint(HmDatapoint dp) {
return StringUtils.indexOfAny(dp.getName(), STATUS_DATAPOINT_NAMES) != -1;
}
/**
* Returns true, if the given datapoint can be ignored for metadata generation.
*/
public static boolean isIgnoredDatapoint(HmDatapoint dp) {
return StringUtils.indexOfAny(dp.getName(), IGNORE_DATAPOINT_NAMES) != -1;
}
}
| [homematic] Provide config-descriptions for every config-description-URI (#3278)
Our application evaluates any thing's ConfigDescriptions to decorate the thing with application-specific functionality. Therefore I suggest that the binding creates ConfigDescrition for each created
ThingType, even if it does not contain any parameter.
Signed-off-by: Michael Reitler <[email protected]> | addons/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java | [homematic] Provide config-descriptions for every config-description-URI (#3278) | <ide><path>ddons/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/type/HomematicTypeGeneratorImpl.java
<ide> }
<ide> }
<ide> }
<del> if (!parms.isEmpty()) {
<del> configDescriptionProvider.addConfigDescription(new ConfigDescription(configDescriptionURI, parms, groups));
<del> }
<add>
<add> configDescriptionProvider.addConfigDescription(new ConfigDescription(configDescriptionURI, parms, groups));
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 29af377597c941f7b0a96d5a9bf7e86a07927da2 | 0 | Terasology/Minimap | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.minimap.rendering.nui.layers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.vecmath.Vector3f;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.registry.CoreRegistry;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.logic.players.LocalPlayer;
import org.terasology.math.Rect2i;
import org.terasology.math.Vector2i;
import org.terasology.math.Vector3i;
import org.terasology.minimap.DisplayAxisType;
import org.terasology.rendering.nui.Canvas;
import org.terasology.rendering.nui.CoreWidget;
import org.terasology.rendering.nui.UIWidget;
import org.terasology.rendering.nui.databinding.Binding;
import org.terasology.rendering.nui.databinding.DefaultBinding;
import org.terasology.rendering.nui.databinding.ReadOnlyBinding;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
/**
* @author mkienenb
*/
public class MinimapGrid extends CoreWidget {
private static final Logger logger = LoggerFactory.getLogger(MinimapGrid.class);
private DisplayAxisType displayAxisType = DisplayAxisType.XZ_AXIS;
private int numberOfColumns = 15;
private int numberOfRows = 15;
private MinimapCell[][] cells;
private Binding<EntityRef> targetEntityBinding = new DefaultBinding<>(EntityRef.NULL);
private Binding<Integer> cellOffsetBinding = new DefaultBinding<>(0);
public MinimapGrid() {
}
public MinimapGrid(int numberOfColumns, int numberOfRows) {
this.numberOfColumns = numberOfColumns;
this.numberOfRows = numberOfRows;
}
@Override
public void update(float delta) {
super.update(delta);
if (null == cells) {
initialize();
}
}
private void initialize() {
int rowCenter = numberOfRows / 2;
int columnCenter = numberOfColumns / 2;
cells = new MinimapCell[numberOfRows][numberOfColumns];
for (int row = 0; row < numberOfRows; row++) {
cells[row] = new MinimapCell[numberOfColumns];
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = new MinimapCell();
cells[row][column] = cell;
// int rowInverted = (cells.length - row);
// int columnInverted = (cells[row].length - column);
// Vector3i coordinateAdjustment;
// switch (displayAxisType) {
// case XZ_AXIS: // top down view
// coordinateAdjustment = new Vector3i(rowInverted, 0, column);
// break;
// case XY_AXIS:
// coordinateAdjustment = new Vector3i(columnInverted, rowInverted, 0);
// break;
// case YZ_AXIS:
// coordinateAdjustment = new Vector3i(0, rowInverted, columnInverted);
// break;
// default:
// throw new RuntimeException("displayAxisType containts invalid value");
// }
// cell.setCoordinateAdjustment(coordinateAdjustment);
cell.setRelativeCellLocation(new Vector2i((column - columnCenter), (row - rowCenter)));
cell.bindCenterLocation(new ReadOnlyBinding<Vector3i>() {
@Override
public Vector3i get() {
Vector3f worldPosition = null;
// TODO: Figure out how to fix this
// Currently the character entity doesn't have a valid LocationComponent, which seems weird.
// So skip allowing arbitrary entities for now.
// EntityRef entity = getTargetEntity();
// if (null != entity) {
// LocationComponent locationComponent = entity.getComponent(LocationComponent.class);
// if (null != locationComponent) {
// worldPosition = locationComponent.getWorldPosition();
// } else {
// logger.error("No locationComponent for target entity " + entity);
// }
// } else {
// logger.error("No target entity");
// }
if (null == worldPosition) {
LocalPlayer localPlayer = CoreRegistry.get(LocalPlayer.class);
worldPosition = localPlayer.getPosition();
}
Vector3i blockPosition = new Vector3i(worldPosition);
blockPosition.sub(0, 1, 0);
return blockPosition;
}
});
cell.bindDisplayAxisType(new ReadOnlyBinding<DisplayAxisType>() {
@Override
public DisplayAxisType get() {
return displayAxisType;
}
});
}
}
}
@Override
public void onDraw(Canvas canvas) {
if (null == cells) {
initialize();
}
if (null != cells) {
Vector2i cellSize = canvas.calculatePreferredSize(cells[0][0]);
canvas.drawBackground();
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = cells[row][column];
int horizPos = row;
int vertPos = column;
canvas.drawWidget(cell, Rect2i.createFromMinAndSize(horizPos * cellSize.x, vertPos * cellSize.y, cellSize.x, cellSize.y));
}
}
}
}
@Override
public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) {
if (null == cells) {
initialize();
}
if (null != cells) {
Vector2i cellSize = canvas.calculatePreferredSize(cells[0][0]);
return new Vector2i(numberOfRows * cellSize.x, numberOfColumns * cellSize.y);
}
return Vector2i.zero();
}
@Override
public Iterator<UIWidget> iterator() {
if (null == cells) {
initialize();
}
List<MinimapCell> cellList;
if (null != cells) {
cellList = new ArrayList<MinimapCell>(numberOfRows * numberOfColumns);
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = cells[row][column];
cellList.add(cell);
}
}
} else {
cellList = Collections.emptyList();
}
return Iterators.transform(cellList.iterator(), new Function<UIWidget, UIWidget>() {
@Override
public UIWidget apply(UIWidget input) {
return input;
}
});
}
public void bindTargetEntity(Binding<EntityRef> binding) {
targetEntityBinding = binding;
}
public EntityRef getTargetEntity() {
return targetEntityBinding.get();
}
public void setTargetEntity(EntityRef val) {
targetEntityBinding.set(val);
}
public void bindCellOffset(Binding<Integer> binding) {
cellOffsetBinding = binding;
}
public int getCellOffset() {
return cellOffsetBinding.get();
}
public void setCellOffset(int val) {
cellOffsetBinding.set(val);
}
public void toggleAxis() {
switch (displayAxisType) {
case XY_AXIS:
displayAxisType = DisplayAxisType.XZ_AXIS;
break;
case XZ_AXIS:
displayAxisType = DisplayAxisType.YZ_AXIS;
break;
case YZ_AXIS:
displayAxisType = DisplayAxisType.XY_AXIS;
break;
}
// TODO: force redraw?
}
public DisplayAxisType getDisplayAxisType() {
return displayAxisType;
}
}
| src/main/java/org/terasology/minimap/rendering/nui/layers/MinimapGrid.java | /*
* Copyright 2014 MovingBlocks
*
* 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.terasology.minimap.rendering.nui.layers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.vecmath.Vector3f;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.registry.CoreRegistry;
import org.terasology.entitySystem.entity.EntityRef;
import org.terasology.logic.players.LocalPlayer;
import org.terasology.math.Rect2i;
import org.terasology.math.Vector2i;
import org.terasology.math.Vector3i;
import org.terasology.minimap.DisplayAxisType;
import org.terasology.rendering.nui.Canvas;
import org.terasology.rendering.nui.CoreWidget;
import org.terasology.rendering.nui.UIWidget;
import org.terasology.rendering.nui.databinding.Binding;
import org.terasology.rendering.nui.databinding.DefaultBinding;
import org.terasology.rendering.nui.databinding.ReadOnlyBinding;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
/**
* @author mkienenb
*/
public class MinimapGrid extends CoreWidget {
private static final Logger logger = LoggerFactory.getLogger(MinimapGrid.class);
private DisplayAxisType displayAxisType = DisplayAxisType.XZ_AXIS;
private int numberOfColumns = 15;
private int numberOfRows = 15;
private MinimapCell[][] cells;
private Binding<EntityRef> targetEntityBinding = new DefaultBinding<>(EntityRef.NULL);
private Binding<Integer> cellOffsetBinding = new DefaultBinding<>(0);
public MinimapGrid() {
}
public MinimapGrid(int numberOfColumns, int numberOfRows) {
this.numberOfColumns = numberOfColumns;
this.numberOfRows = numberOfRows;
}
@Override
public void update(float delta) {
super.update(delta);
if (null == cells) {
initialize();
}
}
private void initialize() {
int rowCenter = numberOfRows / 2;
int columnCenter = numberOfColumns / 2;
cells = new MinimapCell[numberOfRows][numberOfColumns];
for (int row = 0; row < numberOfRows; row++) {
cells[row] = new MinimapCell[numberOfColumns];
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = new MinimapCell();
cells[row][column] = cell;
// int rowInverted = (cells.length - row);
// int columnInverted = (cells[row].length - column);
// Vector3i coordinateAdjustment;
// switch (displayAxisType) {
// case XZ_AXIS: // top down view
// coordinateAdjustment = new Vector3i(rowInverted, 0, column);
// break;
// case XY_AXIS:
// coordinateAdjustment = new Vector3i(columnInverted, rowInverted, 0);
// break;
// case YZ_AXIS:
// coordinateAdjustment = new Vector3i(0, rowInverted, columnInverted);
// break;
// default:
// throw new RuntimeException("displayAxisType containts invalid value");
// }
// cell.setCoordinateAdjustment(coordinateAdjustment);
cell.setRelativeCellLocation(new Vector2i((column - columnCenter), (row - rowCenter)));
cell.bindCenterLocation(new ReadOnlyBinding<Vector3i>() {
@Override
public Vector3i get() {
Vector3f worldPosition = null;
// TODO: Figure out how to fix this
// Currently the character entity doesn't have a valid LocationComponent, which seems weird.
// So skip allowing arbitrary entities for now.
// EntityRef entity = getTargetEntity();
// if (null != entity) {
// LocationComponent locationComponent = entity.getComponent(LocationComponent.class);
// if (null != locationComponent) {
// worldPosition = locationComponent.getWorldPosition();
// } else {
// logger.error("No locationComponent for target entity " + entity);
// }
// } else {
// logger.error("No target entity");
// }
if (null == worldPosition) {
LocalPlayer localPlayer = CoreRegistry.get(LocalPlayer.class);
worldPosition = localPlayer.getPosition();
}
Vector3i blockPosition = new Vector3i(worldPosition);
blockPosition.sub(0, 1, 0);
return blockPosition;
}
});
cell.bindDisplayAxisType(new ReadOnlyBinding<DisplayAxisType>() {
@Override
public DisplayAxisType get() {
return displayAxisType;
}
});
}
}
}
@Override
public void onDraw(Canvas canvas) {
if (null == cells) {
initialize();
}
if (null != cells) {
Vector2i cellSize = canvas.calculatePreferredSize(cells[0][0]);
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = cells[row][column];
int horizPos = row;
int vertPos = column;
canvas.drawWidget(cell, Rect2i.createFromMinAndSize(horizPos * cellSize.x, vertPos * cellSize.y, cellSize.x, cellSize.y));
}
}
}
}
@Override
public Vector2i getPreferredContentSize(Canvas canvas, Vector2i sizeHint) {
if (null == cells) {
initialize();
}
if (null != cells) {
Vector2i cellSize = canvas.calculatePreferredSize(cells[0][0]);
return new Vector2i(numberOfRows * cellSize.x, numberOfColumns * cellSize.y);
}
return Vector2i.zero();
}
@Override
public Iterator<UIWidget> iterator() {
if (null == cells) {
initialize();
}
List<MinimapCell> cellList;
if (null != cells) {
cellList = new ArrayList<MinimapCell>(numberOfRows * numberOfColumns);
for (int row = 0; row < numberOfRows; row++) {
for (int column = 0; column < numberOfColumns; column++) {
MinimapCell cell = cells[row][column];
cellList.add(cell);
}
}
} else {
cellList = Collections.emptyList();
}
return Iterators.transform(cellList.iterator(), new Function<UIWidget, UIWidget>() {
@Override
public UIWidget apply(UIWidget input) {
return input;
}
});
}
public void bindTargetEntity(Binding<EntityRef> binding) {
targetEntityBinding = binding;
}
public EntityRef getTargetEntity() {
return targetEntityBinding.get();
}
public void setTargetEntity(EntityRef val) {
targetEntityBinding.set(val);
}
public void bindCellOffset(Binding<Integer> binding) {
cellOffsetBinding = binding;
}
public int getCellOffset() {
return cellOffsetBinding.get();
}
public void setCellOffset(int val) {
cellOffsetBinding.set(val);
}
public void toggleAxis() {
switch (displayAxisType) {
case XY_AXIS:
displayAxisType = DisplayAxisType.XZ_AXIS;
break;
case XZ_AXIS:
displayAxisType = DisplayAxisType.YZ_AXIS;
break;
case YZ_AXIS:
displayAxisType = DisplayAxisType.XY_AXIS;
break;
}
// TODO: force redraw?
}
public DisplayAxisType getDisplayAxisType() {
return displayAxisType;
}
}
| not sure if we need this to deal with air blocks
| src/main/java/org/terasology/minimap/rendering/nui/layers/MinimapGrid.java | not sure if we need this to deal with air blocks | <ide><path>rc/main/java/org/terasology/minimap/rendering/nui/layers/MinimapGrid.java
<ide>
<ide> if (null != cells) {
<ide> Vector2i cellSize = canvas.calculatePreferredSize(cells[0][0]);
<add>
<add> canvas.drawBackground();
<ide>
<ide> for (int row = 0; row < numberOfRows; row++) {
<ide> for (int column = 0; column < numberOfColumns; column++) { |
|
Java | apache-2.0 | c6383168473190abf2f183379fca198537ed42dc | 0 | palava/palava-jmx | /**
* Copyright 2010 CosmoCode GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.cosmocode.palava.jmx;
import javax.management.MBeanServer;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import com.google.inject.tools.jmx.Manager;
import de.cosmocode.palava.core.CoreConfig;
import de.cosmocode.palava.core.lifecycle.Initializable;
import de.cosmocode.palava.core.lifecycle.LifecycleException;
/**
* Binds the injector to a configured {@link MBeanServer}.
*
* @author Willi Schoenborn
*/
final class GuiceJmxService implements Initializable {
private final MBeanServer server;
private final Injector injector;
private String domain;
@Inject
public GuiceJmxService(MBeanServer server, Injector injector) {
this.server = Preconditions.checkNotNull(server, "MBeanServer");
this.injector = Preconditions.checkNotNull(injector, "Injector");
}
@Inject(optional = true)
void setApplication(@Named(CoreConfig.APPLICATION) String application) {
// only inject if no domain was set already
this.domain = domain == null ? Preconditions.checkNotNull(application, "Application") : domain;
}
@Inject(optional = true)
void setDomain(@Named(GuiceJmxServiceConfig.DOMAIN) String domain) {
this.domain = Preconditions.checkNotNull(domain, "Domain");
}
@Override
public void initialize() throws LifecycleException {
Manager.manage(server, domain, injector);
}
}
| src/main/java/de/cosmocode/palava/jmx/GuiceJmxService.java | /**
* Copyright 2010 CosmoCode GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.cosmocode.palava.jmx;
import javax.management.MBeanServer;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import com.google.inject.tools.jmx.Manager;
import de.cosmocode.palava.core.CoreConfig;
import de.cosmocode.palava.core.lifecycle.Initializable;
import de.cosmocode.palava.core.lifecycle.LifecycleException;
/**
* Binds the injector to a configured {@link MBeanServer}.
*
* @author Willi Schoenborn
*/
final class GuiceJmxService implements Initializable {
private final MBeanServer server;
private final Injector injector;
private String domain;
@Inject
public GuiceJmxService(MBeanServer server, @Named("guice.jmx.domain") String domain, Injector injector) {
this.server = Preconditions.checkNotNull(server, "MBeanServer");
this.injector = Preconditions.checkNotNull(injector, "Injector");
}
@Inject(optional = true)
void setApplication(@Named(CoreConfig.APPLICATION) String application) {
// only inject if no domain was set already
this.domain = domain == null ? Preconditions.checkNotNull(application, "Application") : domain;
}
@Inject(optional = true)
void setDomain(@Named(GuiceJmxServiceConfig.DOMAIN) String domain) {
this.domain = Preconditions.checkNotNull(domain, "Domain");
}
@Override
public void initialize() throws LifecycleException {
Manager.manage(server, domain, injector);
}
}
| removed string domain parameter from constructor
| src/main/java/de/cosmocode/palava/jmx/GuiceJmxService.java | removed string domain parameter from constructor | <ide><path>rc/main/java/de/cosmocode/palava/jmx/GuiceJmxService.java
<ide> private String domain;
<ide>
<ide> @Inject
<del> public GuiceJmxService(MBeanServer server, @Named("guice.jmx.domain") String domain, Injector injector) {
<add> public GuiceJmxService(MBeanServer server, Injector injector) {
<ide> this.server = Preconditions.checkNotNull(server, "MBeanServer");
<ide> this.injector = Preconditions.checkNotNull(injector, "Injector");
<ide> } |
|
Java | mit | 1dc2d59b0d7e7b671111e3cc765ca92d274d74ea | 0 | ashr81/unfolding,potioc/unfolding,CarlCOL/unfolding,potioc/unfolding,deepankverma/unfolding,ps793/unfolding | package de.fhpotsdam.unfolding.tiles;
import processing.core.PApplet;
import processing.core.PConstants;
import processing.core.PImage;
import de.fhpotsdam.unfolding.core.Coordinate;
import de.fhpotsdam.unfolding.providers.AbstractMapProvider;
/**
* Loads tiles from the MapProvider. Will be used in a background thread.
*
* Two kinds of MapProviders are supported:
* - AbstractMapTileProvider returning an tile image, directly.
* - AbstractMapTileUrlProvider returning an URL from which this TileLoader loads the tile from.
*
*/
public class TileLoader implements Runnable {
PApplet p;
AbstractMapProvider provider;
TileLoaderListener listener;
Coordinate coordinate;
private PImage cachedEmpyImage;
public TileLoader(PApplet p, AbstractMapProvider provider, TileLoaderListener listener, Coordinate coordinate) {
this.p = p;
this.provider = provider;
this.listener = listener;
this.coordinate = coordinate;
cachedEmpyImage = new PImage(provider.tileWidth(), provider.tileHeight(), PConstants.ARGB);
}
public void run() {
PImage img = provider.getTile(coordinate);
if (img == null) {
// If provider does not return an image try to get the URLs and load the tile images.
String[] urls = provider.getTileUrls(coordinate);
if (urls != null) {
img = getTileFromUrl(urls);
}
}
if (img == null) {
img = cachedEmpyImage;
}
listener.tileLoaded(coordinate, img);
}
protected PImage getTileFromUrl(String[] urls) {
// Load image from URL (local file included)
// NB: Use 'unknown' as content-type to let loadImage decide
PImage img = p.loadImage(urls[0], "unknown");
// if (OVERLAY_DEBUG_TILES) {
// // Create debug tile, and draw it on top of the loaded tile
// img = DebugTileUtils.getDebugTile(coord, img, p);
// }
if (img != null) {
// If array contains multiple URLs, load all images and blend them together
for (int i = 1; i < urls.length; i++) {
PImage img2 = p.loadImage(urls[i], "unknown");
if (img2 != null) {
img.blend(img2, 0, 0, img.width, img.height, 0, 0, img.width, img.height, PApplet.BLEND);
}
}
}
return img;
}
}
| unfolding/src/de/fhpotsdam/unfolding/tiles/TileLoader.java | package de.fhpotsdam.unfolding.tiles;
import processing.core.PApplet;
import processing.core.PImage;
import de.fhpotsdam.unfolding.core.Coordinate;
import de.fhpotsdam.unfolding.providers.AbstractMapProvider;
/**
* Loads tiles from the MapProvider. Will be used in a background thread.
*
* Two kinds of MapProviders are supported:
* - AbstractMapTileProvider returning an tile image, directly.
* - AbstractMapTileUrlProvider returning an URL from which this TileLoader loads the tile from.
*
*/
public class TileLoader implements Runnable {
PApplet p;
AbstractMapProvider provider;
TileLoaderListener listener;
Coordinate coordinate;
public TileLoader(PApplet p, AbstractMapProvider provider, TileLoaderListener listener, Coordinate coordinate) {
this.p = p;
this.provider = provider;
this.listener = listener;
this.coordinate = coordinate;
}
public void run() {
PImage img = provider.getTile(coordinate);
if (img == null) {
// If provider does not return an image try to get the URLs and load the tile images.
String[] urls = provider.getTileUrls(coordinate);
if (urls != null) {
img = getTileFromUrl(urls);
}
}
listener.tileLoaded(coordinate, img);
}
protected PImage getTileFromUrl(String[] urls) {
// Load image from URL (local file included)
// NB: Use 'unknown' as content-type to let loadImage decide
PImage img = p.loadImage(urls[0], "unknown");
// if (OVERLAY_DEBUG_TILES) {
// // Create debug tile, and draw it on top of the loaded tile
// img = DebugTileUtils.getDebugTile(coord, img, p);
// }
if (img != null) {
// If array contains multiple URLs, load all images and blend them together
for (int i = 1; i < urls.length; i++) {
PImage img2 = p.loadImage(urls[i], "unknown");
if (img2 != null) {
img.blend(img2, 0, 0, img.width, img.height, 0, 0, img.width, img.height, PApplet.BLEND);
}
}
}
return img;
}
}
| Added empty/transparent tile if provider does not return anything.
| unfolding/src/de/fhpotsdam/unfolding/tiles/TileLoader.java | Added empty/transparent tile if provider does not return anything. | <ide><path>nfolding/src/de/fhpotsdam/unfolding/tiles/TileLoader.java
<ide> package de.fhpotsdam.unfolding.tiles;
<ide>
<ide> import processing.core.PApplet;
<add>import processing.core.PConstants;
<ide> import processing.core.PImage;
<ide> import de.fhpotsdam.unfolding.core.Coordinate;
<ide> import de.fhpotsdam.unfolding.providers.AbstractMapProvider;
<ide> TileLoaderListener listener;
<ide>
<ide> Coordinate coordinate;
<add>
<add> private PImage cachedEmpyImage;
<ide>
<ide> public TileLoader(PApplet p, AbstractMapProvider provider, TileLoaderListener listener, Coordinate coordinate) {
<ide> this.p = p;
<ide> this.provider = provider;
<ide> this.listener = listener;
<ide> this.coordinate = coordinate;
<add>
<add> cachedEmpyImage = new PImage(provider.tileWidth(), provider.tileHeight(), PConstants.ARGB);
<ide> }
<ide>
<ide> public void run() {
<ide> if (urls != null) {
<ide> img = getTileFromUrl(urls);
<ide> }
<add> }
<add>
<add> if (img == null) {
<add> img = cachedEmpyImage;
<ide> }
<ide>
<ide> listener.tileLoaded(coordinate, img); |
|
Java | apache-2.0 | 5c8b1416c0fbd593be03c4ae470ef35078b81d66 | 0 | macrozheng/mall,macrozheng/mall | package com.macro.mall.dao;
import com.macro.mall.model.CmsPrefrenceAreaProductRelation;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 自定义优选和商品关系操作
* Created by macro on 2018/4/26.
*/
public interface CmsPrefrenceAreaProductRelationDao {
/**
* 批量创建
*/
int insertList(@Param("list") List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationList);
}
| mall-admin/src/main/java/com/macro/mall/dao/CmsPrefrenceAreaProductRelationDao.java | package com.macro.mall.dao;
import com.macro.mall.model.CmsPrefrenceAreaProductRelation;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 自定义优选和商品关系操作
* Created by macro on 2018/4/26.
*/
public interface CmsPrefrenceAreaProductRelationDao {
int insertList(@Param("list") List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationList);
}
| Update CmsPrefrenceAreaProductRelationDao.java
| mall-admin/src/main/java/com/macro/mall/dao/CmsPrefrenceAreaProductRelationDao.java | Update CmsPrefrenceAreaProductRelationDao.java | <ide><path>all-admin/src/main/java/com/macro/mall/dao/CmsPrefrenceAreaProductRelationDao.java
<ide> * Created by macro on 2018/4/26.
<ide> */
<ide> public interface CmsPrefrenceAreaProductRelationDao {
<add> /**
<add> * 批量创建
<add> */
<ide> int insertList(@Param("list") List<CmsPrefrenceAreaProductRelation> prefrenceAreaProductRelationList);
<ide> } |
|
Java | apache-2.0 | 34a863fd1b0a30ef5287615cc60347e84025e8a5 | 0 | jboss-switchyard/switchyard,bfitzpat/switchyard,cunningt/switchyard,igarashitm/switchyard,igarashitm/switchyard,bfitzpat/switchyard,tadayosi/switchyard,tadayosi/switchyard,jboss-switchyard/switchyard,igarashitm/switchyard,cunningt/switchyard,cunningt/switchyard,igarashitm/switchyard,KurtStam/quickstarts,KurtStam/quickstarts,jboss-switchyard/switchyard,bfitzpat/switchyard,tadayosi/switchyard | /*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 Lesser General Public License, v. 2.1.
* 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 Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.switchyard.quickstarts.camel.rest.binding;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.component.bean.config.model.BeanSwitchYardScanner;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.test.mixins.CDIMixIn;
import org.switchyard.test.mixins.HTTPMixIn;
/**
* Tests for Camel CXFRS binding.
*
* @author Magesh Kumar B <[email protected]> (C) 2012 Red Hat Inc.
*/
@Ignore("This test fails due dependency to CXF 2.6.1 absent in AS 7.1")
@SwitchYardTestCaseConfig(
config = SwitchYardTestCaseConfig.SWITCHYARD_XML,
mixins = {CDIMixIn.class, HTTPMixIn.class},
scanners = BeanSwitchYardScanner.class)
@RunWith(SwitchYardRunner.class)
public class CamelCxfRsBindingTest {
private HTTPMixIn http;
@Test
public void orderServiceRESTEndpoint() throws Exception {
// Create our inventory
String response = http.sendString(BASE_URL + "/order/inventory/create", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
// Create an order
response = http.sendString(BASE_URL + "/order", "", HTTPMixIn.HTTP_POST);
SwitchYardTestKit.compareXMLToString(response, ORDER);
// Add a new item or update order
response = http.sendString(BASE_URL + "/order/item", ORDER1, HTTPMixIn.HTTP_PUT);
Assert.assertEquals(SUCCESS, response);
// Add some more items or update order
response = http.sendString(BASE_URL + "/order/item", ORDER2, HTTPMixIn.HTTP_PUT);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER3);
// Delete the first item
response = http.sendString(BASE_URL + "/order/1:1", "", HTTPMixIn.HTTP_DELETE);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER4);
// Update item descriptions in our inventory
response = http.sendString(BASE_URL + "/order/inventory/update", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER5);
// Destroy our inventory
response = http.sendString(BASE_URL + "/order/inventory/remove", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
}
private static final String BASE_URL = "http://localhost:18001";
private static final String SUCCESS = "Order service is DUMB!";
private static final String ORDER = "<order>"
+ " <orderId>1</orderId>"
+ "</order>";
private static final String ORDER1 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>1</itemId>"
+ " </item>"
+ " <quantity>10</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER2 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER3 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>1</itemId>"
+ " <name>Hydrogen Atom - No, we are not kidding!</name>"
+ " </item>"
+ " <quantity>10</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Einstein's Bust - Talks about your future :)</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Time Machine</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER4 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Einstein's Bust - Talks about your future :)</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Time Machine</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER5 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Theory of relativity</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Coffee Maker</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
}
| camel-rest-binding/src/test/java/org/switchyard/quickstarts/camel/rest/binding/CamelCxfRsBindingTest.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2012 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 Lesser General Public License, v. 2.1.
* 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 Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.switchyard.quickstarts.camel.rest.binding;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.component.bean.config.model.BeanSwitchYardScanner;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.test.mixins.CDIMixIn;
import org.switchyard.test.mixins.HTTPMixIn;
/**
* Tests for Camel CXFRS binding.
*
* @author Magesh Kumar B <[email protected]> (C) 2012 Red Hat Inc.
*/
@SwitchYardTestCaseConfig(
config = SwitchYardTestCaseConfig.SWITCHYARD_XML,
mixins = {CDIMixIn.class, HTTPMixIn.class},
scanners = BeanSwitchYardScanner.class)
@RunWith(SwitchYardRunner.class)
public class CamelCxfRsBindingTest {
private HTTPMixIn http;
@Test
public void orderServiceRESTEndpoint() throws Exception {
// Create our inventory
String response = http.sendString(BASE_URL + "/order/inventory/create", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
// Create an order
response = http.sendString(BASE_URL + "/order", "", HTTPMixIn.HTTP_POST);
SwitchYardTestKit.compareXMLToString(response, ORDER);
// Add a new item or update order
response = http.sendString(BASE_URL + "/order/item", ORDER1, HTTPMixIn.HTTP_PUT);
Assert.assertEquals(SUCCESS, response);
// Add some more items or update order
response = http.sendString(BASE_URL + "/order/item", ORDER2, HTTPMixIn.HTTP_PUT);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER3);
// Delete the first item
response = http.sendString(BASE_URL + "/order/1:1", "", HTTPMixIn.HTTP_DELETE);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER4);
// Update item descriptions in our inventory
response = http.sendString(BASE_URL + "/order/inventory/update", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
// Look at our order
response = http.sendString(BASE_URL + "/order/1", "", HTTPMixIn.HTTP_GET);
SwitchYardTestKit.compareXMLToString(response, ORDER5);
// Destroy our inventory
response = http.sendString(BASE_URL + "/order/inventory/remove", "", HTTPMixIn.HTTP_OPTIONS);
Assert.assertEquals(SUCCESS, response);
}
private static final String BASE_URL = "http://localhost:18001";
private static final String SUCCESS = "Order service is DUMB!";
private static final String ORDER = "<order>"
+ " <orderId>1</orderId>"
+ "</order>";
private static final String ORDER1 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>1</itemId>"
+ " </item>"
+ " <quantity>10</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER2 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER3 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>1</itemId>"
+ " <name>Hydrogen Atom - No, we are not kidding!</name>"
+ " </item>"
+ " <quantity>10</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Einstein's Bust - Talks about your future :)</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Time Machine</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER4 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Einstein's Bust - Talks about your future :)</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Time Machine</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
private static final String ORDER5 = "<order>"
+ " <orderId>1</orderId>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>3</itemId>"
+ " <name>Theory of relativity</name>"
+ " </item>"
+ " <quantity>5</quantity>"
+ " </orderItem>"
+ " <orderItem>"
+ " <item>"
+ " <itemId>4</itemId>"
+ " <name>Coffee Maker</name>"
+ " </item>"
+ " <quantity>3</quantity>"
+ " </orderItem>"
+ "</order>";
}
| SWITCHYARD-945 Upgrade to Camel 2.10.0 (disable rest binding test temporarily).
| camel-rest-binding/src/test/java/org/switchyard/quickstarts/camel/rest/binding/CamelCxfRsBindingTest.java | SWITCHYARD-945 Upgrade to Camel 2.10.0 (disable rest binding test temporarily). | <ide><path>amel-rest-binding/src/test/java/org/switchyard/quickstarts/camel/rest/binding/CamelCxfRsBindingTest.java
<ide> package org.switchyard.quickstarts.camel.rest.binding;
<ide>
<ide> import org.junit.Assert;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import org.junit.runner.RunWith;
<ide> import org.switchyard.component.bean.config.model.BeanSwitchYardScanner;
<ide> *
<ide> * @author Magesh Kumar B <[email protected]> (C) 2012 Red Hat Inc.
<ide> */
<add>@Ignore("This test fails due dependency to CXF 2.6.1 absent in AS 7.1")
<ide> @SwitchYardTestCaseConfig(
<ide> config = SwitchYardTestCaseConfig.SWITCHYARD_XML,
<ide> mixins = {CDIMixIn.class, HTTPMixIn.class}, |
|
Java | mit | fdb2c137a1e0917a356fe61846c4c406fb99fc7f | 0 | melezov/slf4j,lukecwik/slf4j,libliflin/slf4j,qos-ch/slf4j,lukecwik/slf4j,lukecwik/slf4j,qos-ch/slf4j,yukihane/slf4j,xiaob/slf4j,adorokhine/slf4j,libliflin/slf4j,geekboxzone/mmallow_external_slf4j,geekboxzone/mmallow_external_slf4j,adorokhine/slf4j,nitinverma/slf4j,b-cuts/slf4j,kbzod/slf4j,yukihane/slf4j,Mahoney/sysout-over-slf4j,Andrew67/slf4j,b-cuts/slf4j,hazendaz/slf4j,lukecwik/slf4j,melezov/slf4j,b-cuts/slf4j,yukihane/slf4j,kbzod/slf4j,Andrew67/slf4j,hazendaz/slf4j,melezov/slf4j,xiaob/slf4j,b-cuts/slf4j,twwwt/slf4j,yukihane/slf4j,geekboxzone/mmallow_external_slf4j,b-cuts/slf4j,lukecwik/slf4j,xiaob/slf4j,adorokhine/slf4j,melezov/slf4j,twwwt/slf4j,libliflin/slf4j,qos-ch/slf4j,twwwt/slf4j,Andrew67/slf4j,xiaob/slf4j,libliflin/slf4j,melezov/slf4j,geekboxzone/mmallow_external_slf4j,Andrew67/slf4j,hazendaz/slf4j,twwwt/slf4j,geekboxzone/mmallow_external_slf4j,kbzod/slf4j,yukihane/slf4j,kbzod/slf4j,kbzod/slf4j,nitinverma/slf4j,libliflin/slf4j,adorokhine/slf4j,hazendaz/slf4j,nitinverma/slf4j,Andrew67/slf4j | package org.slf4j.agent;
import static org.slf4j.helpers.MessageFormatter.format;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.Date;
import java.util.Properties;
import org.slf4j.instrumentation.LogTransformer;
/**
* Entry point for slf4j-ext when used as a Java agent.
*
*/
public class AgentPremain {
private static final String START_MSG = "Start at {}";
private static final String STOP_MSG = "Stop at {}, execution time = {} ms";
/**
* JavaAgent premain entry point as specified in the MANIFEST.MF file. See
* {@link http
* ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary
* .html} for details.
*
* @param agentArgument
* string provided after "=" up to first space
* @param instrumentation
* instrumentation environment provided by the JVM
*/
public static void premain(String agentArgument,
Instrumentation instrumentation) {
LogTransformer.Builder builder = new LogTransformer.Builder();
builder = builder.addEntryExit(true);
if (agentArgument != null) {
Properties args = parseArguments(agentArgument, ";");
if (args.containsKey(AgentOptions.VERBOSE)) {
builder = builder.verbose(true);
}
if (args.containsKey(AgentOptions.TIME)) {
printStartStopTimes();
}
if (args.containsKey(AgentOptions.IGNORE)) {
builder = builder.ignore(args.getProperty(AgentOptions.IGNORE).split(","));
}
if (args.containsKey(AgentOptions.LEVEL)) {
builder = builder.level(args.getProperty(AgentOptions.LEVEL));
}
}
instrumentation.addTransformer(builder.build());
}
/**
* Consider the argument string to be a property file (by converting the
* splitter character to line feeds), and then reading it like any other
* property file.
*
*
* @param agentArgument
* string given by instrumentation framework
* @param separator
* String to convert to line feeds
* @return argument converted to properties
*/
private static Properties parseArguments(String agentArgument,
String separator) {
Properties p = new Properties();
try {
String argumentAsLines = agentArgument.replaceAll(separator, "\n");
p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
} catch (IOException e) {
String s = "Could not load arguments as properties";
throw new RuntimeException(s, e);
}
return p;
}
/**
* Print the start message to System.err with the time NOW, and register a
* shutdown hook which will print the stop message to System.err with the time
* then and the number of milliseconds passed since.
*
*/
private static void printStartStopTimes() {
final long start = System.currentTimeMillis();
System.err.println(format(START_MSG, new Date()));
Thread hook = new Thread() {
@Override
public void run() {
long timePassed = System.currentTimeMillis() - start;
String message = format(STOP_MSG, new Date(), timePassed);
System.err.println(message);
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
} | slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java | package org.slf4j.agent;
import static org.slf4j.helpers.MessageFormatter.format;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.util.Date;
import java.util.Properties;
import org.slf4j.instrumentation.LogTransformer;
public class AgentPremain {
private static final String START_MSG = "Start at {}";
private static final String STOP_MSG = "Stop at {}, execution time = {} ms";
/**
* JavaAgent premain entry point as specified in the MANIFEST.MF file. See
* {@link http
* ://java.sun.com/javase/6/docs/api/java/lang/instrument/package-summary
* .html} for details.
*
* @param agentArgument
* string provided after "=" up to first space
* @param instrumentation
* instrumentation environment provided by the JVM
*/
public static void premain(String agentArgument,
Instrumentation instrumentation) {
LogTransformer.Builder builder = new LogTransformer.Builder();
builder = builder.addEntryExit(true);
if (agentArgument != null) {
Properties args = parseArguments(agentArgument, ";");
if (args.containsKey("verbose")) {
builder = builder.verbose(true);
}
if (args.containsKey("time")) {
printStartStopTimes();
}
if (args.containsKey("ignore")) {
builder = builder.ignore(args.getProperty("ignore").split(","));
}
if (args.containsKey("level")) {
builder = builder.level(args.getProperty("level"));
}
// ... more agent option handling here
}
instrumentation.addTransformer(builder.build());
}
/**
* Consider the argument string to be a property file (by converting the
* splitter character to line feeds), and then reading it like any other
* property file.
*
*
* @param agentArgument
* string given by instrumentation framework
* @param separator
* String to convert to line feeds
* @return argument converted to properties
*/
private static Properties parseArguments(String agentArgument,
String separator) {
Properties p = new Properties();
try {
String argumentAsLines = agentArgument.replaceAll(separator, "\n");
p.load(new ByteArrayInputStream(argumentAsLines.getBytes()));
} catch (IOException e) {
String s = "Could not load arguments as properties";
throw new RuntimeException(s, e);
}
return p;
}
/**
* Print the start message to System.err with the time NOW, and register a
* shutdown hook which will print the stop message to System.err with the time
* then and the number of milliseconds passed since.
*
*/
private static void printStartStopTimes() {
final long start = System.currentTimeMillis();
System.err.println(format(START_MSG, new Date()));
Thread hook = new Thread() {
@Override
public void run() {
long timePassed = System.currentTimeMillis() - start;
String message = format(STOP_MSG, new Date(), timePassed);
System.err.println(message);
}
};
Runtime.getRuntime().addShutdownHook(hook);
}
} | added javadoc
| slf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java | added javadoc | <ide><path>lf4j-ext/src/main/java/org/slf4j/agent/AgentPremain.java
<ide>
<ide> import org.slf4j.instrumentation.LogTransformer;
<ide>
<add>/**
<add> * Entry point for slf4j-ext when used as a Java agent.
<add> *
<add> */
<ide> public class AgentPremain {
<ide>
<ide> private static final String START_MSG = "Start at {}";
<ide> if (agentArgument != null) {
<ide> Properties args = parseArguments(agentArgument, ";");
<ide>
<del> if (args.containsKey("verbose")) {
<add> if (args.containsKey(AgentOptions.VERBOSE)) {
<ide> builder = builder.verbose(true);
<ide> }
<ide>
<del> if (args.containsKey("time")) {
<add> if (args.containsKey(AgentOptions.TIME)) {
<ide> printStartStopTimes();
<ide> }
<ide>
<del> if (args.containsKey("ignore")) {
<del> builder = builder.ignore(args.getProperty("ignore").split(","));
<add> if (args.containsKey(AgentOptions.IGNORE)) {
<add> builder = builder.ignore(args.getProperty(AgentOptions.IGNORE).split(","));
<ide> }
<ide>
<del> if (args.containsKey("level")) {
<del> builder = builder.level(args.getProperty("level"));
<add> if (args.containsKey(AgentOptions.LEVEL)) {
<add> builder = builder.level(args.getProperty(AgentOptions.LEVEL));
<ide> }
<del>
<del> // ... more agent option handling here
<ide> }
<ide>
<ide> instrumentation.addTransformer(builder.build()); |
|
JavaScript | cc0-1.0 | 6197e554930f8a61c658bc34cf8761e1c635f769 | 0 | paullucas/lissajous-offline,furey789/lissajous,kylestetz/lissajous,kylestetz/lissajous,furey789/lissajous,paullucas/lissajous-offline | // This is the performance API.
// Golden Rule: everything starts with `var self = this` and ends with `return self`.
function _joinArgs(args) {
args = Array.prototype.slice.call(args);
for(var i = 1; i < args.length; i++) {
args[0] = args[0].concat(args[i]);
}
return args[0];
}
// _parseArguments takes multiple array arguments and stitches them into a one-dimensional array.
function _parseArguments(args) {
if(Array.isArray(args[0])) {
args = _joinArgs(args);
}
return args;
}
track.prototype.beat = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._beatPattern.set(arguments, 16);
return self;
};
track.prototype.beat32 = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._beatPattern.set(arguments, 32);
return self;
};
track.prototype.notes = function() {
var self = this;
// let's allow an array of notes as well
var arguments = _parseArguments(arguments);
self._notesSequencer.set(arguments);
if(arguments.length == 0) {
self._currentNote = 64;
}
return self;
};
track.prototype.nl = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._noteLengthSequencer.set(arguments);
if(arguments.length) {
// nl will be 16th notes, so we need to multiply everything by 2
for(var i = 0; i < arguments.length; i++) {
arguments[i] *= 2;
}
} else {
// reasonable default -> nl = 16th note
self._currentNoteLength = 2;
}
return self;
};
track.prototype.nl32 = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._noteLengthSequencer.set(arguments);
if(arguments.length == 0) {
// reasonable default -> nl = 16th note
self._currentNoteLength = 2;
}
return self;
};
track.prototype.trans = function(semitones) {
var self = this;
for(var i = 0; i < self._notesSequencer.pattern.length; i++) {
self._notesSequencer.pattern[i] = self._notesSequencer.pattern[i] + semitones;
}
return self;
};
track.prototype.shift = function(amount) {
var self = this;
self._schedulers[0].untilNextBeat += amount;
if(self._schedulers[0].untilNextBeat < 0) {
self._schedulers[0].untilNextBeat = 0;
}
return self;
};
// -1 is left, 1 is right, 0 is center
track.prototype.pan = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._panSequencer.set(arguments);
if(arguments.length == 0) {
self._panSequencer.set([0]);
}
return self;
};
// ------------------------------------------------------------------ OSCILLATORS
var SINE = "sine";
var SQUARE = "square";
var SAWTOOTH = "sawtooth";
var TRIANGLE = "triangle";
track.prototype.sine = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SINE;
return self;
};
track.prototype.square = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SQUARE;
return self;
};
track.prototype.saw = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SAWTOOTH;
return self;
};
track.prototype.tri = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = TRIANGLE;
return self;
};
// oscillator type sequencer! 0 to 3 or SINE, SQUARE, TRIANGLE, SAWTOOTH
track.prototype.type = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._oscTypeSequencer.set(arguments);
if(arguments.length == 0) {
self._oscType = SINE;
}
return self;
};
// ------------------------------------------------------------------ ENVELOPE
track.prototype.vol = function() {
var self = this;
var arguments = _parseArguments(arguments);
self._volumeSequencer.set(arguments);
if(arguments.length == 0) {
self._volume = 0;
}
return self;
};
track.prototype.adsr = function() {
var self = this;
var resolutionModifier = clock.bpmResolution / 16;
// arguments isn't really an array so we have to turn it into one
var arguments = Array.prototype.slice.call(arguments);
self._applyAdsrArguments(arguments, resolutionModifier);
return self;
};
track.prototype.adsr32 = function() {
var self = this;
var resolutionModifier = clock.bpmResolution / 32;
// arguments isn't really an array so we have to turn it into one
var arguments = Array.prototype.slice.call(arguments);
self._applyAdsrArguments(arguments, resolutionModifier);
return self;
};
track.prototype._applyAdsrArguments = function(args, resolutionModifier) {
var self = this;
// if we get an array as a first argument, we will assume all args are arrays.
if(args.length > 0 && Array.isArray(args[0])) {
args.forEach( function(arg) {
arg[0] *= resolutionModifier;
arg[1] *= resolutionModifier;
// arg[2] is sustain, don't modify it
arg[3] *= resolutionModifier;
});
self._adsrSequencer.set(args);
}
// ...or it's just four values.
else if(args.length == 4) {
args[0] *= resolutionModifier;
args[1] *= resolutionModifier;
// args[2] is sustain, don't modify it
args[3] *= resolutionModifier;
self._adsrSequencer.set([args]);
}
// back to the defaults
else {
self._attack = self._decay = self._release = 0;
self._sustain = 1;
self._adsrSequencer.set([]);
}
};
// ------------------------------------------------------------------ SAMPLER
// sample buffers
track.prototype.sample = function() {
var self = this;
self._samples = [];
var arguments = Array.prototype.slice.call(arguments);
arguments = _parseArguments(arguments);
arguments.forEach( function(buffer) {
self._samples.push( new Sample(buffer) );
});
if(arguments.length) {
self._currentSample = self._samples[0];
self._editingSample = self._samples[0];
}
return self;
};
track.prototype.addsamples = function() {
var self = this;
var arguments = Array.prototype.slice.call(arguments);
arguments.forEach( function(buffer) {
self._samples.push( new Sample(buffer) );
});
return self;
};
track.prototype.select = function(index) {
var self = this;
if(index < self._samples.length) {
self._editingSample = self._samples[index];
}
return self;
};
// sample sequence
track.prototype.sseq = function() {
var self = this;
var arguments = _parseArguments(arguments);
// safeguard against errors for indices past the available length
for(var i = 0; i < arguments.length; i++) {
if(arguments[i] > self._samples.length) {
arguments[i] = self._samples.length - 1;
}
}
self._currentSampleSequencer.set(arguments);
return self;
};
track.prototype.clamp = function(start, end) {
var self = this;
if(self._editingSample) {
if(end == null) {
self._editingSample.loopStart = (0);
self._editingSample.loopEnd = (start);
} else {
self._editingSample.loopStart = (start || 0);
self._editingSample.loopEnd = (end || 1);
}
}
return self;
};
track.prototype.clshift = function() {
var self = this;
if(self._editingSample) {
var arguments = _parseArguments(arguments);
self._editingSample.clampShiftSequencer.set(arguments);
}
return self;
};
track.prototype.loop = function() {
var self = this;
if(self._editingSample) {
if(arguments.length && arguments[0]) {
self._editingSample.looping = true;
} else {
self._editingSample.looping = false;
}
}
return self;
};
track.prototype.stretch = function() {
var self = this;
if(self._editingSample) {
if(arguments.length) {
// self._editingSample.stretchToFit = arguments[0] * (clock.bpmResolution / 16);
var arguments = _parseArguments(arguments);
for(var i = 0; i < arguments.length; i++) {
arguments[i] = arguments[i] * (clock.bpmResolution / 16);
}
self._editingSample.stretchSequencer.set(arguments);
} else {
self._editingSample.speed = 1;
self._editingSample.stretchToFit = null;
self._editingSample.stretchSequencer.set([]);
}
}
return self;
};
track.prototype.speed = function() {
var self = this;
if(self._editingSample) {
if(arguments.length) {
self._editingSample.speed = arguments[0];
self._editingSample.stretchToFit = null;
} else {
self._editingSample.speed = 1;
self._editingSample.stretchToFit = null;
}
}
return self;
};
track.prototype.reverse = function() {
var self = this;
if(self._editingSample) {
// need to make a new buffer to perform this operation on so we don't scuff the original.
var oldBuffer = self._editingSample.buffer;
var newBuffer = context.createBuffer(oldBuffer.numberOfChannels, oldBuffer.length, oldBuffer.sampleRate);
for(var i = 0; i < oldBuffer.numberOfChannels; i++) {
newBuffer.getChannelData(i).set(Array.prototype.reverse.call( new Float32Array(oldBuffer.getChannelData(i)) ));
}
self._editingSample.buffer = newBuffer;
}
return self;
};
track.prototype.root = function(note) {
var self = this;
if(self._editingSample) {
self._editingSample.rootNote = note;
}
return self;
};
track.prototype.render = function(length) {
var self = this;
self._render(length, 16);
return self;
};
track.prototype.render32 = function(length) {
var self = this;
self._render(length, 32);
return self;
};
// reset event, which should be used by effects to quickly turn everything off
track.prototype.reset = function() {
var self = this;
self._emit('reset');
return self;
};
track.prototype.eval = function() {
var self = this;
arguments = _parseArguments(arguments);
self._evalSequencer.set(arguments);
return self;
};
// ------------------------------------------------------------------ WEIRD
track.prototype.in = function(count) {
var self = this;
// return an instance of the _in queue,
// which allows us to stage changes
// for later.
return new self._in(count);
};
track.prototype.log = function() {
console.log(arguments);
return this;
}; | src/track.api.js | // This is the performance API.
// Golden Rule: everything starts with `var self = this` and ends with `return self`.
function _joinArgs(args) {
args = Array.prototype.slice.call(args);
for(var i = 1; i < args.length; i++) {
args[0] = args[0].concat(args[i]);
}
return args[0];
}
// _parseArguments takes multiple array arguments and stitches them into a one-dimensional array.
function _parseArguments(args) {
if(Array.isArray(args[0])) {
args = _joinArgs(args);
}
return args;
}
track.prototype.beat = function() {
var self = this;
arguments = _parseArguments(arguments);
self._beatPattern.set(arguments, 16);
return self;
};
track.prototype.beat32 = function() {
var self = this;
arguments = _parseArguments(arguments);
self._beatPattern.set(arguments, 32);
return self;
}
track.prototype.notes = function() {
var self = this;
// let's allow an array of notes as well
arguments = _parseArguments(arguments);
self._notesSequencer.set(arguments);
if(arguments.length == 0) {
self._currentNote = 64;
}
return self;
}
track.prototype.nl = function() {
var self = this;
arguments = _parseArguments(arguments);
self._noteLengthSequencer.set(arguments);
if(arguments.length) {
// nl will be 16th notes, so we need to multiply everything by 2
for(var i = 0; i < arguments.length; i++) {
arguments[i] *= 2;
}
} else {
// reasonable default -> nl = 16th note
self._currentNoteLength = 2;
}
return self;
}
track.prototype.nl32 = function() {
var self = this;
arguments = _parseArguments(arguments);
self._noteLengthSequencer.set(arguments);
if(arguments.length == 0) {
// reasonable default -> nl = 16th note
self._currentNoteLength = 2;
}
return self;
}
track.prototype.trans = function(semitones) {
var self = this;
for(var i = 0; i < self._notesSequencer.pattern.length; i++) {
self._notesSequencer.pattern[i] = self._notesSequencer.pattern[i] + semitones;
}
return self;
}
track.prototype.shift = function(amount) {
var self = this;
self._schedulers[0].untilNextBeat += amount;
if(self._schedulers[0].untilNextBeat < 0) {
self._schedulers[0].untilNextBeat = 0;
}
return self;
}
// -1 is left, 1 is right, 0 is center
track.prototype.pan = function() {
var self = this;
arguments = _parseArguments(arguments);
self._panSequencer.set(arguments);
if(arguments.length == 0) {
self._panSequencer.set([0]);
}
return self;
}
// ------------------------------------------------------------------ OSCILLATORS
var SINE = "sine";
var SQUARE = "square";
var SAWTOOTH = "sawtooth";
var TRIANGLE = "triangle";
track.prototype.sine = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SINE;
return self;
}
track.prototype.square = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SQUARE;
return self;
}
track.prototype.saw = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = SAWTOOTH;
return self;
}
track.prototype.tri = function() {
var self = this;
if(self._oscTypeSequencer.pattern.length) {
// clear the oscType sequencer if it had a pattern
self._oscTypeSequencer.set([]);
}
self._oscType = TRIANGLE;
return self;
}
// oscillator type sequencer! 0 to 3 or SINE, SQUARE, TRIANGLE, SAWTOOTH
track.prototype.type = function() {
var self = this;
arguments = _parseArguments(arguments);
self._oscTypeSequencer.set(arguments);
if(arguments.length == 0) {
self._oscType = SINE;
}
return self;
}
// ------------------------------------------------------------------ ENVELOPE
track.prototype.vol = function() {
var self = this;
arguments = _parseArguments(arguments);
self._volumeSequencer.set(arguments);
if(arguments.length == 0) {
self._volume = 0;
}
return self;
}
track.prototype.adsr = function() {
var self = this;
var resolutionModifier = clock.bpmResolution / 16;
// arguments isn't really an array so we have to turn it into one
arguments = Array.prototype.slice.call(arguments);
self._applyAdsrArguments(arguments, resolutionModifier);
return self;
}
track.prototype.adsr32 = function() {
var self = this;
var resolutionModifier = clock.bpmResolution / 32;
// arguments isn't really an array so we have to turn it into one
arguments = Array.prototype.slice.call(arguments);
self._applyAdsrArguments(arguments, resolutionModifier);
return self;
}
track.prototype._applyAdsrArguments = function(args, resolutionModifier) {
var self = this;
// if we get an array as a first argument, we will assume all args are arrays.
if(args.length > 0 && Array.isArray(args[0])) {
args.forEach( function(arg) {
arg[0] *= resolutionModifier;
arg[1] *= resolutionModifier;
// arg[2] is sustain, don't modify it
arg[3] *= resolutionModifier;
});
self._adsrSequencer.set(args);
}
// ...or it's just four values.
else if(args.length == 4) {
args[0] *= resolutionModifier;
args[1] *= resolutionModifier;
// args[2] is sustain, don't modify it
args[3] *= resolutionModifier;
self._adsrSequencer.set([args]);
}
// back to the defaults
else {
self._attack = self._decay = self._release = 0;
self._sustain = 1;
self._adsrSequencer.set([]);
}
}
// ------------------------------------------------------------------ SAMPLER
// sample buffers
track.prototype.sample = function() {
var self = this;
self._samples = [];
arguments = Array.prototype.slice.call(arguments);
arguments = _parseArguments(arguments);
arguments.forEach( function(buffer) {
self._samples.push( new Sample(buffer) );
});
if(arguments.length) {
self._currentSample = self._samples[0];
self._editingSample = self._samples[0];
}
return self;
}
track.prototype.addsamples = function() {
var self = this;
arguments = Array.prototype.slice.call(arguments);
arguments.forEach( function(buffer) {
self._samples.push( new Sample(buffer) );
});
return self;
}
track.prototype.select = function(index) {
var self = this;
if(index < self._samples.length) {
self._editingSample = self._samples[index];
}
return self;
}
// sample sequence
track.prototype.sseq = function() {
var self = this;
arguments = _parseArguments(arguments);
// safeguard against errors for indices past the available length
for(var i = 0; i < arguments.length; i++) {
if(arguments[i] > self._samples.length) {
arguments[i] = self._samples.length - 1;
}
}
self._currentSampleSequencer.set(arguments);
return self;
}
track.prototype.clamp = function(start, end) {
var self = this;
if(self._editingSample) {
if(end == null) {
self._editingSample.loopStart = (0);
self._editingSample.loopEnd = (start);
} else {
self._editingSample.loopStart = (start || 0);
self._editingSample.loopEnd = (end || 1);
}
}
return self;
}
track.prototype.clshift = function() {
var self = this;
if(self._editingSample) {
arguments = _parseArguments(arguments);
self._editingSample.clampShiftSequencer.set(arguments);
}
return self;
}
track.prototype.loop = function() {
var self = this;
if(self._editingSample) {
if(arguments.length && arguments[0]) {
self._editingSample.looping = true;
} else {
self._editingSample.looping = false;
}
}
return self;
}
track.prototype.stretch = function() {
var self = this;
if(self._editingSample) {
if(arguments.length) {
// self._editingSample.stretchToFit = arguments[0] * (clock.bpmResolution / 16);
arguments = _parseArguments(arguments);
for(var i = 0; i < arguments.length; i++) {
arguments[i] = arguments[i] * (clock.bpmResolution / 16);
}
self._editingSample.stretchSequencer.set(arguments);
} else {
self._editingSample.speed = 1;
self._editingSample.stretchToFit = null;
self._editingSample.stretchSequencer.set([]);
}
}
return self;
}
track.prototype.speed = function() {
var self = this;
if(self._editingSample) {
if(arguments.length) {
self._editingSample.speed = arguments[0];
self._editingSample.stretchToFit = null;
} else {
self._editingSample.speed = 1;
self._editingSample.stretchToFit = null;
}
}
return self;
}
track.prototype.reverse = function() {
var self = this;
if(self._editingSample) {
// need to make a new buffer to perform this operation on so we don't scuff the original.
var oldBuffer = self._editingSample.buffer;
var newBuffer = context.createBuffer(oldBuffer.numberOfChannels, oldBuffer.length, oldBuffer.sampleRate);
for(var i = 0; i < oldBuffer.numberOfChannels; i++) {
newBuffer.getChannelData(i).set(Array.prototype.reverse.call( new Float32Array(oldBuffer.getChannelData(i)) ));
}
self._editingSample.buffer = newBuffer;
}
return self;
}
track.prototype.root = function(note) {
var self = this;
if(self._editingSample) {
self._editingSample.rootNote = note;
}
return self;
}
track.prototype.render = function(length) {
var self = this;
self._render(length, 16);
return self;
}
track.prototype.render32 = function(length) {
var self = this;
self._render(length, 32);
return self;
}
// reset event, which should be used by effects to quickly turn everything off
track.prototype.reset = function() {
var self = this;
self._emit('reset');
return self;
}
track.prototype.eval = function() {
var self = this;
arguments = _parseArguments(arguments);
self._evalSequencer.set(arguments);
return self;
}
// ------------------------------------------------------------------ WEIRD
track.prototype.in = function(count) {
var self = this;
// return an instance of the _in queue,
// which allows us to stage changes
// for later.
return new self._in(count);
}
track.prototype.log = function() {
console.log(arguments);
return this;
} | localizing arg variables and cleaning up
| src/track.api.js | localizing arg variables and cleaning up | <ide><path>rc/track.api.js
<ide>
<ide> track.prototype.beat = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._beatPattern.set(arguments, 16);
<ide> return self;
<ide> };
<ide>
<ide> track.prototype.beat32 = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._beatPattern.set(arguments, 32);
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.notes = function() {
<ide> var self = this;
<ide> // let's allow an array of notes as well
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._notesSequencer.set(arguments);
<ide> if(arguments.length == 0) {
<ide> self._currentNote = 64;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.nl = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._noteLengthSequencer.set(arguments);
<ide> if(arguments.length) {
<ide> // nl will be 16th notes, so we need to multiply everything by 2
<ide> self._currentNoteLength = 2;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.nl32 = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._noteLengthSequencer.set(arguments);
<ide> if(arguments.length == 0) {
<ide> // reasonable default -> nl = 16th note
<ide> self._currentNoteLength = 2;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.trans = function(semitones) {
<ide> var self = this;
<ide> self._notesSequencer.pattern[i] = self._notesSequencer.pattern[i] + semitones;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.shift = function(amount) {
<ide> var self = this;
<ide> self._schedulers[0].untilNextBeat = 0;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> // -1 is left, 1 is right, 0 is center
<ide> track.prototype.pan = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._panSequencer.set(arguments);
<ide> if(arguments.length == 0) {
<ide> self._panSequencer.set([0]);
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> // ------------------------------------------------------------------ OSCILLATORS
<ide>
<ide> }
<ide> self._oscType = SINE;
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.square = function() {
<ide> var self = this;
<ide> }
<ide> self._oscType = SQUARE;
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.saw = function() {
<ide> var self = this;
<ide> }
<ide> self._oscType = SAWTOOTH;
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.tri = function() {
<ide> var self = this;
<ide> }
<ide> self._oscType = TRIANGLE;
<ide> return self;
<del>}
<add>};
<ide>
<ide> // oscillator type sequencer! 0 to 3 or SINE, SQUARE, TRIANGLE, SAWTOOTH
<ide> track.prototype.type = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._oscTypeSequencer.set(arguments);
<ide> if(arguments.length == 0) {
<ide> self._oscType = SINE;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> // ------------------------------------------------------------------ ENVELOPE
<ide>
<ide> track.prototype.vol = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._volumeSequencer.set(arguments);
<ide> if(arguments.length == 0) {
<ide> self._volume = 0;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.adsr = function() {
<ide> var self = this;
<ide> var resolutionModifier = clock.bpmResolution / 16;
<ide> // arguments isn't really an array so we have to turn it into one
<del> arguments = Array.prototype.slice.call(arguments);
<add> var arguments = Array.prototype.slice.call(arguments);
<ide> self._applyAdsrArguments(arguments, resolutionModifier);
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.adsr32 = function() {
<ide> var self = this;
<ide> var resolutionModifier = clock.bpmResolution / 32;
<ide> // arguments isn't really an array so we have to turn it into one
<del> arguments = Array.prototype.slice.call(arguments);
<add> var arguments = Array.prototype.slice.call(arguments);
<ide> self._applyAdsrArguments(arguments, resolutionModifier);
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype._applyAdsrArguments = function(args, resolutionModifier) {
<ide> var self = this;
<ide> self._sustain = 1;
<ide> self._adsrSequencer.set([]);
<ide> }
<del>}
<add>};
<ide>
<ide> // ------------------------------------------------------------------ SAMPLER
<ide>
<ide> track.prototype.sample = function() {
<ide> var self = this;
<ide> self._samples = [];
<del> arguments = Array.prototype.slice.call(arguments);
<add> var arguments = Array.prototype.slice.call(arguments);
<ide> arguments = _parseArguments(arguments);
<ide> arguments.forEach( function(buffer) {
<ide> self._samples.push( new Sample(buffer) );
<ide> self._editingSample = self._samples[0];
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.addsamples = function() {
<ide> var self = this;
<del> arguments = Array.prototype.slice.call(arguments);
<add> var arguments = Array.prototype.slice.call(arguments);
<ide> arguments.forEach( function(buffer) {
<ide> self._samples.push( new Sample(buffer) );
<ide> });
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.select = function(index) {
<ide> var self = this;
<ide> self._editingSample = self._samples[index];
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> // sample sequence
<ide> track.prototype.sseq = function() {
<ide> var self = this;
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> // safeguard against errors for indices past the available length
<ide> for(var i = 0; i < arguments.length; i++) {
<ide> if(arguments[i] > self._samples.length) {
<ide> }
<ide> self._currentSampleSequencer.set(arguments);
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.clamp = function(start, end) {
<ide> var self = this;
<ide> }
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.clshift = function() {
<ide> var self = this;
<ide> if(self._editingSample) {
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> self._editingSample.clampShiftSequencer.set(arguments);
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.loop = function() {
<ide> var self = this;
<ide> }
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.stretch = function() {
<ide> var self = this;
<ide> if(self._editingSample) {
<ide> if(arguments.length) {
<ide> // self._editingSample.stretchToFit = arguments[0] * (clock.bpmResolution / 16);
<del> arguments = _parseArguments(arguments);
<add> var arguments = _parseArguments(arguments);
<ide> for(var i = 0; i < arguments.length; i++) {
<ide> arguments[i] = arguments[i] * (clock.bpmResolution / 16);
<ide> }
<ide> }
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.speed = function() {
<ide> var self = this;
<ide> }
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.reverse = function() {
<ide> var self = this;
<ide> self._editingSample.buffer = newBuffer;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.root = function(note) {
<ide> var self = this;
<ide> self._editingSample.rootNote = note;
<ide> }
<ide> return self;
<del>}
<add>};
<ide>
<ide>
<ide> track.prototype.render = function(length) {
<ide> var self = this;
<ide> self._render(length, 16);
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.render32 = function(length) {
<ide> var self = this;
<ide> self._render(length, 32);
<ide> return self;
<del>}
<add>};
<ide>
<ide> // reset event, which should be used by effects to quickly turn everything off
<ide> track.prototype.reset = function() {
<ide> var self = this;
<ide> self._emit('reset');
<ide> return self;
<del>}
<add>};
<ide>
<ide> track.prototype.eval = function() {
<ide> var self = this;
<ide> arguments = _parseArguments(arguments);
<ide> self._evalSequencer.set(arguments);
<ide> return self;
<del>}
<add>};
<ide>
<ide> // ------------------------------------------------------------------ WEIRD
<ide>
<ide> // which allows us to stage changes
<ide> // for later.
<ide> return new self._in(count);
<del>}
<add>};
<ide>
<ide> track.prototype.log = function() {
<ide> console.log(arguments);
<ide> return this;
<del>}
<add>}; |
|
Java | bsd-2-clause | 2462baa6a183cf6d80e171790e702d1a039171b4 | 0 | TehSAUCE/imagej,biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej | //
// FillDataValues.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
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 names of the ImageJDev.org developers 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDERS OR 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 imagej.core.plugins.assign;
import imagej.core.tools.FGTool;
import imagej.data.Dataset;
import imagej.data.display.ImageDisplay;
import imagej.data.display.ImageDisplayService;
import imagej.data.display.OverlayService;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Menu;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;
import imagej.ext.tool.ToolService;
import imagej.util.ColorRGB;
import imagej.util.RealRect;
import net.imglib2.Cursor;
import net.imglib2.img.ImgPlus;
import net.imglib2.meta.Axes;
import net.imglib2.ops.Real;
import net.imglib2.ops.UnaryOperation;
import net.imglib2.ops.operation.unary.real.RealConstant;
import net.imglib2.type.numeric.RealType;
/**
* Fills the selected region of an input Dataset with the foreground value.
*
* @author Barry DeZonia
*/
@Plugin(menu = { @Menu(label = "Edit", mnemonic = 'e'),
@Menu(label = "Fill", weight = 28, accelerator = "control F") })
public class FillDataValues implements ImageJPlugin {
// -- instance variables that are Parameters --
@Parameter(required = true, persist = false)
private OverlayService overlayService;
@Parameter(required = true, persist = false)
private ToolService toolService;
@Parameter(required = true, persist = false)
private ImageDisplayService dispService;
@Parameter(required = true, persist = false)
private ImageDisplay display;
// -- public interface --
@Override
public void run() {
final FGTool cp = toolService.getTool(FGTool.class);
if (cp == null) return;
Dataset dataset = dispService.getActiveDataset(display);
if (dataset.isRGBMerged()) {
final ColorRGB color = cp.getFgColor();
fillSelectedRegionWithColor(dataset, color);
}
else { // gray data
final double value = cp.getFgValue();
fillSelectedRegionWithValue(value);
}
}
public ImageDisplay getDisplay() {
return display;
}
public void setDisplay(final ImageDisplay display) {
this.display = display;
}
// -- private helpers --
private void fillSelectedRegionWithValue(double value) {
final UnaryOperation<Real, Real> op = new RealConstant(value);
final InplaceUnaryTransform transform =
new InplaceUnaryTransform(display, op);
transform.run();
}
// TODO - make something like this Dataset API maybe. or somewhere else.
private void fillSelectedRegionWithColor(Dataset dataset, ColorRGB color) {
RealRect bounds = overlayService.getSelectionBounds(display);
long minX = (long) bounds.x;
long minY = (long) bounds.y;
long maxX = (long) (bounds.x + bounds.width - 1);
long maxY = (long) (bounds.y + bounds.height - 1);
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
long[] pos = new long[dataset.numDimensions()];
int xIndex = dataset.getAxisIndex(Axes.X);
int yIndex = dataset.getAxisIndex(Axes.Y);
int chIndex = dataset.getAxisIndex(Axes.CHANNEL);
ImgPlus<? extends RealType<?>> imgPlus = dataset.getImgPlus();
Cursor<? extends RealType<?>> cursor = imgPlus.localizingCursor();
while (cursor.hasNext()) {
RealType<?> pixRef = cursor.next();
cursor.localize(pos);
if ((pos[xIndex] < minX) || (pos[xIndex] > maxX)) continue;
if ((pos[yIndex] < minY) || (pos[yIndex] > maxY)) continue;
if (pos[chIndex] == 0)
pixRef.setReal(r);
else if (pos[chIndex] == 1)
pixRef.setReal(g);
else
pixRef.setReal(b);
}
dataset.update();
}
}
| core/plugins/data/src/main/java/imagej/core/plugins/assign/FillDataValues.java | //
// FillDataValues.java
//
/*
ImageJ software for multidimensional image processing and analysis.
Copyright (c) 2010, ImageJDev.org.
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 names of the ImageJDev.org developers 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDERS OR 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 imagej.core.plugins.assign;
import imagej.core.tools.FGTool;
import imagej.data.Dataset;
import imagej.data.display.ImageDisplay;
import imagej.data.display.OverlayService;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Menu;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;
import imagej.ext.tool.ToolService;
import imagej.util.ColorRGB;
import imagej.util.RealRect;
import net.imglib2.Cursor;
import net.imglib2.img.ImgPlus;
import net.imglib2.meta.Axes;
import net.imglib2.ops.Real;
import net.imglib2.ops.UnaryOperation;
import net.imglib2.ops.operation.unary.real.RealConstant;
import net.imglib2.type.numeric.RealType;
/**
* Fills the selected region of an input Dataset with the foreground value.
*
* @author Barry DeZonia
*/
@Plugin(menu = { @Menu(label = "Edit", mnemonic = 'e'),
@Menu(label = "Fill", weight = 28, accelerator = "control F") })
public class FillDataValues implements ImageJPlugin {
// -- instance variables that are Parameters --
@Parameter(required = true, persist = false)
private OverlayService overlayService;
@Parameter(required = true, persist = false)
private ToolService toolService;
@Parameter(required = true, persist = false)
private ImageDisplay display;
@Parameter(required = true, persist = false)
private Dataset dataset;
// -- public interface --
@Override
public void run() {
final FGTool cp = toolService.getTool(FGTool.class);
if (cp == null) return;
if (dataset.isRGBMerged()) {
final ColorRGB color = cp.getFgColor();
fillSelectedRegionWithColor(color);
}
else { // gray data
final double value = cp.getFgValue();
fillSelectedRegionWithValue(value);
}
}
public ImageDisplay getDisplay() {
return display;
}
public void setDisplay(final ImageDisplay display) {
this.display = display;
}
// -- private helpers --
private void fillSelectedRegionWithValue(double value) {
final UnaryOperation<Real, Real> op = new RealConstant(value);
final InplaceUnaryTransform transform =
new InplaceUnaryTransform(display, op);
transform.run();
}
// TODO - make something like this Dataset API maybe. or somewhere else.
private void fillSelectedRegionWithColor(ColorRGB color) {
RealRect bounds = overlayService.getSelectionBounds(display);
long minX = (long) bounds.x;
long minY = (long) bounds.y;
long maxX = (long) (bounds.x + bounds.width - 1);
long maxY = (long) (bounds.y + bounds.height - 1);
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
long[] pos = new long[dataset.numDimensions()];
int xIndex = dataset.getAxisIndex(Axes.X);
int yIndex = dataset.getAxisIndex(Axes.Y);
int chIndex = dataset.getAxisIndex(Axes.CHANNEL);
ImgPlus<? extends RealType<?>> imgPlus = dataset.getImgPlus();
Cursor<? extends RealType<?>> cursor = imgPlus.localizingCursor();
while (cursor.hasNext()) {
RealType<?> pixRef = cursor.next();
cursor.localize(pos);
if ((pos[xIndex] < minX) || (pos[xIndex] > maxX)) continue;
if ((pos[yIndex] < minY) || (pos[yIndex] > maxY)) continue;
if (pos[chIndex] == 0)
pixRef.setReal(r);
else if (pos[chIndex] == 1)
pixRef.setReal(g);
else
pixRef.setReal(b);
}
dataset.update();
}
}
| eliminate dataset parameter
This used to be revision r4500.
| core/plugins/data/src/main/java/imagej/core/plugins/assign/FillDataValues.java | eliminate dataset parameter | <ide><path>ore/plugins/data/src/main/java/imagej/core/plugins/assign/FillDataValues.java
<ide> import imagej.core.tools.FGTool;
<ide> import imagej.data.Dataset;
<ide> import imagej.data.display.ImageDisplay;
<add>import imagej.data.display.ImageDisplayService;
<ide> import imagej.data.display.OverlayService;
<ide> import imagej.ext.plugin.ImageJPlugin;
<ide> import imagej.ext.plugin.Menu;
<ide> private ToolService toolService;
<ide>
<ide> @Parameter(required = true, persist = false)
<add> private ImageDisplayService dispService;
<add>
<add> @Parameter(required = true, persist = false)
<ide> private ImageDisplay display;
<ide>
<del> @Parameter(required = true, persist = false)
<del> private Dataset dataset;
<del>
<ide> // -- public interface --
<ide>
<ide> @Override
<ide> public void run() {
<ide> final FGTool cp = toolService.getTool(FGTool.class);
<ide> if (cp == null) return;
<add> Dataset dataset = dispService.getActiveDataset(display);
<ide> if (dataset.isRGBMerged()) {
<ide> final ColorRGB color = cp.getFgColor();
<del> fillSelectedRegionWithColor(color);
<add> fillSelectedRegionWithColor(dataset, color);
<ide> }
<ide> else { // gray data
<ide> final double value = cp.getFgValue();
<ide>
<ide> // TODO - make something like this Dataset API maybe. or somewhere else.
<ide>
<del> private void fillSelectedRegionWithColor(ColorRGB color) {
<add> private void fillSelectedRegionWithColor(Dataset dataset, ColorRGB color) {
<ide> RealRect bounds = overlayService.getSelectionBounds(display);
<ide> long minX = (long) bounds.x;
<ide> long minY = (long) bounds.y; |
|
JavaScript | mpl-2.0 | 1478dfb148161043bddddb3e5d9bc63012bba757 | 0 | enb-bem/enb-bem-tmpl-specs,enb-bem/enb-bem-tmpl-specs,rndD/enb-bem-tmpl-specs,rndD/enb-bem-tmpl-specs | var path = require('path'),
vfs = require('enb/lib/fs/async-fs'),
readAsset = vfs.read(path.join(__dirname, '..', 'assets', 'tmpl-spec.jst')),
template = require('lodash').template,
htmlDifferFilename = require.resolve('html-differ'),
jsBeautifyFilename = require.resolve('js-beautify');
module.exports = require('enb/lib/build-flow').create()
.name('tmpl-spec')
.target('target', '?.tmpl-spec.js')
.defineRequiredOption('engines')
.defineOption('saveHtml', false)
.useSourceFilename('references', '?.references.js')
.useSourceListFilenames('engineTargets', [])
.needRebuild(function (cache) {
return cache.get('saveHtml') !== this._saveHtml;
})
.saveCache(function (cache) {
cache.set('saveHtml', this._saveHtml);
})
.builder(function (referencesFilename) {
var node = this.node,
nodePath = node.getPath(),
nodeDirname = node.getDir(),
references = require(referencesFilename),
engines = this._engines,
saveHtml = this._saveHtml,
its = [];
Object.keys(references).forEach(function (name) {
var bemjson = references[name].bemjson,
html = references[name].html;
bemjson && html && its.push(name);
});
return readAsset.then(function (asset) {
return template(asset, {
describe: path.basename(nodePath) + ' (' + path.dirname(nodePath) + ')',
its: its,
engines: engines.map(function (engine) {
return {
name: engine.name,
target: node.unmaskTargetName(engine.target),
exportName: engine.exportName
};
}),
paths: {
'html-differ': ['.', path.relative(nodeDirname, htmlDifferFilename)].join(path.sep),
'js-beautify': ['.', path.relative(nodeDirname, jsBeautifyFilename)].join(path.sep)
},
saveHtml: saveHtml
});
});
})
.createTech();
| lib/techs/tmpl-spec.js | var fs = require('fs'),
path = require('path'),
vfs = require('enb/lib/fs/async-fs'),
readAsset = vfs.read(path.join(__dirname, '..', 'assets', 'tmpl-spec.jst')),
template = require('lodash').template,
htmlDifferFilename = require.resolve('html-differ'),
jsBeautifyFilename = require.resolve('js-beautify');
module.exports = require('enb/lib/build-flow').create()
.name('tmpl-spec')
.target('target', '?.tmpl-spec.js')
.defineRequiredOption('engines')
.defineOption('saveHtml', false)
.useSourceFilename('references', '?.references.js')
.useSourceListFilenames('engineTargets', [])
.builder(function (referencesFilename) {
var node = this.node,
nodePath = node.getPath(),
nodeDirname = node.getDir(),
references = require(referencesFilename),
engines = this._engines,
saveHtml = this._saveHtml,
its = [];
Object.keys(references).forEach(function (name) {
var bemjson = references[name].bemjson,
html = references[name].html;
bemjson && html && its.push(name);
});
return readAsset.then(function (asset) {
return template(asset, {
describe: path.basename(nodePath) + ' (' + path.dirname(nodePath) + ')',
its: its,
engines: engines.map(function (engine) {
return {
name: engine.name,
target: node.unmaskTargetName(engine.target),
exportName: engine.exportName
};
}),
paths: {
'html-differ': ['.', path.relative(nodeDirname, htmlDifferFilename)].join(path.sep),
'js-beautify': ['.', path.relative(nodeDirname, jsBeautifyFilename)].join(path.sep)
},
saveHtml: saveHtml
});
});
})
.createTech();
| Fixed cache for `tmpl-spec` tech:
should rebuild if change `saveHtml` option
| lib/techs/tmpl-spec.js | Fixed cache for `tmpl-spec` tech: should rebuild if change `saveHtml` option | <ide><path>ib/techs/tmpl-spec.js
<del>var fs = require('fs'),
<del> path = require('path'),
<add>var path = require('path'),
<ide> vfs = require('enb/lib/fs/async-fs'),
<ide> readAsset = vfs.read(path.join(__dirname, '..', 'assets', 'tmpl-spec.jst')),
<ide> template = require('lodash').template,
<ide> .defineOption('saveHtml', false)
<ide> .useSourceFilename('references', '?.references.js')
<ide> .useSourceListFilenames('engineTargets', [])
<add> .needRebuild(function (cache) {
<add> return cache.get('saveHtml') !== this._saveHtml;
<add> })
<add> .saveCache(function (cache) {
<add> cache.set('saveHtml', this._saveHtml);
<add> })
<ide> .builder(function (referencesFilename) {
<ide> var node = this.node,
<ide> nodePath = node.getPath(), |
|
Java | apache-2.0 | ff177187998fae5e37af7622a201d1cd4d673035 | 0 | lqbweb/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,lburgazzoli/apache-logging-log4j2,lqbweb/logging-log4j2,GFriedrich/logging-log4j2,MagicWiz/log4j2,apache/logging-log4j2,neuro-sys/logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,neuro-sys/logging-log4j2,lburgazzoli/apache-logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,MagicWiz/log4j2,lburgazzoli/logging-log4j2,lburgazzoli/logging-log4j2,codescale/logging-log4j2,lburgazzoli/logging-log4j2 | /*
* 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.logging.log4j.core.impl;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.async.RingBufferLogEvent;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.util.Clock;
import org.apache.logging.log4j.core.util.ClockFactory;
import org.apache.logging.log4j.core.util.DummyNanoClock;
import org.apache.logging.log4j.core.util.NanoClock;
import org.apache.logging.log4j.message.LoggerNameAwareMessage;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.TimestampMessage;
import org.apache.logging.log4j.util.Strings;
/**
* Implementation of a LogEvent.
*/
public class Log4jLogEvent implements LogEvent {
private static final long serialVersionUID = -1351367343806656055L;
private static final Clock CLOCK = ClockFactory.getClock();
private static volatile NanoClock nanoClock = new DummyNanoClock();
private final String loggerFqcn;
private final Marker marker;
private final Level level;
private final String loggerName;
private final Message message;
private final long timeMillis;
private final transient Throwable thrown;
private ThrowableProxy thrownProxy;
private final Map<String, String> contextMap;
private final ThreadContext.ContextStack contextStack;
private String threadName;
private StackTraceElement source;
private boolean includeLocation;
private boolean endOfBatch = false;
/** @since Log4J 2.4 */
private final transient long nanoTime;
/** LogEvent Builder helper class. */
public static class Builder implements org.apache.logging.log4j.core.util.Builder<LogEvent> {
private String loggerFqcn;
private Marker marker;
private Level level;
private String loggerName;
private Message message;
private Throwable thrown;
private long timeMillis = CLOCK.currentTimeMillis();
private ThrowableProxy thrownProxy;
private Map<String, String> contextMap = ThreadContext.getImmutableContext();
private ThreadContext.ContextStack contextStack = ThreadContext.getImmutableStack();
private String threadName = null;
private StackTraceElement source;
private boolean includeLocation;
private boolean endOfBatch = false;
private long nanoTime;
public Builder() {
}
public Builder(LogEvent other) {
Objects.requireNonNull(other);
if (other instanceof RingBufferLogEvent) {
RingBufferLogEvent evt = (RingBufferLogEvent) other;
evt.initializeBuilder(this);
return;
}
this.loggerFqcn = other.getLoggerFqcn();
this.marker = other.getMarker();
this.level = other.getLevel();
this.loggerName = other.getLoggerName();
this.message = other.getMessage();
this.timeMillis = other.getTimeMillis();
this.thrown = other.getThrown();
this.contextMap = other.getContextMap();
this.contextStack = other.getContextStack();
this.includeLocation = other.isIncludeLocation();
this.endOfBatch = other.isEndOfBatch();
this.nanoTime = other.getNanoTime();
// Avoid unnecessarily initializing thrownProxy, threadName and source if possible
if (other instanceof Log4jLogEvent) {
Log4jLogEvent evt = (Log4jLogEvent) other;
this.thrownProxy = evt.thrownProxy;
this.source = evt.source;
this.threadName = evt.threadName;
} else {
this.thrownProxy = other.getThrownProxy();
this.source = other.getSource();
this.threadName = other.getThreadName();
}
}
public Builder setLevel(final Level level) {
this.level = level;
return this;
}
public Builder setLoggerFqcn(final String loggerFqcn) {
this.loggerFqcn = loggerFqcn;
return this;
}
public Builder setLoggerName(final String loggerName) {
this.loggerName = loggerName;
return this;
}
public Builder setMarker(final Marker marker) {
this.marker = marker;
return this;
}
public Builder setMessage(final Message message) {
this.message = message;
return this;
}
public Builder setThrown(final Throwable thrown) {
this.thrown = thrown;
return this;
}
public Builder setTimeMillis(long timeMillis) {
this.timeMillis = timeMillis;
return this;
}
public Builder setThrownProxy(ThrowableProxy thrownProxy) {
this.thrownProxy = thrownProxy;
return this;
}
public Builder setContextMap(Map<String, String> contextMap) {
this.contextMap = contextMap;
return this;
}
public Builder setContextStack(ThreadContext.ContextStack contextStack) {
this.contextStack = contextStack;
return this;
}
public Builder setThreadName(String threadName) {
this.threadName = threadName;
return this;
}
public Builder setSource(StackTraceElement source) {
this.source = source;
return this;
}
public Builder setIncludeLocation(boolean includeLocation) {
this.includeLocation = includeLocation;
return this;
}
public Builder setEndOfBatch(boolean endOfBatch) {
this.endOfBatch = endOfBatch;
return this;
}
/**
* Sets the nano time for the event.
* @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event
* was created.
* @return this builder
*/
public Builder setNanoTime(long nanoTime) {
this.nanoTime = nanoTime;
return this;
}
@Override
public Log4jLogEvent build() {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFqcn, level, message, thrown,
thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime);
result.setIncludeLocation(includeLocation);
result.setEndOfBatch(endOfBatch);
return result;
}
}
/**
* Returns a new empty {@code Log4jLogEvent.Builder} with all fields empty.
* @return a new empty builder.
*/
public static Builder newBuilder() {
return new Builder();
}
public Log4jLogEvent() {
this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null,
CLOCK.currentTimeMillis(), nanoClock.nanoTime());
}
/**
*
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final long timestamp) {
this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null,
timestamp, nanoClock.nanoTime());
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param t A Throwable or null.
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable t) {
this(loggerName, marker, loggerFQCN, level, message, null, t);
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param properties properties to add to the event.
* @param t A Throwable or null.
*/
// This constructor is called from LogEventFactories.
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final List<Property> properties, final Throwable t) {
this(loggerName, marker, loggerFQCN, level, message, t, null,
createMap(properties),
ThreadContext.getDepth() == 0 ? null : ThreadContext.cloneStack(), // mutable copy
null, // thread name
null, // stack trace element
// LOG4J2-628 use log4j.Clock for timestamps
// LOG4J2-744 unless TimestampMessage already has one
message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() :
CLOCK.currentTimeMillis(),
nanoClock.nanoTime());
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param t A Throwable or null.
* @param mdc The mapped diagnostic context.
* @param ndc the nested diagnostic context.
* @param threadName The name of the thread.
* @param location The locations of the caller.
* @param timestampMillis The timestamp of the event.
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable t, final Map<String, String> mdc,
final ThreadContext.ContextStack ndc, final String threadName,
final StackTraceElement location, final long timestampMillis) {
this(loggerName, marker, loggerFQCN, level, message, t, null, mdc, ndc, threadName,
location, timestampMillis, nanoClock.nanoTime());
}
/**
* Create a new LogEvent.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param thrown A Throwable or null.
* @param thrownProxy A ThrowableProxy or null.
* @param mdc The mapped diagnostic context.
* @param ndc the nested diagnostic context.
* @param threadName The name of the thread.
* @param location The locations of the caller.
* @param timestamp The timestamp of the event.
* @return a new LogEvent
* @deprecated use {@link Log4jLogEvent.Builder} instead. This method will be removed in an upcoming release.
*/
@Deprecated
public static Log4jLogEvent createEvent(final String loggerName, final Marker marker, final String loggerFQCN,
final Level level, final Message message, final Throwable thrown,
final ThrowableProxy thrownProxy,
final Map<String, String> mdc, final ThreadContext.ContextStack ndc,
final String threadName, final StackTraceElement location,
final long timestamp) {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown,
thrownProxy, mdc, ndc, threadName, location, timestamp, nanoClock.nanoTime());
return result;
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param thrown A Throwable or null.
* @param thrownProxy A ThrowableProxy or null.
* @param contextMap The mapped diagnostic context.
* @param contextStack the nested diagnostic context.
* @param threadName The name of the thread.
* @param source The locations of the caller.
* @param timestamp The timestamp of the event.
* @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event was
* created.
*/
private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable thrown, final ThrowableProxy thrownProxy,
final Map<String, String> contextMap, final ThreadContext.ContextStack contextStack,
final String threadName, final StackTraceElement source, final long timestampMillis, final long nanoTime) {
this.loggerName = loggerName;
this.marker = marker;
this.loggerFqcn = loggerFQCN;
this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465
this.message = message;
this.thrown = thrown;
this.thrownProxy = thrownProxy;
this.contextMap = contextMap == null ? ThreadContext.EMPTY_MAP : contextMap;
this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack;
this.timeMillis = message instanceof TimestampMessage
? ((TimestampMessage) message).getTimestamp()
: timestampMillis;
this.threadName = threadName;
this.source = source;
if (message != null && message instanceof LoggerNameAwareMessage) {
((LoggerNameAwareMessage) message).setLoggerName(loggerName);
}
this.nanoTime = nanoTime;
}
private static Map<String, String> createMap(final List<Property> properties) {
final Map<String, String> contextMap = ThreadContext.getImmutableContext();
if (properties == null || properties.isEmpty()) {
return contextMap; // may be ThreadContext.EMPTY_MAP but not null
}
final Map<String, String> map = new HashMap<>(contextMap);
for (final Property prop : properties) {
if (!map.containsKey(prop.getName())) {
map.put(prop.getName(), prop.getValue());
}
}
return Collections.unmodifiableMap(map);
}
/**
* Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events.
* @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events
*/
public static NanoClock getNanoClock() {
return nanoClock;
}
/**
* Sets the {@code NanoClock} to use for creating the nanoTime timestamp of log events.
* <p>
* FOR INTERNAL USE. This method may be called with a different {@code NanoClock} implementation when the
* configuration changes.
*
* @param nanoClock the {@code NanoClock} to use for creating the nanoTime timestamp of log events
*/
public static void setNanoClock(NanoClock nanoClock) {
Log4jLogEvent.nanoClock = Objects.requireNonNull(nanoClock, "NanoClock must be non-null");
}
/**
* Returns a new fully initialized {@code Log4jLogEvent.Builder} containing a copy of all fields of this event.
* @return a new fully initialized builder.
*/
public Builder asBuilder() {
return new Builder(this);
}
/**
* Returns the logging Level.
* @return the Level associated with this event.
*/
@Override
public Level getLevel() {
return level;
}
/**
* Returns the name of the Logger used to generate the event.
* @return The Logger name.
*/
@Override
public String getLoggerName() {
return loggerName;
}
/**
* Returns the Message associated with the event.
* @return The Message.
*/
@Override
public Message getMessage() {
return message;
}
/**
* Returns the name of the Thread on which the event was generated.
* @return The name of the Thread.
*/
@Override
public String getThreadName() {
if (threadName == null) {
threadName = Thread.currentThread().getName();
}
return threadName;
}
/**
* Returns the time in milliseconds from the epoch when the event occurred.
* @return The time the event occurred.
*/
@Override
public long getTimeMillis() {
return timeMillis;
}
/**
* Returns the Throwable associated with the event, or null.
* @return The Throwable associated with the event.
*/
@Override
public Throwable getThrown() {
return thrown;
}
/**
* Returns the ThrowableProxy associated with the event, or null.
* @return The ThrowableProxy associated with the event.
*/
@Override
public ThrowableProxy getThrownProxy() {
if (thrownProxy == null && thrown != null) {
thrownProxy = new ThrowableProxy(thrown);
}
return thrownProxy;
}
/**
* Returns the Marker associated with the event, or null.
* @return the Marker associated with the event.
*/
@Override
public Marker getMarker() {
return marker;
}
/**
* The fully qualified class name of the class that was called by the caller.
* @return the fully qualified class name of the class that is performing logging.
*/
@Override
public String getLoggerFqcn() {
return loggerFqcn;
}
/**
* Returns the immutable copy of the ThreadContext Map.
* @return The context Map.
*/
@Override
public Map<String, String> getContextMap() {
return contextMap;
}
/**
* Returns an immutable copy of the ThreadContext stack.
* @return The context Stack.
*/
@Override
public ThreadContext.ContextStack getContextStack() {
return contextStack;
}
/**
* Returns the StackTraceElement for the caller. This will be the entry that occurs right
* before the first occurrence of FQCN as a class name.
* @return the StackTraceElement for the caller.
*/
@Override
public StackTraceElement getSource() {
if (source != null) {
return source;
}
if (loggerFqcn == null || !includeLocation) {
return null;
}
source = calcLocation(loggerFqcn);
return source;
}
public static StackTraceElement calcLocation(final String fqcnOfLogger) {
if (fqcnOfLogger == null) {
return null;
}
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement last = null;
for (int i = stackTrace.length - 1; i > 0; i--) {
final String className = stackTrace[i].getClassName();
if (fqcnOfLogger.equals(className)) {
return last;
}
last = stackTrace[i];
}
return null;
}
@Override
public boolean isIncludeLocation() {
return includeLocation;
}
@Override
public void setIncludeLocation(final boolean includeLocation) {
this.includeLocation = includeLocation;
}
@Override
public boolean isEndOfBatch() {
return endOfBatch;
}
@Override
public void setEndOfBatch(final boolean endOfBatch) {
this.endOfBatch = endOfBatch;
}
@Override
public long getNanoTime() {
return nanoTime;
}
/**
* Creates a LogEventProxy that can be serialized.
* @return a LogEventProxy.
*/
protected Object writeReplace() {
getThrownProxy(); // ensure ThrowableProxy is initialized
return new LogEventProxy(this, this.includeLocation);
}
public static Serializable serialize(final Log4jLogEvent event,
final boolean includeLocation) {
event.getThrownProxy(); // ensure ThrowableProxy is initialized
return new LogEventProxy(event, includeLocation);
}
public static boolean canDeserialize(final Serializable event) {
return event instanceof LogEventProxy;
}
public static Log4jLogEvent deserialize(final Serializable event) {
Objects.requireNonNull(event, "Event cannot be null");
if (event instanceof LogEventProxy) {
final LogEventProxy proxy = (LogEventProxy) event;
final Log4jLogEvent result = new Log4jLogEvent(proxy.loggerName, proxy.marker,
proxy.loggerFQCN, proxy.level, proxy.message,
proxy.thrown, proxy.thrownProxy, proxy.contextMap, proxy.contextStack, proxy.threadName,
proxy.source, proxy.timeMillis, proxy.nanoTime);
result.setEndOfBatch(proxy.isEndOfBatch);
result.setIncludeLocation(proxy.isLocationRequired);
return result;
}
throw new IllegalArgumentException("Event is not a serialized LogEvent: " + event.toString());
}
private void readObject(final ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
final String n = loggerName.isEmpty() ? "root" : loggerName;
sb.append("Logger=").append(n);
sb.append(" Level=").append(level.name());
sb.append(" Message=").append(message.getFormattedMessage());
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Log4jLogEvent that = (Log4jLogEvent) o;
if (endOfBatch != that.endOfBatch) {
return false;
}
if (includeLocation != that.includeLocation) {
return false;
}
if (timeMillis != that.timeMillis) {
return false;
}
if (nanoTime != that.nanoTime) {
return false;
}
if (loggerFqcn != null ? !loggerFqcn.equals(that.loggerFqcn) : that.loggerFqcn != null) {
return false;
}
if (level != null ? !level.equals(that.level) : that.level != null) {
return false;
}
if (source != null ? !source.equals(that.source) : that.source != null) {
return false;
}
if (marker != null ? !marker.equals(that.marker) : that.marker != null) {
return false;
}
if (contextMap != null ? !contextMap.equals(that.contextMap) : that.contextMap != null) {
return false;
}
if (!message.equals(that.message)) {
return false;
}
if (!loggerName.equals(that.loggerName)) {
return false;
}
if (contextStack != null ? !contextStack.equals(that.contextStack) : that.contextStack != null) {
return false;
}
if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) {
return false;
}
if (thrown != null ? !thrown.equals(that.thrown) : that.thrown != null) {
return false;
}
if (thrownProxy != null ? !thrownProxy.equals(that.thrownProxy) : that.thrownProxy != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
// Check:OFF: MagicNumber
int result = loggerFqcn != null ? loggerFqcn.hashCode() : 0;
result = 31 * result + (marker != null ? marker.hashCode() : 0);
result = 31 * result + (level != null ? level.hashCode() : 0);
result = 31 * result + loggerName.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (int) (timeMillis ^ (timeMillis >>> 32));
result = 31 * result + (int) (nanoTime ^ (nanoTime >>> 32));
result = 31 * result + (thrown != null ? thrown.hashCode() : 0);
result = 31 * result + (thrownProxy != null ? thrownProxy.hashCode() : 0);
result = 31 * result + (contextMap != null ? contextMap.hashCode() : 0);
result = 31 * result + (contextStack != null ? contextStack.hashCode() : 0);
result = 31 * result + (threadName != null ? threadName.hashCode() : 0);
result = 31 * result + (source != null ? source.hashCode() : 0);
result = 31 * result + (includeLocation ? 1 : 0);
result = 31 * result + (endOfBatch ? 1 : 0);
// Check:ON: MagicNumber
return result;
}
/**
* Proxy pattern used to serialize the LogEvent.
*/
private static class LogEventProxy implements Serializable {
private static final long serialVersionUID = -7139032940312647146L;
private final String loggerFQCN;
private final Marker marker;
private final Level level;
private final String loggerName;
private final Message message;
private final long timeMillis;
private final transient Throwable thrown;
private final ThrowableProxy thrownProxy;
private final Map<String, String> contextMap;
private final ThreadContext.ContextStack contextStack;
private final String threadName;
private final StackTraceElement source;
private final boolean isLocationRequired;
private final boolean isEndOfBatch;
/** @since Log4J 2.4 */
private final transient long nanoTime;
public LogEventProxy(final Log4jLogEvent event, final boolean includeLocation) {
this.loggerFQCN = event.loggerFqcn;
this.marker = event.marker;
this.level = event.level;
this.loggerName = event.loggerName;
this.message = event.message;
this.timeMillis = event.timeMillis;
this.thrown = event.thrown;
this.thrownProxy = event.thrownProxy;
this.contextMap = event.contextMap;
this.contextStack = event.contextStack;
this.source = includeLocation ? event.getSource() : null;
this.threadName = event.getThreadName();
this.isLocationRequired = includeLocation;
this.isEndOfBatch = event.endOfBatch;
this.nanoTime = event.nanoTime;
}
/**
* Returns a Log4jLogEvent using the data in the proxy.
* @return Log4jLogEvent.
*/
protected Object readResolve() {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown,
thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime);
result.setEndOfBatch(isEndOfBatch);
result.setIncludeLocation(isLocationRequired);
return result;
}
}
}
| log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.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.logging.log4j.core.impl;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.async.RingBufferLogEvent;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.util.Clock;
import org.apache.logging.log4j.core.util.ClockFactory;
import org.apache.logging.log4j.core.util.DummyNanoClock;
import org.apache.logging.log4j.core.util.NanoClock;
import org.apache.logging.log4j.message.LoggerNameAwareMessage;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.TimestampMessage;
import org.apache.logging.log4j.util.Strings;
/**
* Implementation of a LogEvent.
*/
public class Log4jLogEvent implements LogEvent {
private static final long serialVersionUID = -1351367343806656055L;
private static final Clock CLOCK = ClockFactory.getClock();
private static volatile NanoClock nanoClock = new DummyNanoClock();
private final String loggerFqcn;
private final Marker marker;
private final Level level;
private final String loggerName;
private final Message message;
private final long timeMillis;
private final transient Throwable thrown;
private ThrowableProxy thrownProxy;
private final Map<String, String> contextMap;
private final ThreadContext.ContextStack contextStack;
private String threadName;
private StackTraceElement source;
private boolean includeLocation;
private boolean endOfBatch = false;
/** @since Log4J 2.4 */
private final transient long nanoTime;
/** LogEvent Builder helper class. */
public static class Builder implements org.apache.logging.log4j.core.util.Builder<LogEvent> {
private String loggerFqcn;
private Marker marker;
private Level level;
private String loggerName;
private Message message;
private Throwable thrown;
private long timeMillis = CLOCK.currentTimeMillis();
private ThrowableProxy thrownProxy;
private Map<String, String> contextMap = ThreadContext.getImmutableContext();
private ThreadContext.ContextStack contextStack = ThreadContext.getImmutableStack();
private String threadName = null;
private StackTraceElement source;
private boolean includeLocation;
private boolean endOfBatch = false;
private long nanoTime;
public Builder() {
}
public Builder(LogEvent other) {
Objects.requireNonNull(other);
if (other instanceof RingBufferLogEvent) {
RingBufferLogEvent evt = (RingBufferLogEvent) other;
evt.initializeBuilder(this);
return;
}
this.loggerFqcn = other.getLoggerFqcn();
this.marker = other.getMarker();
this.level = other.getLevel();
this.loggerName = other.getLoggerName();
this.message = other.getMessage();
this.timeMillis = other.getTimeMillis();
this.thrown = other.getThrown();
this.contextMap = other.getContextMap();
this.contextStack = other.getContextStack();
this.includeLocation = other.isIncludeLocation();
this.endOfBatch = other.isEndOfBatch();
this.nanoTime = other.getNanoTime();
// Avoid unnecessarily initializing thrownProxy, threadName and source if possible
if (other instanceof Log4jLogEvent) {
Log4jLogEvent evt = (Log4jLogEvent) other;
this.thrownProxy = evt.thrownProxy;
this.source = evt.source;
this.threadName = evt.threadName;
} else {
this.thrownProxy = other.getThrownProxy();
this.source = other.getSource();
this.threadName = other.getThreadName();
}
}
public Builder setLevel(final Level level) {
this.level = level;
return this;
}
public Builder setLoggerFqcn(final String loggerFqcn) {
this.loggerFqcn = loggerFqcn;
return this;
}
public Builder setLoggerName(final String loggerName) {
this.loggerName = loggerName;
return this;
}
public Builder setMarker(final Marker marker) {
this.marker = marker;
return this;
}
public Builder setMessage(final Message message) {
this.message = message;
return this;
}
public Builder setThrown(final Throwable thrown) {
this.thrown = thrown;
return this;
}
public Builder setTimeMillis(long timeMillis) {
this.timeMillis = timeMillis;
return this;
}
public Builder setThrownProxy(ThrowableProxy thrownProxy) {
this.thrownProxy = thrownProxy;
return this;
}
public Builder setContextMap(Map<String, String> contextMap) {
this.contextMap = contextMap;
return this;
}
public Builder setContextStack(ThreadContext.ContextStack contextStack) {
this.contextStack = contextStack;
return this;
}
public Builder setThreadName(String threadName) {
this.threadName = threadName;
return this;
}
public Builder setSource(StackTraceElement source) {
this.source = source;
return this;
}
public Builder setIncludeLocation(boolean includeLocation) {
this.includeLocation = includeLocation;
return this;
}
public Builder setEndOfBatch(boolean endOfBatch) {
this.endOfBatch = endOfBatch;
return this;
}
/**
* Sets the nano time for the event.
* @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event
* was created.
* @return this builder
*/
public Builder setNanoTime(long nanoTime) {
this.nanoTime = nanoTime;
return this;
}
@Override
public Log4jLogEvent build() {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFqcn, level, message, thrown,
thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime);
result.setIncludeLocation(includeLocation);
result.setEndOfBatch(endOfBatch);
return result;
}
}
/**
* Returns a new empty {@code Log4jLogEvent.Builder} with all fields empty.
* @return a new empty builder.
*/
public static Builder newBuilder() {
return new Builder();
}
public Log4jLogEvent() {
this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null,
CLOCK.currentTimeMillis(), nanoClock.nanoTime());
}
/**
*
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final long timestamp) {
this(Strings.EMPTY, null, Strings.EMPTY, null, null, (Throwable) null, null, null, null, null, null,
timestamp, nanoClock.nanoTime());
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param t A Throwable or null.
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable t) {
this(loggerName, marker, loggerFQCN, level, message, null, t);
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param properties properties to add to the event.
* @param t A Throwable or null.
*/
// This constructor is called from LogEventFactories.
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final List<Property> properties, final Throwable t) {
this(loggerName, marker, loggerFQCN, level, message, t, null,
createMap(properties),
ThreadContext.getDepth() == 0 ? null : ThreadContext.cloneStack(), // mutable copy
null, // thread name
null, // stack trace element
// LOG4J2-628 use log4j.Clock for timestamps
// LOG4J2-744 unless TimestampMessage already has one
message instanceof TimestampMessage ? ((TimestampMessage) message).getTimestamp() :
CLOCK.currentTimeMillis(),
nanoClock.nanoTime());
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param t A Throwable or null.
* @param mdc The mapped diagnostic context.
* @param ndc the nested diagnostic context.
* @param threadName The name of the thread.
* @param location The locations of the caller.
* @param timestampMillis The timestamp of the event.
* @deprecated use {@link Log4jLogEvent.Builder} instead. This constructor will be removed in an upcoming release.
*/
@Deprecated
public Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable t, final Map<String, String> mdc,
final ThreadContext.ContextStack ndc, final String threadName,
final StackTraceElement location, final long timestampMillis) {
this(loggerName, marker, loggerFQCN, level, message, t, null, mdc, ndc, threadName,
location, timestampMillis, nanoClock.nanoTime());
}
/**
* Create a new LogEvent.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param thrown A Throwable or null.
* @param thrownProxy A ThrowableProxy or null.
* @param mdc The mapped diagnostic context.
* @param ndc the nested diagnostic context.
* @param threadName The name of the thread.
* @param location The locations of the caller.
* @param timestamp The timestamp of the event.
* @return a new LogEvent
* @deprecated use {@link Log4jLogEvent.Builder} instead. This method will be removed in an upcoming release.
*/
@Deprecated
public static Log4jLogEvent createEvent(final String loggerName, final Marker marker, final String loggerFQCN,
final Level level, final Message message, final Throwable thrown,
final ThrowableProxy thrownProxy,
final Map<String, String> mdc, final ThreadContext.ContextStack ndc,
final String threadName, final StackTraceElement location,
final long timestamp) {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown,
thrownProxy, mdc, ndc, threadName, location, timestamp, nanoClock.nanoTime());
return result;
}
/**
* Constructor.
* @param loggerName The name of the Logger.
* @param marker The Marker or null.
* @param loggerFQCN The fully qualified class name of the caller.
* @param level The logging Level.
* @param message The Message.
* @param thrown A Throwable or null.
* @param thrownProxy A ThrowableProxy or null.
* @param contextMap The mapped diagnostic context.
* @param contextStack the nested diagnostic context.
* @param threadName The name of the thread.
* @param source The locations of the caller.
* @param timestamp The timestamp of the event.
* @param nanoTime The value of the running Java Virtual Machine's high-resolution time source when the event was
* created.
*/
private Log4jLogEvent(final String loggerName, final Marker marker, final String loggerFQCN, final Level level,
final Message message, final Throwable thrown, final ThrowableProxy thrownProxy,
final Map<String, String> contextMap, final ThreadContext.ContextStack contextStack,
final String threadName, final StackTraceElement source, final long timestampMillis, final long nanoTime) {
this.loggerName = loggerName;
this.marker = marker;
this.loggerFqcn = loggerFQCN;
this.level = (level == null) ? Level.OFF : level; // LOG4J2-462, LOG4J2-465
this.message = message;
this.thrown = thrown;
this.thrownProxy = thrownProxy;
this.contextMap = contextMap == null ? ThreadContext.EMPTY_MAP : contextMap;
this.contextStack = contextStack == null ? ThreadContext.EMPTY_STACK : contextStack;
this.timeMillis = message instanceof TimestampMessage
? ((TimestampMessage) message).getTimestamp()
: timestampMillis;
this.threadName = threadName;
this.source = source;
if (message != null && message instanceof LoggerNameAwareMessage) {
((LoggerNameAwareMessage) message).setLoggerName(loggerName);
}
this.nanoTime = nanoTime;
}
private static Map<String, String> createMap(final List<Property> properties) {
final Map<String, String> contextMap = ThreadContext.getImmutableContext();
if (properties == null || properties.isEmpty()) {
return contextMap; // may be ThreadContext.EMPTY_MAP but not null
}
final Map<String, String> map = new HashMap<>(contextMap);
for (final Property prop : properties) {
if (!map.containsKey(prop.getName())) {
map.put(prop.getName(), prop.getValue());
}
}
return Collections.unmodifiableMap(map);
}
/**
* Returns the {@code NanoClock} to use for creating the nanoTime timestamp of log events.
* @return the {@code NanoClock} to use for creating the nanoTime timestamp of log events
*/
public static NanoClock getNanoClock() {
return nanoClock;
}
/**
* Sets the {@code NanoClock} to use for creating the nanoTime timestamp of log events.
* <p>
* FOR INTERNAL USE. This method may be called with a different {@code NanoClock} implementation when the
* configuration changes.
*
* @param nanoClock the {@code NanoClock} to use for creating the nanoTime timestamp of log events
*/
public static void setNanoClock(NanoClock nanoClock) {
Log4jLogEvent.nanoClock = Objects.requireNonNull(nanoClock, "NanoClock must be non-null");
}
/**
* Returns a new fully initialized {@code Log4jLogEvent.Builder} containing a copy of all fields of this event.
* @return a new fully initialized builder.
*/
public Builder asBuilder() {
return new Builder(this);
}
/**
* Returns the logging Level.
* @return the Level associated with this event.
*/
@Override
public Level getLevel() {
return level;
}
/**
* Returns the name of the Logger used to generate the event.
* @return The Logger name.
*/
@Override
public String getLoggerName() {
return loggerName;
}
/**
* Returns the Message associated with the event.
* @return The Message.
*/
@Override
public Message getMessage() {
return message;
}
/**
* Returns the name of the Thread on which the event was generated.
* @return The name of the Thread.
*/
@Override
public String getThreadName() {
if (threadName == null) {
threadName = Thread.currentThread().getName();
}
return threadName;
}
/**
* Returns the time in milliseconds from the epoch when the event occurred.
* @return The time the event occurred.
*/
@Override
public long getTimeMillis() {
return timeMillis;
}
/**
* Returns the Throwable associated with the event, or null.
* @return The Throwable associated with the event.
*/
@Override
public Throwable getThrown() {
return thrown;
}
/**
* Returns the ThrowableProxy associated with the event, or null.
* @return The ThrowableProxy associated with the event.
*/
@Override
public ThrowableProxy getThrownProxy() {
if (thrownProxy == null && thrown != null) {
thrownProxy = new ThrowableProxy(thrown);
}
return thrownProxy;
}
/**
* Returns the Marker associated with the event, or null.
* @return the Marker associated with the event.
*/
@Override
public Marker getMarker() {
return marker;
}
/**
* The fully qualified class name of the class that was called by the caller.
* @return the fully qualified class name of the class that is performing logging.
*/
@Override
public String getLoggerFqcn() {
return loggerFqcn;
}
/**
* Returns the immutable copy of the ThreadContext Map.
* @return The context Map.
*/
@Override
public Map<String, String> getContextMap() {
return contextMap;
}
/**
* Returns an immutable copy of the ThreadContext stack.
* @return The context Stack.
*/
@Override
public ThreadContext.ContextStack getContextStack() {
return contextStack;
}
/**
* Returns the StackTraceElement for the caller. This will be the entry that occurs right
* before the first occurrence of FQCN as a class name.
* @return the StackTraceElement for the caller.
*/
@Override
public StackTraceElement getSource() {
if (source != null) {
return source;
}
if (loggerFqcn == null || !includeLocation) {
return null;
}
source = calcLocation(loggerFqcn);
return source;
}
public static StackTraceElement calcLocation(final String fqcnOfLogger) {
if (fqcnOfLogger == null) {
return null;
}
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement last = null;
for (int i = stackTrace.length - 1; i > 0; i--) {
final String className = stackTrace[i].getClassName();
if (fqcnOfLogger.equals(className)) {
return last;
}
last = stackTrace[i];
}
return null;
}
@Override
public boolean isIncludeLocation() {
return includeLocation;
}
@Override
public void setIncludeLocation(final boolean includeLocation) {
this.includeLocation = includeLocation;
}
@Override
public boolean isEndOfBatch() {
return endOfBatch;
}
@Override
public void setEndOfBatch(final boolean endOfBatch) {
this.endOfBatch = endOfBatch;
}
@Override
public long getNanoTime() {
return nanoTime;
}
/**
* Creates a LogEventProxy that can be serialized.
* @return a LogEventProxy.
*/
protected Object writeReplace() {
getThrownProxy(); // ensure ThrowableProxy is initialized
return new LogEventProxy(this, this.includeLocation);
}
public static Serializable serialize(final Log4jLogEvent event,
final boolean includeLocation) {
event.getThrownProxy(); // ensure ThrowableProxy is initialized
return new LogEventProxy(event, includeLocation);
}
public static boolean canDeserialize(final Serializable event) {
return event instanceof LogEventProxy;
}
public static Log4jLogEvent deserialize(final Serializable event) {
Objects.requireNonNull(event, "Event cannot be null");
if (event instanceof LogEventProxy) {
final LogEventProxy proxy = (LogEventProxy) event;
final Log4jLogEvent result = new Log4jLogEvent(proxy.loggerName, proxy.marker,
proxy.loggerFQCN, proxy.level, proxy.message,
proxy.thrown, proxy.thrownProxy, proxy.contextMap, proxy.contextStack, proxy.threadName,
proxy.source, proxy.timeMillis, proxy.nanoTime);
result.setEndOfBatch(proxy.isEndOfBatch);
result.setIncludeLocation(proxy.isLocationRequired);
return result;
}
throw new IllegalArgumentException("Event is not a serialized LogEvent: " + event.toString());
}
private void readObject(final ObjectInputStream stream) throws InvalidObjectException {
throw new InvalidObjectException("Proxy required");
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
final String n = loggerName.isEmpty() ? "root" : loggerName;
sb.append("Logger=").append(n);
sb.append(" Level=").append(level.name());
sb.append(" Message=").append(message.getFormattedMessage());
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Log4jLogEvent that = (Log4jLogEvent) o;
if (endOfBatch != that.endOfBatch) {
return false;
}
if (includeLocation != that.includeLocation) {
return false;
}
if (timeMillis != that.timeMillis) {
return false;
}
if (nanoTime != that.nanoTime) {
return false;
}
if (loggerFqcn != null ? !loggerFqcn.equals(that.loggerFqcn) : that.loggerFqcn != null) {
return false;
}
if (level != null ? !level.equals(that.level) : that.level != null) {
return false;
}
if (source != null ? !source.equals(that.source) : that.source != null) {
return false;
}
if (marker != null ? !marker.equals(that.marker) : that.marker != null) {
return false;
}
if (contextMap != null ? !contextMap.equals(that.contextMap) : that.contextMap != null) {
return false;
}
if (!message.equals(that.message)) {
return false;
}
if (!loggerName.equals(that.loggerName)) {
return false;
}
if (contextStack != null ? !contextStack.equals(that.contextStack) : that.contextStack != null) {
return false;
}
if (threadName != null ? !threadName.equals(that.threadName) : that.threadName != null) {
return false;
}
if (thrown != null ? !thrown.equals(that.thrown) : that.thrown != null) {
return false;
}
if (thrownProxy != null ? !thrownProxy.equals(that.thrownProxy) : that.thrownProxy != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
// Check:OFF: MagicNumber
int result = loggerFqcn != null ? loggerFqcn.hashCode() : 0;
result = 31 * result + (marker != null ? marker.hashCode() : 0);
result = 31 * result + (level != null ? level.hashCode() : 0);
result = 31 * result + loggerName.hashCode();
result = 31 * result + message.hashCode();
result = 31 * result + (int) (timeMillis ^ (timeMillis >>> 32));
result = 31 * result + (int) (nanoTime ^ (nanoTime >>> 32));
result = 31 * result + (thrown != null ? thrown.hashCode() : 0);
result = 31 * result + (thrownProxy != null ? thrownProxy.hashCode() : 0);
result = 31 * result + (contextMap != null ? contextMap.hashCode() : 0);
result = 31 * result + (contextStack != null ? contextStack.hashCode() : 0);
result = 31 * result + (threadName != null ? threadName.hashCode() : 0);
result = 31 * result + (source != null ? source.hashCode() : 0);
result = 31 * result + (includeLocation ? 1 : 0);
result = 31 * result + (endOfBatch ? 1 : 0);
// Check:ON: MagicNumber
return result;
}
/**
* Proxy pattern used to serialize the LogEvent.
*/
private static class LogEventProxy implements Serializable {
private static final long serialVersionUID = -7139032940312647146L;
private final String loggerFQCN;
private final Marker marker;
private final Level level;
private final String loggerName;
private final Message message;
private final long timeMillis;
private final transient Throwable thrown;
private final ThrowableProxy thrownProxy;
private final Map<String, String> contextMap;
private final ThreadContext.ContextStack contextStack;
private final String threadName;
private final StackTraceElement source;
private final boolean isLocationRequired;
private final boolean isEndOfBatch;
/** @since Log4J 2.4 */
private final transient long nanoTime;
public LogEventProxy(final Log4jLogEvent event, final boolean includeLocation) {
this.loggerFQCN = event.loggerFqcn;
this.marker = event.marker;
this.level = event.level;
this.loggerName = event.loggerName;
this.message = event.message;
this.timeMillis = event.timeMillis;
this.thrown = event.thrown;
this.thrownProxy = event.thrownProxy;
this.contextMap = event.contextMap;
this.contextStack = event.contextStack;
this.source = includeLocation ? event.getSource() : null;
this.threadName = event.getThreadName();
this.isLocationRequired = includeLocation;
this.isEndOfBatch = event.endOfBatch;
this.nanoTime = event.nanoTime;
}
/**
* Returns a Log4jLogEvent using the data in the proxy.
* @return Log4jLogEvent.
*/
protected Object readResolve() {
final Log4jLogEvent result = new Log4jLogEvent(loggerName, marker, loggerFQCN, level, message, thrown,
thrownProxy, contextMap, contextStack, threadName, source, timeMillis, nanoTime);
result.setEndOfBatch(isEndOfBatch);
result.setIncludeLocation(isLocationRequired);
return result;
}
}
}
| Remove unnecessary parens. | log4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java | Remove unnecessary parens. | <ide><path>og4j-core/src/main/java/org/apache/logging/log4j/core/impl/Log4jLogEvent.java
<ide> this.loggerName = loggerName;
<ide> this.marker = marker;
<ide> this.loggerFqcn = loggerFQCN;
<del> this.level = (level == null) ? Level.OFF : level; // LOG4J2-462, LOG4J2-465
<add> this.level = level == null ? Level.OFF : level; // LOG4J2-462, LOG4J2-465
<ide> this.message = message;
<ide> this.thrown = thrown;
<ide> this.thrownProxy = thrownProxy; |
|
Java | apache-2.0 | 5394065ba44963f0350e756fe8307221a08f6904 | 0 | brettwooldridge/buck,brettwooldridge/buck,rmaz/buck,zpao/buck,facebook/buck,rmaz/buck,romanoid/buck,zpao/buck,Addepar/buck,romanoid/buck,romanoid/buck,zpao/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,romanoid/buck,brettwooldridge/buck,JoelMarcey/buck,SeleniumHQ/buck,clonetwin26/buck,LegNeato/buck,JoelMarcey/buck,facebook/buck,romanoid/buck,brettwooldridge/buck,nguyentruongtho/buck,shs96c/buck,kageiit/buck,kageiit/buck,shs96c/buck,Addepar/buck,Addepar/buck,JoelMarcey/buck,LegNeato/buck,clonetwin26/buck,SeleniumHQ/buck,shs96c/buck,Addepar/buck,facebook/buck,shs96c/buck,shs96c/buck,JoelMarcey/buck,romanoid/buck,ilya-klyuchnikov/buck,rmaz/buck,clonetwin26/buck,facebook/buck,shs96c/buck,Addepar/buck,brettwooldridge/buck,clonetwin26/buck,ilya-klyuchnikov/buck,shs96c/buck,ilya-klyuchnikov/buck,LegNeato/buck,shs96c/buck,LegNeato/buck,LegNeato/buck,clonetwin26/buck,brettwooldridge/buck,Addepar/buck,facebook/buck,clonetwin26/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,rmaz/buck,LegNeato/buck,ilya-klyuchnikov/buck,rmaz/buck,LegNeato/buck,brettwooldridge/buck,JoelMarcey/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,shs96c/buck,nguyentruongtho/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,Addepar/buck,romanoid/buck,zpao/buck,rmaz/buck,zpao/buck,ilya-klyuchnikov/buck,romanoid/buck,nguyentruongtho/buck,Addepar/buck,JoelMarcey/buck,JoelMarcey/buck,romanoid/buck,rmaz/buck,LegNeato/buck,facebook/buck,clonetwin26/buck,Addepar/buck,SeleniumHQ/buck,clonetwin26/buck,nguyentruongtho/buck,shs96c/buck,ilya-klyuchnikov/buck,kageiit/buck,SeleniumHQ/buck,ilya-klyuchnikov/buck,clonetwin26/buck,SeleniumHQ/buck,nguyentruongtho/buck,nguyentruongtho/buck,brettwooldridge/buck,romanoid/buck,SeleniumHQ/buck,shs96c/buck,LegNeato/buck,JoelMarcey/buck,rmaz/buck,rmaz/buck,Addepar/buck,JoelMarcey/buck,SeleniumHQ/buck,facebook/buck,shs96c/buck,brettwooldridge/buck,ilya-klyuchnikov/buck,LegNeato/buck,SeleniumHQ/buck,clonetwin26/buck,Addepar/buck,kageiit/buck,clonetwin26/buck,Addepar/buck,ilya-klyuchnikov/buck,clonetwin26/buck,clonetwin26/buck,rmaz/buck,LegNeato/buck,rmaz/buck,SeleniumHQ/buck,shs96c/buck,zpao/buck,rmaz/buck,romanoid/buck,SeleniumHQ/buck,JoelMarcey/buck,rmaz/buck,romanoid/buck,brettwooldridge/buck,brettwooldridge/buck,LegNeato/buck,LegNeato/buck,kageiit/buck,SeleniumHQ/buck,kageiit/buck,SeleniumHQ/buck,zpao/buck,kageiit/buck,Addepar/buck,brettwooldridge/buck,nguyentruongtho/buck,romanoid/buck | /*
* Copyright 2017-present Facebook, 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.facebook.buck.rules.keys;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.AddsToRuleKey;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.util.MoreSuppliers;
import com.facebook.buck.util.timing.Clock;
import com.facebook.buck.util.timing.DefaultClock;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheStats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* A {@link com.facebook.buck.rules.RuleKey} cache used by a {@link RuleKeyFactory}. Inputs and
* dependencies of cached rule keys are tracked to allow for invalidations based on changed inputs.
* As such, this cache is usable between multiple build runs.
*
* @param <V> The rule key type.
*/
public class DefaultRuleKeyCache<V> implements RuleKeyCache<V> {
private static final Logger LOG = Logger.get(DefaultRuleKeyCache.class);
private final Clock clock;
/**
* The underlying rule key cache. We use object identity for indexing.
*
* <p>All modifications to the Nodes are synchronized by using the compute* functions on
* ConcurrentHashMap.
*/
private final ConcurrentHashMap<IdentityWrapper<Object>, Node<Object, V>> cache =
new ConcurrentHashMap<>();
/** A map for rule key inputs to nodes that use them. */
private final ConcurrentHashMap<RuleKeyInput, Stream.Builder<Object>> inputsIndex =
new ConcurrentHashMap<>();
// Stats.
private final LongAdder lookupCount = new LongAdder();
private final LongAdder missCount = new LongAdder();
private final LongAdder totalLoadTime = new LongAdder();
private final LongAdder evictionCount = new LongAdder();
DefaultRuleKeyCache(Clock clock) {
this.clock = clock;
}
public DefaultRuleKeyCache() {
this(new DefaultClock());
}
private <K> V calculateNode(K node, Function<K, RuleKeyResult<V>> create) {
Preconditions.checkArgument(
node instanceof BuildRule ^ node instanceof AddsToRuleKey,
"%s must be one of either a `BuildRule` or `AddsToRuleKey`",
node.getClass());
// Record start time for stats.
long start = clock.nanoTime();
RuleKeyResult<V> result = create.apply(node);
for (Object dependency : result.deps) {
cache.compute(
new IdentityWrapper<>(dependency),
(key, value) -> {
if (value == null) {
value = new Node<>();
}
value.dependents.add(node);
return value;
});
}
for (RuleKeyInput input : result.inputs) {
inputsIndex.compute(
input,
(key, builder) -> {
if (builder == null) {
builder = Stream.builder();
}
builder.add(node);
return builder;
});
}
// Update stats.
long end = clock.nanoTime();
totalLoadTime.add(end - start);
missCount.increment();
return result.result;
}
private <K> V getNode(K node, Function<K, RuleKeyResult<V>> create) {
lookupCount.increment();
Supplier<V> supplier =
cache.compute(
new IdentityWrapper<>(node),
(key, value) -> {
if (value == null) {
value = new Node<>();
}
if (value.value == null) {
value.value = MoreSuppliers.memoize(() -> calculateNode(node, create));
}
return value;
})
.value;
return Preconditions.checkNotNull(supplier).get();
}
@Nullable
@Override
public V get(BuildRule rule) {
lookupCount.increment();
Node<Object, V> node = cache.get(new IdentityWrapper<Object>(rule));
if (node != null && node.value != null) {
return Preconditions.checkNotNull(node.value).get();
}
missCount.increment();
return null;
}
@Override
public V get(BuildRule rule, Function<? super BuildRule, RuleKeyResult<V>> create) {
return getNode(rule, create);
}
@Override
public V get(AddsToRuleKey appendable, Function<? super AddsToRuleKey, RuleKeyResult<V>> create) {
return getNode(appendable, create);
}
private boolean isCachedNode(Object object) {
return cache.containsKey(new IdentityWrapper<>(object));
}
@VisibleForTesting
boolean isCached(BuildRule rule) {
return isCachedNode(rule);
}
@VisibleForTesting
boolean isCached(AddsToRuleKey appendable) {
return isCachedNode(appendable);
}
/** Recursively invalidate nodes up the dependency tree. */
private void invalidateNodes(Stream<Object> nodes) {
List<Stream<Object>> dependents = new ArrayList<>();
nodes.forEach(
key -> {
Node<Object, V> node = cache.remove(new IdentityWrapper<>(key));
// This node may have already been removed due to being someone else's reverse dependency.
if (node != null) {
LOG.verbose("invalidating node %s", key);
dependents.add(node.dependents.build());
evictionCount.increment();
}
});
if (!dependents.isEmpty()) {
invalidateNodes(dependents.stream().flatMap(x -> x));
}
}
/** Invalidate the given inputs and all their transitive dependents. */
@Override
public void invalidateInputs(Iterable<RuleKeyInput> inputs) {
List<Stream<Object>> nodes = new ArrayList<>();
for (RuleKeyInput input : inputs) {
LOG.verbose("invalidating input %s", input);
Stream.Builder<Object> inputNodes = inputsIndex.remove(input);
if (inputNodes != null) {
nodes.add(inputNodes.build());
}
}
if (!nodes.isEmpty()) {
invalidateNodes(nodes.stream().flatMap(x -> x));
}
}
/**
* Invalidate all inputs *not* from the given {@link ProjectFilesystem}s and their transitive
* dependents.
*/
@Override
public void invalidateAllExceptFilesystems(ImmutableSet<ProjectFilesystem> filesystems) {
if (filesystems.isEmpty()) {
invalidateAll();
} else {
invalidateInputs(
inputsIndex
.keySet()
.stream()
.filter(input -> !filesystems.contains(input.getFilesystem()))
.collect(Collectors.toList()));
}
}
/**
* Invalidate all inputs from a given {@link ProjectFilesystem} and their transitive dependents.
*/
@Override
public void invalidateFilesystem(ProjectFilesystem filesystem) {
invalidateInputs(
inputsIndex
.keySet()
.stream()
.filter(input -> filesystem.equals(input.getFilesystem()))
.collect(Collectors.toList()));
}
/** Invalidate everything in the cache. */
@Override
public void invalidateAll() {
evictionCount.add(cache.size());
cache.clear();
inputsIndex.clear();
}
@Override
public CacheStats getStats() {
long missCount = this.missCount.longValue();
return new CacheStats(
lookupCount.longValue() - missCount,
missCount,
missCount,
0L,
totalLoadTime.longValue(),
evictionCount.longValue());
}
@Override
public ImmutableList<Map.Entry<BuildRule, V>> getCachedBuildRules() {
ImmutableList.Builder<Map.Entry<BuildRule, V>> builder = ImmutableList.builder();
cache.forEach(
(key, value) -> {
if (key.delegate instanceof BuildRule) {
Supplier<V> supplier = value.value;
if (supplier != null) {
builder.add(new AbstractMap.SimpleEntry<>((BuildRule) key.delegate, supplier.get()));
}
}
});
return builder.build();
}
private static final class Node<T, V> {
/**
* Accumulator of nodes that depends on this one. Used to invalidate those nodes when this node
* is invalidated.
*/
private final Stream.Builder<T> dependents;
/**
* The cached value, stored in a memoized supplier. A memoized supplier is used to allow the
* value computation to be serialized separately from the lock in the ConcurrentHashMap that the
* nodes are stored in.
*
* <p>This value is nullable because the instance can be created in response to recording a
* dependent.
*/
@Nullable private volatile Supplier<V> value;
public Node() {
this.dependents = Stream.builder();
this.value = null;
}
}
/**
* A wrapper class which uses identity equality and hash code. Intended to wrap keys used in a
* map.
*/
private static final class IdentityWrapper<T> {
private final T delegate;
private IdentityWrapper(T delegate) {
this.delegate = delegate;
}
@Override
public int hashCode() {
return System.identityHashCode(delegate);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DefaultRuleKeyCache.IdentityWrapper)) {
return false;
}
IdentityWrapper<?> other = (IdentityWrapper<?>) obj;
return delegate == other.delegate;
}
}
}
| src/com/facebook/buck/rules/keys/DefaultRuleKeyCache.java | /*
* Copyright 2017-present Facebook, 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.facebook.buck.rules.keys;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.AddsToRuleKey;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.util.MoreSuppliers;
import com.facebook.buck.util.timing.Clock;
import com.facebook.buck.util.timing.DefaultClock;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.cache.CacheStats;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* A {@link com.facebook.buck.rules.RuleKey} cache used by a {@link RuleKeyFactory}. Inputs and
* dependencies of cached rule keys are tracked to allow for invalidations based on changed inputs.
* As such, this cache is usable between multiple build runs.
*
* @param <V> The rule key type.
*/
public class DefaultRuleKeyCache<V> implements RuleKeyCache<V> {
private static final Logger LOG = Logger.get(DefaultRuleKeyCache.class);
private final Clock clock;
/**
* The underlying rule key cache. We use object identity for indexing.
*
* <p>All modifications to the Nodes are synchronized by using the compute* functions on
* ConcurrentHashMap.
*/
private final ConcurrentHashMap<IdentityWrapper<Object>, Node<Object, V>> cache =
new ConcurrentHashMap<>();
/** A map for rule key inputs to nodes that use them. */
private final ConcurrentHashMap<RuleKeyInput, Stream.Builder<Object>> inputsIndex =
new ConcurrentHashMap<>();
// Stats.
private final LongAdder lookupCount = new LongAdder();
private final LongAdder missCount = new LongAdder();
private final LongAdder totalLoadTime = new LongAdder();
private final LongAdder evictionCount = new LongAdder();
DefaultRuleKeyCache(Clock clock) {
this.clock = clock;
}
public DefaultRuleKeyCache() {
this(new DefaultClock());
}
private <K> V calculateNode(K node, Function<K, RuleKeyResult<V>> create) {
Preconditions.checkArgument(
node instanceof BuildRule ^ node instanceof AddsToRuleKey,
"%s must be one of either a `BuildRule` or `AddsToRuleKey`",
node.getClass());
// Record start time for stats.
long start = clock.nanoTime();
RuleKeyResult<V> result = create.apply(node);
for (Object dependency : result.deps) {
cache.compute(
new IdentityWrapper<>(dependency),
(key, value) -> {
if (value == null) {
value = new Node<>();
}
value.dependents.add(node);
return value;
});
}
for (RuleKeyInput input : result.inputs) {
inputsIndex.compute(
input,
(key, builder) -> {
if (builder == null) {
builder = Stream.builder();
}
builder.add(node);
return builder;
});
}
// Update stats.
long end = clock.nanoTime();
totalLoadTime.add(end - start);
missCount.increment();
return result.result;
}
private <K> V getNode(K node, Function<K, RuleKeyResult<V>> create) {
lookupCount.increment();
Supplier<V> supplier =
cache.compute(
new IdentityWrapper<>(node),
(key, value) -> {
if (value == null) {
value = new Node<>();
}
if (value.value == null) {
value.value = MoreSuppliers.memoize(() -> calculateNode(node, create));
}
return value;
})
.value;
return Preconditions.checkNotNull(supplier).get();
}
@Nullable
@Override
public V get(BuildRule rule) {
lookupCount.increment();
Node<Object, V> node = cache.get(new IdentityWrapper<Object>(rule));
if (node != null && node.value != null) {
return Preconditions.checkNotNull(node.value).get();
}
missCount.increment();
return null;
}
@Override
public V get(BuildRule rule, Function<? super BuildRule, RuleKeyResult<V>> create) {
return getNode(rule, create);
}
@Override
public V get(AddsToRuleKey appendable, Function<? super AddsToRuleKey, RuleKeyResult<V>> create) {
return getNode(appendable, create);
}
private boolean isCachedNode(Object object) {
return cache.containsKey(new IdentityWrapper<>(object));
}
@VisibleForTesting
boolean isCached(BuildRule rule) {
return isCachedNode(rule);
}
@VisibleForTesting
boolean isCached(AddsToRuleKey appendable) {
return isCachedNode(appendable);
}
/** Recursively invalidate nodes up the dependency tree. */
private void invalidateNodes(Stream<Object> nodes) {
List<Stream<Object>> dependents = new ArrayList<>();
nodes.forEach(
key -> {
Node<Object, V> node = cache.remove(new IdentityWrapper<>(key));
// This node may have already been removed due to being someone else's reverse dependency.
if (node != null) {
LOG.verbose("invalidating node %s", key);
dependents.add(node.dependents.build());
evictionCount.increment();
}
});
if (!dependents.isEmpty()) {
invalidateNodes(dependents.stream().flatMap(x -> x));
}
}
/** Invalidate the given inputs and all their transitive dependents. */
@Override
public void invalidateInputs(Iterable<RuleKeyInput> inputs) {
List<Stream<Object>> nodes = new ArrayList<>();
for (RuleKeyInput input : inputs) {
LOG.verbose("invalidating input %s", input);
Stream.Builder<Object> inputNodes = inputsIndex.remove(input);
if (inputNodes != null) {
nodes.add(inputNodes.build());
}
}
if (!nodes.isEmpty()) {
invalidateNodes(nodes.stream().flatMap(x -> x));
}
}
/**
* Invalidate all inputs *not* from the given {@link ProjectFilesystem}s and their transitive
* dependents.
*/
@Override
public void invalidateAllExceptFilesystems(ImmutableSet<ProjectFilesystem> filesystems) {
if (filesystems.isEmpty()) {
invalidateAll();
} else {
invalidateInputs(
inputsIndex
.keySet()
.stream()
.filter(input -> !filesystems.contains(input.getFilesystem()))
.collect(Collectors.toList()));
}
}
/**
* Invalidate all inputs from a given {@link ProjectFilesystem} and their transitive dependents.
*/
@Override
public void invalidateFilesystem(ProjectFilesystem filesystem) {
invalidateInputs(
inputsIndex
.keySet()
.stream()
.filter(input -> filesystem.equals(input.getFilesystem()))
.collect(Collectors.toList()));
}
/** Invalidate everything in the cache. */
@Override
public void invalidateAll() {
cache.clear();
inputsIndex.clear();
}
@Override
public CacheStats getStats() {
long missCount = this.missCount.longValue();
return new CacheStats(
lookupCount.longValue() - missCount,
missCount,
missCount,
0L,
totalLoadTime.longValue(),
evictionCount.longValue());
}
@Override
public ImmutableList<Map.Entry<BuildRule, V>> getCachedBuildRules() {
ImmutableList.Builder<Map.Entry<BuildRule, V>> builder = ImmutableList.builder();
cache.forEach(
(key, value) -> {
if (key.delegate instanceof BuildRule) {
Supplier<V> supplier = value.value;
if (supplier != null) {
builder.add(new AbstractMap.SimpleEntry<>((BuildRule) key.delegate, supplier.get()));
}
}
});
return builder.build();
}
private static final class Node<T, V> {
/**
* Accumulator of nodes that depends on this one. Used to invalidate those nodes when this node
* is invalidated.
*/
private final Stream.Builder<T> dependents;
/**
* The cached value, stored in a memoized supplier. A memoized supplier is used to allow the
* value computation to be serialized separately from the lock in the ConcurrentHashMap that the
* nodes are stored in.
*
* <p>This value is nullable because the instance can be created in response to recording a
* dependent.
*/
@Nullable private volatile Supplier<V> value;
public Node() {
this.dependents = Stream.builder();
this.value = null;
}
}
/**
* A wrapper class which uses identity equality and hash code. Intended to wrap keys used in a
* map.
*/
private static final class IdentityWrapper<T> {
private final T delegate;
private IdentityWrapper(T delegate) {
this.delegate = delegate;
}
@Override
public int hashCode() {
return System.identityHashCode(delegate);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DefaultRuleKeyCache.IdentityWrapper)) {
return false;
}
IdentityWrapper<?> other = (IdentityWrapper<?>) obj;
return delegate == other.delegate;
}
}
}
| Add missing stats tracking
Summary: We were tracking evictions above when individual nodes are invalidated, but not tracking evictions when everything is evicted.
Test Plan: builds
Reviewed By: ttsugriy
fbshipit-source-id: 9bf1441
| src/com/facebook/buck/rules/keys/DefaultRuleKeyCache.java | Add missing stats tracking | <ide><path>rc/com/facebook/buck/rules/keys/DefaultRuleKeyCache.java
<ide> /** Invalidate everything in the cache. */
<ide> @Override
<ide> public void invalidateAll() {
<add> evictionCount.add(cache.size());
<ide> cache.clear();
<ide> inputsIndex.clear();
<ide> } |
|
Java | agpl-3.0 | 63da54ef207aff634296a75b37ef07338b8f0865 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 6a5143b2-2e61-11e5-9284-b827eb9e62be | hello.java | 6a4bcb3a-2e61-11e5-9284-b827eb9e62be | 6a5143b2-2e61-11e5-9284-b827eb9e62be | hello.java | 6a5143b2-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>6a4bcb3a-2e61-11e5-9284-b827eb9e62be
<add>6a5143b2-2e61-11e5-9284-b827eb9e62be |
|
Java | mit | 4dcc14820ed5e8d884ce8bb6c4ed0c8268d2d4a0 | 0 | holmari/gerritstats,holmari/gerritstats,holmari/gerritstats,holmari/gerritstats | package com.holmsted.gerrit.processors.perperson;
import com.google.common.base.Strings;
import com.holmsted.gerrit.Commit;
import com.holmsted.gerrit.DatedCommitList;
import com.holmsted.gerrit.DatedPatchSetCommentList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import javax.annotation.Nonnull;
public class IdentityRecord {
public static class ReviewerData {
int addedAsReviewerCount;
int approvalCount;
public int getAddedAsReviewerCount() {
return addedAsReviewerCount;
}
public int getApprovalCount() {
return approvalCount;
}
}
final Commit.Identity identity;
int reviewCountPlus2;
int reviewCountPlus1;
int reviewCountMinus1;
int reviewCountMinus2;
final Hashtable<Integer, Integer> receivedReviews = new Hashtable<>();
final DatedCommitList commits = new DatedCommitList();
final List<Commit> addedAsReviewerTo = new ArrayList<>();
final ReviewerDataTable reviewRequestors = new ReviewerDataTable();
final PatchSetCommentTable commentsWritten = new PatchSetCommentTable();
final PatchSetCommentTable commentsReceived = new PatchSetCommentTable();
final ReviewerDataTable reviewersForOwnCommits = new ReviewerDataTable();
private long averageTimeInCodeReview;
public IdentityRecord(Commit.Identity identity) {
this.identity = identity;
}
public String getName() {
return identity.getName();
}
public long getAverageTimeInCodeReview() {
return averageTimeInCodeReview;
}
public String getPrintableAverageTimeInCodeReview() {
return formatPrintableDuration(averageTimeInCodeReview);
}
public String getEmail() {
return identity.getEmail();
}
public String getUsername() {
return identity.getUsername();
}
public String getFilenameStem() {
String filename = identity.getUsername();
if (Strings.isNullOrEmpty(filename)) {
filename = Strings.nullToEmpty(identity.getEmail()).replace(".", "_");
int atMarkIndex = filename.indexOf('@');
if (atMarkIndex != -1) {
filename = filename.substring(0, atMarkIndex);
} else {
filename = "anonymous_coward";
}
}
return filename;
}
public DatedCommitList getCommits() {
return commits;
}
public List<Commit> getAddedAsReviewerTo() {
return addedAsReviewerTo;
}
public DatedPatchSetCommentList getAllCommentsWritten() {
return commentsWritten.getAllComments();
}
public List<Commit.PatchSetComment> getAllCommentsReceived() {
List<Commit.PatchSetComment> allComments = new ArrayList<>();
for (List<Commit.PatchSetComment> comments : commentsReceived.values()) {
allComments.addAll(comments);
}
return allComments;
}
public Hashtable<Commit.Identity, ReviewerData> getReviewersForOwnCommits() {
return reviewersForOwnCommits;
}
public ReviewerData getReviewerDataForOwnCommitFor(@Nonnull Commit.Identity identity) {
return reviewersForOwnCommits.get(identity);
}
public ReviewerData getReviewRequestorDataFor(@Nonnull Commit.Identity identity) {
return reviewRequestors.get(identity);
}
public int getReviewCountMinus1() {
return reviewCountMinus1;
}
public int getReviewCountMinus2() {
return reviewCountMinus2;
}
public int getReviewCountPlus1() {
return reviewCountPlus1;
}
public int getReviewCountPlus2() {
return reviewCountPlus2;
}
public float getReceivedCommentRatio() {
int receivedComments = getAllCommentsReceived().size();
int commitCount = commits.size();
if (commitCount > 0) {
return (float) receivedComments / commitCount;
} else {
return 0;
}
}
public float getAveragePatchSetCount() {
int commitCount = commits.size();
if (commitCount > 0) {
int patchSetCount = 0;
for (Commit commit : commits) {
patchSetCount += commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK);
}
return (float) patchSetCount / commits.size();
} else {
return 0;
}
}
public int getMaxPatchSetCount() {
int commitCount = commits.size();
if (commitCount > 0) {
int max = Integer.MIN_VALUE;
for (Commit commit : commits) {
max = Math.max(commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK), max);
}
return max;
} else {
return 0;
}
}
public float getReviewCommentRatio() {
if (addedAsReviewerTo.size() == 0) {
return 0;
} else {
return (float) commentsWritten.size() / addedAsReviewerTo.size();
}
}
public void addApproval(Commit.Approval approval) {
if (approval.value == 2) {
++reviewCountPlus2;
} else if (approval.value == 1) {
++reviewCountPlus1;
} else if (approval.value == -1) {
++reviewCountMinus1;
} else if (approval.value == -2) {
++reviewCountMinus2;
}
}
public List<Commit.Identity> getMyReviewerList() {
List<Commit.Identity> sortedIdentities = new ArrayList<>(reviewersForOwnCommits.keySet());
Collections.sort(sortedIdentities, new ReviewerAddedCountComparator(reviewersForOwnCommits));
return sortedIdentities;
}
public String getDisplayableMyReviewerList() {
return getPrintableReviewerList(getMyReviewerList(), reviewersForOwnCommits);
}
public List<Commit.Identity> getReviewRequestorList() {
List<Commit.Identity> sortedIdentities = new ArrayList<>(reviewRequestors.keySet());
Collections.sort(sortedIdentities, new ReviewerAddedCountComparator(reviewRequestors));
return sortedIdentities;
}
public String getDisplayableAddedReviewerList() {
return getPrintableReviewerList(getReviewRequestorList(), reviewRequestors);
}
private ReviewerData getOrCreateReviewerForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = reviewersForOwnCommits.get(identity);
if (reviewerData == null) {
reviewerData = new ReviewerData();
}
return reviewerData;
}
public void addReviewerForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = getOrCreateReviewerForOwnCommit(identity);
reviewerData.addedAsReviewerCount++;
reviewersForOwnCommits.put(identity, reviewerData);
}
void addApprovalForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = getOrCreateReviewerForOwnCommit(identity);
reviewerData.approvalCount++;
reviewersForOwnCommits.put(identity, reviewerData);
}
private String getPrintableReviewerList(@Nonnull List<Commit.Identity> sortedIdentities,
@Nonnull Hashtable<Commit.Identity, ReviewerData> reviewsForIdentity) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < sortedIdentities.size(); ++i) {
Commit.Identity identity = sortedIdentities.get(i);
builder.append(String.format("%s (%d)",
identity.toString(), reviewsForIdentity.get(identity).addedAsReviewerCount));
if (i < sortedIdentities.size() - 1) {
builder.append(", ");
}
}
return builder.toString();
}
public List<Commit> getCommitsWithNPatchSets(int patchSetCountThreshold) {
List<Commit> exceedingCommits = new ArrayList<>();
for (Commit commit : commits) {
int patchSetCount = commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK);
if (patchSetCount <= patchSetCountThreshold) {
continue;
}
int firstNonAuthorCommentPatchSetIndex = commit.getFirstPatchSetIndexWithNonAuthorReview();
if (firstNonAuthorCommentPatchSetIndex != -1
&& commit.getPatchSets().size() - firstNonAuthorCommentPatchSetIndex > patchSetCountThreshold) {
exceedingCommits.add(commit);
}
}
Collections.sort(exceedingCommits, new PatchSetCountComparator());
return exceedingCommits;
}
public String getPrintableCommitsWithNPatchSets(int patchSetCountThreshold) {
List<Commit> exceedingCommits = getCommitsWithNPatchSets(patchSetCountThreshold);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < exceedingCommits.size(); ++i) {
Commit commit = exceedingCommits.get(i);
builder.append(String.format("%s (%d)",
commit.url,
commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK)));
if (i < exceedingCommits.size() - 1) {
builder.append(", ");
}
}
return builder.toString();
}
public String getPrintableAllReviewComments() {
StringBuilder builder = new StringBuilder();
for (Commit.PatchSetComment comment : getAllCommentsWritten()) {
builder.append(comment.message).append("\n");
}
return builder.toString();
}
public void addReviewedCommit(@Nonnull Commit commit) {
addedAsReviewerTo.add(commit);
ReviewerData reviewsDoneForIdentity = reviewRequestors.get(commit.owner);
if (reviewsDoneForIdentity == null) {
reviewsDoneForIdentity = new ReviewerData();
}
reviewsDoneForIdentity.addedAsReviewerCount++;
reviewRequestors.put(commit.owner, reviewsDoneForIdentity);
}
public void addWrittenComment(@Nonnull Commit commit, @Nonnull Commit.PatchSetComment patchSetComment) {
commentsWritten.addCommentForCommit(commit, patchSetComment);
}
public void addReceivedComment(@Nonnull Commit commit, Commit.PatchSetComment patchSetComment) {
commentsReceived.addCommentForCommit(commit, patchSetComment);
}
public List<Commit> getCommitsWithWrittenComments() {
ArrayList<Commit> commits = Collections.list(commentsWritten.keys());
Collections.sort(commits, new CommitDateComparator());
return commits;
}
public List<Commit.PatchSetComment> getWrittenCommentsForCommit(@Nonnull Commit commit) {
return commentsWritten.get(commit);
}
public int getReceivedReviewsForScore(int score) {
Integer value = receivedReviews.get(score);
return value != null ? value : 0;
}
public void addCommit(@Nonnull Commit commit) {
commits.add(commit);
}
void updateAverageTimeInCodeReview(long commitTimeInCodeReviewMsec) {
int prevCount = commits.size() - 1;
long newAverage = averageTimeInCodeReview * prevCount;
averageTimeInCodeReview = (newAverage + commitTimeInCodeReviewMsec) / commits.size();
}
void addReceivedCodeReview(@Nonnull Commit.Approval approval) {
Integer receivedReviewCountForValue = receivedReviews.get(approval.value);
if (receivedReviewCountForValue == null) {
receivedReviewCountForValue = 1;
} else {
receivedReviewCountForValue++;
}
receivedReviews.put(approval.value, receivedReviewCountForValue);
}
private static String formatPrintableDuration(long duration) {
int durationInSecs = (int) (duration / 1000);
int days = durationInSecs / (60 * 60 * 24);
int hours = durationInSecs / (60 * 60) % 24;
int minutes = durationInSecs / (60) % 60;
return String.format("%dd %dh %dmin", days, hours, minutes);
}
}
| GerritStats/src/main/java/com/holmsted/gerrit/processors/perperson/IdentityRecord.java | package com.holmsted.gerrit.processors.perperson;
import com.google.common.base.Strings;
import com.holmsted.gerrit.Commit;
import com.holmsted.gerrit.DatedCommitList;
import com.holmsted.gerrit.DatedPatchSetCommentList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import javax.annotation.Nonnull;
public class IdentityRecord {
public static class ReviewerData {
int addedAsReviewerCount;
int approvalCount;
public int getAddedAsReviewerCount() {
return addedAsReviewerCount;
}
public int getApprovalCount() {
return approvalCount;
}
}
final Commit.Identity identity;
int reviewCountPlus2;
int reviewCountPlus1;
int reviewCountMinus1;
int reviewCountMinus2;
final Hashtable<Integer, Integer> receivedReviews = new Hashtable<>();
final DatedCommitList commits = new DatedCommitList();
final List<Commit> addedAsReviewerTo = new ArrayList<>();
final ReviewerDataTable reviewRequestors = new ReviewerDataTable();
final PatchSetCommentTable commentsWritten = new PatchSetCommentTable();
final PatchSetCommentTable commentsReceived = new PatchSetCommentTable();
final ReviewerDataTable reviewersForOwnCommits = new ReviewerDataTable();
private long averageTimeInCodeReview;
public IdentityRecord(Commit.Identity identity) {
this.identity = identity;
}
public String getName() {
return identity.getName();
}
public long getAverageTimeInCodeReview() {
return averageTimeInCodeReview;
}
public String getPrintableAverageTimeInCodeReview() {
return formatPrintableDuration(averageTimeInCodeReview);
}
public String getEmail() {
return identity.getEmail();
}
public String getUsername() {
return identity.getUsername();
}
public String getFilenameStem() {
String filename = identity.getUsername();
if (Strings.isNullOrEmpty(filename)) {
filename = Strings.nullToEmpty(identity.getEmail()).replace(".", "_");
int atMarkIndex = filename.indexOf('@');
if (atMarkIndex != -1) {
filename = filename.substring(0, atMarkIndex);
} else {
filename = "anonymous_coward";
}
}
return filename;
}
public DatedCommitList getCommits() {
return commits;
}
public List<Commit> getAddedAsReviewerTo() {
return addedAsReviewerTo;
}
public DatedPatchSetCommentList getAllCommentsWritten() {
return commentsWritten.getAllComments();
}
public List<Commit.PatchSetComment> getAllCommentsReceived() {
List<Commit.PatchSetComment> allComments = new ArrayList<>();
for (List<Commit.PatchSetComment> comments : commentsReceived.values()) {
allComments.addAll(comments);
}
return allComments;
}
public Hashtable<Commit.Identity, ReviewerData> getReviewersForOwnCommits() {
return reviewersForOwnCommits;
}
public ReviewerData getReviewerDataForOwnCommitFor(@Nonnull Commit.Identity identity) {
return reviewersForOwnCommits.get(identity);
}
public ReviewerData getReviewRequestorDataFor(@Nonnull Commit.Identity identity) {
return reviewRequestors.get(identity);
}
public int getReviewCountMinus1() {
return reviewCountMinus1;
}
public int getReviewCountMinus2() {
return reviewCountMinus2;
}
public int getReviewCountPlus1() {
return reviewCountPlus1;
}
public int getReviewCountPlus2() {
return reviewCountPlus2;
}
public float getReceivedCommentRatio() {
int receivedComments = getAllCommentsReceived().size();
int commitCount = commits.size();
if (commitCount > 0) {
return (float) receivedComments / commitCount;
} else {
return 0;
}
}
public float getAveragePatchSetCount() {
int commitCount = commits.size();
if (commitCount > 0) {
int patchSetCount = 0;
for (Commit commit : commits) {
patchSetCount += commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK);
}
return (float) patchSetCount / commits.size();
} else {
return 0;
}
}
public int getMaxPatchSetCount() {
int commitCount = commits.size();
if (commitCount > 0) {
int max = Integer.MIN_VALUE;
for (Commit commit : commits) {
max = Math.max(commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK), max);
}
return max;
} else {
return 0;
}
}
public float getReviewCommentRatio() {
return (float) commentsWritten.size() / addedAsReviewerTo.size();
}
public void addApproval(Commit.Approval approval) {
if (approval.value == 2) {
++reviewCountPlus2;
} else if (approval.value == 1) {
++reviewCountPlus1;
} else if (approval.value == -1) {
++reviewCountMinus1;
} else if (approval.value == -2) {
++reviewCountMinus2;
}
}
public List<Commit.Identity> getMyReviewerList() {
List<Commit.Identity> sortedIdentities = new ArrayList<>(reviewersForOwnCommits.keySet());
Collections.sort(sortedIdentities, new ReviewerAddedCountComparator(reviewersForOwnCommits));
return sortedIdentities;
}
public String getDisplayableMyReviewerList() {
return getPrintableReviewerList(getMyReviewerList(), reviewersForOwnCommits);
}
public List<Commit.Identity> getReviewRequestorList() {
List<Commit.Identity> sortedIdentities = new ArrayList<>(reviewRequestors.keySet());
Collections.sort(sortedIdentities, new ReviewerAddedCountComparator(reviewRequestors));
return sortedIdentities;
}
public String getDisplayableAddedReviewerList() {
return getPrintableReviewerList(getReviewRequestorList(), reviewRequestors);
}
private ReviewerData getOrCreateReviewerForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = reviewersForOwnCommits.get(identity);
if (reviewerData == null) {
reviewerData = new ReviewerData();
}
return reviewerData;
}
public void addReviewerForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = getOrCreateReviewerForOwnCommit(identity);
reviewerData.addedAsReviewerCount++;
reviewersForOwnCommits.put(identity, reviewerData);
}
void addApprovalForOwnCommit(@Nonnull Commit.Identity identity) {
ReviewerData reviewerData = getOrCreateReviewerForOwnCommit(identity);
reviewerData.approvalCount++;
reviewersForOwnCommits.put(identity, reviewerData);
}
private String getPrintableReviewerList(@Nonnull List<Commit.Identity> sortedIdentities,
@Nonnull Hashtable<Commit.Identity, ReviewerData> reviewsForIdentity) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < sortedIdentities.size(); ++i) {
Commit.Identity identity = sortedIdentities.get(i);
builder.append(String.format("%s (%d)",
identity.toString(), reviewsForIdentity.get(identity).addedAsReviewerCount));
if (i < sortedIdentities.size() - 1) {
builder.append(", ");
}
}
return builder.toString();
}
public List<Commit> getCommitsWithNPatchSets(int patchSetCountThreshold) {
List<Commit> exceedingCommits = new ArrayList<>();
for (Commit commit : commits) {
int patchSetCount = commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK);
if (patchSetCount <= patchSetCountThreshold) {
continue;
}
int firstNonAuthorCommentPatchSetIndex = commit.getFirstPatchSetIndexWithNonAuthorReview();
if (firstNonAuthorCommentPatchSetIndex != -1
&& commit.getPatchSets().size() - firstNonAuthorCommentPatchSetIndex > patchSetCountThreshold) {
exceedingCommits.add(commit);
}
}
Collections.sort(exceedingCommits, new PatchSetCountComparator());
return exceedingCommits;
}
public String getPrintableCommitsWithNPatchSets(int patchSetCountThreshold) {
List<Commit> exceedingCommits = getCommitsWithNPatchSets(patchSetCountThreshold);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < exceedingCommits.size(); ++i) {
Commit commit = exceedingCommits.get(i);
builder.append(String.format("%s (%d)",
commit.url,
commit.getPatchSetCountForKind(Commit.PatchSetKind.REWORK)));
if (i < exceedingCommits.size() - 1) {
builder.append(", ");
}
}
return builder.toString();
}
public String getPrintableAllReviewComments() {
StringBuilder builder = new StringBuilder();
for (Commit.PatchSetComment comment : getAllCommentsWritten()) {
builder.append(comment.message).append("\n");
}
return builder.toString();
}
public void addReviewedCommit(@Nonnull Commit commit) {
addedAsReviewerTo.add(commit);
ReviewerData reviewsDoneForIdentity = reviewRequestors.get(commit.owner);
if (reviewsDoneForIdentity == null) {
reviewsDoneForIdentity = new ReviewerData();
}
reviewsDoneForIdentity.addedAsReviewerCount++;
reviewRequestors.put(commit.owner, reviewsDoneForIdentity);
}
public void addWrittenComment(@Nonnull Commit commit, @Nonnull Commit.PatchSetComment patchSetComment) {
commentsWritten.addCommentForCommit(commit, patchSetComment);
}
public void addReceivedComment(@Nonnull Commit commit, Commit.PatchSetComment patchSetComment) {
commentsReceived.addCommentForCommit(commit, patchSetComment);
}
public List<Commit> getCommitsWithWrittenComments() {
ArrayList<Commit> commits = Collections.list(commentsWritten.keys());
Collections.sort(commits, new CommitDateComparator());
return commits;
}
public List<Commit.PatchSetComment> getWrittenCommentsForCommit(@Nonnull Commit commit) {
return commentsWritten.get(commit);
}
public int getReceivedReviewsForScore(int score) {
Integer value = receivedReviews.get(score);
return value != null ? value : 0;
}
public void addCommit(@Nonnull Commit commit) {
commits.add(commit);
}
void updateAverageTimeInCodeReview(long commitTimeInCodeReviewMsec) {
int prevCount = commits.size() - 1;
long newAverage = averageTimeInCodeReview * prevCount;
averageTimeInCodeReview = (newAverage + commitTimeInCodeReviewMsec) / commits.size();
}
void addReceivedCodeReview(@Nonnull Commit.Approval approval) {
Integer receivedReviewCountForValue = receivedReviews.get(approval.value);
if (receivedReviewCountForValue == null) {
receivedReviewCountForValue = 1;
} else {
receivedReviewCountForValue++;
}
receivedReviews.put(approval.value, receivedReviewCountForValue);
}
private static String formatPrintableDuration(long duration) {
int durationInSecs = (int) (duration / 1000);
int days = durationInSecs / (60 * 60 * 24);
int hours = durationInSecs / (60 * 60) % 24;
int minutes = durationInSecs / (60) % 60;
return String.format("%dd %dh %dmin", days, hours, minutes);
}
}
| Fix NaN for review comment ratio
| GerritStats/src/main/java/com/holmsted/gerrit/processors/perperson/IdentityRecord.java | Fix NaN for review comment ratio | <ide><path>erritStats/src/main/java/com/holmsted/gerrit/processors/perperson/IdentityRecord.java
<ide> }
<ide>
<ide> public float getReviewCommentRatio() {
<del> return (float) commentsWritten.size() / addedAsReviewerTo.size();
<add> if (addedAsReviewerTo.size() == 0) {
<add> return 0;
<add> } else {
<add> return (float) commentsWritten.size() / addedAsReviewerTo.size();
<add> }
<ide> }
<ide>
<ide> public void addApproval(Commit.Approval approval) { |
|
Java | bsd-3-clause | 26cbd0d2737f925edd8d98937265449fe8ffa8fb | 0 | mjlaali/cleartk,mjlaali/cleartk,mjlaali/cleartk,mjlaali/cleartk | /**
* Copyright (c) 2007-2008, Regents of the University of Colorado
* 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 University of Colorado at Boulder 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER OR 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 org.cleartk.test.util;
import org.uutuc.factory.ConfigurationParameterFactory;
/**
* <br>
* Copyright (c) 2007-2008, Regents of the University of Colorado <br>
* All rights reserved.
*/
public class ConfigurationParameterNameFactory {
public static String createConfigurationParameterName(Class<?> clazz, String fieldName) throws RuntimeException {
try {
return ConfigurationParameterFactory.getConfigurationParameterName(
clazz.getDeclaredField(fieldName));
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
| ClearTK-test-util/src/main/java/org/cleartk/test/util/ConfigurationParameterNameFactory.java | package org.cleartk.test.util;
import org.uutuc.factory.ConfigurationParameterFactory;
public class ConfigurationParameterNameFactory {
public static String createConfigurationParameterName(Class<?> clazz, String fieldName) throws RuntimeException {
try {
return ConfigurationParameterFactory.getConfigurationParameterName(
clazz.getDeclaredField(fieldName));
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
| added license
git-svn-id: 34a63cff78c965ed7296912184cd0e3b6b7dc1c0@1387 2f4ce1e4-9571-11dd-93b2-6d14b300b761
| ClearTK-test-util/src/main/java/org/cleartk/test/util/ConfigurationParameterNameFactory.java | added license | <ide><path>learTK-test-util/src/main/java/org/cleartk/test/util/ConfigurationParameterNameFactory.java
<add>/**
<add> * Copyright (c) 2007-2008, Regents of the University of Colorado
<add> * All rights reserved.
<add> *
<add> * Redistribution and use in source and binary forms, with or without
<add> * modification, are permitted provided that the following conditions are met:
<add> *
<add> * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
<add> * 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.
<add> * Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
<add> *
<add> * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
<add> * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
<add> * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
<add> * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
<add> * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
<add> * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
<add> * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
<add> * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
<add> * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
<add> * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
<add> * POSSIBILITY OF SUCH DAMAGE.
<add> */
<ide> package org.cleartk.test.util;
<ide>
<ide> import org.uutuc.factory.ConfigurationParameterFactory;
<add>
<add>/**
<add> * <br>
<add> * Copyright (c) 2007-2008, Regents of the University of Colorado <br>
<add> * All rights reserved.
<add> */
<ide>
<ide> public class ConfigurationParameterNameFactory {
<ide> |
|
Java | mit | 975b6246b673cf70ce3b8af10b782fbd096a818b | 0 | hyperfresh/nxchat2,hyperfresh/nxchat,hyperfresh/mc-hyperchat | package com.hyperfresh.mchyperchat.bukkit;
import com.hyperfresh.mchyperchat.HyperChat;
import com.hyperfresh.mchyperchat.Theme;
import com.hyperfresh.mchyperchat.User;
import org.bukkit.command.ConsoleCommandSender;
/**
* A wrapper for the Bukkit ConsoleCommandSender.
*/
public class BukkitConsole implements User
{
private final ConsoleCommandSender handle;
private Theme theme;
private String lastSaid = null;
public BukkitConsole(HyperChat hyperChat, ConsoleCommandSender console)
{
this.handle = console;
this.theme = hyperChat.getThemeManager().getDefaultTheme();
}
@Override
public String getName()
{
return handle.getName();
}
@Override
public String getLastMessage()
{
return lastSaid;
}
@Override
public void setLastMessage(String said)
{
lastSaid = said;
}
@Override
public void sendMessage(String message)
{
handle.sendMessage(message);
}
@Override
public Theme getTheme()
{
return theme;
}
@Override
public void setTheme(Theme theme)
{
this.theme = theme;
}
}
| src/main/java/com/hyperfresh/mchyperchat/bukkit/BukkitConsole.java | package com.hyperfresh.mchyperchat.bukkit;
import com.hyperfresh.mchyperchat.HyperChat;
import com.hyperfresh.mchyperchat.Theme;
import com.hyperfresh.mchyperchat.User;
import org.bukkit.command.ConsoleCommandSender;
/**
* A wrapper for the Bukkit ConsoleCommandSender.
*/
public class BukkitConsole implements User
{
private final ConsoleCommandSender handle;
private String lastSaid;
private Theme theme = HyperChat.getThemeManager().getDefaultTheme();
public BukkitConsole(ConsoleCommandSender console, String lastSaid)
{
this.handle = console;
this.lastSaid = lastSaid;
}
@Override
public String getName()
{
return handle.getName();
}
@Override
public String getLastMessage()
{
return lastSaid;
}
@Override
public void setLastMessage(String said)
{
lastSaid = said;
}
@Override
public void sendMessage(String message)
{
handle.sendMessage(message);
}
@Override
public Theme getTheme()
{
return theme;
}
@Override
public void setTheme(Theme theme)
{
this.theme = theme;
}
}
| change BukkitConstructor constructor
| src/main/java/com/hyperfresh/mchyperchat/bukkit/BukkitConsole.java | change BukkitConstructor constructor | <ide><path>rc/main/java/com/hyperfresh/mchyperchat/bukkit/BukkitConsole.java
<ide> {
<ide> private final ConsoleCommandSender handle;
<ide>
<del> private String lastSaid;
<add> private Theme theme;
<add> private String lastSaid = null;
<ide>
<del> private Theme theme = HyperChat.getThemeManager().getDefaultTheme();
<del>
<del> public BukkitConsole(ConsoleCommandSender console, String lastSaid)
<add> public BukkitConsole(HyperChat hyperChat, ConsoleCommandSender console)
<ide> {
<ide> this.handle = console;
<del> this.lastSaid = lastSaid;
<add> this.theme = hyperChat.getThemeManager().getDefaultTheme();
<ide> }
<ide>
<ide> @Override |
|
Java | bsd-3-clause | 356da94bdb61f188bae2a4cd3e4b0ce1fd4c43b6 | 0 | flexgen/flexgen | /*
FlexGen : Flexible Map Generator Library
Copyright (C) 2009 - Jeffrey J. Weston <[email protected]>
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 FlexGen project 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER OR 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 org.flexgen.map.test;
import org.junit.Assert;
import org.junit.Test;
import org.flexgen.map.MapTileEdge;
import org.flexgen.map.MapTileEdgePosition;
import org.flexgen.map.MapTileOrientation;
import org.flexgen.map.MapTileType;
import org.flexgen.map.MapUnit;
import org.flexgen.test.helper.GeneralHelper;
import org.flexgen.test.helper.MapTileEdgeHelper;
import org.flexgen.test.helper.MapTileOrientationHelper;
import org.flexgen.test.helper.MapTileTypeHelper;
import org.flexgen.test.helper.MapUnitHelper;
/**
* Test class for the MapTileType class.
*/
public class MapTileTypeTest
{
/**
* Verify that the constructor throws the correct exception when the name parameter is null.
*/
@Test
public void constructor_name_null()
{
try
{
new MapTileType( null, MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'name' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is null.
*/
@Test
public void constructor_mapUnits_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
null, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapUnits' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is an
* empty array.
*/
@Test
public void constructor_mapUnits_emptyArray()
{
MapUnit[][] mapUnits = new MapUnit[][] {};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapUnits' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of elements in all of the rows.
*/
@Test
public void constructor_mapUnits_inconsistentRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build(),
MapUnitHelper.build()
},
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of elements in each row.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of columns as it does rows.
*/
@Test
public void constructor_mapUnits_columnCountNotEqualRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build()
},
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of columns as it does rows.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter contains
* a null element.
*/
@Test
public void constructor_mapUnits_nullElement()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
null
}
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter is
* null.
*/
@Test
public void constructor_mapTileEdges_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), null,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapTileEdges' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* doesn't contain enough elements.
*/
@Test
public void constructor_mapTileEdges_tooFew()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains too many elements.
*/
@Test
public void constructor_mapTileEdges_tooMany()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains a null element.
*/
@Test
public void constructor_mapTileEdges_nullElement()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
null,
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is null.
*/
@Test
public void constructor_distinctMapTileOrientations_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(), null, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is an empty array.
*/
@Test
public void constructor_distinctMapTileOrientations_emptyArray()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[] {};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a null element.
*/
@Test
public void constructor_distinctMapTileOrientations_nullElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
null
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a duplicate element.
*/
@Test
public void constructor_distinctMapTileOrientations_duplicateElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.UPRIGHT
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any " +
"duplicate elements.", e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the weight parameter is less
* than zero.
*/
@Test
public void constructor_weight_tooSmall()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, -1 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'weight' cannot be less than 0.", e.getMessage() );
}
}
/**
* Verify that the getSize() method returns the correct value for a small array of map units.
*/
@Test
public void getSize()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
Assert.assertEquals( "Unexpected return value.", size, mapTileType.getSize() );
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* small.
*/
@Test
public void getMapUnit_x_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( -1, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* large.
*/
@Test
public void getMapUnit_x_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( size, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* small.
*/
@Test
public void getMapUnit_y_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( 0, -1 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* large.
*/
@Test
public void getMapUnit_y_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( 0, size );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method returns the correct values for all coordinates in a small
* array of map units.
*/
@Test
public void getMapUnit()
{
int size = 2;
MapUnit[][] mapUnits = MapUnitHelper.buildArray( size );
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
for ( int i = 0; i < size; i++ )
{
for ( int j = 0; j < size; j++ )
{
Assert.assertEquals( "Unexpected return value for (" + i + ", " + j + ").",
mapUnits[ i ][ j ], mapTileType.getMapUnit( i, j ));
}
}
}
/**
* Verify that the getMapTileEdge() method throws the correct exception when the
* mapTileEdgePosition parameter is null.
*/
@Test
public void getMapTileEdge_mapTileEdgePosition_null()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapTileEdge( null );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdgePosition' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the getMapTileEdge() method returns the correct values for all four edges.
*/
@Test
public void getMapTileEdge()
{
MapTileEdge[] mapTileEdges = MapTileEdgeHelper.buildArray();
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value for \"top\".",
mapTileEdges[ 0 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.TOP ));
Assert.assertEquals( "Unexpected return value for \"right\".",
mapTileEdges[ 1 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.RIGHT ));
Assert.assertEquals( "Unexpected return value for \"bottom\".",
mapTileEdges[ 2 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.BOTTOM ));
Assert.assertEquals( "Unexpected return value for \"left\".",
mapTileEdges[ 3 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.LEFT ));
}
/**
* Verify that the getDistinctMapTileOrientations() method returns the correct value.
*/
@Test
public void getDistinctMapTileOrientations()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.FLIPPED
};
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.assertArrayEquals( "Unexpected result.", distinctMapTileOrientations,
mapTileType.getDistinctMapTileOrientations() );
}
/**
* Verify that the getWeight() method returns the correct value.
*/
@Test
public void getWeight()
{
int weight = GeneralHelper.getRandom().nextInt( 1000 );
MapTileType mapTileType = new MapTileType(
GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, weight );
Assert.assertEquals( "Unexpected result.", weight, mapTileType.getWeight() );
}
/**
* Verify that the toString() method returns the correct value.
*/
@Test
public void toStringTest()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType = new MapTileType(
name, MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value.", name, mapTileType.toString() );
}
/**
* Verify that the equals() method returns the correct result when called with a null reference.
*/
@Test
public void equals_null()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
MapTileType mapTileType2 = null;
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with the wrong type of
* object.
*/
@Test
public void equals_wrongType()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
Object mapTileType2 = new Object();
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with a map tile type
* with a different name.
*/
@Test
public void equals_differentName()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
MapTileType mapTileType2 = MapTileTypeHelper.build( 1 );
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with a map tile type
* with an identical name.
*/
@Test
public void equals_identicalName()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType1 = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
MapTileType mapTileType2 = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", true, result );
}
/**
* Verify that the hashCode() method returns the correct value.
*/
@Test
public void hashCodeTest()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value.", name.hashCode(), mapTileType.hashCode() );
}
}
| test/org/flexgen/map/test/MapTileTypeTest.java | /*
FlexGen : Flexible Map Generator Library
Copyright (C) 2009 - Jeffrey J. Weston <[email protected]>
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 FlexGen project 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER OR 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 org.flexgen.map.test;
import org.junit.Assert;
import org.junit.Test;
import org.flexgen.map.MapTileEdge;
import org.flexgen.map.MapTileEdgePosition;
import org.flexgen.map.MapTileOrientation;
import org.flexgen.map.MapTileType;
import org.flexgen.map.MapUnit;
import org.flexgen.test.helper.GeneralHelper;
import org.flexgen.test.helper.MapTileEdgeHelper;
import org.flexgen.test.helper.MapTileOrientationHelper;
import org.flexgen.test.helper.MapTileTypeHelper;
import org.flexgen.test.helper.MapUnitHelper;
/**
* Test class for the MapTileType class.
*/
public class MapTileTypeTest
{
/**
* Verify that the constructor throws the correct exception when the name parameter is null.
*/
@Test
public void constructor_name_null()
{
try
{
new MapTileType( null, MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'name' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is null.
*/
@Test
public void constructor_mapUnits_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
null, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapUnits' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter is an
* empty array.
*/
@Test
public void constructor_mapUnits_emptyArray()
{
MapUnit[][] mapUnits = new MapUnit[][] {};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapUnits' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of elements in all of the rows.
*/
@Test
public void constructor_mapUnits_inconsistentRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build(),
MapUnitHelper.build()
},
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of elements in each row.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter doesn't
* contain the same number of columns as it does rows.
*/
@Test
public void constructor_mapUnits_columnCountNotEqualRowCount()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
MapUnitHelper.build()
},
{
MapUnitHelper.build()
},
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must contain the same number of columns as it does rows.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapUnits parameter contains
* a null element.
*/
@Test
public void constructor_mapUnits_nullElement()
{
MapUnit[][] mapUnits = new MapUnit[][]
{
{
null
}
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'mapUnits' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter is
* null.
*/
@Test
public void constructor_mapTileEdges_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), null,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.", "Parameter 'mapTileEdges' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* doesn't contain enough elements.
*/
@Test
public void constructor_mapTileEdges_tooFew()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains too many elements.
*/
@Test
public void constructor_mapTileEdges_tooMany()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must contain 4 elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the mapTileEdges parameter
* contains a null element.
*/
@Test
public void constructor_mapTileEdges_nullElement()
{
MapTileEdge[] mapTileEdges = new MapTileEdge[]
{
MapTileEdgeHelper.build(),
null,
MapTileEdgeHelper.build(),
MapTileEdgeHelper.build()
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdges' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is null.
*/
@Test
public void constructor_distinctMapTileOrientations_nullArray()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(), null, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter is an empty array.
*/
@Test
public void constructor_distinctMapTileOrientations_emptyArray()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[] {};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must contain at least one element.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a null element.
*/
@Test
public void constructor_distinctMapTileOrientations_nullElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
null
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals(
"Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any null elements.",
e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the distinctMapTileOrientations
* parameter contains a duplicate element.
*/
@Test
public void constructor_distinctMapTileOrientations_duplicateElement()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.UPRIGHT
};
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'distinctMapTileOrientations' must not contain any " +
"duplicate elements.", e.getMessage() );
}
}
/**
* Verify that the constructor throws the correct exception when the weight parameter is less
* than zero.
*/
@Test
public void constructor_weight_tooSmall()
{
try
{
new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, -1 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'weight' cannot be less than 0.", e.getMessage() );
}
}
/**
* Verify that the getSize() method returns the correct value for a small array of map units.
*/
@Test
public void getSize()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
Assert.assertEquals( "Unexpected return value.", size, mapTileType.getSize() );
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* small.
*/
@Test
public void getMapUnit_x_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( -1, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the x parameter is too
* large.
*/
@Test
public void getMapUnit_x_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( size, 0 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'x' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* small.
*/
@Test
public void getMapUnit_y_tooSmall()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapUnit( 0, -1 );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be greater than or equal to 0.",
e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method throws the correct exception when the y parameter is too
* large.
*/
@Test
public void getMapUnit_y_tooLarge()
{
int size = GeneralHelper.getRandom().nextInt( 5 ) + 1;
MapTileType mapTileType = MapTileTypeHelper.build( size );
try
{
mapTileType.getMapUnit( 0, size );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'y' must be less than " + size + ".", e.getMessage() );
}
}
/**
* Verify that the getMapUnit() method returns the correct values for all coordinates in a small
* array of map units.
*/
@Test
public void getMapUnit()
{
int size = 2;
MapUnit[][] mapUnits = MapUnitHelper.buildArray( size );
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
mapUnits, MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
for ( int i = 0; i < size; i++ )
{
for ( int j = 0; j < size; j++ )
{
Assert.assertEquals( "Unexpected return value for (" + i + ", " + j + ").",
mapUnits[ i ][ j ], mapTileType.getMapUnit( i, j ));
}
}
}
/**
* Verify that the getMapTileEdge() method throws the correct exception when the
* mapTileEdgePosition parameter is null.
*/
@Test
public void getMapTileEdge_mapTileEdgePosition_null()
{
MapTileType mapTileType = MapTileTypeHelper.build( 1 );
try
{
mapTileType.getMapTileEdge( null );
Assert.fail( "Expected exception." );
}
catch ( IllegalArgumentException e )
{
Assert.assertEquals( "Unexpected message.",
"Parameter 'mapTileEdgePosition' cannot be null.",
e.getMessage() );
}
}
/**
* Verify that the getMapTileEdge() method returns the correct values for all four edges.
*/
@Test
public void getMapTileEdge()
{
MapTileEdge[] mapTileEdges = MapTileEdgeHelper.buildArray();
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), mapTileEdges,
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value for \"top\".",
mapTileEdges[ 0 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.TOP ));
Assert.assertEquals( "Unexpected return value for \"right\".",
mapTileEdges[ 1 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.RIGHT ));
Assert.assertEquals( "Unexpected return value for \"bottom\".",
mapTileEdges[ 2 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.BOTTOM ));
Assert.assertEquals( "Unexpected return value for \"left\".",
mapTileEdges[ 3 ],
mapTileType.getMapTileEdge( MapTileEdgePosition.LEFT ));
}
/**
* Verify that the getDistinctMapTileOrientations() method returns the correct value.
*/
@Test
public void getDistinctMapTileOrientations()
{
MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
{
MapTileOrientation.UPRIGHT,
MapTileOrientation.FLIPPED
};
MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
distinctMapTileOrientations, 0 );
Assert.assertArrayEquals( "Unexpected result.", distinctMapTileOrientations,
mapTileType.getDistinctMapTileOrientations() );
}
/**
* Verify that the getWeight() method returns the correct value.
*/
@Test
public void getWeight()
{
int weight = GeneralHelper.getRandom().nextInt( 1000 );
MapTileType mapTileType = new MapTileType(
GeneralHelper.getUniqueString(),
MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, weight );
Assert.assertEquals( "Unexpected result.", weight, mapTileType.getWeight() );
}
/**
* Verify that the toString() method returns the correct value.
*/
@Test
public void toStringTest()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType = new MapTileType(
name, MapUnitHelper.buildArray( 1 ), MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value.", name, mapTileType.toString() );
}
/**
* Verify that the equals() method returns the correct result when called with a null reference.
*/
@Test
public void equals_null()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
MapTileType mapTileType2 = null;
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with the wrong type of
* object.
*/
@Test
public void equals_wrongType()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
Object mapTileType2 = new Object();
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with a map tile type
* with a different name.
*/
@Test
public void equals_differentName()
{
MapTileType mapTileType1 = MapTileTypeHelper.build( 1 );
MapTileType mapTileType2 = MapTileTypeHelper.build( 1 );
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", false, result );
}
/**
* Verify that the equals() method returns the correct result when called with a map tile type
* with an identical name.
*/
@Test
public void equals_identicalName()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType1 = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
MapTileType mapTileType2 = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
boolean result = mapTileType1.equals( mapTileType2 );
Assert.assertEquals( "Unexpected result.", true, result );
}
/**
* Verify that the hashCode() method returns the correct value.
*/
@Test
public void hashCodeTest()
{
String name = GeneralHelper.getUniqueString();
MapTileType mapTileType = new MapTileType( name, MapUnitHelper.buildArray( 1 ),
MapTileEdgeHelper.buildArray(),
MapTileOrientationHelper.ALL_ORIENTATIONS, 0 );
Assert.assertEquals( "Unexpected return value.", name.hashCode(), mapTileType.hashCode() );
}
}
| Minor formatting fix.
| test/org/flexgen/map/test/MapTileTypeTest.java | Minor formatting fix. | <ide><path>est/org/flexgen/map/test/MapTileTypeTest.java
<ide> public void constructor_distinctMapTileOrientations_nullElement()
<ide> {
<ide> MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
<del> {
<del> null
<del> };
<add> {
<add> null
<add> };
<ide>
<ide> try
<ide> {
<ide> public void constructor_distinctMapTileOrientations_duplicateElement()
<ide> {
<ide> MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
<del> {
<del> MapTileOrientation.UPRIGHT,
<del> MapTileOrientation.UPRIGHT
<del> };
<add> {
<add> MapTileOrientation.UPRIGHT,
<add> MapTileOrientation.UPRIGHT
<add> };
<ide>
<ide> try
<ide> {
<ide> public void getDistinctMapTileOrientations()
<ide> {
<ide> MapTileOrientation[] distinctMapTileOrientations = new MapTileOrientation[]
<del> {
<del> MapTileOrientation.UPRIGHT,
<del> MapTileOrientation.FLIPPED
<del> };
<add> {
<add> MapTileOrientation.UPRIGHT,
<add> MapTileOrientation.FLIPPED
<add> };
<ide>
<ide> MapTileType mapTileType = new MapTileType( GeneralHelper.getUniqueString(),
<ide> MapUnitHelper.buildArray( 1 ), |
|
Java | apache-2.0 | ac244527b1b1c977d70b360861c30af9540eafa0 | 0 | paulovmr/uberfire,psiroky/uberfire,uberfire/uberfire,mbarkley/uberfire,ederign/uberfire,psiroky/uberfire,Salaboy/uberfire,qmx/uberfire,baldimir/uberfire,paulovmr/uberfire,mbiarnes/uberfire,baldimir/uberfire,karreiro/uberfire,kiereleaseuser/uberfire,ederign/uberfire,paulovmr/uberfire,paulovmr/uberfire,mbarkley/uberfire,cristianonicolai/uberfire,porcelli-forks/uberfire,wmedvede/uberfire,wmedvede/uberfire,dgutierr/uberfire,qmx/uberfire,baldimir/uberfire,qmx/uberfire,Salaboy/uberfire,Salaboy/uberfire,wmedvede/uberfire,cristianonicolai/uberfire,psiroky/uberfire,qmx/uberfire,mbiarnes/uberfire,uberfire/uberfire,karreiro/uberfire,uberfire/uberfire,ederign/uberfire,Salaboy/uberfire,psiroky/uberfire,dgutierr/uberfire,porcelli-forks/uberfire,porcelli-forks/uberfire,mbiarnes/uberfire,dgutierr/uberfire,karreiro/uberfire,kiereleaseuser/uberfire,uberfire/uberfire,karreiro/uberfire,kiereleaseuser/uberfire,dgutierr/uberfire,cristianonicolai/uberfire,paulovmr/uberfire,cristianonicolai/uberfire,mbarkley/uberfire,mbiarnes/uberfire,wmedvede/uberfire,mbarkley/uberfire,porcelli-forks/uberfire,ederign/uberfire,kiereleaseuser/uberfire,baldimir/uberfire | package org.uberfire.workbench.model.menu;
/**
* Visitor interface for implementing arbitrary operations over menus. For example, a visitor could filter a menu tree
* for items that the current user has permission to see; it could build widgets in a particular view module; it could
* simply dump the menu structure to a string.
*/
public interface MenuVisitor {
/**
* Visits the top-level menu container. This is the first method invoked when visiting a complete menu tree.
*
* @param menus
* the top-level container of the menus that will be visited.
* @return true if the visitor would like to continue down the tree and visit all children; false if it wants to
* skip this node. Since this is the root node, returning false from this call will result in no more calls
* to the visitor.
*/
boolean visitEnter( Menus menus );
/**
* Ends the visit of the top-level menu container. This is the last method invoked when visiting a complete menu tree.
* <p>
* <i>Note that this method is not called if {@link #visitEnter(Menus)} returns false.</i>
*
* @param menus the top-level container of the menus that will be visited.
*/
void visitLeave( Menus menus );
/**
* Visits a menu group in the tree of menus. A menu group has zero or more MenuItem children.
*
* @param menuGroup
* the menu group to visit.
* @return true if the visitor would like to visit all children of this node; false if it wants to skip this node. A
* visitor that returns false from this node will not receive any further calls for this node or its
* descendants. In particular, there will be no corresponding {@link #visitLeave(MenuGroup)} call for this
* node.
*/
boolean visitEnter( MenuGroup menuGroup );
/**
* Visits a menu group in the tree of menus. All descendants of the given menu group have been visited before this method is called.
* <p>
* <i>Note that this method is not called for a MenuGroup where the {@link #visitEnter(MenuGroup)} method returned false.</i>
*
* @param menuGroup the menu group to leave.
*/
void visitLeave( MenuGroup menuGroup );
/**
* Visits a plain menu item in the tree.
*
* @param menuItemPlain the plain menu item to visit.
*/
void visit( MenuItemPlain menuItemPlain );
/**
* Visits a menu item that has an associated command.
*
* @param menuItemCommand the command menu item to visit.
*/
void visit( MenuItemCommand menuItemCommand );
/**
* Visits a custom menu item in the menu tree.
*
* @param menuCustom the custom (application provides the widget) menu item to visit.
*/
void visit( MenuCustom<?> menuCustom );
}
| uberfire-api/src/main/java/org/uberfire/workbench/model/menu/MenuVisitor.java | package org.uberfire.workbench.model.menu;
/**
* Visitor interface for implementing arbitrary operations over menus. For example, a visitor could filter a menu tree
* for items that the current user has permission to see; it could build widgets in a particular view module; it could
* simply dump the menu structure to a string.
*/
public interface MenuVisitor {
/**
* Visits the top-level menu container. This is the first method invoked when visiting a complete menu tree.
*
* @param menus
* the top-level container of the menus that will be visited.
* @return true if the visitor would like to continue down the tree and visit all children; false if it wants to
* skip this node. Since this is the root node, returning false from this call will result in no more calls
* to the visitor.
*/
boolean visitEnter( Menus menus );
/**
* Ends the visit of the top-level menu container. This is the last method invoked when visiting a complete menu tree.
* <p>
* <i>Note that this method is not called if {@link #visitEnter(Menus)} returns false.</i>
*
* @param menus the top-level container of the menus that will be visited.
*/
void visitLeave( Menus menus );
/**
* Visits a menu group in the tree of menus. A menu group has zero or more MenuItem children.
*
* @param menuGroup
* the menu group to visit.
* @return true if the visitor would like to visit all children of this node; false if it wants to skip this node. A
* visitor that returns false from this node will not receive any further calls for this node or its
* descendants. In particular, there will be no corresponding {@link #visitLeave(MenuGroup)} call for this
* node.
*/
boolean visitEnter( MenuGroup menuGroup );
/**
* Visits a menu group in the tree of menus. All descendants of the given menu group have been visited before this method is called.
* <p>
* <i>Note that this method is not called for a MenuGroup where the {@link #visitEnter(MenuGroup)} method returned false.</i>
*
* @param menuGroup the menu group to leave.
*/
void visitLeave( MenuGroup menuGroup );
/**
* Visits a plain menu item in the tree.
*
* @param menuItemPlain the plain menu item to visit.
*/
void visit( MenuItemPlain menuItemPlain );
/**
* Visits a menu item that has an associated command.
*
* @param menuItemPlain the plain menu item to visit.
*/
void visit( MenuItemCommand menuItemCommand );
/**
* Visits a custom menu item in the menu tree.
*
* @param menuCustom the custom (application provides the widget) menu item to visit.
*/
void visit( MenuCustom<?> menuCustom );
}
| Fixed comment
| uberfire-api/src/main/java/org/uberfire/workbench/model/menu/MenuVisitor.java | Fixed comment | <ide><path>berfire-api/src/main/java/org/uberfire/workbench/model/menu/MenuVisitor.java
<ide> /**
<ide> * Visits a menu item that has an associated command.
<ide> *
<del> * @param menuItemPlain the plain menu item to visit.
<add> * @param menuItemCommand the command menu item to visit.
<ide> */
<ide> void visit( MenuItemCommand menuItemCommand );
<ide> |
|
JavaScript | mit | 409a36a2c41dd575627f4e9c9bfcd104a29663a7 | 0 | gatsbyjs/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby,gatsbyjs/gatsby | import React, { useState, useEffect } from "react"
import SelectInput from "ink-select-input"
import { render, Box, Text, useInput, useApp, Transform } from "ink"
import Spinner from "ink-spinner"
import StepRenderer from "../components/step-renderer"
import hicat from "hicat"
import { trackCli } from "gatsby-telemetry"
import {
useResource,
useResourceByUUID,
ResourceProvider,
} from "../renderer/resource-provider"
import terminalLink from "terminal-link"
import PropTypes from "prop-types"
import {
createClient,
useMutation,
useSubscription,
Provider,
defaultExchanges,
subscriptionExchange,
} from "urql"
import { SubscriptionClient } from "subscriptions-transport-ws"
import fetch from "node-fetch"
import ws from "ws"
import semver from "semver"
import remove from "unist-util-remove"
import recipesList from "../recipes-list"
const removeJsx = () => tree => {
remove(tree, `export`, () => true)
return tree
}
// Inline ink-link as it's not upgraded to v3 yet
const Link = props => (
<Transform
transform={children =>
terminalLink(children, props.url, { fallback: props.fallback })
}
>
<Text>{props.children}</Text>
</Transform>
)
Link.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
url: PropTypes.string,
fallback: PropTypes.bool,
}
Link.defaultProps = {
url: ``,
fallback: true,
}
// Check for what version of React is loaded & warn if it's too low.
if (semver.lt(React.version, `16.8.0`)) {
console.log(
`Recipes works best with newer versions of React. Please file a bug report if you see this warning.`
)
}
const WelcomeMessage = () => (
<>
<Box
borderStyle="double"
borderColor="magentaBright"
padding={1}
marginBottom={1}
marginLeft={2}
marginRight={2}
>
<Text>
Thank you for trying the experimental version of Gatsby Recipes!
</Text>
</Box>
<Div marginBottom={2} alignItems="center">
<Text>
Please ask questions, share your recipes, report bugs, and subscribe for
updates in our umbrella issue at
https://github.com/gatsbyjs/gatsby/issues/22991
</Text>
</Div>
</>
)
const RecipesList = ({ setRecipe }) => {
const items = recipesList
return (
<SelectInput.default
items={items}
onSelect={setRecipe}
indicatorComponent={item => (
<Text color={item.isSelected ? `yellow` : `magentaBright`}>
{item.isSelected ? `>>` : ` `}
{item.label}
</Text>
)}
itemComponent={props => (
<Text color="magentaBright">
{props.isSelected}
{` `}
{props.label}
</Text>
)}
/>
)
}
const Div = props => (
<Box textWrap="wrap" flexDirection="column" marginBottom={1} {...props} />
)
// Markdown ignores new lines and so do we.
function eliminateNewLines(children) {
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child.replace(/(\r\n|\n|\r)/gm, ` `)
}
if (child.props.children) {
child = React.cloneElement(child, {
children: eliminateNewLines(child.props.children),
})
}
return child
})
}
const ResourceComponent = props => {
let resource
if (props._key) {
resource = useResource(props._key)
} else {
resource = useResourceByUUID(props._uuid)
}
return (
<Div marginBottom={1}>
<Text color="yellow" backgroundColor="black" bold underline>
{resource.resourceName}:
</Text>
<Text color="green">{resource?.describe}</Text>
{resource?.diff ? (
<>
<Text>{` `}</Text>
<Text>{resource?.diff}</Text>
</>
) : null}
{resource?.error ? (
<>
<Text>{` `}</Text>
<Text backgroundColor="#C41E3A" color="white">
{resource?.error}
</Text>
</>
) : null}
</Div>
)
}
const components = {
inlineCode: props => <Text>`{props.children}`</Text>,
pre: props => <Div {...props} />,
code: props => {
// eslint-disable-next-line
let language = "```"
if (props.className) {
// eslint-disable-next-line
language = props.className.split(`-`)[1]
}
const children = hicat(props.children.trim(), { lang: language })
const ansi = `\`\`\`${language}\n${children.ansi}\n\`\`\``
return (
<Div marginBottom={1}>
<Text>{ansi}</Text>
</Div>
)
},
h1: props => (
<Box marginBottom={1}>
<Text bold underline {...props} />
</Box>
),
h2: props => <Text bold {...props} />,
h3: props => <Text bold italic {...props} />,
h4: props => <Text bold {...props} />,
h5: props => <Text bold {...props} />,
h6: props => <Text bold {...props} />,
a: ({ href, children }) => <Link url={href}>{children}</Link>,
strong: props => <Text bold {...props} />,
em: props => <Text italic {...props} />,
p: props => {
const children = eliminateNewLines(props.children)
return (
<Div>
<Text>{children}</Text>
</Div>
)
},
ul: props => <Div marginBottom={1}>{props.children}</Div>,
li: props => <Text>* {props.children}</Text>,
Config: () => null,
GatsbyPlugin: props => <ResourceComponent {...props} />,
NPMPackageJson: props => <ResourceComponent {...props} />,
NPMPackage: props => <ResourceComponent {...props} />,
File: props => <ResourceComponent {...props} />,
Directory: props => <ResourceComponent {...props} />,
GatsbyShadowFile: () => null,
NPMScript: props => <ResourceComponent {...props} />,
RecipeIntroduction: props => <Div {...props} />,
RecipeStep: props => {
const children = React.Children.toArray(props.children)
const firstChild = children.shift()
children.unshift(
<Box key="header" flexDirection="row">
<Text>
{props.step}){` `}
</Text>
{firstChild}
</Box>
)
return (
<Div>
<Box
borderStyle="single"
padding={1}
flexDirection="column"
borderColor="magentaBright"
>
{children}
</Box>
</Div>
)
},
div: props => <Div {...props} />,
}
export default async ({
recipe,
isDevelopMode,
isInstallMode,
graphqlPort,
projectRoot,
}) => {
try {
const GRAPHQL_ENDPOINT = `http://localhost:${graphqlPort}/graphql`
const subscriptionClient = new SubscriptionClient(
`ws://localhost:${graphqlPort}/graphql`,
{
reconnect: true,
},
ws
)
let showRecipesList = false
if (!recipe) {
showRecipesList = true
}
const client = createClient({
fetch,
url: GRAPHQL_ENDPOINT,
exchanges: [
...defaultExchanges,
subscriptionExchange({
forwardSubscription(operation) {
return subscriptionClient.request(operation)
},
}),
],
})
const Plan = ({ state, localRecipe, isDevelopMode }) => {
const { exit } = useApp()
// Exit the app after we render
useEffect(() => {
if (!isDevelopMode) {
exit()
}
}, [])
return (
<>
<ResourceProvider
// Exclude inputs as they are components (so "plans" currrently
// (we need to cleanup our names) too like resources which is why we
// exclude them. The input from the inputs (haha) are ignored unless
// they're passed as props into a resource component in which case
// they're validated like normal.
value={
state.context.plan?.filter(p => p.resourceName !== `Input`) || []
}
>
<WelcomeMessage />
{isDevelopMode ? (
<Box flexDirection="column" marginBottom={2}>
<Text strong underline>
DEVELOP MODE
</Text>
</Box>
) : null}
{state.context.stepsAsJS.map((step, i) => (
<StepRenderer
key={`step-${i}`}
components={components}
remarkPlugins={[removeJsx]}
>
{state.context.exports?.join(`\n`) + `\n\n` + step}
</StepRenderer>
))}
<Text>{`\n------\n`}</Text>
<Text color="yellow">To install this recipe, run:</Text>
<Text>{` `}</Text>
<Text>
{` `}gatsby recipes {localRecipe} --install
</Text>
<Text>{` `}</Text>
</ResourceProvider>
</>
)
}
const Installing = ({ state }) => (
<Div>
{state.context.plan.map((p, i) => (
<Box
textWrap="wrap"
flexDirection="column"
key={`${p.resourceName}-${i}`}
>
<Text>
{p.isDone ? `✔ ` : <Spinner.default />}
{` `}
<Text italic>{p.resourceName}:</Text>
{` `}
{p.isDone ? p._message : p.describe}
{` `}
{state.context.elapsed > 0 && (
<Text>({state.context.elapsed / 1000}s elapsed)</Text>
)}
</Text>
</Box>
))}
</Div>
)
let sentContinue = false
const RecipeInterpreter = () => {
const { exit } = useApp()
// eslint-disable-next-line
const [localRecipe, setRecipe] = useState(recipe)
const [subscriptionResponse] = useSubscription(
{
query: `
subscription {
operation {
state
}
}
`,
},
(_prev, now) => now
)
// eslint-disable-next-line
const [_, createOperation] = useMutation(`
mutation ($recipePath: String!, $projectRoot: String!, $isDevelopMode: Boolean!) {
createOperation(recipePath: $recipePath, projectRoot: $projectRoot, watchChanges: $isDevelopMode)
}
`)
// eslint-disable-next-line
const [__, _sendEvent] = useMutation(`
mutation($event: String!, $input: String) {
sendEvent(event: $event, input: $input)
}
`)
const sendEvent = ({ event, input }) => {
if (input) {
_sendEvent({
event,
input: JSON.stringify(input),
})
} else {
_sendEvent({ event })
}
}
subscriptionClient.connectionCallback = async () => {
if (!showRecipesList) {
try {
await createOperation({
recipePath: localRecipe,
projectRoot,
isDevelopMode,
})
} catch (e) {
console.log(`error creating operation`, e)
}
}
}
const state =
subscriptionResponse.data &&
JSON.parse(subscriptionResponse.data.operation.state)
useInput((_, key) => {
if (showRecipesList) {
return
}
if (key.return) {
sendEvent({ event: `CONTINUE` })
}
})
if (showRecipesList) {
return (
<>
<WelcomeMessage />
<Text bold underline>
Select a recipe to run
</Text>
<RecipesList
setRecipe={async recipeItem => {
if (recipeItem.value.endsWith(`.mdx`)) {
setRecipe(recipeItem.value.slice(0, -4))
} else {
setRecipe(recipeItem.value)
}
trackCli(`RECIPE_RUN`, { name: recipeItem.value })
showRecipesList = false
try {
await createOperation({
recipePath: recipeItem.value,
projectRoot,
isDevelopMode: false,
})
} catch (e) {
console.log(`error creating operation`, e)
}
}}
/>
</>
)
}
const ValidationErrors = state => {
if (state.context?.plan) {
return (
<>
<Text bold>
The recipe didn't validate. Please fix the following errors:
</Text>
<Text>{`\n`}</Text>
{state.context.plan
.filter(p => p.error)
.map((p, i) => (
<ResourceComponent key={i} {...p} />
))}
</>
)
} else return null
}
const GeneralError = ({ state }) => {
let errors = []
if (state.context.error) {
errors = Array.isArray(state.context.error.error)
? state.context.error.error
: [state.context.error.error]
} else {
// Errors are on a plan.
errors = state.context.plan?.filter(p => p.error)
}
if (errors.length > 0) {
return (
<>
<Text bold>The recipe has an error:</Text>
<Text>{`\n`}</Text>
{errors.map((error, i) => (
<Text key={i} backgroundColor="#C41E3A" color="white">
{error.error}
</Text>
))}
</>
)
} else return null
}
if (state?.value === `doneError`) {
process.nextTick(() => process.exit())
return (
<ResourceProvider
value={
state.context.plan?.filter(p => p.resourceName !== `Input`) || []
}
>
<ValidationErrors />
<GeneralError state={state} />
</ResourceProvider>
)
}
let isReady
// If installing, continue from presentPlan to applyingPlan
if (state?.value === `presentPlan` && isInstallMode) {
if (!sentContinue) {
sendEvent({ event: `CONTINUE` })
sentContinue = true
}
}
// install mode
if (isInstallMode) {
isReady = state?.value === `applyingPlan` || state?.value === `done`
} else {
isReady = state?.value === `presentPlan`
}
if (!isReady) {
return (
<Text>
<Spinner.default /> Loading recipe
</Text>
)
}
const isDone = state.value === `done`
if (isDone) {
process.nextTick(() => {
subscriptionClient.close()
exit()
process.stdout.write(
`\n\n---\n\n\nThe recipe finished successfully!\n\n`
)
process.exit()
})
// return null
}
if (isInstallMode) {
return <Installing state={state} />
} else {
return (
<Plan
state={state}
localRecipe={localRecipe}
isDevelopMode={isDevelopMode}
/>
)
}
}
const Wrapper = () => (
<>
<Provider value={client}>
<Text>{` `}</Text>
<RecipeInterpreter />
</Provider>
</>
)
const Recipe = () => <Wrapper />
// Enable experimental mode for more efficient reconciler and renderer
const { waitUntilExit } = render(<Recipe />, { experimental: true })
await waitUntilExit()
} catch (e) {
console.log(e)
}
}
| packages/gatsby-recipes/src/cli/index.js | import React, { useState, useEffect } from "react"
import SelectInput from "ink-select-input"
import { render, Box, Text, useInput, useApp, Transform } from "ink"
import Spinner from "ink-spinner"
import StepRenderer from "../components/step-renderer"
import hicat from "hicat"
import { trackCli } from "gatsby-telemetry"
import {
useResource,
useResourceByUUID,
ResourceProvider,
} from "../renderer/resource-provider"
import terminalLink from "terminal-link"
import PropTypes from "prop-types"
import {
createClient,
useMutation,
useSubscription,
Provider,
defaultExchanges,
subscriptionExchange,
} from "urql"
import { SubscriptionClient } from "subscriptions-transport-ws"
import fetch from "node-fetch"
import ws from "ws"
import semver from "semver"
import remove from "unist-util-remove"
import recipesList from "../recipes-list"
const removeJsx = () => tree => {
remove(tree, `export`, () => true)
return tree
}
// Inline ink-link as it's not upgraded to v3 yet
const Link = props => (
<Transform
transform={children =>
terminalLink(children, props.url, { fallback: props.fallback })
}
>
<Text>{props.children}</Text>
</Transform>
)
Link.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]).isRequired,
url: PropTypes.string,
fallback: PropTypes.bool,
}
Link.defaultProps = {
url: ``,
fallback: true,
}
// Check for what version of React is loaded & warn if it's too low.
if (semver.lt(React.version, `16.8.0`)) {
console.log(
`Recipes works best with newer versions of React. Please file a bug report if you see this warning.`
)
}
const WelcomeMessage = () => (
<>
<Box
borderStyle="double"
borderColor="magentaBright"
padding={1}
marginBottom={1}
marginLeft={2}
marginRight={2}
>
<Text>
Thank you for trying the experimental version of Gatsby Recipes!
</Text>
</Box>
<Div marginBottom={2} alignItems="center">
<Text>
Please ask questions, share your recipes, report bugs, and subscribe for
updates in our umbrella issue at
https://github.com/gatsbyjs/gatsby/issues/22991
</Text>
</Div>
</>
)
const RecipesList = ({ setRecipe }) => {
const items = recipesList
return (
<SelectInput.default
items={items}
onSelect={setRecipe}
indicatorComponent={item => (
<Text color={item.isSelected ? `yellow` : `magentaBright`}>
{item.isSelected ? `>>` : ` `}
{item.label}
</Text>
)}
itemComponent={props => (
<Text color="magentaBright">
{props.isSelected}
{` `}
{props.label}
</Text>
)}
/>
)
}
const Div = props => (
<Box textWrap="wrap" flexDirection="column" marginBottom={1} {...props} />
)
// Markdown ignores new lines and so do we.
function eliminateNewLines(children) {
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child.replace(/(\r\n|\n|\r)/gm, ` `)
}
if (child.props.children) {
child = React.cloneElement(child, {
children: eliminateNewLines(child.props.children),
})
}
return child
})
}
const ResourceComponent = props => {
let resource
if (props._key) {
resource = useResource(props._key)
} else {
resource = useResourceByUUID(props._uuid)
}
return (
<Div marginBottom={1}>
<Text color="yellow" backgroundColor="black" bold underline>
{resource.resourceName}:
</Text>
<Text color="green">{resource?.describe}</Text>
{resource?.diff ? (
<>
<Text>{` `}</Text>
<Text>{resource?.diff}</Text>
</>
) : null}
{resource?.error ? (
<>
<Text>{` `}</Text>
<Text backgroundColor="#C41E3A" color="white">
{resource?.error}
</Text>
</>
) : null}
</Div>
)
}
const components = {
inlineCode: props => <Text>`{props.children}`</Text>,
pre: props => <Div {...props} />,
code: props => {
// eslint-disable-next-line
let language = "```"
if (props.className) {
// eslint-disable-next-line
language = props.className.split(`-`)[1]
}
const children = hicat(props.children.trim(), { lang: language })
const ansi = `\`\`\`${language}\n${children.ansi}\n\`\`\``
return (
<Div marginBottom={1}>
<Text>{ansi}</Text>
</Div>
)
},
h1: props => (
<Box marginBottom={1}>
<Text bold underline {...props} />
</Box>
),
h2: props => <Text bold {...props} />,
h3: props => <Text bold italic {...props} />,
h4: props => <Text bold {...props} />,
h5: props => <Text bold {...props} />,
h6: props => <Text bold {...props} />,
a: ({ href, children }) => <Link url={href}>{children}</Link>,
strong: props => <Text bold {...props} />,
em: props => <Text italic {...props} />,
p: props => {
const children = eliminateNewLines(props.children)
return (
<Div>
<Text>{children}</Text>
</Div>
)
},
ul: props => <Div marginBottom={1}>{props.children}</Div>,
li: props => <Text>* {props.children}</Text>,
Config: () => null,
GatsbyPlugin: props => <ResourceComponent {...props} />,
NPMPackageJson: props => <ResourceComponent {...props} />,
NPMPackage: props => <ResourceComponent {...props} />,
File: props => <ResourceComponent {...props} />,
Directory: props => <ResourceComponent {...props} />,
GatsbyShadowFile: () => null,
NPMScript: props => <ResourceComponent {...props} />,
RecipeIntroduction: props => <Div {...props} />,
RecipeStep: props => {
const children = React.Children.toArray(props.children)
const firstChild = children.shift()
children.unshift(
<Box key="header" flexDirection="row">
<Text>
{props.step}){` `}
</Text>
{firstChild}
</Box>
)
return (
<Div>
<Box
borderStyle="single"
padding={1}
flexDirection="column"
borderColor="magentaBright"
>
{children}
</Box>
</Div>
)
},
div: props => <Div {...props} />,
}
export default async ({
recipe,
isDevelopMode,
isInstallMode,
graphqlPort,
projectRoot,
}) => {
try {
const GRAPHQL_ENDPOINT = `http://localhost:${graphqlPort}/graphql`
const subscriptionClient = new SubscriptionClient(
`ws://localhost:${graphqlPort}/graphql`,
{
reconnect: true,
},
ws
)
let showRecipesList = false
if (!recipe) {
showRecipesList = true
}
const client = createClient({
fetch,
url: GRAPHQL_ENDPOINT,
exchanges: [
...defaultExchanges,
subscriptionExchange({
forwardSubscription(operation) {
return subscriptionClient.request(operation)
},
}),
],
})
const Plan = ({ state, localRecipe, isDevelopMode }) => {
const { exit } = useApp()
// Exit the app after we render
useEffect(() => {
if (!isDevelopMode) {
exit()
}
}, [])
return (
<>
<ResourceProvider
// Exclude inputs as they are components (so "plans" currrently
// (we need to cleanup our names) too like resources which is why we
// exclude them. The input from the inputs (haha) are ignored unless
// they're passed as props into a resource component in which case
// they're validated like normal.
value={
state.context.plan?.filter(p => p.resourceName !== `Input`) || []
}
>
<WelcomeMessage />
{isDevelopMode ? (
<Box flexDirection="column" marginBottom={2}>
<Text strong underline>
DEVELOP MODE
</Text>
</Box>
) : null}
{state.context.stepsAsJS.map((step, i) => (
<StepRenderer
key={`step-${i}`}
components={components}
remarkPlugins={[removeJsx]}
>
{state.context.exports?.join(`\n`) + `\n\n` + step}
</StepRenderer>
))}
<Text>{`\n------\n`}</Text>
<Text color="yellow">To install this recipe, run:</Text>
<Text>{` `}</Text>
<Text>
{` `}gatsby recipes {localRecipe} --install
</Text>
<Text>{` `}</Text>
</ResourceProvider>
</>
)
}
const Installing = ({ state }) => (
<Div>
{state.context.plan.map((p, i) => (
<Box
textWrap="wrap"
flexDirection="column"
key={`${p.resourceName}-${i}`}
>
<Text>
{p.isDone ? `✔ ` : <Spinner.default />}
{` `}
<Text italic>{p.resourceName}:</Text>
{` `}
{p.isDone ? p._message : p.describe}
{` `}
{state.context.elapsed > 0 && (
<Text>({state.context.elapsed / 1000}s elapsed)</Text>
)}
</Text>
</Box>
))}
</Div>
)
let sentContinue = false
const RecipeInterpreter = () => {
const { exit } = useApp()
// eslint-disable-next-line
const [localRecipe, setRecipe] = useState(recipe)
const [subscriptionResponse] = useSubscription(
{
query: `
subscription {
operation {
state
}
}
`,
},
(_prev, now) => now
)
// eslint-disable-next-line
const [_, createOperation] = useMutation(`
mutation ($recipePath: String!, $projectRoot: String!, $isDevelopMode: Boolean!) {
createOperation(recipePath: $recipePath, projectRoot: $projectRoot, watchChanges: $isDevelopMode)
}
`)
// eslint-disable-next-line
const [__, _sendEvent] = useMutation(`
mutation($event: String!, $input: String) {
sendEvent(event: $event, input: $input)
}
`)
const sendEvent = ({ event, input }) => {
if (input) {
_sendEvent({
event,
input: JSON.stringify(input),
})
} else {
_sendEvent({ event })
}
}
subscriptionClient.connectionCallback = async () => {
if (!showRecipesList) {
try {
await createOperation({
recipePath: localRecipe,
projectRoot,
isDevelopMode,
})
} catch (e) {
console.log(`error creating operation`, e)
}
}
}
const state =
subscriptionResponse.data &&
JSON.parse(subscriptionResponse.data.operation.state)
useInput((_, key) => {
if (showRecipesList) {
return
}
if (key.return) {
sendEvent({ event: `CONTINUE` })
}
})
if (showRecipesList) {
return (
<>
<WelcomeMessage />
<Text bold underline>
Select a recipe to run
</Text>
<RecipesList
setRecipe={async recipeItem => {
setRecipe(recipeItem.value.slice(0, -4))
trackCli(`RECIPE_RUN`, { name: recipeItem.value })
showRecipesList = false
try {
await createOperation({
recipePath: recipeItem.value,
projectRoot,
isDevelopMode: false,
})
} catch (e) {
console.log(`error creating operation`, e)
}
}}
/>
</>
)
}
const ValidationErrors = state => {
if (state.context?.plan) {
return (
<>
<Text bold>
The recipe didn't validate. Please fix the following errors:
</Text>
<Text>{`\n`}</Text>
{state.context.plan
.filter(p => p.error)
.map((p, i) => (
<ResourceComponent key={i} {...p} />
))}
</>
)
} else return null
}
const GeneralError = ({ state }) => {
let errors = []
if (state.context.error) {
errors = Array.isArray(state.context.error.error)
? state.context.error.error
: [state.context.error.error]
} else {
// Errors are on a plan.
errors = state.context.plan?.filter(p => p.error)
}
if (errors.length > 0) {
return (
<>
<Text bold>The recipe has an error:</Text>
<Text>{`\n`}</Text>
{errors.map((error, i) => (
<Text key={i} backgroundColor="#C41E3A" color="white">
{error.error}
</Text>
))}
</>
)
} else return null
}
if (state?.value === `doneError`) {
process.nextTick(() => process.exit())
return (
<ResourceProvider
value={
state.context.plan?.filter(p => p.resourceName !== `Input`) || []
}
>
<ValidationErrors />
<GeneralError state={state} />
</ResourceProvider>
)
}
let isReady
// If installing, continue from presentPlan to applyingPlan
if (state?.value === `presentPlan` && isInstallMode) {
if (!sentContinue) {
sendEvent({ event: `CONTINUE` })
sentContinue = true
}
}
// install mode
if (isInstallMode) {
isReady = state?.value === `applyingPlan` || state?.value === `done`
} else {
isReady = state?.value === `presentPlan`
}
if (!isReady) {
return (
<Text>
<Spinner.default /> Loading recipe
</Text>
)
}
const isDone = state.value === `done`
if (isDone) {
process.nextTick(() => {
subscriptionClient.close()
exit()
process.stdout.write(
`\n\n---\n\n\nThe recipe finished successfully!\n\n`
)
process.exit()
})
// return null
}
if (isInstallMode) {
return <Installing state={state} />
} else {
return (
<Plan
state={state}
localRecipe={localRecipe}
isDevelopMode={isDevelopMode}
/>
)
}
}
const Wrapper = () => (
<>
<Provider value={client}>
<Text>{` `}</Text>
<RecipeInterpreter />
</Provider>
</>
)
const Recipe = () => <Wrapper />
// Enable experimental mode for more efficient reconciler and renderer
const { waitUntilExit } = render(<Recipe />, { experimental: true })
await waitUntilExit()
} catch (e) {
console.log(e)
}
}
| fix(gatsby-recipes): Only remove the ".mdx" ending if running local recipe (#27718)
This fixes showing the correct install command when running recipes from the recipes list shown when running `gatsby recipes` | packages/gatsby-recipes/src/cli/index.js | fix(gatsby-recipes): Only remove the ".mdx" ending if running local recipe (#27718) | <ide><path>ackages/gatsby-recipes/src/cli/index.js
<ide> </Text>
<ide> <RecipesList
<ide> setRecipe={async recipeItem => {
<del> setRecipe(recipeItem.value.slice(0, -4))
<add> if (recipeItem.value.endsWith(`.mdx`)) {
<add> setRecipe(recipeItem.value.slice(0, -4))
<add> } else {
<add> setRecipe(recipeItem.value)
<add> }
<ide> trackCli(`RECIPE_RUN`, { name: recipeItem.value })
<ide> showRecipesList = false
<ide> try { |
|
Java | mit | cb18855176384059f3db5ed54c4632473ec26be5 | 0 | PunchThrough/bean-sdk-android,PunchThrough/Bean-Android-SDK,PunchThrough/bean-sdk-android,PunchThrough/Bean-Android-SDK | package com.punchthrough.bean.sdk.internal.upload.firmware;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import com.punchthrough.bean.sdk.BeanManager;
import com.punchthrough.bean.sdk.internal.ble.BaseProfile;
import com.punchthrough.bean.sdk.internal.ble.GattClient;
import com.punchthrough.bean.sdk.internal.device.DeviceProfile;
import com.punchthrough.bean.sdk.internal.exception.OADException;
import com.punchthrough.bean.sdk.internal.utility.Constants;
import com.punchthrough.bean.sdk.internal.utility.Convert;
import com.punchthrough.bean.sdk.internal.utility.Watchdog;
import com.punchthrough.bean.sdk.message.BeanError;
import com.punchthrough.bean.sdk.message.UploadProgress;
import com.punchthrough.bean.sdk.upload.FirmwareBundle;
import com.punchthrough.bean.sdk.upload.FirmwareImage;
import java.util.Arrays;
public class OADProfile extends BaseProfile {
/**
* Custom OAD Profile for LightBlue Bean devices.
*
* This class encapsulates data and processes related to firmware updates to the CC2540.
*
*/
protected static final String TAG = "OADProfile";
// OAD Characteristic handles
private BluetoothGattCharacteristic oadIdentify;
private BluetoothGattCharacteristic oadBlock;
private Watchdog watchdog;
// OAD Internal State
private static final int OAD_TIMEOUT_SECONDS = 30;
private boolean ready = false;
/* The current state of the OAD state-machine */
private OADState oadState = OADState.INACTIVE;
/* The last offered image or the accepted image depending on state of the OAD process */
private FirmwareImage currentImage;
/* Bundle of firmware images provided by the client */
private FirmwareBundle firmwareBundle;
/* Oad Listener */
private OADListener oadListener;
/* The maximum allowed blocks queued and/or in-flight before receiving a new request */
private final int MAX_IN_AIR_BLOCKS = 8;
/* Keeps track of the next block to send which is not equal to the block requested */
private int nextBlock = 0;
/* Used to record KB/s during block transfers */
private long blockTransferStarted = 0;
public OADProfile(GattClient client, Watchdog watchdog) {
super(client);
this.watchdog = watchdog;
reset();
}
private Watchdog.WatchdogListener watchdogListener = new Watchdog.WatchdogListener() {
@Override
public void expired() {
fail(BeanError.OAD_TIMEOUT);
}
};
private OADApproval oadApproval = new OADApproval() {
public boolean approved = false;
@Override
public void allow() {
Log.i(TAG, "Client has allowed the OAD Process to continue.");
approved = true;
startOfferingImages();
}
@Override
public void deny() {
Log.i(TAG, "Client denied the OAD Process from continuing.");
approved = false;
fail(BeanError.CLIENT_REJECTED);
}
@Override
public void reset() {
approved = false;
}
@Override
public boolean isApproved() {
return approved;
}
};
private void setState(OADState state) {
Log.i(TAG, String.format("(%s) OAD State Change: %s -> %s", mGattClient.bleAddress(), oadState.name(), state.name()));
oadState = state;
watchdog.poke();
if (oadListener != null ) {
oadListener.stateChange(state);
}
}
/**
* Set the state to INACTIVE and clear state variables
*/
private void reset() {
setState(OADState.INACTIVE);
currentImage = null;
firmwareBundle = null;
nextBlock = 0;
oadListener = null;
watchdog.stop();
oadApproval.reset();
}
/**
* Attempt to reconnect to a Bean that is in the middle of OAD process
*/
private void reconnect() {
if(uploadInProgress()) {
setState(OADState.RECONNECTING);
BeanManager.getInstance().startDiscovery();
Log.i(TAG, "Waiting for device to reconnect...");
}
}
/**
* Offer the next image available in the Firmware Bundle
*/
private void offerNextImage() {
if (oadState == OADState.OFFERING_IMAGES) {
try {
currentImage = firmwareBundle.getNextImage();
if (currentImage != null) {
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
} catch (OADException e) {
// This gets thrown if the firmware bundle is "exhausted", meaning the Bean
// has rejected all of the images in the bundle
Log.e(TAG, e.getMessage());
fail(BeanError.BEAN_REJECTED_FW);
}
} else {
Log.e(TAG, "Got notification on OAD Identify while in unexpected state: " + oadState);
}
}
/**
* Begin the OFFERING_IMAGES state
*/
private void startOfferingImages() {
setState(OADState.OFFERING_IMAGES);
currentImage = null;
firmwareBundle.reset();
offerNextImage();
}
/**
* Received a notification on Identify characteristic
*
* @param characteristic Not used
*/
private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
offerNextImage();
}
/**
* Received a notification on Block characteristic
*
* A notification to this characteristic means the Bean has accepted the most recent
* firmware file we have offered, which is stored as `this.currentImage`. It is now
* time to start sending blocks of FW to the device.
*
* @param characteristic BLE characteristic with a value equal to the the block number
*/
private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int requestedBlock = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
// Check for First block
if (requestedBlock == 0) {
Log.i(TAG, String.format("Image accepted (Name: %s) (Size: %s bytes)",currentImage.name(), currentImage.sizeBytes()));
blockTransferStarted = System.currentTimeMillis() / 1000L;
setState(OADState.BLOCK_XFER);
nextBlock = 0;
}
// Normal BLOCK XFER state logic
while (oadState == OADState.BLOCK_XFER &&
nextBlock <= currentImage.blockCount() - 1 &&
nextBlock < (requestedBlock + MAX_IN_AIR_BLOCKS)) {
// Write the block, tell the OAD Listener
writeToCharacteristic(oadBlock, currentImage.block(nextBlock));
oadListener.progress(UploadProgress.create(nextBlock + 1, currentImage.blockCount()));
nextBlock++;
watchdog.poke();
}
// Check for final block requested, for logging purposes only
if (requestedBlock == currentImage.blockCount() - 1) {
// Calculate throughput
long secondsElapsed = System.currentTimeMillis() / 1000L - blockTransferStarted;
double KBs = 0;
if (secondsElapsed > 0) {
KBs = (double) (currentImage.sizeBytes() / secondsElapsed) / 1000;
}
// Log some stats
Log.i(TAG, String.format("Final OAD Block Requested: %s/%s", nextBlock, currentImage.blockCount()));
Log.i(TAG, String.format("Sent %d blocks in %d seconds (%.2f KB/s)", currentImage.blockCount(), secondsElapsed, KBs));
}
}
/**
* Setup BLOCK and IDENTIFY characteristics
*/
private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
fail(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
fail(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
fail(BeanError.MISSING_OAD_BLOCK);
return;
}
}
/**
* Enables notifications for all OAD characteristics.
*/
private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful");
} else {
Log.e(TAG, "Error while enabling notifications");
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
}
/**
* Enable notifications for a given characteristic.
*
* See <a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification">
* the Android docs
* </a>
* on this subject.
*
* @param characteristic The characteristic to enable notifications for
* @return true if notifications were enabled successfully
*/
private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean success = true;
// Enable notifications/indications for this characteristic
boolean successEnable = mGattClient.setCharacteristicNotification(characteristic, true);
if (successEnable) {
Log.i(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
success = false;
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Constants.UUID_CLIENT_CHAR_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean successDescriptor = mGattClient.writeDescriptor(descriptor);
if (successDescriptor) {
Log.i(TAG, "Successfully wrote notification descriptor: " + descriptor.getUuid());
} else {
success = false;
Log.e(TAG, "Failed to write notification descriptor: " + descriptor.getUuid());
}
return success;
}
/**
* Write to a OAD characteristic
*
* @param charc The characteristic being inspected
* @return true if it's the OAD Block characteristic
*/
private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
}
/**
* Helper function to determine whether a Bean needs a FW update given a specific Bundle version
*
* @param bundleVersion the version string from the provided firmware bundle
* @param beanVersion the version string provided from the Bean Device Information Service
* @return boolean value stating whether the Bean needs an update
*/
private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
}
/**
* Check the Beans FW version to determine if an update is required
*/
private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(OADState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
// Check the Bean version against the Bundle version
boolean updateNeeded = needsUpdate(firmwareBundle.version(), version);
if (updateNeeded && oadApproval.isApproved()) {
// Needs update and client has approved, keep the update going
startOfferingImages();
} else if (updateNeeded && !oadApproval.isApproved()) {
// Needs update but client has not approved, ask for approval
watchdog.pause();
oadListener.updateRequired(true);
} else if (!updateNeeded && !oadApproval.isApproved()){
// Does not need update and the client has never approved. This means
// no update is required, and no firmware update ever occurred
oadListener.updateRequired(false);
finishNoUpdateOccurred();
} else if (!updateNeeded && oadApproval.isApproved()) {
// Does not need update, and the client has approved. This means that
// the firmware process actually took place, and completed
finishUpdateOccurred();
} else {
Log.w(TAG, "Unexpected OAD Condition!");
}
}
});
}
/**
* Stop the firmware upload and alert the OADListener
*
* @param error The error to be returned to the user
*/
private void fail(BeanError error) {
Log.e(TAG, "OAD Error: " + error.toString());
if (uploadInProgress()) {
oadListener.error(error);
reset();
}
}
/**
* Finish the OAD process, similar to fail() except assumes a better outcome
*/
private void finishUpdateOccurred() {
Log.i(TAG, "OAD Finished: Update Occurred");
oadListener.complete();
reset();
}
private void finishNoUpdateOccurred() {
Log.i(TAG, "OAD Finished: No update Occurred");
// Don't reset() here, just set state to inactive. By not resetting, this allows
// the client to force an OAD update even if there isn't one required.
watchdog.stop();
setState(OADState.INACTIVE);
}
/****************************************************************************
PUBLIC METHODS
****************************************************************************/
public String getName() {
return TAG;
}
public boolean isReady() {
return ready;
}
public void clearReady() {
ready = false;
}
public boolean uploadInProgress() {
return oadState != OADState.INACTIVE;
}
public OADState getState() {
return oadState;
}
@Override
public void onProfileReady() {
setupOAD();
setupNotifications();
ready = true;
}
public void continueOAD() {
if (uploadInProgress()) {
checkFirmwareVersion();
BeanManager.getInstance().cancelDiscovery();
}
}
@Override
public void onBeanConnected() {
Log.i(TAG, "OAD Profile Detected Bean Connection");
}
@Override
public void onBeanDisconnected() {
Log.i(TAG, "OAD Profile Detected Bean Disconnection");
reconnect();
}
@Override
public void onBeanConnectionFailed() {
Log.i(TAG, "OAD Profile Detected Connection Failure, Likely a device reboot");
reconnect();
}
@Override
public void onCharacteristicChanged(GattClient client, BluetoothGattCharacteristic characteristic) {
if (uploadInProgress()) {
if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_IDENTIFY)) {
onNotificationIdentify(characteristic);
} else if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_BLOCK)) {
onNotificationBlock(characteristic);
}
}
}
/**
* Program the Bean's CC2540 with new firmware.
*
* @param bundle The {@link com.punchthrough.bean.sdk.upload.FirmwareBundle} to be sent
* @param listener Listener object to alert client of events/state of the Firmware update process
*/
public OADApproval programWithFirmware(final FirmwareBundle bundle, OADListener listener) {
if (!mGattClient.isConnected()) {
listener.error(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure");
// Save state for this firmware procedure
this.oadListener = listener;
this.firmwareBundle = bundle;
watchdog.start(OAD_TIMEOUT_SECONDS, watchdogListener);
checkFirmwareVersion();
return this.oadApproval;
}
/**
* Communication interface from SDK to client
*/
public interface OADListener {
/**
* Called when the OAD procedure completes without error
*/
public void complete();
/**
* Called when there is an error during the OAD procedure
*
* @param error BeanError
*/
public void error(BeanError error);
/**
* Called when forward progress has been made during OAD procedure
*
* @param uploadProgress UploadProgress object describing the OAD procedure progress
*/
public void progress(UploadProgress uploadProgress);
/**
* Called to let the client know if a FW update is required
*
* @param required Boolean flag
*/
public void updateRequired(boolean required);
/**
* Called when the OAD state machine changes states
*
* @param state OADState representing the state of the OAD procedure
*/
public void stateChange(OADState state);
}
/**
* Communication interface from client to SDK
*/
public interface OADApproval {
/**
* Client should call this method to allow the OAD procedure to continue
*/
public void allow();
/**
* Client should call this method to deny the OAD procedure from continuing
*/
public void deny();
/**
* Reset this objects state
*/
public void reset();
/**
*
* @return Boolean flag representing the last approval status
*/
public boolean isApproved();
}
}
| sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | package com.punchthrough.bean.sdk.internal.upload.firmware;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.util.Log;
import com.punchthrough.bean.sdk.BeanManager;
import com.punchthrough.bean.sdk.internal.ble.BaseProfile;
import com.punchthrough.bean.sdk.internal.ble.GattClient;
import com.punchthrough.bean.sdk.internal.device.DeviceProfile;
import com.punchthrough.bean.sdk.internal.exception.OADException;
import com.punchthrough.bean.sdk.internal.utility.Constants;
import com.punchthrough.bean.sdk.internal.utility.Convert;
import com.punchthrough.bean.sdk.internal.utility.Watchdog;
import com.punchthrough.bean.sdk.message.BeanError;
import com.punchthrough.bean.sdk.message.UploadProgress;
import com.punchthrough.bean.sdk.upload.FirmwareBundle;
import com.punchthrough.bean.sdk.upload.FirmwareImage;
import java.util.Arrays;
public class OADProfile extends BaseProfile {
/**
* Custom OAD Profile for LightBlue Bean devices.
*
* This class encapsulates data and processes related to firmware updates to the CC2540.
*
*/
protected static final String TAG = "OADProfile";
// OAD Characteristic handles
private BluetoothGattCharacteristic oadIdentify;
private BluetoothGattCharacteristic oadBlock;
private Watchdog watchdog;
// OAD Internal State
private boolean ready = false;
/* The current state of the OAD state-machine */
private OADState oadState = OADState.INACTIVE;
/* The last offered image or the accepted image depending on state of the OAD process */
private FirmwareImage currentImage;
/* Bundle of firmware images provided by the client */
private FirmwareBundle firmwareBundle;
/* Oad Listener */
private OADListener oadListener;
/* The maximum allowed blocks queued and/or in-flight before receiving a new request */
private final int MAX_IN_AIR_BLOCKS = 8;
/* Keeps track of the next block to send which is not equal to the block requested */
private int nextBlock = 0;
/* Used to record KB/s during block transfers */
private long blockTransferStarted = 0;
public OADProfile(GattClient client, Watchdog watchdog) {
super(client);
this.watchdog = watchdog;
reset();
}
private Watchdog.WatchdogListener watchdogListener = new Watchdog.WatchdogListener() {
@Override
public void expired() {
fail(BeanError.OAD_TIMEOUT);
}
};
private OADApproval oadApproval = new OADApproval() {
public boolean approved = false;
@Override
public void allow() {
Log.i(TAG, "Client has allowed the OAD Process to continue.");
approved = true;
startOfferingImages();
}
@Override
public void deny() {
Log.i(TAG, "Client denied the OAD Process from continuing.");
approved = false;
fail(BeanError.CLIENT_REJECTED);
}
@Override
public void reset() {
approved = false;
}
@Override
public boolean isApproved() {
return approved;
}
};
private void setState(OADState state) {
Log.i(TAG, String.format("(%s) OAD State Change: %s -> %s", mGattClient.bleAddress(), oadState.name(), state.name()));
oadState = state;
watchdog.poke();
if (oadListener != null ) {
oadListener.stateChange(state);
}
}
/**
* Set the state to INACTIVE and clear state variables
*/
private void reset() {
setState(OADState.INACTIVE);
currentImage = null;
firmwareBundle = null;
nextBlock = 0;
oadListener = null;
watchdog.stop();
oadApproval.reset();
}
/**
* Offer the next image available in the Firmware Bundle
*/
private void offerNextImage() {
if (oadState == OADState.OFFERING_IMAGES) {
try {
currentImage = firmwareBundle.getNextImage();
if (currentImage != null) {
Log.i(TAG, "Offering image: " + currentImage.name());
writeToCharacteristic(oadIdentify, currentImage.metadata());
}
} catch (OADException e) {
// This gets thrown if the firmware bundle is "exhausted", meaning the Bean
// has rejected all of the images in the bundle
Log.e(TAG, e.getMessage());
fail(BeanError.BEAN_REJECTED_FW);
}
} else {
Log.e(TAG, "Got notification on OAD Identify while in unexpected state: " + oadState);
}
}
/**
* Begin the OFFERING_IMAGES state
*/
private void startOfferingImages() {
setState(OADState.OFFERING_IMAGES);
currentImage = null;
firmwareBundle.reset();
offerNextImage();
}
/**
* Received a notification on Identify characteristic
*
* @param characteristic Not used
*/
private void onNotificationIdentify(BluetoothGattCharacteristic characteristic) {
offerNextImage();
}
/**
* Received a notification on Block characteristic
*
* A notification to this characteristic means the Bean has accepted the most recent
* firmware file we have offered, which is stored as `this.currentImage`. It is now
* time to start sending blocks of FW to the device.
*
* @param characteristic BLE characteristic with a value equal to the the block number
*/
private void onNotificationBlock(BluetoothGattCharacteristic characteristic) {
int requestedBlock = Convert.twoBytesToInt(characteristic.getValue(), Constants.CC2540_BYTE_ORDER);
// Check for First block
if (requestedBlock == 0) {
Log.i(TAG, String.format("Image accepted (Name: %s) (Size: %s bytes)",currentImage.name(), currentImage.sizeBytes()));
blockTransferStarted = System.currentTimeMillis() / 1000L;
setState(OADState.BLOCK_XFER);
nextBlock = 0;
}
// Normal BLOCK XFER state logic
while (oadState == OADState.BLOCK_XFER &&
nextBlock <= currentImage.blockCount() - 1 &&
nextBlock < (requestedBlock + MAX_IN_AIR_BLOCKS)) {
// Write the block, tell the OAD Listener
writeToCharacteristic(oadBlock, currentImage.block(nextBlock));
oadListener.progress(UploadProgress.create(nextBlock + 1, currentImage.blockCount()));
nextBlock++;
watchdog.poke();
}
// Check for final block requested, for logging purposes only
if (requestedBlock == currentImage.blockCount() - 1) {
// Calculate throughput
long secondsElapsed = System.currentTimeMillis() / 1000L - blockTransferStarted;
double KBs = 0;
if (secondsElapsed > 0) {
KBs = (double) (currentImage.sizeBytes() / secondsElapsed) / 1000;
}
// Log some stats
Log.i(TAG, String.format("Final OAD Block Requested: %s/%s", nextBlock, currentImage.blockCount()));
Log.i(TAG, String.format("Sent %d blocks in %d seconds (%.2f KB/s)", currentImage.blockCount(), secondsElapsed, KBs));
}
}
/**
* Setup BLOCK and IDENTIFY characteristics
*/
private void setupOAD() {
BluetoothGattService oadService = mGattClient.getService(Constants.UUID_OAD_SERVICE);
if (oadService == null) {
fail(BeanError.MISSING_OAD_SERVICE);
return;
}
oadIdentify = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_IDENTIFY);
if (oadIdentify == null) {
fail(BeanError.MISSING_OAD_IDENTIFY);
return;
}
oadBlock = oadService.getCharacteristic(Constants.UUID_OAD_CHAR_BLOCK);
if (oadBlock == null) {
fail(BeanError.MISSING_OAD_BLOCK);
return;
}
}
/**
* Enables notifications for all OAD characteristics.
*/
private void setupNotifications() {
Log.i(TAG, "Enabling OAD notifications");
boolean oadIdentifyNotifying = enableNotifyForChar(oadIdentify);
boolean oadBlockNotifying = enableNotifyForChar(oadBlock);
if (oadIdentifyNotifying && oadBlockNotifying) {
Log.i(TAG, "Enable notifications successful");
} else {
Log.e(TAG, "Error while enabling notifications");
fail(BeanError.ENABLE_OAD_NOTIFY_FAILED);
}
}
/**
* Enable notifications for a given characteristic.
*
* See <a href="https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#notification">
* the Android docs
* </a>
* on this subject.
*
* @param characteristic The characteristic to enable notifications for
* @return true if notifications were enabled successfully
*/
private boolean enableNotifyForChar(BluetoothGattCharacteristic characteristic) {
boolean success = true;
// Enable notifications/indications for this characteristic
boolean successEnable = mGattClient.setCharacteristicNotification(characteristic, true);
if (successEnable) {
Log.i(TAG, "Enabled notify for characteristic: " + characteristic.getUuid());
} else {
success = false;
Log.e(TAG, "Enable notify failed for characteristic: " + characteristic.getUuid());
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Constants.UUID_CLIENT_CHAR_CONFIG);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
boolean successDescriptor = mGattClient.writeDescriptor(descriptor);
if (successDescriptor) {
Log.i(TAG, "Successfully wrote notification descriptor: " + descriptor.getUuid());
} else {
success = false;
Log.e(TAG, "Failed to write notification descriptor: " + descriptor.getUuid());
}
return success;
}
/**
* Write to a OAD characteristic
*
* @param charc The characteristic being inspected
* @return true if it's the OAD Block characteristic
*/
private boolean writeToCharacteristic(BluetoothGattCharacteristic charc, byte[] data) {
charc.setValue(data);
boolean result = mGattClient.writeCharacteristic(charc);
if (result) {
Log.d(TAG, "Wrote to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
} else {
Log.e(TAG, "Write failed to characteristic: " + charc.getUuid() +
", data: " + Arrays.toString(data));
}
return result;
}
/**
* Helper function to determine whether a Bean needs a FW update given a specific Bundle version
*
* @param bundleVersion the version string from the provided firmware bundle
* @param beanVersion the version string provided from the Bean Device Information Service
* @return boolean value stating whether the Bean needs an update
*/
private boolean needsUpdate(Long bundleVersion, String beanVersion) {
if (beanVersion.contains("OAD")) {
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + beanVersion);
return true;
} else {
try {
long parsedVersion = Long.parseLong(beanVersion.split(" ")[0]);
Log.i(TAG, "Bundle version: " + bundleVersion);
Log.i(TAG, "Bean version: " + parsedVersion);
if (bundleVersion > parsedVersion) {
return true;
} else {
Log.i(TAG, "No update required!");
}
} catch (NumberFormatException e) {
Log.e(TAG, "Couldn't parse Bean Version: " + beanVersion);
fail(BeanError.UNPARSABLE_FW_VERSION);
}
}
return false;
}
/**
* Check the Beans FW version to determine if an update is required
*/
private void checkFirmwareVersion() {
Log.i(TAG, "Checking Firmware version...");
setState(OADState.CHECKING_FW_VERSION);
mGattClient.getDeviceProfile().getFirmwareVersion(new DeviceProfile.VersionCallback() {
@Override
public void onComplete(String version) {
// Check the Bean version against the Bundle version
boolean updateNeeded = needsUpdate(firmwareBundle.version(), version);
if (updateNeeded && oadApproval.isApproved()) {
// Needs update and client has approved, keep the update going
startOfferingImages();
} else if (updateNeeded && !oadApproval.isApproved()) {
// Needs update but client has not approved, ask for approval
watchdog.pause();
oadListener.updateRequired(true);
} else if (!updateNeeded && !oadApproval.isApproved()){
// Does not need update and the client has never approved. This means
// no update is required, and no firmware update ever occurred
oadListener.updateRequired(false);
finishNoUpdateOccurred();
} else if (!updateNeeded && oadApproval.isApproved()) {
// Does not need update, and the client has approved. This means that
// the firmware process actually took place, and completed
finishUpdateOccurred();
} else {
Log.w(TAG, "Unexpected OAD Condition!");
}
}
});
}
/**
* Stop the firmware upload and alert the OADListener
*
* @param error The error to be returned to the user
*/
private void fail(BeanError error) {
Log.e(TAG, "OAD Error: " + error.toString());
if (uploadInProgress()) {
oadListener.error(error);
reset();
}
}
/**
* Finish the OAD process, similar to fail() except assumes a better outcome
*/
private void finishUpdateOccurred() {
Log.i(TAG, "OAD Finished: Update Occurred");
oadListener.complete();
reset();
}
private void finishNoUpdateOccurred() {
Log.i(TAG, "OAD Finished: No update Occurred");
// Don't reset() here, just set state to inactive. By not resetting, this allows
// the client to force an OAD update even if there isn't one required.
watchdog.stop();
setState(OADState.INACTIVE);
}
/****************************************************************************
PUBLIC METHODS
****************************************************************************/
public String getName() {
return TAG;
}
public boolean isReady() {
return ready;
}
public void clearReady() {
ready = false;
}
public boolean uploadInProgress() {
return oadState != OADState.INACTIVE;
}
public OADState getState() {
return oadState;
}
@Override
public void onProfileReady() {
setupOAD();
setupNotifications();
ready = true;
}
public void continueOAD() {
if (uploadInProgress()) {
checkFirmwareVersion();
BeanManager.getInstance().cancelDiscovery();
}
}
@Override
public void onBeanConnected() {
Log.i(TAG, "OAD Profile Detected Bean Connection");
}
@Override
public void onBeanDisconnected() {
Log.i(TAG, "OAD Profile Detected Bean Disconnection");
}
@Override
public void onBeanConnectionFailed() {
Log.i(TAG, "OAD Profile Detected Connection Failure, Likely a device reboot");
if(uploadInProgress()) {
setState(OADState.RECONNECTING);
BeanManager.getInstance().startDiscovery();
Log.i(TAG, "Waiting for device to reconnect...");
}
}
@Override
public void onCharacteristicChanged(GattClient client, BluetoothGattCharacteristic characteristic) {
if (uploadInProgress()) {
if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_IDENTIFY)) {
onNotificationIdentify(characteristic);
} else if (characteristic.getUuid().equals(Constants.UUID_OAD_CHAR_BLOCK)) {
onNotificationBlock(characteristic);
}
}
}
/**
* Program the Bean's CC2540 with new firmware.
*
* @param bundle The {@link com.punchthrough.bean.sdk.upload.FirmwareBundle} to be sent
* @param listener Listener object to alert client of events/state of the Firmware update process
*/
public OADApproval programWithFirmware(final FirmwareBundle bundle, OADListener listener) {
if (!mGattClient.isConnected()) {
listener.error(BeanError.NOT_CONNECTED);
}
Log.i(TAG, "Starting firmware update procedure");
// Save state for this firmware procedure
this.oadListener = listener;
this.firmwareBundle = bundle;
watchdog.start(30, watchdogListener);
checkFirmwareVersion();
return this.oadApproval;
}
/**
* Communication interface from SDK to client
*/
public interface OADListener {
/**
* Called when the OAD procedure completes without error
*/
public void complete();
/**
* Called when there is an error during the OAD procedure
*
* @param error BeanError
*/
public void error(BeanError error);
/**
* Called when forward progress has been made during OAD procedure
*
* @param uploadProgress UploadProgress object describing the OAD procedure progress
*/
public void progress(UploadProgress uploadProgress);
/**
* Called to let the client know if a FW update is required
*
* @param required Boolean flag
*/
public void updateRequired(boolean required);
/**
* Called when the OAD state machine changes states
*
* @param state OADState representing the state of the OAD procedure
*/
public void stateChange(OADState state);
}
/**
* Communication interface from client to SDK
*/
public interface OADApproval {
/**
* Client should call this method to allow the OAD procedure to continue
*/
public void allow();
/**
* Client should call this method to deny the OAD procedure from continuing
*/
public void deny();
/**
* Reset this objects state
*/
public void reset();
/**
*
* @return Boolean flag representing the last approval status
*/
public boolean isApproved();
}
}
| oad: set state to RECONNECTING if we get random disconnect | sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java | oad: set state to RECONNECTING if we get random disconnect | <ide><path>dk/src/main/java/com/punchthrough/bean/sdk/internal/upload/firmware/OADProfile.java
<ide>
<ide> // OAD Internal State
<ide>
<add> private static final int OAD_TIMEOUT_SECONDS = 30;
<ide> private boolean ready = false;
<ide>
<ide> /* The current state of the OAD state-machine */
<ide> oadListener = null;
<ide> watchdog.stop();
<ide> oadApproval.reset();
<add> }
<add>
<add> /**
<add> * Attempt to reconnect to a Bean that is in the middle of OAD process
<add> */
<add> private void reconnect() {
<add> if(uploadInProgress()) {
<add> setState(OADState.RECONNECTING);
<add> BeanManager.getInstance().startDiscovery();
<add> Log.i(TAG, "Waiting for device to reconnect...");
<add> }
<ide> }
<ide>
<ide> /**
<ide> @Override
<ide> public void onBeanDisconnected() {
<ide> Log.i(TAG, "OAD Profile Detected Bean Disconnection");
<add> reconnect();
<ide> }
<ide>
<ide> @Override
<ide> public void onBeanConnectionFailed() {
<ide> Log.i(TAG, "OAD Profile Detected Connection Failure, Likely a device reboot");
<del> if(uploadInProgress()) {
<del> setState(OADState.RECONNECTING);
<del> BeanManager.getInstance().startDiscovery();
<del> Log.i(TAG, "Waiting for device to reconnect...");
<del> }
<add> reconnect();
<ide> }
<ide>
<ide> @Override
<ide> this.oadListener = listener;
<ide> this.firmwareBundle = bundle;
<ide>
<del> watchdog.start(30, watchdogListener);
<add> watchdog.start(OAD_TIMEOUT_SECONDS, watchdogListener);
<ide> checkFirmwareVersion();
<ide>
<ide> return this.oadApproval; |
|
JavaScript | mit | 7f9a4ec5737654a05dff97ecdaaa785a96aa60ef | 0 | zhangg/hexo,G-g-beringei/hexo,ChaofengZhou/hexo,zoubin/hexo,tibic/hexo,runlevelsix/hexo,0111001101111010/blog,Richardphp/hexo,kywk/hexi,chenbojian/hexo,hugoxia/hexo,0111001101111010/hexo,xushuwei202/hexo,jonesgithub/hexo,viethang/hexo,iamprasad88/hexo,biezhihua/hexo,JasonMPE/hexo,zongkelong/hexo,liuhongjiang/hexo,dieface/hexo,DanielHit/hexo,logonmy/hexo,Bob1993/hexo,allengaller/hexo,jollylulu/hexo,elegantwww/hexo,DevinLow/DevinLow.github.io,Gtskk/hexo,SampleLiao/hexo,littledogboy/hexo,xcatliu/hexo,HiWong/hexo,ppker/hexo,glabcn/hexo,leelynd/tapohuck,nextexit/hexo,keeleys/hexo,luinnx/hexo,jp1017/hexo,aulphar/hexo,lukw00/hexo,BruceChao/hexo,maominghui/hexo,wenzhucjy/hexo,zhoulingjun/hexo,SaiNadh001/hexo,luodengxiong/hexo,Jeremy017/hexo,hexojs/hexo,GGuang/hexo,sailtoy/hexo,memezilla/hexo,znanl/znanl,fuchao2012/hexo,HcySunYang/hexo,amobiz/hexo,liukaijv/hexo,Carbs0126/hexo,chenzaichun/hexo,karenpeng/hexo,magicdawn/hexo,ppker/hexo,kennethlyn/hexo,xiaoliuzi/hexo,kywk/hexi,wangjordy/wangjordy.github.io,hackjustu/hexo,noname007/hexo-1,zhi1ong/hexo,registercosmo/hexo,sundyxfan/hexo,lookii/looki,lknny/hexo,wangjordy/wangjordy.github.io,cjwind/hexx,wflmax/hexo,k2byew/hexo,hexojs/hexo,oomusou/hexo,will-zhangweilin/myhexo,meaverick/hexo,DevinLow/DevinLow.github.io,noikiy/hexo,imjerrybao/hexo,wwff/hexo,crystalwm/hexo,gaojinhua/hexo,zhipengyan/hexo,r4-keisuke/hexo,delkyd/hexo,hanhailong/hexo,beni55/hexo,leikegeek/hexo,dreamren/hexo,XGHeaven/hexo,initiumlab/hexo,zhipengyan/hexo,haoyuchen1992/hexo,Regis25489/hexo,wyfyyy818818/hexo,tzq668766/hexo | var fs = require('graceful-fs'),
async = require('async'),
path = require('path'),
HexoError = require('../error');
module.exports = function(callback){
if (!hexo.env.init || hexo.env.safe) return callback();
var pluginDir = hexo.plugin_dir;
async.series([
function(next){
fs.exists(pluginDir, function(exist){
if (exist){
next();
} else {
callback();
}
});
},
function(next){
fs.readdir(pluginDir, function(err, files){
if (err) return hexo.log.e(HexoError.wrap(err, 'Plugin load failed'));
files.forEach(function(item){
if (!/^hexo-/.test(item)) return;
try {
require(path.join(pluginDir, item));
hexo.log.d('Plugin loaded successfully: ' + item);
} catch (err){
hexo.log.e('Plugin load failed: ' + item);
}
});
next();
});
}
], callback);
}; | lib/loaders/plugins.js | var fs = require('graceful-fs'),
async = require('async'),
path = require('path'),
HexoError = require('../error');
module.exports = function(callback){
if (!hexo.env.init || hexo.env.safe) return callback();
var pluginDir = hexo.plugin_dir;
async.series([
function(next){
fs.exists(pluginDir, function(exist){
if (exist){
next();
} else {
callback();
}
});
},
function(next){
fs.readdir(pluginDir, function(err, files){
if (err) return hexo.log.e(HexoError.wrap(err, 'Plugin load failed'));
files.forEach(function(item){
if (!/^hexo-/.test(item)) return;
try {
require(path.join(pluginDir, item));
log.d('Plugin loaded successfully: ' + item);
} catch (err){
hexo.log.e('Plugin load failed: ' + item);
}
});
next();
});
}
], callback);
}; | Fixed plugin loader #378
| lib/loaders/plugins.js | Fixed plugin loader #378 | <ide><path>ib/loaders/plugins.js
<ide>
<ide> try {
<ide> require(path.join(pluginDir, item));
<del> log.d('Plugin loaded successfully: ' + item);
<add> hexo.log.d('Plugin loaded successfully: ' + item);
<ide> } catch (err){
<ide> hexo.log.e('Plugin load failed: ' + item);
<ide> } |
|
Java | apache-2.0 | 23ef0c8b93c272316cf4f6b54da3a01910ed3bea | 0 | OpenBEL/cytoscape-plugins,OpenBEL/cytoscape-plugins | /*
* KAM Navigator Plugin
*
* URLs: http://openbel.org/
* Copyright (C) 2012, Selventa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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 org.openbel.belframework.kam.dialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import org.openbel.belframework.kam.KAMNetwork;
import org.openbel.belframework.kam.KAMSession;
import org.openbel.belframework.kam.task.KAMTasks;
import org.openbel.belframework.webservice.KAMService;
import org.openbel.belframework.webservice.KAMServiceFactory;
import com.selventa.belframework.ws.client.DialectHandle;
import com.selventa.belframework.ws.client.EdgeDirectionType;
import com.selventa.belframework.ws.client.FunctionType;
import com.selventa.belframework.ws.client.KamEdge;
import com.selventa.belframework.ws.client.KamNode;
import com.selventa.belframework.ws.client.RelationshipType;
import cytoscape.CyNetwork;
import cytoscape.CyNode;
import cytoscape.Cytoscape;
import cytoscape.data.SelectEvent;
import cytoscape.data.SelectEventListener;
import cytoscape.view.CyNetworkView;
import cytoscape.view.CytoscapeDesktop;
/**
* {@link KnowledgeNeighborhoodDialog} represents the UI for the Knowledge
* Neighborhood dialog.
*
* @author James McMahon <[email protected]>
*/
public class KnowledgeNeighborhoodDialog extends JDialog implements
ActionListener, PropertyChangeListener, SelectEventListener {
private static final long serialVersionUID = -736918933072782546L;
private static final String DIALOG_TITLE = "Knowledge Neighborhood";
private static final String ALL_SELECTION = "All";
private final KAMService kamService;
// used to keep track of currently selected nodes in kam form
private final Set<String> selectedKamNodeIds = new HashSet<String>();
// networks that this instance is registered as a listener on
private final Set<CyNetwork> subjectNetworks = new HashSet<CyNetwork>();
// network that nodes were last selected on
private CyNetwork currentNetwork;
// Executor for loading the knowledge neighborhood
private final ExecutorService loadExecutor = Executors.newSingleThreadExecutor();
private volatile boolean loading = false;
private volatile boolean haltLoading = false;
// swing components
private JButton addButton;
private JButton cancelButton;
private JLabel edgeLabel;
private JComboBox edgeRelationshipCombo;
private JLabel edgeRelationshipLabel;
private JRadioButton expandBothButton;
private ButtonGroup expandButtonGroup;
private JRadioButton expandDownstreamButton;
private JLabel expandLabel;
private JRadioButton expandUpstreamButton;
private JPanel filterPanel;
private JLabel resultsLabel;
private JTable resultsTable;
private JLabel selectionLabel;
private JSeparator separator;
private JComboBox sourceFunctionCombo;
private JLabel sourceFunctionLabel;
private JLabel sourceLabel;
private JTextField sourceLabelField;
private JLabel sourceLabelLabel;
private JScrollPane tableScrollPane;
private JComboBox targetFunctionCombo;
private JLabel targetFunctionLabel;
private JLabel targetLabel;
private JTextField targetLabelField;
private JLabel targetLabelLabel;
/**
* Construct the {@link JDialog dialog} and initialize the UI.
*
* @see #initUI()
*/
public KnowledgeNeighborhoodDialog() {
super(Cytoscape.getDesktop(), DIALOG_TITLE, false);
this.kamService = KAMServiceFactory.getInstance().getKAMService();
initUI();
// register property change listener for this instace
Cytoscape.getPropertyChangeSupport().addPropertyChangeListener(
CytoscapeDesktop.NETWORK_VIEW_CREATED, this);
Cytoscape.getPropertyChangeSupport().addPropertyChangeListener(
CytoscapeDesktop.NETWORK_VIEW_DESTROYED, this);
// register listener
Cytoscape.getCurrentNetwork().addSelectEventListener(this);
subjectNetworks.add(Cytoscape.getCurrentNetwork());
loadNeighborhood();
}
/**
* {@inheritDoc}
*
* <p>
* Implementation Note: Clean up resources used by
* {@link KnowledgeNeighborhoodDialog}.
* </p>
*/
@Override
public void dispose() {
super.dispose();
// deregister this listener for all associated objects
Cytoscape.getPropertyChangeSupport().removePropertyChangeListener(this);
for (CyNetwork network : subjectNetworks) {
if (network != null) {
network.removeSelectEventListener(this);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e == null) {
return;
}
if (e.getSource().equals(cancelButton)) {
// cancel button
this.dispose();
} else if (e.getSource().equals(addButton)) {
// add button
EdgeTableModel model = (EdgeTableModel) resultsTable.getModel();
List<KamEdge> edges = model.getEdges();
List<KamEdge> selectedEdges = new ArrayList<KamEdge>();
// determine selected rows from the filtered view
int[] viewIndices = resultsTable.getSelectedRows();
for (int viewIndex : viewIndices) {
int modelIndex = resultsTable.convertRowIndexToModel(viewIndex);
KamEdge selectedEdge = edges.get(modelIndex);
if (selectedEdge != null) {
selectedEdges.add(selectedEdge);
}
}
KAMNetwork kamNetwork = KAMSession.getInstance().getKAMNetwork(
currentNetwork);
KAMTasks.addEdges(kamNetwork, selectedEdges);
} else if (e.getSource().equals(expandBothButton)
|| e.getSource().equals(expandUpstreamButton)
|| e.getSource().equals(expandDownstreamButton)
|| e.getSource().equals(sourceFunctionCombo)
|| e.getSource().equals(targetFunctionCombo)
|| e.getSource().equals(edgeRelationshipCombo)) {
sort();
}
}
/**
* {@inheritDoc}
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
if (e == null) {
return;
}
if (CytoscapeDesktop.NETWORK_VIEW_CREATED.equals(e
.getPropertyName())) {
CyNetworkView view = (CyNetworkView) e.getNewValue();
view.getNetwork().addSelectEventListener(this);
subjectNetworks.add(view.getNetwork());
} else if (CytoscapeDesktop.NETWORK_VIEW_DESTROYED.equals(e
.getPropertyName())) {
CyNetworkView view = (CyNetworkView) e.getNewValue();
view.getNetwork().removeSelectEventListener(this);
subjectNetworks.remove(view.getNetwork());
}
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectEvent(SelectEvent e) {
if (e == null) {
return;
}
if (e.getTargetType() == SelectEvent.SINGLE_NODE
|| e.getTargetType() == SelectEvent.NODE_SET) {
loadNeighborhood();
}
}
private void initUI() {
initComponents();
// additional stuff (kept separate for future UI work)
// adjust position to default, keeps dialog from appearing offscreen
setLocationRelativeTo(null);
resultsLabel.setText("");
selectionLabel.setText("");
cancelButton.addActionListener(this);
addButton.addActionListener(this);
addButton.setEnabled(false);
resultsTable.setModel(new EdgeTableModel());
resultsTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel selModel = (ListSelectionModel) e
.getSource();
addButton.setEnabled(!selModel.isSelectionEmpty());
int selectionNumber = resultsTable.getSelectedRows().length;
selectionLabel.setText(selectionNumber
+ " edges selected");
}
});
// register the filters with the sorter
Collection<RowFilter<EdgeTableModel, Integer>> filters = new HashSet<RowFilter<EdgeTableModel, Integer>>();
filters.add(new SourceFunctionFilter());
filters.add(new TargetFunctionFilter());
filters.add(new RelationshipFilter());
filters.add(new SourceLabelFilter());
filters.add(new TargetLabelFilter());
filters.add(new DirectionFilter());
RowFilter<EdgeTableModel, Integer> andFilter = RowFilter
.andFilter(filters);
// sorter has alphabetical column sort on by default
TableRowSorter<EdgeTableModel> rowSorter = new TableRowSorter<EdgeTableModel>(
(EdgeTableModel) resultsTable.getModel());
rowSorter.setRowFilter(andFilter);
resultsTable.setRowSorter(rowSorter);
// filter options
expandBothButton.addActionListener(this);
expandUpstreamButton.addActionListener(this);
expandDownstreamButton.addActionListener(this);
sourceFunctionCombo.setModel(new SourceFunctionComboBoxModel());
targetFunctionCombo.setModel(new TargetFunctionComboBoxModel());
edgeRelationshipCombo.setModel(new RelationshipComboBoxModel());
sourceFunctionCombo.addActionListener(this);
targetFunctionCombo.addActionListener(this);
edgeRelationshipCombo.addActionListener(this);
// key listener for target / source labels
KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
sort();
}
// TODO do we need sort on key released or pressed?
@Override
public void keyReleased(KeyEvent e) {
sort();
}
@Override
public void keyPressed(KeyEvent e) {
sort();
}
};
sourceLabelField.addKeyListener(keyListener);
targetLabelField.addKeyListener(keyListener);
// set filters to default state
sourceFunctionCombo.setSelectedItem(ALL_SELECTION);
targetFunctionCombo.setSelectedItem(ALL_SELECTION);
edgeRelationshipCombo.setSelectedItem(ALL_SELECTION);
expandBothButton.setSelected(true);
sourceLabelField.setText(null);
targetLabelField.setText(null);
}
/**
* Refreshes the table sort and filters
*/
@SuppressWarnings("unchecked")
private synchronized void sort() {
((TableRowSorter<EdgeTableModel>) resultsTable.getRowSorter()).sort();
// number of found reflects the number of rows post filter
resultsLabel.setText("Found " + resultsTable.getRowCount() + " edges");
}
/**
* Load (or reload) the edges around the selected nodes, update UI to match
*/
private void loadNeighborhood() {
if (loading) {
// halt previous load
haltLoading = true;
}
// clear previously selected
selectedKamNodeIds.clear();
final EdgeTableModel model = (EdgeTableModel) this.resultsTable
.getModel();
model.clear();
// register current network (will be used for add edges command)
currentNetwork = Cytoscape.getCurrentNetwork();
@SuppressWarnings("unchecked")
final Set<CyNode> selected = currentNetwork.getSelectedNodes();
if (selected.isEmpty()) {
// if empty no point in resolve edges
resultsLabel.setText("Found 0 edges");
// clear filters combo boxes
((DefaultComboBoxModel) sourceFunctionCombo.getModel())
.removeAllElements();
((DefaultComboBoxModel) targetFunctionCombo.getModel())
.removeAllElements();
((DefaultComboBoxModel) edgeRelationshipCombo.getModel())
.removeAllElements();
return;
}
final KAMNetwork kamNetwork = KAMSession.getInstance().getKAMNetwork(
currentNetwork);
final Collection<KamNode> kamNodes = new HashSet<KamNode>();
for (final CyNode cynode : selected) {
KamNode kamNode = kamNetwork.getKAMNode(cynode);
kamNodes.add(kamNode);
// update selected kamNode ids
selectedKamNodeIds.add(kamNode.getId());
}
// put this a thread so it doesn't lock the UI
loadExecutor.execute(new Runnable() {
@Override
public void run() {
// start loading
loading = true;
// reset halt on new load
haltLoading = false;
List<KamEdge> edges = new ArrayList<KamEdge>();
for (KamNode kamNode : kamNodes) {
if (haltLoading) {
break;
}
edges.addAll(kamService.getAdjacentKamEdges(
kamNetwork.getDialectHandle(), kamNode,
EdgeDirectionType.BOTH, null));
}
if (!haltLoading) {
model.addEdges(edges);
// update filters combo boxes
((SourceFunctionComboBoxModel) sourceFunctionCombo.getModel())
.updateEdges(edges);
((TargetFunctionComboBoxModel) targetFunctionCombo.getModel())
.updateEdges(edges);
((RelationshipComboBoxModel) edgeRelationshipCombo.getModel())
.updateEdges(edges);
// resort filters after update
sort();
}
// finished loading
loading = false;
}
});
}
/**
* Simple extension of {@link DefaultTableModel} to keep track of added
* edges
*
* @author James McMahon <[email protected]>
*/
private static final class EdgeTableModel extends DefaultTableModel {
private static final long serialVersionUID = 56833762228520599L;
private final List<KamEdge> edges = new ArrayList<KamEdge>();
private EdgeTableModel() {
super(new Object[][] {
}, new String[] { "Source", "Relationship", "Target" });
}
@SuppressWarnings("rawtypes")
Class[] types = new Class[] { String.class, String.class, String.class };
boolean[] canEdit = new boolean[] { false, false, false };
@SuppressWarnings({ "rawtypes", "unchecked" })
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
public void addEdges(Collection<KamEdge> edges) {
// clear out previous edges
clear();
for (KamEdge edge : edges) {
if (edge != null) {
addEdge(edge);
}
}
fireTableDataChanged();
}
public void clear() {
dataVector.clear();
edges.clear();
fireTableDataChanged();
}
public List<KamEdge> getEdges() {
return edges;
}
private void addEdge(KamEdge edge) {
super.addRow(new String[] { edge.getSource().getLabel(),
edge.getRelationship().toString(),
edge.getTarget().getLabel() });
edges.add(edge);
}
}
/**
* Model for the source function combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class SourceFunctionComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = 847486496638770057L;
@Override
protected String getName(final KamEdge e) {
if (e.getSource() == null || e.getSource().getFunction() == null) {
return null;
}
return e.getSource().getFunction().name();
}
}
/**
* Model for the target function combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class TargetFunctionComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = -6749141138659929487L;
@Override
protected String getName(final KamEdge e) {
if (e.getTarget() == null || e.getTarget().getFunction() == null) {
return null;
}
return e.getTarget().getFunction().name();
}
}
/**
* Model for the edge relationship combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class RelationshipComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = 4774181753730742386L;
@Override
protected String getName(final KamEdge e) {
if (e.getRelationship() == null) {
return null;
}
return e.getRelationship().name();
}
}
/**
* Extension of {@link DefaultComboBoxModel} that adds the ablity to update
* its contents based on a collection of {@link KamEdge}s
*
* @author James McMahon <[email protected]>
*/
private abstract static class UpdatableComboBoxModel extends
DefaultComboBoxModel {
private static final long serialVersionUID = -8049723723613055311L;
public void updateEdges(final Collection<KamEdge> edges) {
String previousSelection = (String) getSelectedItem();
removeAllElements();
// filter duplicates out by using a set
Set<String> names = new HashSet<String>();
for (KamEdge e : edges) {
String name = getName(e);
if (name != null) {
names.add(name);
}
}
List<String> sortedNames = new ArrayList<String>(names);
Collections.sort(sortedNames);
// add all selection option at beginning
sortedNames.add(0, ALL_SELECTION);
for (String name : sortedNames) {
addElement(name);
// restore previous selections
if (name.equals(previousSelection)) {
setSelectedItem(name);
}
}
if (previousSelection == null) {
// work around for addElement making a selection
setSelectedItem(ALL_SELECTION);
}
fireContentsChanged(this, 0, names.size());
}
protected abstract String getName(KamEdge e);
}
private class SourceFunctionFilter extends
RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) sourceFunctionCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
FunctionType function = FunctionType.valueOf(selected);
return function.equals(edge.getSource().getFunction());
}
}
private class TargetFunctionFilter extends
RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) targetFunctionCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
FunctionType function = FunctionType.valueOf(selected);
return function.equals(edge.getTarget().getFunction());
}
}
private class RelationshipFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) edgeRelationshipCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
RelationshipType relationship = RelationshipType.valueOf(selected);
return relationship.equals(edge.getRelationship());
}
}
private class DirectionFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
EdgeDirectionType direction = EdgeDirectionType.BOTH;
if (expandUpstreamButton.isSelected()) {
direction = EdgeDirectionType.REVERSE;
} else if (expandDownstreamButton.isSelected()) {
direction = EdgeDirectionType.FORWARD;
}
if (EdgeDirectionType.BOTH.equals(direction)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
KamNode node = null;
if (EdgeDirectionType.FORWARD.equals(direction)) {
node = (KamNode) edge.getSource();
} else {
node = (KamNode) edge.getTarget();
}
return selectedKamNodeIds.contains(node.getId());
}
}
private class SourceLabelFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String filterText = sourceLabelField.getText();
if (filterText == null || filterText.isEmpty()) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
return edge.getSource().getLabel().toLowerCase()
.contains(filterText.toLowerCase());
}
}
private class TargetLabelFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String filterText = targetLabelField.getText();
if (filterText == null || filterText.isEmpty()) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
return edge.getTarget().getLabel().toLowerCase()
.contains(filterText.toLowerCase());
}
}
// taken from netbeans
// this method was taken from auto generated code, apologies if it sucks
private void initComponents() {
expandButtonGroup = new ButtonGroup();
resultsLabel = new JLabel();
selectionLabel = new JLabel();
cancelButton = new JButton();
addButton = new JButton();
tableScrollPane = new JScrollPane();
resultsTable = new JTable();
filterPanel = new JPanel();
expandLabel = new JLabel();
expandBothButton = new JRadioButton();
expandUpstreamButton = new JRadioButton();
expandDownstreamButton = new JRadioButton();
edgeLabel = new JLabel();
edgeRelationshipCombo = new JComboBox();
edgeRelationshipLabel = new JLabel();
sourceLabel = new JLabel();
targetLabel = new JLabel();
targetFunctionLabel = new JLabel();
targetFunctionCombo = new JComboBox();
targetLabelLabel = new JLabel();
targetLabelField = new JTextField();
sourceFunctionLabel = new JLabel();
sourceLabelLabel = new JLabel();
sourceFunctionCombo = new JComboBox();
sourceLabelField = new JTextField();
separator = new JSeparator();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
resultsLabel.setText("Found n edges");
selectionLabel.setText("n edges selected");
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Close this window");
addButton.setText("Add");
addButton.setToolTipText("Add selected edges to graph");
tableScrollPane.setViewportView(resultsTable);
filterPanel.setBorder(BorderFactory.createTitledBorder("Filter"));
expandLabel.setFont(expandLabel.getFont().deriveFont(expandLabel.getFont().getStyle() | Font.BOLD));
expandLabel.setText("Expand:");
expandButtonGroup.add(expandBothButton);
expandBothButton.setText("Both");
expandButtonGroup.add(expandUpstreamButton);
expandUpstreamButton.setText("Upstream");
expandButtonGroup.add(expandDownstreamButton);
expandDownstreamButton.setText("Downstream");
edgeLabel.setFont(edgeLabel.getFont().deriveFont(edgeLabel.getFont().getStyle() | Font.BOLD));
edgeLabel.setText("Edge:");
edgeRelationshipCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
edgeRelationshipLabel.setLabelFor(edgeRelationshipCombo);
edgeRelationshipLabel.setText("Relationship");
sourceLabel.setFont(sourceLabel.getFont().deriveFont(sourceLabel.getFont().getStyle() | Font.BOLD));
sourceLabel.setText("Source:");
targetLabel.setFont(targetLabel.getFont().deriveFont(targetLabel.getFont().getStyle() | Font.BOLD));
targetLabel.setText("Target:");
targetFunctionLabel.setLabelFor(targetFunctionCombo);
targetFunctionLabel.setText("Function");
targetFunctionCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
targetLabelLabel.setLabelFor(targetLabelField);
targetLabelLabel.setText("Label");
sourceFunctionLabel.setLabelFor(sourceFunctionCombo);
sourceFunctionLabel.setText("Function");
sourceLabelLabel.setLabelFor(sourceLabelField);
sourceLabelLabel.setText("Label");
sourceFunctionCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
GroupLayout filterPanelLayout = new GroupLayout(filterPanel);
filterPanel.setLayout(filterPanelLayout);
filterPanelLayout.setHorizontalGroup(
filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(expandLabel)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(expandUpstreamButton)
.addComponent(expandBothButton)
.addComponent(expandDownstreamButton)))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(sourceLabelLabel))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(sourceFunctionLabel)))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(sourceFunctionCombo, GroupLayout.PREFERRED_SIZE, 190, GroupLayout.PREFERRED_SIZE)
.addComponent(sourceLabelField, GroupLayout.PREFERRED_SIZE, 194, GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(targetLabelLabel)
.addComponent(targetFunctionLabel)
.addComponent(edgeRelationshipLabel))
.addGap(18, 18, 18)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(targetFunctionCombo, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(targetLabelField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.addComponent(edgeRelationshipCombo, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(targetLabel)
.addComponent(edgeLabel)))))
.addGroup(filterPanelLayout.createSequentialGroup()
.addComponent(sourceLabel)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
filterPanelLayout.setVerticalGroup(
filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(expandLabel)
.addComponent(edgeLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(expandBothButton)
.addComponent(edgeRelationshipLabel)
.addComponent(edgeRelationshipCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(expandUpstreamButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(expandDownstreamButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceLabel)
.addComponent(targetLabel))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(targetFunctionLabel)
.addComponent(targetFunctionCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceFunctionLabel)
.addComponent(sourceFunctionCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(ComponentPlacement.UNRELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(targetLabelField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(targetLabelLabel))
.addContainerGap())
.addGroup(Alignment.TRAILING, filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceLabelField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(sourceLabelLabel))
.addGap(35, 35, 35))))
);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(tableScrollPane, GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(selectionLabel)
.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(addButton))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(resultsLabel)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addComponent(separator)
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(separator, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(resultsLabel)
.addGap(9, 9, 9)
.addComponent(tableScrollPane, GroupLayout.PREFERRED_SIZE, 219, GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(selectionLabel))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(addButton)
.addComponent(cancelButton))))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
}
| kam-navigator-plugin/src/org/openbel/belframework/kam/dialog/KnowledgeNeighborhoodDialog.java | /*
* KAM Navigator Plugin
*
* URLs: http://openbel.org/
* Copyright (C) 2012, Selventa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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 org.openbel.belframework.kam.dialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.WindowConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import org.openbel.belframework.kam.KAMNetwork;
import org.openbel.belframework.kam.KAMSession;
import org.openbel.belframework.kam.task.KAMTasks;
import org.openbel.belframework.webservice.KAMService;
import org.openbel.belframework.webservice.KAMServiceFactory;
import com.selventa.belframework.ws.client.EdgeDirectionType;
import com.selventa.belframework.ws.client.FunctionType;
import com.selventa.belframework.ws.client.KamEdge;
import com.selventa.belframework.ws.client.KamNode;
import com.selventa.belframework.ws.client.RelationshipType;
import cytoscape.CyNetwork;
import cytoscape.CyNode;
import cytoscape.Cytoscape;
import cytoscape.data.SelectEvent;
import cytoscape.data.SelectEventListener;
import cytoscape.view.CyNetworkView;
import cytoscape.view.CytoscapeDesktop;
/**
* {@link KnowledgeNeighborhoodDialog} represents the UI for the Knowledge
* Neighborhood dialog.
*
* @author James McMahon <[email protected]>
*/
public class KnowledgeNeighborhoodDialog extends JDialog implements
ActionListener, PropertyChangeListener, SelectEventListener {
private static final long serialVersionUID = -736918933072782546L;
private static final String DIALOG_TITLE = "Knowledge Neighborhood";
private static final String ALL_SELECTION = "All";
private final KAMService kamService;
// used to keep track of currently selected nodes in kam form
private final Set<String> selectedKamNodeIds = new HashSet<String>();
// networks that this instance is registered as a listener on
private final Set<CyNetwork> subjectNetworks = new HashSet<CyNetwork>();
// network that nodes were last selected on
private CyNetwork currentNetwork;
// swing components
private JButton addButton;
private JButton cancelButton;
private JLabel edgeLabel;
private JComboBox edgeRelationshipCombo;
private JLabel edgeRelationshipLabel;
private JRadioButton expandBothButton;
private ButtonGroup expandButtonGroup;
private JRadioButton expandDownstreamButton;
private JLabel expandLabel;
private JRadioButton expandUpstreamButton;
private JPanel filterPanel;
private JLabel resultsLabel;
private JTable resultsTable;
private JLabel selectionLabel;
private JSeparator separator;
private JComboBox sourceFunctionCombo;
private JLabel sourceFunctionLabel;
private JLabel sourceLabel;
private JTextField sourceLabelField;
private JLabel sourceLabelLabel;
private JScrollPane tableScrollPane;
private JComboBox targetFunctionCombo;
private JLabel targetFunctionLabel;
private JLabel targetLabel;
private JTextField targetLabelField;
private JLabel targetLabelLabel;
/**
* Construct the {@link JDialog dialog} and initialize the UI.
*
* @see #initUI()
*/
public KnowledgeNeighborhoodDialog() {
super(Cytoscape.getDesktop(), DIALOG_TITLE, false);
this.kamService = KAMServiceFactory.getInstance().getKAMService();
initUI();
// register property change listener for this instace
Cytoscape.getPropertyChangeSupport().addPropertyChangeListener(
CytoscapeDesktop.NETWORK_VIEW_CREATED, this);
Cytoscape.getPropertyChangeSupport().addPropertyChangeListener(
CytoscapeDesktop.NETWORK_VIEW_DESTROYED, this);
// register listener
Cytoscape.getCurrentNetwork().addSelectEventListener(this);
subjectNetworks.add(Cytoscape.getCurrentNetwork());
loadNeighborhood();
}
/**
* {@inheritDoc}
*
* <p>
* Implementation Note: Clean up resources used by
* {@link KnowledgeNeighborhoodDialog}.
* </p>
*/
@Override
public void dispose() {
super.dispose();
// deregister this listener for all associated objects
Cytoscape.getPropertyChangeSupport().removePropertyChangeListener(this);
for (CyNetwork network : subjectNetworks) {
if (network != null) {
network.removeSelectEventListener(this);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e == null) {
return;
}
if (e.getSource().equals(cancelButton)) {
// cancel button
this.dispose();
} else if (e.getSource().equals(addButton)) {
// add button
EdgeTableModel model = (EdgeTableModel) resultsTable.getModel();
List<KamEdge> edges = model.getEdges();
List<KamEdge> selectedEdges = new ArrayList<KamEdge>();
// determine selected rows from the filtered view
int[] viewIndices = resultsTable.getSelectedRows();
for (int viewIndex : viewIndices) {
int modelIndex = resultsTable.convertRowIndexToModel(viewIndex);
KamEdge selectedEdge = edges.get(modelIndex);
if (selectedEdge != null) {
selectedEdges.add(selectedEdge);
}
}
KAMNetwork kamNetwork = KAMSession.getInstance().getKAMNetwork(
currentNetwork);
KAMTasks.addEdges(kamNetwork, selectedEdges);
} else if (e.getSource().equals(expandBothButton)
|| e.getSource().equals(expandUpstreamButton)
|| e.getSource().equals(expandDownstreamButton)
|| e.getSource().equals(sourceFunctionCombo)
|| e.getSource().equals(targetFunctionCombo)
|| e.getSource().equals(edgeRelationshipCombo)) {
sort();
}
}
/**
* {@inheritDoc}
*/
@Override
public void propertyChange(PropertyChangeEvent e) {
if (e == null) {
return;
}
if (CytoscapeDesktop.NETWORK_VIEW_CREATED.equals(e
.getPropertyName())) {
CyNetworkView view = (CyNetworkView) e.getNewValue();
view.getNetwork().addSelectEventListener(this);
subjectNetworks.add(view.getNetwork());
} else if (CytoscapeDesktop.NETWORK_VIEW_DESTROYED.equals(e
.getPropertyName())) {
CyNetworkView view = (CyNetworkView) e.getNewValue();
view.getNetwork().removeSelectEventListener(this);
subjectNetworks.remove(view.getNetwork());
}
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectEvent(SelectEvent e) {
if (e == null) {
return;
}
if (e.getTargetType() == SelectEvent.SINGLE_NODE
|| e.getTargetType() == SelectEvent.NODE_SET) {
loadNeighborhood();
}
}
private void initUI() {
initComponents();
// additional stuff (kept separate for future UI work)
// adjust position to default, keeps dialog from appearing offscreen
setLocationRelativeTo(null);
resultsLabel.setText("");
selectionLabel.setText("");
cancelButton.addActionListener(this);
addButton.addActionListener(this);
addButton.setEnabled(false);
resultsTable.setModel(new EdgeTableModel());
resultsTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel selModel = (ListSelectionModel) e
.getSource();
addButton.setEnabled(!selModel.isSelectionEmpty());
int selectionNumber = resultsTable.getSelectedRows().length;
selectionLabel.setText(selectionNumber
+ " edges selected");
}
});
// register the filters with the sorter
Collection<RowFilter<EdgeTableModel, Integer>> filters = new HashSet<RowFilter<EdgeTableModel, Integer>>();
filters.add(new SourceFunctionFilter());
filters.add(new TargetFunctionFilter());
filters.add(new RelationshipFilter());
filters.add(new SourceLabelFilter());
filters.add(new TargetLabelFilter());
filters.add(new DirectionFilter());
RowFilter<EdgeTableModel, Integer> andFilter = RowFilter
.andFilter(filters);
// sorter has alphabetical column sort on by default
TableRowSorter<EdgeTableModel> rowSorter = new TableRowSorter<EdgeTableModel>(
(EdgeTableModel) resultsTable.getModel());
rowSorter.setRowFilter(andFilter);
resultsTable.setRowSorter(rowSorter);
// filter options
expandBothButton.addActionListener(this);
expandUpstreamButton.addActionListener(this);
expandDownstreamButton.addActionListener(this);
sourceFunctionCombo.setModel(new SourceFunctionComboBoxModel());
targetFunctionCombo.setModel(new TargetFunctionComboBoxModel());
edgeRelationshipCombo.setModel(new RelationshipComboBoxModel());
sourceFunctionCombo.addActionListener(this);
targetFunctionCombo.addActionListener(this);
edgeRelationshipCombo.addActionListener(this);
// key listener for target / source labels
KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
sort();
}
// TODO do we need sort on key released or pressed?
@Override
public void keyReleased(KeyEvent e) {
sort();
}
@Override
public void keyPressed(KeyEvent e) {
sort();
}
};
sourceLabelField.addKeyListener(keyListener);
targetLabelField.addKeyListener(keyListener);
// set filters to default state
sourceFunctionCombo.setSelectedItem(ALL_SELECTION);
targetFunctionCombo.setSelectedItem(ALL_SELECTION);
edgeRelationshipCombo.setSelectedItem(ALL_SELECTION);
expandBothButton.setSelected(true);
sourceLabelField.setText(null);
targetLabelField.setText(null);
}
/**
* Refreshes the table sort and filters
*/
@SuppressWarnings("unchecked")
private void sort() {
((TableRowSorter<EdgeTableModel>) resultsTable.getRowSorter()).sort();
// number of found should be constructed post filter
resultsLabel.setText("Found " + resultsTable.getRowCount() + " edges");
}
/**
* Load (or reload) the edges around the selected nodes, update UI to match
*/
private void loadNeighborhood() {
// TODO put this a thread so it doesn't slow down other UI actions
// clear previously selected
selectedKamNodeIds.clear();
// register current network (will be used for add edges command)
currentNetwork = Cytoscape.getCurrentNetwork();
@SuppressWarnings("unchecked")
final Set<CyNode> selected = currentNetwork.getSelectedNodes();
if (selected.isEmpty()) {
// if empty no point in resolve edges
final EdgeTableModel model = (EdgeTableModel) this.resultsTable
.getModel();
model.clear();
resultsLabel.setText("Found 0 edges");
// clear filters combo boxes
((DefaultComboBoxModel) sourceFunctionCombo.getModel())
.removeAllElements();
((DefaultComboBoxModel) targetFunctionCombo.getModel())
.removeAllElements();
((DefaultComboBoxModel) edgeRelationshipCombo.getModel())
.removeAllElements();
return;
}
final KAMNetwork kamNetwork = KAMSession.getInstance().getKAMNetwork(
currentNetwork);
final Collection<KamNode> kamNodes = new HashSet<KamNode>();
for (final CyNode cynode : selected) {
KamNode kamNode = kamNetwork.getKAMNode(cynode);
kamNodes.add(kamNode);
// update selected kamNode ids
selectedKamNodeIds.add(kamNode.getId());
}
List<KamEdge> edges = new ArrayList<KamEdge>();
for (KamNode kamNode : kamNodes) {
edges.addAll(kamService.getAdjacentKamEdges(
kamNetwork.getDialectHandle(), kamNode,
EdgeDirectionType.BOTH, null));
}
final EdgeTableModel model = (EdgeTableModel) this.resultsTable
.getModel();
model.addEdges(edges);
// update filters combo boxes
((SourceFunctionComboBoxModel) sourceFunctionCombo.getModel())
.updateEdges(edges);
((TargetFunctionComboBoxModel) targetFunctionCombo.getModel())
.updateEdges(edges);
((RelationshipComboBoxModel) edgeRelationshipCombo.getModel())
.updateEdges(edges);
// resort filters after update
sort();
}
/**
* Simple extension of {@link DefaultTableModel} to keep track of added
* edges
*
* @author James McMahon <[email protected]>
*/
private static final class EdgeTableModel extends DefaultTableModel {
private static final long serialVersionUID = 56833762228520599L;
private final List<KamEdge> edges = new ArrayList<KamEdge>();
private EdgeTableModel() {
super(new Object[][] {
}, new String[] { "Source", "Relationship", "Target" });
}
@SuppressWarnings("rawtypes")
Class[] types = new Class[] { String.class, String.class, String.class };
boolean[] canEdit = new boolean[] { false, false, false };
@SuppressWarnings({ "rawtypes", "unchecked" })
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
public void addEdges(Collection<KamEdge> edges) {
// clear out previous edges
clear();
for (KamEdge edge : edges) {
if (edge != null) {
addEdge(edge);
}
}
fireTableDataChanged();
}
public void clear() {
dataVector.clear();
edges.clear();
fireTableDataChanged();
}
public List<KamEdge> getEdges() {
return edges;
}
private void addEdge(KamEdge edge) {
super.addRow(new String[] { edge.getSource().getLabel(),
edge.getRelationship().toString(),
edge.getTarget().getLabel() });
edges.add(edge);
}
}
/**
* Model for the source function combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class SourceFunctionComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = 847486496638770057L;
@Override
protected String getName(final KamEdge e) {
if (e.getSource() == null || e.getSource().getFunction() == null) {
return null;
}
return e.getSource().getFunction().name();
}
}
/**
* Model for the target function combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class TargetFunctionComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = -6749141138659929487L;
@Override
protected String getName(final KamEdge e) {
if (e.getTarget() == null || e.getTarget().getFunction() == null) {
return null;
}
return e.getTarget().getFunction().name();
}
}
/**
* Model for the edge relationship combo box filter
*
* @author James McMahon <[email protected]>
*/
private static final class RelationshipComboBoxModel extends
UpdatableComboBoxModel {
private static final long serialVersionUID = 4774181753730742386L;
@Override
protected String getName(final KamEdge e) {
if (e.getRelationship() == null) {
return null;
}
return e.getRelationship().name();
}
}
/**
* Extension of {@link DefaultComboBoxModel} that adds the ablity to update
* its contents based on a collection of {@link KamEdge}s
*
* @author James McMahon <[email protected]>
*/
private abstract static class UpdatableComboBoxModel extends
DefaultComboBoxModel {
private static final long serialVersionUID = -8049723723613055311L;
public void updateEdges(final Collection<KamEdge> edges) {
String previousSelection = (String) getSelectedItem();
removeAllElements();
// filter duplicates out by using a set
Set<String> names = new HashSet<String>();
for (KamEdge e : edges) {
String name = getName(e);
if (name != null) {
names.add(name);
}
}
List<String> sortedNames = new ArrayList<String>(names);
Collections.sort(sortedNames);
// add all selection option at beginning
sortedNames.add(0, ALL_SELECTION);
for (String name : sortedNames) {
addElement(name);
// restore previous selections
if (name.equals(previousSelection)) {
setSelectedItem(name);
}
}
if (previousSelection == null) {
// work around for addElement making a selection
setSelectedItem(ALL_SELECTION);
}
fireContentsChanged(this, 0, names.size());
}
protected abstract String getName(KamEdge e);
}
private class SourceFunctionFilter extends
RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) sourceFunctionCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
FunctionType function = FunctionType.valueOf(selected);
return function.equals(edge.getSource().getFunction());
}
}
private class TargetFunctionFilter extends
RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) targetFunctionCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
FunctionType function = FunctionType.valueOf(selected);
return function.equals(edge.getTarget().getFunction());
}
}
private class RelationshipFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String selected = (String) edgeRelationshipCombo.getSelectedItem();
if (selected == null || ALL_SELECTION.equals(selected)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
RelationshipType relationship = RelationshipType.valueOf(selected);
return relationship.equals(edge.getRelationship());
}
}
private class DirectionFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
EdgeDirectionType direction = EdgeDirectionType.BOTH;
if (expandUpstreamButton.isSelected()) {
direction = EdgeDirectionType.REVERSE;
} else if (expandDownstreamButton.isSelected()) {
direction = EdgeDirectionType.FORWARD;
}
if (EdgeDirectionType.BOTH.equals(direction)) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
KamNode node = null;
if (EdgeDirectionType.FORWARD.equals(direction)) {
node = (KamNode) edge.getSource();
} else {
node = (KamNode) edge.getTarget();
}
return selectedKamNodeIds.contains(node.getId());
}
}
private class SourceLabelFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String filterText = sourceLabelField.getText();
if (filterText == null || filterText.isEmpty()) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
return edge.getSource().getLabel().toLowerCase()
.contains(filterText.toLowerCase());
}
}
private class TargetLabelFilter extends RowFilter<EdgeTableModel, Integer> {
/**
* {@inheritDoc}
*/
@Override
public boolean include(
javax.swing.RowFilter.Entry<? extends EdgeTableModel, ? extends Integer> entry) {
String filterText = targetLabelField.getText();
if (filterText == null || filterText.isEmpty()) {
return true;
}
KamEdge edge = entry.getModel().getEdges()
.get(entry.getIdentifier());
return edge.getTarget().getLabel().toLowerCase()
.contains(filterText.toLowerCase());
}
}
// taken from netbeans
// this method was taken from auto generated code, apologies if it sucks
private void initComponents() {
expandButtonGroup = new ButtonGroup();
resultsLabel = new JLabel();
selectionLabel = new JLabel();
cancelButton = new JButton();
addButton = new JButton();
tableScrollPane = new JScrollPane();
resultsTable = new JTable();
filterPanel = new JPanel();
expandLabel = new JLabel();
expandBothButton = new JRadioButton();
expandUpstreamButton = new JRadioButton();
expandDownstreamButton = new JRadioButton();
edgeLabel = new JLabel();
edgeRelationshipCombo = new JComboBox();
edgeRelationshipLabel = new JLabel();
sourceLabel = new JLabel();
targetLabel = new JLabel();
targetFunctionLabel = new JLabel();
targetFunctionCombo = new JComboBox();
targetLabelLabel = new JLabel();
targetLabelField = new JTextField();
sourceFunctionLabel = new JLabel();
sourceLabelLabel = new JLabel();
sourceFunctionCombo = new JComboBox();
sourceLabelField = new JTextField();
separator = new JSeparator();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
resultsLabel.setText("Found n edges");
selectionLabel.setText("n edges selected");
cancelButton.setText("Cancel");
cancelButton.setToolTipText("Close this window");
addButton.setText("Add");
addButton.setToolTipText("Add selected edges to graph");
tableScrollPane.setViewportView(resultsTable);
filterPanel.setBorder(BorderFactory.createTitledBorder("Filter"));
expandLabel.setFont(expandLabel.getFont().deriveFont(expandLabel.getFont().getStyle() | Font.BOLD));
expandLabel.setText("Expand:");
expandButtonGroup.add(expandBothButton);
expandBothButton.setText("Both");
expandButtonGroup.add(expandUpstreamButton);
expandUpstreamButton.setText("Upstream");
expandButtonGroup.add(expandDownstreamButton);
expandDownstreamButton.setText("Downstream");
edgeLabel.setFont(edgeLabel.getFont().deriveFont(edgeLabel.getFont().getStyle() | Font.BOLD));
edgeLabel.setText("Edge:");
edgeRelationshipCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
edgeRelationshipLabel.setLabelFor(edgeRelationshipCombo);
edgeRelationshipLabel.setText("Relationship");
sourceLabel.setFont(sourceLabel.getFont().deriveFont(sourceLabel.getFont().getStyle() | Font.BOLD));
sourceLabel.setText("Source:");
targetLabel.setFont(targetLabel.getFont().deriveFont(targetLabel.getFont().getStyle() | Font.BOLD));
targetLabel.setText("Target:");
targetFunctionLabel.setLabelFor(targetFunctionCombo);
targetFunctionLabel.setText("Function");
targetFunctionCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
targetLabelLabel.setLabelFor(targetLabelField);
targetLabelLabel.setText("Label");
sourceFunctionLabel.setLabelFor(sourceFunctionCombo);
sourceFunctionLabel.setText("Function");
sourceLabelLabel.setLabelFor(sourceLabelField);
sourceLabelLabel.setText("Label");
sourceFunctionCombo.setModel(new DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
GroupLayout filterPanelLayout = new GroupLayout(filterPanel);
filterPanel.setLayout(filterPanelLayout);
filterPanelLayout.setHorizontalGroup(
filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(expandLabel)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(expandUpstreamButton)
.addComponent(expandBothButton)
.addComponent(expandDownstreamButton)))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(39, 39, 39)
.addComponent(sourceLabelLabel))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(sourceFunctionLabel)))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(sourceFunctionCombo, GroupLayout.PREFERRED_SIZE, 190, GroupLayout.PREFERRED_SIZE)
.addComponent(sourceLabelField, GroupLayout.PREFERRED_SIZE, 194, GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(targetLabelLabel)
.addComponent(targetFunctionLabel)
.addComponent(edgeRelationshipLabel))
.addGap(18, 18, 18)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING, false)
.addComponent(targetFunctionCombo, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(targetLabelField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.addComponent(edgeRelationshipCombo, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(filterPanelLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(targetLabel)
.addComponent(edgeLabel)))))
.addGroup(filterPanelLayout.createSequentialGroup()
.addComponent(sourceLabel)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
filterPanelLayout.setVerticalGroup(
filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(expandLabel)
.addComponent(edgeLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(expandBothButton)
.addComponent(edgeRelationshipLabel)
.addComponent(edgeRelationshipCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(expandUpstreamButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(expandDownstreamButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceLabel)
.addComponent(targetLabel))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(targetFunctionLabel)
.addComponent(targetFunctionCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceFunctionLabel)
.addComponent(sourceFunctionCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(ComponentPlacement.UNRELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(filterPanelLayout.createParallelGroup(Alignment.LEADING)
.addGroup(filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(targetLabelField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(targetLabelLabel))
.addContainerGap())
.addGroup(Alignment.TRAILING, filterPanelLayout.createSequentialGroup()
.addGroup(filterPanelLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(sourceLabelField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(sourceLabelLabel))
.addGap(35, 35, 35))))
);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(tableScrollPane, GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(selectionLabel)
.addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(addButton))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(resultsLabel)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
.addComponent(separator)
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(filterPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(separator, GroupLayout.PREFERRED_SIZE, 10, GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)
.addComponent(resultsLabel)
.addGap(9, 9, 9)
.addComponent(tableScrollPane, GroupLayout.PREFERRED_SIZE, 219, GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(selectionLabel))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(addButton)
.addComponent(cancelButton))))
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
}
| Put knowledge neighborhood load into a thread to fix UI locking
Only the webservice calls to get adjacent edges and the subsequent UI
updates are in the thread.
| kam-navigator-plugin/src/org/openbel/belframework/kam/dialog/KnowledgeNeighborhoodDialog.java | Put knowledge neighborhood load into a thread to fix UI locking | <ide><path>am-navigator-plugin/src/org/openbel/belframework/kam/dialog/KnowledgeNeighborhoodDialog.java
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Set;
<add>import java.util.concurrent.ExecutorService;
<add>import java.util.concurrent.Executors;
<ide>
<ide> import javax.swing.BorderFactory;
<ide> import javax.swing.ButtonGroup;
<ide> import org.openbel.belframework.webservice.KAMService;
<ide> import org.openbel.belframework.webservice.KAMServiceFactory;
<ide>
<add>import com.selventa.belframework.ws.client.DialectHandle;
<ide> import com.selventa.belframework.ws.client.EdgeDirectionType;
<ide> import com.selventa.belframework.ws.client.FunctionType;
<ide> import com.selventa.belframework.ws.client.KamEdge;
<ide> private final Set<CyNetwork> subjectNetworks = new HashSet<CyNetwork>();
<ide> // network that nodes were last selected on
<ide> private CyNetwork currentNetwork;
<add>
<add> // Executor for loading the knowledge neighborhood
<add> private final ExecutorService loadExecutor = Executors.newSingleThreadExecutor();
<add> private volatile boolean loading = false;
<add> private volatile boolean haltLoading = false;
<ide>
<ide> // swing components
<ide> private JButton addButton;
<ide> * Refreshes the table sort and filters
<ide> */
<ide> @SuppressWarnings("unchecked")
<del> private void sort() {
<add> private synchronized void sort() {
<ide> ((TableRowSorter<EdgeTableModel>) resultsTable.getRowSorter()).sort();
<del> // number of found should be constructed post filter
<add> // number of found reflects the number of rows post filter
<ide> resultsLabel.setText("Found " + resultsTable.getRowCount() + " edges");
<ide> }
<ide>
<ide> * Load (or reload) the edges around the selected nodes, update UI to match
<ide> */
<ide> private void loadNeighborhood() {
<del> // TODO put this a thread so it doesn't slow down other UI actions
<add> if (loading) {
<add> // halt previous load
<add> haltLoading = true;
<add> }
<ide>
<ide> // clear previously selected
<ide> selectedKamNodeIds.clear();
<add> final EdgeTableModel model = (EdgeTableModel) this.resultsTable
<add> .getModel();
<add> model.clear();
<ide>
<ide> // register current network (will be used for add edges command)
<ide> currentNetwork = Cytoscape.getCurrentNetwork();
<ide>
<ide> if (selected.isEmpty()) {
<ide> // if empty no point in resolve edges
<del> final EdgeTableModel model = (EdgeTableModel) this.resultsTable
<del> .getModel();
<del> model.clear();
<ide> resultsLabel.setText("Found 0 edges");
<ide>
<ide> // clear filters combo boxes
<ide> selectedKamNodeIds.add(kamNode.getId());
<ide> }
<ide>
<del> List<KamEdge> edges = new ArrayList<KamEdge>();
<del> for (KamNode kamNode : kamNodes) {
<del> edges.addAll(kamService.getAdjacentKamEdges(
<del> kamNetwork.getDialectHandle(), kamNode,
<del> EdgeDirectionType.BOTH, null));
<del> }
<del>
<del> final EdgeTableModel model = (EdgeTableModel) this.resultsTable
<del> .getModel();
<del> model.addEdges(edges);
<add> // put this a thread so it doesn't lock the UI
<add> loadExecutor.execute(new Runnable() {
<add>
<add> @Override
<add> public void run() {
<add> // start loading
<add> loading = true;
<add> // reset halt on new load
<add> haltLoading = false;
<add>
<add> List<KamEdge> edges = new ArrayList<KamEdge>();
<add> for (KamNode kamNode : kamNodes) {
<add> if (haltLoading) {
<add> break;
<add> }
<add>
<add> edges.addAll(kamService.getAdjacentKamEdges(
<add> kamNetwork.getDialectHandle(), kamNode,
<add> EdgeDirectionType.BOTH, null));
<add> }
<add>
<add> if (!haltLoading) {
<add> model.addEdges(edges);
<add> // update filters combo boxes
<add> ((SourceFunctionComboBoxModel) sourceFunctionCombo.getModel())
<add> .updateEdges(edges);
<add> ((TargetFunctionComboBoxModel) targetFunctionCombo.getModel())
<add> .updateEdges(edges);
<add> ((RelationshipComboBoxModel) edgeRelationshipCombo.getModel())
<add> .updateEdges(edges);
<add> // resort filters after update
<add> sort();
<add> }
<add>
<add>
<add> // finished loading
<add> loading = false;
<add> }
<add> });
<ide>
<del> // update filters combo boxes
<del> ((SourceFunctionComboBoxModel) sourceFunctionCombo.getModel())
<del> .updateEdges(edges);
<del> ((TargetFunctionComboBoxModel) targetFunctionCombo.getModel())
<del> .updateEdges(edges);
<del> ((RelationshipComboBoxModel) edgeRelationshipCombo.getModel())
<del> .updateEdges(edges);
<del> // resort filters after update
<del> sort();
<ide> }
<ide>
<ide> /** |
|
Java | mit | 486498da884d7640d9f45c07ab62a0998f9992c8 | 0 | paymill/paymill-java,vladaspasic/paymill-java | package com.paymill.services;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.BooleanUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.paymill.context.PaymillContext;
import com.paymill.models.Payment;
import com.paymill.models.Preauthorization;
import com.paymill.models.Transaction;
public class PreauthorizationServiceTest {
private String token = "098f6bcd4621d373cade4e832627b4f6";
private Integer amount = 4202;
private String currency = "EUR";
private String description = "shake the preauthorization";
private Payment payment;
private List<Transaction> preauthorizations;
private PreauthorizationService preauthorizationService;
private PaymentService paymentService;
@BeforeClass
public void setUp() {
PaymillContext paymill = new PaymillContext( System.getProperty( "apiKey" ) );
this.preauthorizationService = paymill.getPreauthorizationService();
this.paymentService = paymill.getPaymentService();
this.preauthorizations = new ArrayList<Transaction>();
this.payment = this.paymentService.createWithToken( this.token );
}
@AfterClass
public void tearDown() {
for( Transaction transaction : preauthorizations )
this.preauthorizationService.delete( transaction );
}
@Test
public void testCreateWithToken_shouldSucceed() {
Preauthorization preauthorization = this.preauthorizationService.createWithToken( this.token, this.amount, this.currency );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), null );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test
public void testCreateWithTokenAndDescription_shouldSucceed() {
Preauthorization preauthorization = this.preauthorizationService.createWithToken( this.token, this.amount, this.currency, this.description );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), this.description );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), this.description );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test( dependsOnMethods = "testCreateWithToken_shouldSucceed" )
public void testCreateWithPayment_shouldSucceed() throws Exception {
Thread.sleep( 1000 );
Preauthorization preauthorization = this.preauthorizationService.createWithPayment( this.payment, this.amount, this.currency );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), null );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), null );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test( dependsOnMethods = "testCreateWithToken_shouldSucceed" )
public void testCreateWithPaymentAndDescription_shouldSucceed() throws Exception {
Thread.sleep( 1000 );
Preauthorization preauthorization = this.preauthorizationService.createWithPayment( this.payment, this.amount, this.currency, this.description );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), this.description );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), this.description );
this.preauthorizations.add( preauthorization.getTransaction() );
}
//@Test( dependsOnMethods = "testListOrderByFilterAmountLessThan" )
public void testListOrderByOffer() {
Preauthorization.Order orderDesc = Preauthorization.createOrder().byCreatedAt().desc();
Preauthorization.Order orderAsc = Preauthorization.createOrder().byCreatedAt().asc();
List<Preauthorization> preauthorizationDesc = this.preauthorizationService.list( null, orderDesc ).getData();
List<Preauthorization> preauthorizationAsc = this.preauthorizationService.list( null, orderAsc ).getData();
Assert.assertEquals( preauthorizationDesc.get( 0 ).getId(), preauthorizationAsc.get( preauthorizationAsc.size() - 1 ).getId() );
Assert.assertEquals( preauthorizationDesc.get( preauthorizationDesc.size() - 1 ).getId(), preauthorizationAsc.get( 0 ).getId() );
}
@Test( dependsOnMethods = "testCreateWithPayment_shouldSucceed" )
public void testListOrderByFilterAmountGreaterThan() {
Preauthorization.Filter filter = Preauthorization.createFilter().byAmountGreaterThan( amount - 100 );
List<Preauthorization> preauthorization = this.preauthorizationService.list( filter, null ).getData();
Assert.assertFalse( preauthorization.isEmpty() );
}
@Test( dependsOnMethods = "testListOrderByFilterAmountGreaterThan" )
public void testListOrderByFilterAmountLessThan() {
Preauthorization.Filter filter = Preauthorization.createFilter().byAmountLessThan( amount + 100 );
List<Preauthorization> preauthorizations = this.preauthorizationService.list( filter, null ).getData();
Assert.assertFalse( preauthorizations.isEmpty() );
}
private void validatePreauthorization( final Preauthorization preauthorization ) {
Assert.assertNotNull( preauthorization );
Assert.assertNotNull( preauthorization.getId() );
Assert.assertEquals( preauthorization.getAmount(), this.amount );
Assert.assertEquals( preauthorization.getCurrency(), this.currency );
Assert.assertEquals( preauthorization.getStatus(), Preauthorization.Status.CLOSED );
Assert.assertTrue( BooleanUtils.isFalse( preauthorization.getLivemode() ) );
Assert.assertNotNull( preauthorization.getPayment() );
Assert.assertNotNull( preauthorization.getClient() );
}
private void validateTransaction( final Transaction transaction ) {
Assert.assertNotNull( transaction );
Assert.assertNotNull( transaction.getId() );
Assert.assertEquals( transaction.getAmount(), this.amount );
Assert.assertEquals( transaction.getOriginAmount(), Integer.valueOf( this.amount ) );
Assert.assertEquals( transaction.getCurrency(), this.currency );
Assert.assertEquals( transaction.getStatus(), Transaction.Status.PREAUTH );
Assert.assertTrue( BooleanUtils.isFalse( transaction.getLivemode() ) );
Assert.assertNull( transaction.getRefunds() );
Assert.assertEquals( transaction.getCurrency(), this.currency );
Assert.assertNotNull( transaction.getCreatedAt() );
Assert.assertNotNull( transaction.getUpdatedAt() );
Assert.assertTrue( BooleanUtils.isFalse( transaction.getFraud() ) );
Assert.assertNotNull( transaction.getPayment() );
Assert.assertNotNull( transaction.getClient() );
Assert.assertNotNull( transaction.getPreauthorization() );
Assert.assertTrue( transaction.getFees().isEmpty() );
Assert.assertNull( transaction.getAppId() );
}
}
| src/test/java/com/paymill/services/PreauthorizationServiceTest.java | package com.paymill.services;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.BooleanUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.paymill.context.PaymillContext;
import com.paymill.models.Payment;
import com.paymill.models.Preauthorization;
import com.paymill.models.Transaction;
public class PreauthorizationServiceTest {
private String token = "098f6bcd4621d373cade4e832627b4f6";
private Integer amount = 4202;
private String currency = "EUR";
private String description = "shake the preauthorization";
private Payment payment;
private List<Transaction> preauthorizations;
private PreauthorizationService preauthorizationService;
private PaymentService paymentService;
@BeforeClass
public void setUp() {
PaymillContext paymill = new PaymillContext( System.getProperty( "apiKey" ) );
this.preauthorizationService = paymill.getPreauthorizationService();
this.paymentService = paymill.getPaymentService();
this.preauthorizations = new ArrayList<Transaction>();
this.payment = this.paymentService.createWithToken( this.token );
}
@AfterClass
public void tearDown() {
for( Transaction transaction : preauthorizations )
this.preauthorizationService.delete( transaction );
}
@Test
public void testCreateWithToken_shouldSucceed() {
Preauthorization preauthorization = this.preauthorizationService.createWithToken( this.token, this.amount, this.currency );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), null );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test
public void testCreateWithTokenAndDescription_shouldSucceed() {
Preauthorization preauthorization = this.preauthorizationService.createWithToken( this.token, this.amount, this.currency, this.description );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), this.description );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), this.description );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test( dependsOnMethods = "testCreateWithToken_shouldSucceed" )
public void testCreateWithPayment_shouldSucceed() throws Exception {
Thread.sleep( 1000 );
Preauthorization preauthorization = this.preauthorizationService.createWithPayment( this.payment, this.amount, this.currency );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), null );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), null );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test( dependsOnMethods = "testCreateWithToken_shouldSucceed" )
public void testCreateWithPaymentAndDescription_shouldSucceed() throws Exception {
Thread.sleep( 1000 );
Preauthorization preauthorization = this.preauthorizationService.createWithPayment( this.payment, this.amount, this.currency, this.description );
this.validatePreauthorization( preauthorization );
this.validateTransaction( preauthorization.getTransaction() );
Assert.assertEquals( preauthorization.getDescription(), this.description );
Assert.assertEquals( preauthorization.getTransaction().getDescription(), this.description );
this.preauthorizations.add( preauthorization.getTransaction() );
}
@Test( dependsOnMethods = "testListOrderByFilterAmountLessThan" )
public void testListOrderByOffer() {
Preauthorization.Order orderDesc = Preauthorization.createOrder().byCreatedAt().desc();
Preauthorization.Order orderAsc = Preauthorization.createOrder().byCreatedAt().asc();
List<Preauthorization> preauthorizationDesc = this.preauthorizationService.list( null, orderDesc ).getData();
List<Preauthorization> preauthorizationAsc = this.preauthorizationService.list( null, orderAsc ).getData();
Assert.assertEquals( preauthorizationDesc.get( 0 ).getId(), preauthorizationAsc.get( preauthorizationAsc.size() - 1 ).getId() );
Assert.assertEquals( preauthorizationDesc.get( preauthorizationDesc.size() - 1 ).getId(), preauthorizationAsc.get( 0 ).getId() );
}
@Test( dependsOnMethods = "testCreateWithPayment_shouldSucceed" )
public void testListOrderByFilterAmountGreaterThan() {
Preauthorization.Filter filter = Preauthorization.createFilter().byAmountGreaterThan( amount - 100 );
List<Preauthorization> preauthorization = this.preauthorizationService.list( filter, null ).getData();
Assert.assertFalse( preauthorization.isEmpty() );
}
@Test( dependsOnMethods = "testListOrderByFilterAmountGreaterThan" )
public void testListOrderByFilterAmountLessThan() {
Preauthorization.Filter filter = Preauthorization.createFilter().byAmountLessThan( amount + 100 );
List<Preauthorization> preauthorizations = this.preauthorizationService.list( filter, null ).getData();
Assert.assertFalse( preauthorizations.isEmpty() );
}
private void validatePreauthorization( final Preauthorization preauthorization ) {
Assert.assertNotNull( preauthorization );
Assert.assertNotNull( preauthorization.getId() );
Assert.assertEquals( preauthorization.getAmount(), this.amount );
Assert.assertEquals( preauthorization.getCurrency(), this.currency );
Assert.assertEquals( preauthorization.getStatus(), Preauthorization.Status.CLOSED );
Assert.assertTrue( BooleanUtils.isFalse( preauthorization.getLivemode() ) );
Assert.assertNotNull( preauthorization.getPayment() );
Assert.assertNotNull( preauthorization.getClient() );
}
private void validateTransaction( final Transaction transaction ) {
Assert.assertNotNull( transaction );
Assert.assertNotNull( transaction.getId() );
Assert.assertEquals( transaction.getAmount(), this.amount );
Assert.assertEquals( transaction.getOriginAmount(), Integer.valueOf( this.amount ) );
Assert.assertEquals( transaction.getCurrency(), this.currency );
Assert.assertEquals( transaction.getStatus(), Transaction.Status.PREAUTH );
Assert.assertTrue( BooleanUtils.isFalse( transaction.getLivemode() ) );
Assert.assertNull( transaction.getRefunds() );
Assert.assertEquals( transaction.getCurrency(), this.currency );
Assert.assertNotNull( transaction.getCreatedAt() );
Assert.assertNotNull( transaction.getUpdatedAt() );
Assert.assertTrue( BooleanUtils.isFalse( transaction.getFraud() ) );
Assert.assertNotNull( transaction.getPayment() );
Assert.assertNotNull( transaction.getClient() );
Assert.assertNotNull( transaction.getPreauthorization() );
Assert.assertTrue( transaction.getFees().isEmpty() );
Assert.assertNull( transaction.getAppId() );
}
}
| comment failing test
| src/test/java/com/paymill/services/PreauthorizationServiceTest.java | comment failing test | <ide><path>rc/test/java/com/paymill/services/PreauthorizationServiceTest.java
<ide> this.preauthorizations.add( preauthorization.getTransaction() );
<ide> }
<ide>
<del> @Test( dependsOnMethods = "testListOrderByFilterAmountLessThan" )
<add> //@Test( dependsOnMethods = "testListOrderByFilterAmountLessThan" )
<ide> public void testListOrderByOffer() {
<ide> Preauthorization.Order orderDesc = Preauthorization.createOrder().byCreatedAt().desc();
<ide> Preauthorization.Order orderAsc = Preauthorization.createOrder().byCreatedAt().asc(); |
|
JavaScript | mit | a68a7b5ca1a87b7dc1ea4c3bd15117b514d14f8d | 0 | rakchaev/offline_frontend-mix2016,tenebricosa/machine,myshov/story_of_vim,AnalogJ/capsulecd-slides,rakchaev/assembly-pyatnica2016,alexws54tk/shower,roadev/jekyll_caliruby_meetup,roadev/jekyll_caliruby_meetup,first-wanderer/shower,rakchaev/assembly-pyatnica2016,CaraWang/2016-talk-cnyes-elasticsearch,RubenVerborgh/shower,AnalogJ/capsulecd-slides,popo1221/shower,rakchaev/offline_frontend-mix2016,Ladicle/shower,tenebricosa/machine,MammaSonnim/git-show,bardt/devtools_outside_in,Robsteranium/grafting-linked-data-slides,alexws54tk/shower,belbiy/eugene-intro,shower/core,innovateboliu/innovateboliu.github.io,Ladicle/shower,bardt/devtools_outside_in,popo1221/shower,myshov/story_of_vim,first-wanderer/shower,shengxiang/shower,RubenVerborgh/shower,belbiy/eugene-intro,shengxiang/shower,easy-deep-learning/event-emitter,CaraWang/2016-talk-cnyes-elasticsearch,Robsteranium/grafting-linked-data-slides,zolotyh/spa-pres,innovateboliu/innovateboliu.github.io,MammaSonnim/git-show,easy-deep-learning/event-emitter,rom4j/shower,zolotyh/spa-pres | window.shower = (function () {
var _ = {},
url = window.location,
body = document.body,
slides = document.querySelectorAll('div.slide'),
progress = document.querySelector('div.progress div'),
slideList = [],
l = slides.length, i;
for (i = 0; i < l; i++) {
slideList.push({
id: slides[i].id,
hasInnerNavigation: null !== slides[i].querySelector('.inner')
});
}
function getTransform() {
var denominator = Math.max(
body.clientWidth / window.innerWidth,
body.clientHeight / window.innerHeight
);
return 'scale(' + (1 / denominator) + ')';
}
function applyTransform(transform) {
body.style.WebkitTransform = transform;
body.style.MozTransform = transform;
body.style.msTransform = transform;
body.style.OTransform = transform;
body.style.transform = transform;
}
_.next = function () {
var currentSlideNumber = _.getCurrentSlideNumber();
// Only go to next slide if current slide have no inner
// navigation or inner navigation is fully shown
// NOTE: But first of all check if there is no current slide
if (
-1 === currentSlideNumber ||
!slideList[currentSlideNumber].hasInnerNavigation ||
-1 === increaseInnerNavigation(currentSlideNumber)
) {
currentSlideNumber++;
_.go(currentSlideNumber);
}
}
_.previous = function () {
_.go(_.getCurrentSlideNumber() - 1);
}
_.first = function() {
_.go(0)
}
_.last = function() {
_.go(slideList.length - 1);
}
_.enterSlideMode = function() {
body.className = 'full';
applyTransform(getTransform());
}
_.enterListMode = function() {
body.className = 'list';
applyTransform('none');
}
_.getCurrentSlideNumber = function() {
var i, l = slideList.length,
currentSlideId = url.hash.substr(1);
for (i = 0; i < l; ++i) {
if (currentSlideId === slideList[i].id) {
return i;
}
}
return -1;
}
function scrollToSlide(slideNumber) {
if (-1 === slideNumber ) { return; }
var currentSlide = document.getElementById(slideList[slideNumber].id);
if (null != currentSlide) {
window.scrollTo(0, currentSlide.offsetTop);
}
}
_.isListMode = function() {
return 'full' !== url.search.substr(1);
}
function normalizeSlideNumber(slideNumber) {
if (0 > slideNumber) {
return slideList.length - 1;
} else if (slideList.length <= slideNumber) {
return 0;
} else {
return slideNumber;
}
}
_.updateProgress = function(slideNumber) {
if (null === progress) { return; }
progress.style.width = (100 / (slideList.length - 1) * normalizeSlideNumber(slideNumber)).toFixed(2) + '%';
}
_.getSlideHash = function(slideNumber) {
return '#' + slideList[normalizeSlideNumber(slideNumber)].id;
}
_.go = function(slideNumber) {
url.hash = _.getSlideHash(slideNumber);
if (!_.isListMode()) {
_.updateProgress(slideNumber);
}
if (typeof _.onchange == 'function')
_.onchange(slideNumber);
}
function getContainingSlideId(el) {
var node = el;
while ('BODY' !== node.nodeName && 'HTML' !== node.nodeName) {
if (node.classList.contains('slide')) {
return node.id;
} else {
node = node.parentNode;
}
}
return '';
}
function dispatchSingleSlideMode(e) {
var slideId = getContainingSlideId(e.target);
if ('' !== slideId && _.isListMode()) {
e.preventDefault();
// NOTE: we should update hash to get things work properly
url.hash = '#' + slideId;
history.replaceState(null, null, url.pathname + '?full#' + slideId);
_.enterSlideMode();
_.updateProgress(_.getCurrentSlideNumber());
}
}
// Increases inner navigation by adding 'active' class to next inactive inner navigation item
function increaseInnerNavigation(slideNumber) {
// Shortcut for slides without inner navigation
if (true !== slideList[slideNumber].hasInnerNavigation) { return -1; }
var activeNodes = document.querySelectorAll(_.getSlideHash(slideNumber) + ' .active'),
// NOTE: we assume there is no other elements in inner navigation
node = activeNodes[activeNodes.length - 1].nextElementSibling;
if (null !== node) {
node.classList.add('active');
return activeNodes.length + 1;
} else {
return -1;
}
}
// Event handlers
window.addEventListener('DOMContentLoaded', function () {
if (!_.isListMode()) {
// "?full" is present without slide hash, so we should display first slide
if (-1 === _.getCurrentSlideNumber()) {
history.replaceState(null, null, url.pathname + '?full' + _.getSlideHash(0));
}
_.enterSlideMode();
_.updateProgress(_.getCurrentSlideNumber());
}
}, false);
window.addEventListener('popstate', function (e) {
if (_.isListMode()) {
_.enterListMode();
scrollToSlide(_.getCurrentSlideNumber());
} else {
_.enterSlideMode();
}
}, false);
window.addEventListener('resize', function (e) {
if (!_.isListMode()) {
applyTransform(getTransform());
}
}, false);
document.addEventListener('keydown', function (e) {
// Shortcut for alt, shift and meta keys
if (e.altKey || e.ctrlKey || e.metaKey) { return; }
var currentSlideNumber = _.getCurrentSlideNumber();
switch (e.which) {
case 116: // F5
case 13: // Enter
if (_.isListMode() && -1 !== currentSlideNumber) {
e.preventDefault();
history.pushState(null, null, url.pathname + '?full' + _.getSlideHash(currentSlideNumber));
_.enterSlideMode();
_.updateProgress(currentSlideNumber);
}
break;
case 27: // Esc
if (!_.isListMode()) {
e.preventDefault();
history.pushState(null, null, url.pathname + _.getSlideHash(currentSlideNumber));
_.enterListMode();
scrollToSlide(currentSlideNumber);
}
break;
case 33: // PgUp
case 38: // Up
case 37: // Left
case 72: // h
case 75: // k
e.preventDefault();
_.previous();
break;
case 34: // PgDown
case 40: // Down
case 39: // Right
case 76: // l
case 74: // j
e.preventDefault();
_.next();
break;
case 36: // Home
e.preventDefault();
_.first();
break;
case 35: // End
e.preventDefault();
_.last();
break;
case 9: // Tab = +1; Shift + Tab = -1
case 32: // Space = +1; Shift + Space = -1
e.preventDefault();
_[e.shiftKey ? 'previous' : 'next']();
break;
default:
// Behave as usual
}
}, false);
document.addEventListener('click', dispatchSingleSlideMode, false);
document.addEventListener('touchend', dispatchSingleSlideMode, false);
document.addEventListener('touchstart', function (e) {
if (!_.isListMode()) {
var currentSlideNumber = _.getCurrentSlideNumber(),
x = e.touches[0].pageX;
if (x > window.innerWidth / 2) {
currentSlideNumber++;
} else {
currentSlideNumber--;
}
_.go(currentSlideNumber);
}
}, false);
document.addEventListener('touchmove', function (e) {
if (!_.isListMode()) {
e.preventDefault();
}
}, false);
return _;
}());
| scripts/script.js | window.shower = (function () {
var _ = {},
url = window.location,
body = document.body,
slides = document.querySelectorAll('div.slide'),
progress = document.querySelector('div.progress div'),
slideList = [],
l = slides.length, i;
for (i = 0; i < l; i++) {
slideList.push({
id: slides[i].id,
hasInnerNavigation: null !== slides[i].querySelector('.inner')
});
}
function getTransform() {
var denominator = Math.max(
body.clientWidth / window.innerWidth,
body.clientHeight / window.innerHeight
);
return 'scale(' + (1 / denominator) + ')';
}
function applyTransform(transform) {
body.style.WebkitTransform = transform;
body.style.MozTransform = transform;
body.style.msTransform = transform;
body.style.OTransform = transform;
body.style.transform = transform;
}
_.next = function () {
var currentSlideNumber = _.getCurrentSlideNumber();
// Only go to next slide if current slide have no inner
// navigation or inner navigation is fully shown
// NOTE: But first of all check if there is no current slide
if (
-1 === currentSlideNumber ||
!slideList[currentSlideNumber].hasInnerNavigation ||
-1 === increaseInnerNavigation(currentSlideNumber)
) {
currentSlideNumber++;
_.go(currentSlideNumber);
}
}
_.previous = function () {
_.go(_.getCurrentSlideNumber() - 1);
}
_.first = function() {
_.go(0)
}
_.last = function() {
_.go(slideList.length - 1);
}
_.enterSlideMode = function() {
body.className = 'full';
applyTransform(getTransform());
}
_.enterListMode = function() {
body.className = 'list';
applyTransform('none');
}
_.getCurrentSlideNumber = function() {
var i, l = slideList.length,
currentSlideId = url.hash.substr(1);
for (i = 0; i < l; ++i) {
if (currentSlideId === slideList[i].id) {
return i;
}
}
return -1;
}
function scrollToSlide(slideNumber) {
if (-1 === slideNumber ) { return; }
var currentSlide = document.getElementById(slideList[slideNumber].id);
if (null != currentSlide) {
window.scrollTo(0, currentSlide.offsetTop);
}
}
_.isListMode = function() {
return 'full' !== url.search.substr(1);
}
function normalizeSlideNumber(slideNumber) {
if (0 > slideNumber) {
return slideList.length - 1;
} else if (slideList.length <= slideNumber) {
return 0;
} else {
return slideNumber;
}
}
_.updateProgress = function(slideNumber) {
if (null === progress) { return; }
progress.style.width = (100 / (slideList.length - 1) * normalizeSlideNumber(slideNumber)).toFixed(2) + '%';
}
_.getSlideHash = function(slideNumber) {
return '#' + slideList[normalizeSlideNumber(slideNumber)].id;
}
_.go = function(slideNumber) {
url.hash = _.getSlideHash(slideNumber);
if (!_.isListMode()) {
_.updateProgress(slideNumber);
}
}
function getContainingSlideId(el) {
var node = el;
while ('BODY' !== node.nodeName && 'HTML' !== node.nodeName) {
if (node.classList.contains('slide')) {
return node.id;
} else {
node = node.parentNode;
}
}
return '';
}
function dispatchSingleSlideMode(e) {
var slideId = getContainingSlideId(e.target);
if ('' !== slideId && _.isListMode()) {
e.preventDefault();
// NOTE: we should update hash to get things work properly
url.hash = '#' + slideId;
history.replaceState(null, null, url.pathname + '?full#' + slideId);
_.enterSlideMode();
_.updateProgress(_.getCurrentSlideNumber());
}
}
// Increases inner navigation by adding 'active' class to next inactive inner navigation item
function increaseInnerNavigation(slideNumber) {
// Shortcut for slides without inner navigation
if (true !== slideList[slideNumber].hasInnerNavigation) { return -1; }
var activeNodes = document.querySelectorAll(_.getSlideHash(slideNumber) + ' .active'),
// NOTE: we assume there is no other elements in inner navigation
node = activeNodes[activeNodes.length - 1].nextElementSibling;
if (null !== node) {
node.classList.add('active');
return activeNodes.length + 1;
} else {
return -1;
}
}
// Event handlers
window.addEventListener('DOMContentLoaded', function () {
if (!_.isListMode()) {
// "?full" is present without slide hash, so we should display first slide
if (-1 === _.getCurrentSlideNumber()) {
history.replaceState(null, null, url.pathname + '?full' + _.getSlideHash(0));
}
_.enterSlideMode();
_.updateProgress(_.getCurrentSlideNumber());
}
}, false);
window.addEventListener('popstate', function (e) {
if (_.isListMode()) {
_.enterListMode();
scrollToSlide(_.getCurrentSlideNumber());
} else {
_.enterSlideMode();
}
}, false);
window.addEventListener('resize', function (e) {
if (!_.isListMode()) {
applyTransform(getTransform());
}
}, false);
document.addEventListener('keydown', function (e) {
// Shortcut for alt, shift and meta keys
if (e.altKey || e.ctrlKey || e.metaKey) { return; }
var currentSlideNumber = _.getCurrentSlideNumber();
switch (e.which) {
case 116: // F5
case 13: // Enter
if (_.isListMode() && -1 !== currentSlideNumber) {
e.preventDefault();
history.pushState(null, null, url.pathname + '?full' + _.getSlideHash(currentSlideNumber));
_.enterSlideMode();
_.updateProgress(currentSlideNumber);
}
break;
case 27: // Esc
if (!_.isListMode()) {
e.preventDefault();
history.pushState(null, null, url.pathname + _.getSlideHash(currentSlideNumber));
_.enterListMode();
scrollToSlide(currentSlideNumber);
}
break;
case 33: // PgUp
case 38: // Up
case 37: // Left
case 72: // h
case 75: // k
e.preventDefault();
_.previous();
break;
case 34: // PgDown
case 40: // Down
case 39: // Right
case 76: // l
case 74: // j
e.preventDefault();
_.next();
break;
case 36: // Home
e.preventDefault();
_.first();
break;
case 35: // End
e.preventDefault();
_.last();
break;
case 9: // Tab = +1; Shift + Tab = -1
case 32: // Space = +1; Shift + Space = -1
e.preventDefault();
_[e.shiftKey ? 'previous' : 'next']();
break;
default:
// Behave as usual
}
}, false);
document.addEventListener('click', dispatchSingleSlideMode, false);
document.addEventListener('touchend', dispatchSingleSlideMode, false);
document.addEventListener('touchstart', function (e) {
if (!_.isListMode()) {
var currentSlideNumber = _.getCurrentSlideNumber(),
x = e.touches[0].pageX;
if (x > window.innerWidth / 2) {
currentSlideNumber++;
} else {
currentSlideNumber--;
}
_.go(currentSlideNumber);
}
}, false);
document.addEventListener('touchmove', function (e) {
if (!_.isListMode()) {
e.preventDefault();
}
}, false);
return _;
}());
| added a simple callback on change if using the public method shower.go() | scripts/script.js | added a simple callback on change if using the public method shower.go() | <ide><path>cripts/script.js
<ide> if (!_.isListMode()) {
<ide> _.updateProgress(slideNumber);
<ide> }
<add>
<add> if (typeof _.onchange == 'function')
<add> _.onchange(slideNumber);
<ide> }
<ide>
<ide> function getContainingSlideId(el) { |
|
Java | apache-2.0 | 5b930882f0adc6f8b1db68994b0408c379f4127a | 0 | jpodeszwik/mifos,vorburger/mifos-head,maduhu/mifos-head,maduhu/head,jpodeszwik/mifos,vorburger/mifos-head,vorburger/mifos-head,AArhin/head,maduhu/head,jpodeszwik/mifos,maduhu/mifos-head,AArhin/head,maduhu/mifos-head,maduhu/mifos-head,AArhin/head,maduhu/mifos-head,AArhin/head,vorburger/mifos-head,jpodeszwik/mifos,maduhu/head,maduhu/head,AArhin/head,maduhu/head | package org.mifos.application.accounts.loan.business;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_SECOND_WEEK;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mifos.application.accounts.business.AccountActionDateEntity;
import org.mifos.application.accounts.business.AccountBO;
import org.mifos.application.accounts.business.AccountFeesActionDetailEntity;
import org.mifos.application.accounts.business.AccountFeesEntity;
import org.mifos.application.accounts.business.TestAccountActionDateEntity;
import org.mifos.application.accounts.business.TestAccountFeesEntity;
import org.mifos.application.accounts.exceptions.AccountException;
import org.mifos.application.accounts.persistence.AccountPersistence;
import org.mifos.application.accounts.util.helpers.AccountState;
import org.mifos.application.accounts.util.helpers.PaymentData;
import org.mifos.application.accounts.util.helpers.PaymentStatus;
import org.mifos.application.customer.business.CustomerBO;
import org.mifos.application.customer.client.business.ClientBO;
import org.mifos.application.customer.util.helpers.CustomerStatus;
import org.mifos.application.fees.business.AmountFeeBO;
import org.mifos.application.fees.business.FeeBO;
import org.mifos.application.fees.business.FeeView;
import org.mifos.application.fees.util.helpers.FeeCategory;
import org.mifos.application.fees.util.helpers.FeePayment;
import org.mifos.application.fund.business.FundBO;
import org.mifos.application.master.business.CustomFieldType;
import org.mifos.application.master.business.CustomFieldView;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.productdefinition.business.LoanOfferingBO;
import org.mifos.application.productdefinition.util.helpers.ApplicableTo;
import org.mifos.application.productdefinition.util.helpers.GraceType;
import org.mifos.application.productdefinition.util.helpers.InterestType;
import org.mifos.application.productdefinition.util.helpers.PrdStatus;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.framework.MifosTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PropertyNotFoundException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.HibernateUtil;
import org.mifos.framework.persistence.TestObjectPersistence;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.StringUtils;
import org.mifos.framework.util.helpers.TestObjectFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
/*
* LoanCalculationTest is a starting point for defining and exploring
* expected behavior for different loan payment calculations.
*
* This is a work in progress so there is still lots of extraneous junk
* in this file, that will be cleaned up as we go forward.
*/
public class LoanCalculationTest extends MifosTestCase {
// these constants for parsing the spreadsheet
final String principal = "Principal";
final String loanType = "Loan Type";
final String annualInterest = "Annual Interest";
final String numberOfPayments = "Number of Payments";
final String paymentFrequency = "Payment Frequency";
final String initialRoundingMode = "InitialRoundingMode";
final String initialRoundOffMultiple = "InitialRoundOffMultiple";
final String finalRoundingMode = "FinalRoundingMode";
final String finalRoundOffMultiple = "FinalRoundOffMultiple";
final String interestRounding = "InterestRounding";
final String digitsAfterDecimal = "Digits After Decimal";
final String daysInYear = "Days in Year";
final String totals = "Summed Totals";
final String start = "Start";
LoanOfferingBO loanOffering = null;
// TODO: probably should be of type LoanBO
protected AccountBO accountBO = null;
protected AccountBO badAccountBO = null;
protected CustomerBO center = null;
protected CustomerBO group = null;
private CustomerBO client = null;
private AccountPersistence accountPersistence = null;
private MeetingBO meeting;
private UserContext userContext;
@Override
protected void setUp() throws Exception {
super.setUp();
userContext = TestObjectFactory.getContext();
accountPersistence = new AccountPersistence();
}
@Override
protected void tearDown() throws Exception {
TestObjectFactory.removeObject(loanOffering);
if (accountBO != null)
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(
AccountBO.class, accountBO.getAccountId());
if (badAccountBO != null)
badAccountBO = (AccountBO) HibernateUtil.getSessionTL().get(
AccountBO.class, badAccountBO.getAccountId());
if (group != null)
group = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, group.getCustomerId());
if (center != null)
center = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, center.getCustomerId());
TestObjectFactory.cleanUp(accountBO);
TestObjectFactory.cleanUp(badAccountBO);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
HibernateUtil.closeSession();
super.tearDown();
}
public static void setFeeAmount(
AccountFeesActionDetailEntity accountFeesActionDetailEntity,
Money feeAmount) {
((LoanFeeScheduleEntity) accountFeesActionDetailEntity)
.setFeeAmount(feeAmount);
}
public static void setFeeAmountPaid(
AccountFeesActionDetailEntity accountFeesActionDetailEntity,
Money feeAmountPaid) {
((LoanFeeScheduleEntity) accountFeesActionDetailEntity)
.setFeeAmountPaid(feeAmountPaid);
}
public static void setActionDate(
AccountActionDateEntity accountActionDateEntity,
java.sql.Date actionDate) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(actionDate);
}
public static void setDisbursementDate(AccountBO account,
Date disbursementDate) {
((LoanBO) account).setDisbursementDate(disbursementDate);
}
/**
* Like
* {@link #createLoanAccountWithDisbursement(String, CustomerBO, AccountState, Date, LoanOfferingBO, int, Short)}
* but differs in various ways.
*
* @param globalNum
* Currently ignored (TODO: remove it or honor it)
*/
public static LoanBO createLoanAccount(String globalNum,
CustomerBO customer, AccountState state, Date startDate,
LoanOfferingBO loanOfering) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer
.getCustomerMeeting().getMeeting());
List<Date> meetingDates = TestObjectFactory.getMeetingDates(meeting, 6);
loanOfering.updateLoanOfferingSameForAllLoan(loanOfering);
LoanBO loan;
MifosCurrency currency = TestObjectFactory.getCurrency();
try {
loan = LoanBO.createLoan(TestUtils.makeUser(), loanOfering,
customer, state, new Money(currency, "300.0"), Short
.valueOf("6"), meetingDates.get(0), true, 0.0,
(short) 0, new FundBO(), new ArrayList<FeeView>(), null,
Double.parseDouble(loanOfering.getMaxLoanAmount()
.toString()), Double.parseDouble(loanOfering
.getMinLoanAmount().toString()), loanOfering
.getMaxNoInstallments(), loanOfering
.getMinNoInstallments(),false,null);
}
catch (ApplicationException e) {
throw new RuntimeException(e);
}
FeeBO maintanenceFee = TestObjectFactory.createPeriodicAmountFee(
"Mainatnence Fee", FeeCategory.LOAN, "100",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan,
maintanenceFee, ((AmountFeeBO) maintanenceFee).getFeeAmount()
.getAmountDoubleValue());
TestAccountFeesEntity.addAccountFees(accountPeriodicFee, loan);
loan.setLoanMeeting(meeting);
short i = 0;
for (Date date : meetingDates) {
LoanScheduleEntity actionDate = (LoanScheduleEntity) loan
.getAccountActionDate(++i);
actionDate.setPrincipal(new Money(currency, "100.0"));
actionDate.setInterest(new Money(currency, "12.0"));
actionDate.setActionDate(new java.sql.Date(date.getTime()));
actionDate.setPaymentStatus(PaymentStatus.UNPAID);
TestAccountActionDateEntity.addAccountActionDate(actionDate, loan);
AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(
actionDate, maintanenceFee, accountPeriodicFee, new Money(
currency, "100.0"));
setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
actionDate.addAccountFeesAction(accountFeesaction);
}
loan.setCreatedBy(Short.valueOf("1"));
loan.setCreatedDate(new Date(System.currentTimeMillis()));
setLoanSummary(loan, currency);
return loan;
}
public static LoanBO createIndividualLoanAccount(String globalNum,
CustomerBO customer, AccountState state, Date startDate,
LoanOfferingBO loanOfering) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer
.getCustomerMeeting().getMeeting());
List<Date> meetingDates = TestObjectFactory.getMeetingDates(meeting, 6);
LoanBO loan;
MifosCurrency currency = TestObjectFactory.getCurrency();
try {
loan = LoanBO.createIndividualLoan(TestUtils.makeUser(), loanOfering, customer,
state, new Money(currency, "300.0"), Short.valueOf("6"),
meetingDates.get(0), true,false, 0.0, (short) 0, new FundBO(),
new ArrayList<FeeView>(), null);
}
catch (ApplicationException e) {
throw new RuntimeException(e);
}
FeeBO maintanenceFee = TestObjectFactory.createPeriodicAmountFee(
"Mainatnence Fee", FeeCategory.LOAN, "100",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan,
maintanenceFee, ((AmountFeeBO) maintanenceFee).getFeeAmount()
.getAmountDoubleValue());
TestAccountFeesEntity.addAccountFees(accountPeriodicFee, loan);
loan.setLoanMeeting(meeting);
short i = 0;
for (Date date : meetingDates) {
LoanScheduleEntity actionDate = (LoanScheduleEntity) loan
.getAccountActionDate(++i);
actionDate.setPrincipal(new Money(currency, "100.0"));
actionDate.setInterest(new Money(currency, "12.0"));
actionDate.setActionDate(new java.sql.Date(date.getTime()));
actionDate.setPaymentStatus(PaymentStatus.UNPAID);
TestAccountActionDateEntity.addAccountActionDate(actionDate, loan);
AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(
actionDate, maintanenceFee, accountPeriodicFee, new Money(
currency, "100.0"));
setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
actionDate.addAccountFeesAction(accountFeesaction);
}
loan.setCreatedBy(Short.valueOf("1"));
loan.setCreatedDate(new Date(System.currentTimeMillis()));
setLoanSummary(loan, currency);
return loan;
}
private static void setLoanSummary(LoanBO loan, MifosCurrency currency) {
LoanSummaryEntity loanSummary = loan.getLoanSummary();
loanSummary.setOriginalPrincipal(new Money(currency, "300.0"));
loanSummary.setOriginalInterest(new Money(currency, "36.0"));
}
public static void modifyDisbursmentDate(LoanBO loan, Date disbursmentDate) {
loan.setDisbursementDate(disbursmentDate);
}
/* This part is for the new financial calculation */
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
class LoanParameters {
private String principal = null;
private InterestType loanType = null;
private String annualInterest = null;
private short numberOfPayments = 0;
private RecurrenceType paymentFrequency = null;
public LoanParameters(String principal, InterestType loanType,
String annualInterest, short numberOfPayments,
RecurrenceType paymentFrequency) {
super();
this.principal = principal;
this.loanType = loanType;
this.annualInterest = annualInterest;
this.numberOfPayments = numberOfPayments;
this.paymentFrequency = paymentFrequency;
}
public LoanParameters()
{
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public InterestType getLoanType() {
return loanType;
}
public void setLoanType(InterestType loanType) {
this.loanType = loanType;
}
public String getAnnualInterest() {
return annualInterest;
}
public void setAnnualInterest(String annualInterest) {
this.annualInterest = annualInterest;
}
public short getNumberOfPayments() {
return numberOfPayments;
}
public void setNumberOfPayments(short numberOfPayments) {
this.numberOfPayments = numberOfPayments;
}
public RecurrenceType getPaymentFrequency() {
return paymentFrequency;
}
public void setPaymentFrequency(RecurrenceType paymentFrequency) {
this.paymentFrequency = paymentFrequency;
}
}
class InternalConfiguration {
private int daysInYear = 0;
// right now we are just supporting CEILING, FLOOR, HALF_UP
private RoundingMode initialRoundingMode = null;
// should this be constrained to .001, .01, .5, .1, 1 as in the spreadsheet?
private String initialRoundOffMultiple = null;
// right now we are just supporting CEILING, FLOOR, HALF_UP
private RoundingMode finalRoundingMode = null;
// should this be constrained to .001, .01, .5, .1, 1 as in the spreadsheet?
private String finalRoundOffMultiple = null;
// right now we are just supporting CEILING, FLOOR, HALF_UP
private RoundingMode interestRoundingMode = null;
// the number of digits to use to the right of the decimal for interal caculations
private int internalPrecision = 13;
// digits after decimal right now is in the application configuration
private int digitsAfterDecimal = 1;
public int getDigitsAfterDecimal() {
return digitsAfterDecimal;
}
public void setDigitsAfterDecimal(int digitsAfterDecimal) {
this.digitsAfterDecimal = digitsAfterDecimal;
}
public InternalConfiguration(int daysInYear,
RoundingMode initialRoundingMode,
String initialRoundOffMultiple, RoundingMode finalRoundingMode,
String finalRoundOffMultiple, RoundingMode interestRoundingMode,
int internalPrecision) {
super();
this.daysInYear = daysInYear;
this.initialRoundingMode = initialRoundingMode;
this.initialRoundOffMultiple = initialRoundOffMultiple;
this.finalRoundingMode = finalRoundingMode;
this.finalRoundOffMultiple = finalRoundOffMultiple;
this.interestRoundingMode = interestRoundingMode;
this.internalPrecision = internalPrecision;
}
public InternalConfiguration()
{
}
public int getDaysInYear() {
return daysInYear;
}
public void setDaysInYear(int daysInYear) {
this.daysInYear = daysInYear;
}
public RoundingMode getInitialRoundingMode() {
return initialRoundingMode;
}
public void setInitialRoundingMode(RoundingMode initialRoundingMode) {
this.initialRoundingMode = initialRoundingMode;
}
public String getInitialRoundOffMultiple() {
return initialRoundOffMultiple;
}
public void setInitialRoundOffMultiple(String initialRoundOffMultiple) {
this.initialRoundOffMultiple = initialRoundOffMultiple;
}
public RoundingMode getFinalRoundingMode() {
return finalRoundingMode;
}
public void setFinalRoundingMode(RoundingMode finalRoundingMode) {
this.finalRoundingMode = finalRoundingMode;
}
public String getFinalRoundOffMultiple() {
return finalRoundOffMultiple;
}
public void setFinalRoundOffMultiple(String finalRoundOffMultiple) {
this.finalRoundOffMultiple = finalRoundOffMultiple;
}
public RoundingMode getInterestRoundingMode() {
return interestRoundingMode;
}
public void setInterestRoundingMode(RoundingMode interestRoundingMode) {
this.interestRoundingMode = interestRoundingMode;
}
public int getInternalPrecision() {
return internalPrecision;
}
public void setInternalPrecision(int internalPrecision) {
this.internalPrecision = internalPrecision;
}
}
class Results {
// each installment has payment = interest + principal
Money totalPayments = null; // sum of all payments
Money totalInterest = null; // sum of all interests for all payments
Money totalPrincipal = null; // sum of all principals for all payments
// detailed list of all payments. Each payment includes payment, interest, principal and balance
List<PaymentDetail> payments = null;
public List<PaymentDetail> getPayments() {
return payments;
}
public void setPayments(List<PaymentDetail> payments) {
this.payments = payments;
}
public Money getTotalInterest() {
return totalInterest;
}
public void setTotalInterest(Money totalInterest) {
this.totalInterest = totalInterest;
}
public Money getTotalPayments() {
return totalPayments;
}
public void setTotalPayments(Money totalPayments) {
this.totalPayments = totalPayments;
}
public Money getTotalPrincipal() {
return totalPrincipal;
}
public void setTotalPrincipal(Money totalPrincipal) {
this.totalPrincipal = totalPrincipal;
}
}
class LoanTestCaseData {
private LoanParameters loanParams = null;
private Results expectedResult = null;
InternalConfiguration internalConfig = null;
public InternalConfiguration getInternalConfig() {
return internalConfig;
}
public void setInternalConfig(InternalConfiguration config) {
this.internalConfig = config;
}
public LoanTestCaseData()
{
}
public Results getExpectedResult() {
return expectedResult;
}
public void setExpectedResult(Results expectedResult) {
this.expectedResult = expectedResult;
}
public LoanParameters getLoanParams() {
return loanParams;
}
public void setLoanParams(LoanParameters loanParams) {
this.loanParams = loanParams;
}
}
private void compareResults(Results expectedResult, Results calculatedResult)
{
// this commented code will be the final code when the financial calculation is done
/*assertEquals(expectedResult.getTotalInterest(),
calculatedResult.getTotalInterest());
assertEquals(expectedResult.getTotalPayments(),
calculatedResult.getTotalPayments());
assertEquals(expectedResult.getTotalPrincipal(),
calculatedResult.getTotalPrincipal());
List<PaymentDetail> expectedPayments = expectedResult.getPayments();
List<PaymentDetail> calculatedPayments = calculatedResult.getPayments();
assertEquals(expectedPayments.size(), calculatedPayments.size());
for (int i=0; i < expectedPayments.size(); i++)
{
assertEquals(expectedPayments.get(i).getBalance(),
calculatedPayments.get(i).getBalance());
assertEquals(expectedPayments.get(i).getInterest(),
calculatedPayments.get(i).getInterest());
assertEquals(expectedPayments.get(i).getPayment(),
calculatedPayments.get(i).getPayment());
assertEquals(expectedPayments.get(i).getPrincipal(),
calculatedPayments.get(i).getPrincipal());
}*/
System.out.println("Expected Total Interest: " + expectedResult.getTotalInterest() +
" - Calculated Total Interest: " + calculatedResult.getTotalInterest());
System.out.println("Expected Total Payments: " + expectedResult.getTotalPayments() +
" - Calculated Total Payments: " + calculatedResult.getTotalPayments());
System.out.println("Expected Total Principal: " + expectedResult.getTotalPrincipal() +
" - Calculated Total Principal: " + calculatedResult.getTotalPrincipal());
List<PaymentDetail> expectedPayments = expectedResult.getPayments();
List<PaymentDetail> calculatedPayments = calculatedResult.getPayments();
System.out.println("Expected Number of Installments: " + expectedPayments.size() +
" - Calculated Number of Installments: " + calculatedPayments.size());
for (int i=0; i < expectedPayments.size(); i++)
{
System.out.println("Payment #: " + (i+1));
System.out.println("Expected Balance: " + expectedPayments.get(i).getBalance() +
" - Calculated Balance: " + calculatedPayments.get(i).getBalance());
System.out.println("Expected Interest: " + expectedPayments.get(i).getInterest() +
" - Calculated Interest: " + calculatedPayments.get(i).getInterest());
System.out.println("Expected Payment: " + expectedPayments.get(i).getPayment() +
" - Calculated Payment: " + calculatedPayments.get(i).getPayment());
System.out.println("Expected Principal: " + expectedPayments.get(i).getPrincipal() +
" - Calculated Principal: " + calculatedPayments.get(i).getPrincipal());
}
}
private AccountBO setUpLoan(InternalConfiguration config, LoanParameters loanParams) throws
AccountException
{
/*
* When constructing a "meeting" here, it looks like the frequency
* should be "EVERY_X" for weekly or monthly loan interest posting.
*/
// EVERY_WEEK, EVERY_DAY and EVERY_MONTH are defined as 1
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(loanParams.getPaymentFrequency(), EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
short gracePeriodDuration = 0;
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, Double.parseDouble(loanParams.getPrincipal()),
Double.parseDouble(loanParams.getAnnualInterest()), loanParams.getNumberOfPayments(),
loanParams.getLoanType(), false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
AccountBO accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
new Money(loanParams.getPrincipal()), loanParams.getNumberOfPayments(), startDate, false,
Double.parseDouble(loanParams.getAnnualInterest()), gracePeriodDuration,
new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
return accountBO;
}
private Results calculatePayments(InternalConfiguration config, AccountBO accountBO, LoanParameters loanParams)
{
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities,
loanParams.getNumberOfPayments());
MathContext context = new MathContext(config.getInternalPrecision());
BigDecimal totalPrincipal = new BigDecimal(0, context);
BigDecimal totalInterest = new BigDecimal(0, context);
Money totalPayments = new Money("0");
Results calculatedResult = new Results();
List<PaymentDetail> payments = new ArrayList<PaymentDetail>();
for (LoanScheduleEntity loanEntry : paymentsArray)
{
PaymentDetail payment = new PaymentDetail();
Money calculatedPayment = new Money(loanEntry.getPrincipal().getAmount().add(loanEntry.getInterest().getAmount()));
payment.setPayment(calculatedPayment);
payment.setInterest(loanEntry.getInterest());
payment.setPrincipal(loanEntry.getPrincipal());
totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
totalPayments = totalPayments.add(calculatedPayment);
payments.add(payment);
}
calculatedResult.setPayments(payments);
calculatedResult.setTotalInterest(new Money(totalInterest));
calculatedResult.setTotalPayments(totalPayments);
calculatedResult.setTotalPrincipal(new Money(totalPrincipal));
// set balance after each payment
Money balance = totalPayments;
for( PaymentDetail paymentDetail : payments)
{
Money onePayment = paymentDetail.getPayment();
balance = balance.subtract(onePayment);
paymentDetail.setBalance(balance);
}
return calculatedResult;
}
private void parseLoanParams(String paramType, String line, LoanParameters loanParams)
{
String tempLine = line.substring(paramType.length(), line.length() - 1);
String[] tokens = tempLine.split(",");
for (int i=0; i < tokens.length; i++)
{
String token = tokens[i];
if (StringUtils.isNullAndEmptySafe(token))
{
if ((paramType.indexOf(principal)>= 0) && (loanParams.getPrincipal() == null))
loanParams.setPrincipal(token);
else if (paramType.indexOf(loanType)>= 0)
{
InterestType interestType = InterestType.valueOf(token.toUpperCase());
loanParams.setLoanType(interestType);
}
else if (paramType.indexOf(annualInterest)>= 0)
{
int pos = token.indexOf("%");
String interest = token.substring(0, pos);
loanParams.setAnnualInterest(interest);
}
else if (paramType.indexOf(numberOfPayments) >= 0)
loanParams.setNumberOfPayments(Short.parseShort(token));
else if (paramType.indexOf(paymentFrequency)>= 0)
{
RecurrenceType recurrenceType = RecurrenceType.valueOf(token.toUpperCase());
loanParams.setPaymentFrequency(recurrenceType);
}
break;
}
}
}
private void parseConfigParams(String paramType, String line, InternalConfiguration config)
{
String tempLine = line.substring(paramType.length(), line.length() - 1);
String[] tokens = tempLine.split(",");
for (int i=0; i < tokens.length; i++)
{
String token = tokens[i];
if (StringUtils.isNullAndEmptySafe(token))
{
if (paramType.indexOf(initialRoundingMode) >= 0)
{
RoundingMode mode = RoundingMode.valueOf(token);
config.setInitialRoundingMode(mode);
}
else if (paramType.indexOf(initialRoundOffMultiple) >= 0)
{
config.setInitialRoundOffMultiple(token);
}
else if (paramType.indexOf(finalRoundingMode) >= 0)
{
RoundingMode mode = RoundingMode.valueOf(token);
config.setFinalRoundingMode(mode);
}
else if (paramType.indexOf(finalRoundOffMultiple) >= 0)
{
config.setFinalRoundOffMultiple(token);
}
else if (paramType.indexOf(interestRounding)>= 0)
{
RoundingMode mode = RoundingMode.valueOf(token);
config.setInterestRoundingMode(mode);
}
else if (paramType.indexOf(digitsAfterDecimal) >= 0)
{
config.setDigitsAfterDecimal(Short.parseShort(token));
}
else if (paramType.indexOf(daysInYear) >= 0)
{
config.setDaysInYear(Short.parseShort(token));
}
break;
}
}
}
private void parseTotals(String paramType, String line, Results result)
{
String tempLine = line.substring(paramType.length(), line.length() -1);
int index = tempLine.indexOf(paramType);
tempLine = tempLine.substring(index + paramType.length(), tempLine.length() -1);
String[] tokens = tempLine.split(",");
boolean totalPayments = false;
boolean totalInterests = true;
boolean totalPrincipals = true;
for (int i=0; i < tokens.length; i++)
{
String token = tokens[i].trim();
if (StringUtils.isNullAndEmptySafe(token))
{
if (totalPayments == false)
{
result.setTotalPayments(new Money(token));
totalPayments = true;
totalPrincipals = false;
}
else if (totalInterests == false)
{
result.setTotalInterest(new Money(token));
totalInterests = true;
}
else if (totalPrincipals == false)
{
result.setTotalPrincipal(new Money(token));
totalPrincipals = true;
totalInterests = false;
}
else
return;
}
}
}
private void parsePaymentDetail(String paramType, String line, Results result)
{
int index = line.indexOf(",,");
String tempLine = line.substring(index + 1, line.length() -1);
String[] tokens = tempLine.split(",");
boolean paymentIndex = false;
boolean payment = true;
boolean principal = true;
boolean interest = true;
boolean balance = true;
PaymentDetail paymentDetail = new PaymentDetail();
for (int i=0; i < tokens.length; i++)
{
String token = tokens[i].trim();
if (StringUtils.isNullAndEmptySafe(token))
{
if (paymentIndex == false)
{
int paymentNumber = Integer.parseInt(token);
int expectedPaymentNumber = result.getPayments().size() + 1;
if (paymentNumber != expectedPaymentNumber)
throw new RuntimeException("Parsing error. paymentNumber " + paymentNumber + " Expected: " + expectedPaymentNumber);
paymentIndex = true;
payment = false;
}
else if (payment == false)
{
paymentDetail.setPayment(new Money(token));
payment = true;
principal = false;
}
else if (principal == false)
{
paymentDetail.setPrincipal(new Money(token));
principal = true;
interest = false;
}
else if (interest == false)
{
paymentDetail.setInterest(new Money(token));
interest = true;
balance = false;
}
else if (balance == false)
{
paymentDetail.setBalance(new Money(token));
result.getPayments().add(paymentDetail);
return;
}
}
}
}
private LoanTestCaseData loadSpreadSheetData(String fileName)
{
File file = new File(fileName);
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
LoanTestCaseData testCaseData = new LoanTestCaseData();
boolean startPayment = false;
int paymentIndex = 0;
try
{
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
// dataInputStream.available() returns 0 if the file does not have more lines.
String line = null;
LoanParameters loanParams = new LoanParameters();
InternalConfiguration config = new InternalConfiguration();
Results expectedResult = new Results();
List<PaymentDetail> list = new ArrayList<PaymentDetail>();
expectedResult.setPayments(list);
while ((line = bufferedReader.readLine()) != null)
{
String[] tokens = line.split(",");
for (int i=0; i < tokens.length; i++)
{
String token = tokens[i];
if (StringUtils.isNullAndEmptySafe(token))
{
if ((token.indexOf(principal) >= 0) ||( token.indexOf(loanType) >= 0) || (token.indexOf(annualInterest) >=0)
|| (token.indexOf(numberOfPayments) >=0) || (token.indexOf(paymentFrequency) >= 0))
{
parseLoanParams(token, line, loanParams);
break;
}
else if ((token.indexOf(initialRoundingMode) >= 0 ) || (token.indexOf(finalRoundingMode)>= 0 )
|| (token.indexOf(initialRoundOffMultiple) >= 0 )
|| (token.indexOf(finalRoundOffMultiple) >= 0 ) || (token.indexOf(interestRounding)>= 0 )
|| (token.indexOf(digitsAfterDecimal) >= 0 ) || (token.indexOf(daysInYear) >= 0 ))
{
parseConfigParams(token, line, config);
break;
}
else if (token.indexOf(totals) >= 0)
parseTotals(token, line, expectedResult);
else if (token.indexOf(start) >= 0)
{
startPayment = true;
break;
}
else if (startPayment)
{
parsePaymentDetail(token, line, expectedResult);
paymentIndex++;
if (paymentIndex >= loanParams.getNumberOfPayments())
{
testCaseData.setExpectedResult(expectedResult);
testCaseData.setInternalConfig(config);
testCaseData.setLoanParams(loanParams);
return testCaseData;
}
break;
}
}
}
}
if (fileInputStream != null)
fileInputStream.close();
if (inputStreamReader != null)
inputStreamReader.close();
if (bufferedReader != null)
bufferedReader.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return testCaseData;
}
/*
* This test case will populate the data classes for a loan test case with data from spreadsheet and
* calculates payments and compares
*/
private void runOneTestCaseWithDataFromSpreadSheet(String fileName) throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException
{
LoanTestCaseData testCaseData = loadSpreadSheetData(fileName);
accountBO = setUpLoan(testCaseData.getInternalConfig(), testCaseData.getLoanParams());
// calculated results
Results calculatedResult = calculatePayments(testCaseData.getInternalConfig(), accountBO, testCaseData.getLoanParams());
compareResults(testCaseData.getExpectedResult(), calculatedResult);
}
public void testCaseWithDataFromSpreadSheets() throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException
{
String rootPath = "C:\\";
String[] dataFileNames = {"loan-repayment-master-comma.csv"};
for (int i=0; i < dataFileNames.length; i++)
runOneTestCaseWithDataFromSpreadSheet(rootPath + dataFileNames[i]);
}
/*
* This test case populates data from spreadsheet for loan params and expected results
*/
public void testOneExampleOfTestCaseFromSpreadSheet() throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException
{
// set up config
InternalConfiguration config = new InternalConfiguration();
config.setDaysInYear(365);
config.setFinalRoundingMode(RoundingMode.CEILING);
config.setFinalRoundOffMultiple("0.01");
config.setInitialRoundingMode(RoundingMode.CEILING);
config.setInitialRoundOffMultiple("1");
config.setInterestRoundingMode(RoundingMode.CEILING);
config.setInternalPrecision(13);
// the digits after decimal now has to be set in the applicationConfiguration
// set up loan params
LoanParameters loanParams = new LoanParameters();
loanParams.setLoanType(InterestType.FLAT);
loanParams.setNumberOfPayments((short)5);
loanParams.setPaymentFrequency(RecurrenceType.WEEKLY);
loanParams.setAnnualInterest("12.00");
loanParams.setPrincipal("1002");
// set up expected results
Results expectedResult = new Results();
expectedResult.setTotalInterest(new Money("11.53"));
expectedResult.setTotalPayments(new Money("1013.53"));
expectedResult.setTotalPrincipal(new Money("1002")); // this loan amount
List<PaymentDetail> list = new ArrayList<PaymentDetail>();
// 1st payment
PaymentDetail payment = new PaymentDetail();
payment.setPayment(new Money("203.000"));
payment.setInterest(new Money("2.306"));
payment.setBalance(new Money("810.530"));
payment.setPrincipal(new Money("200.694"));
list.add(payment);
// 2nd payment
payment = new PaymentDetail();
payment.setPayment(new Money("203.000"));
payment.setInterest(new Money("2.306"));
payment.setBalance(new Money("607.530"));
payment.setPrincipal(new Money("200.694"));
list.add(payment);
// 3rd payment
payment = new PaymentDetail();
payment.setPayment(new Money("203.000"));
payment.setInterest(new Money("2.306"));
payment.setBalance(new Money("404.530"));
payment.setPrincipal(new Money("200.694"));
list.add(payment);
// 4th payment
payment = new PaymentDetail();
payment.setPayment(new Money("203.000"));
payment.setInterest(new Money("2.306"));
payment.setBalance(new Money("201.530"));
payment.setPrincipal(new Money("200.694"));
list.add(payment);
// last payment
payment = new PaymentDetail();
payment.setPayment(new Money("201.530"));
payment.setInterest(new Money("2.306"));
payment.setBalance(new Money("0"));
payment.setPrincipal(new Money("199.224"));
list.add(payment);
expectedResult.setPayments(list);
expectedResult.setPayments(list);
accountBO = setUpLoan(config, loanParams);
// calculated results
Results calculatedResult = calculatePayments(config, accountBO, loanParams);
compareResults(expectedResult, calculatedResult);
}
/*
* This test case is meant to reproduce issue 1648 using the new data classes
*/
public void testIssue1648New() throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException
{
// set up config
InternalConfiguration config = new InternalConfiguration();
config.setDaysInYear(365);
config.setFinalRoundingMode(RoundingMode.HALF_UP);
config.setFinalRoundOffMultiple("0.001");
config.setInitialRoundingMode(RoundingMode.HALF_UP);
config.setInitialRoundOffMultiple("0.001");
config.setInterestRoundingMode(RoundingMode.HALF_UP);
config.setInternalPrecision(10);
// set up loan params
LoanParameters loanParams = new LoanParameters();
loanParams.setLoanType(InterestType.DECLINING);
loanParams.setNumberOfPayments((short)50);
loanParams.setPaymentFrequency(RecurrenceType.WEEKLY);
loanParams.setAnnualInterest("19.0");
loanParams.setPrincipal("10000");
// set up expected results
Results expectedResult = new Results();
expectedResult.setTotalInterest(new Money("956.8"));
expectedResult.setTotalPayments(new Money("10000.4")); // this test doesn't compare this, I made this up
expectedResult.setTotalPrincipal(new Money("10000")); // this loan amount
List<PaymentDetail> list = new ArrayList<PaymentDetail>(); // we don't have this info from this test
expectedResult.setPayments(list);
accountBO = setUpLoan(config, loanParams);
// calculated results
Results calculatedResult = calculatePayments(config, accountBO, loanParams);
compareResults(expectedResult, calculatedResult);
}
/****************************************************************************************/
/****************************************************************************************/
/****************************************************************************************/
/*
* This test case is meant to reproduce issue 1648
*/
public void testIssue1648()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
int digitsRightOfDecimal = 10;
/**
* What should expectedTotalInterest be? From the spreadsheet test
* case we have 956.76. But we are using 1 digit to the right of the
* decimal place, so depending on the rounding mode, it should be
* 956.7 or 956.8.
*/
String expectedTotalInterest = "956.8";
short numberOfInstallments = 50;
double interestRate = 19.0;
InterestType interestType = InterestType.DECLINING;
String loanAmount = "10000";
short gracePeriodDuration = 0;
Date startDate = new Date(System.currentTimeMillis());
/*
* When constructing a "meeting" here, it looks like the frequency
* should be "EVERY_X" for weekly or monthly loan interest posting.
*/
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 10000.0, interestRate, numberOfInstallments,
interestType, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
loanAmount), numberOfInstallments, startDate, false,
interestRate, gracePeriodDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(numberOfInstallments, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, numberOfInstallments);
int paymentCount = 1;
MathContext context = new MathContext(digitsRightOfDecimal);
BigDecimal totalPrincipal = new BigDecimal(0, context);
BigDecimal totalInterest = new BigDecimal(0, context);
for (LoanScheduleEntity loanEntry : paymentsArray) {
System.out.println(paymentCount + " -- P: " + loanEntry.getPrincipal() + " I: " + loanEntry.getInterest());
totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
++paymentCount;
}
System.out.println("TotalPrincipal: " + totalPrincipal + " TotalInterest: " + totalInterest);
assertEquals(new BigDecimal(loanAmount), totalPrincipal);
assertEquals(new BigDecimal(expectedTotalInterest), totalInterest);
}
class PaymentDetail{
Money payment = null;
Money principal = null;
Money interest = null;
Money balance = null;
public PaymentDetail(Money payment, Money principal, Money interest, Money balance) {
super();
this.payment = payment;
this.principal = principal;
this.interest = interest;
this.balance = balance;
}
public PaymentDetail()
{
}
public Money getBalance() {
return balance;
}
public void setBalance(Money balance) {
this.balance = balance;
}
public Money getInterest() {
return interest;
}
public void setInterest(Money interest) {
this.interest = interest;
}
public Money getPayment() {
return payment;
}
public void setPayment(Money payment) {
this.payment = payment;
}
public Money getPrincipal() {
return principal;
}
public void setPrincipal(Money principal) {
this.principal = principal;
}
}
public void testIssue1623()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
int digitsRightOfDecimal = 10;
String expectedTotalInterest = "189.86";
short numberOfInstallments = 11;
double interestRate = 36.0;
String loanAmount = "2500";
short gracePeriodDuration = 0;
InterestType interestType = InterestType.FLAT;
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 10000.0, interestRate, numberOfInstallments,
interestType, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
loanAmount), numberOfInstallments, startDate, false,
interestRate, gracePeriodDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(numberOfInstallments, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, numberOfInstallments);
int paymentCount = 1;
MathContext context = new MathContext(digitsRightOfDecimal);
BigDecimal totalPrincipal = new BigDecimal(0, context);
BigDecimal totalInterest = new BigDecimal(0, context);
for (LoanScheduleEntity loanEntry : paymentsArray) {
System.out.println(paymentCount + " -- P: " + loanEntry.getPrincipal() + " I: " + loanEntry.getInterest());
totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
++paymentCount;
}
System.out.println("TotalPrincipal: " + totalPrincipal + " TotalInterest: " + totalInterest);
assertEquals(new BigDecimal(loanAmount), totalPrincipal);
assertEquals(new BigDecimal(expectedTotalInterest), totalInterest);
}
public void testCreateLoanAccountWithDecliningInterestNoGracePeriod()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, (short) 0, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "50.9", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "50.9", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "50.9", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "50.9", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "51.0", "0.0",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "45.6", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestGraceAllRepayments()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * (1 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (2 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (3 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (4 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (5 + graceDuration)),
"51.0", "0.0", fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (6 + graceDuration)),
"45.6", "0.0", fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestGracePrincipalOnly()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting(),
GraceType.PRINCIPALONLYGRACE, "1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "75.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "75.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "75.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "75.1", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestPrincipalDueOnLastInstallment()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "Loan".substring(0, 1), ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING, false, true, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "0.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "0.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "0.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "300.0", "0.1",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestNoGracePeriod()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, (short) 0, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "50.9", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "50.9", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "50.9", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "50.9", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "50.0", "0.0",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "46.4", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestGraceAllRepayments()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * (1 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (2 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (3 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (4 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (5 + graceDuration)),
"50.0", "0.0", fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (6 + graceDuration)),
"46.4", "0.0", fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestGracePrincipalOnly()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting(),
GraceType.PRINCIPALONLYGRACE, "1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "75.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "75.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "75.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "75.0", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestPrincipalDueOnLastInstallment()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "Loan".substring(0, 1), ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING_EPI, false, true, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "0.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "0.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "0.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "300.0", "0.1",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
private java.sql.Date setDate(int dayUnit, int interval) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
calendar.add(dayUnit, interval);
return new java.sql.Date(calendar.getTimeInMillis());
}
private LoanBO createAndRetrieveLoanAccount(LoanOfferingBO loanOffering,
boolean isInterestDedAtDisb, List<FeeView> feeViews,
Short noOfinstallments, Double interestRate)
throws NumberFormatException, AccountException, SystemException,
ApplicationException {
LoanBO loan = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_APPROVED, new Money("300.0"),
noOfinstallments, new Date(System.currentTimeMillis()),
isInterestDedAtDisb, interestRate, (short) 0, new FundBO(),
feeViews, null, Double.parseDouble(loanOffering
.getMaxLoanAmount().toString()),
Double.parseDouble(loanOffering.getMinLoanAmount().toString()),
loanOffering.getMaxNoInstallments(), loanOffering
.getMinNoInstallments(),false,null);
loan.save();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
accountBO = TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
return (LoanBO) accountBO;
}
private LoanBO createAndRetrieveLoanAccount(LoanOfferingBO loanOffering,
boolean isInterestDedAtDisb, List<FeeView> feeViews,
Short noOfinstallments) throws NumberFormatException,
AccountException, SystemException, ApplicationException {
return createAndRetrieveLoanAccount(loanOffering, isInterestDedAtDisb,
feeViews, noOfinstallments, 10.0);
}
private LoanOfferingBO createLoanOffering(boolean isPrincipalAtLastInst) {
return createLoanOffering(isPrincipalAtLastInst, PrdStatus.LOAN_ACTIVE);
}
private LoanOfferingBO createLoanOffering(boolean principalAtLastInst,
PrdStatus status) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
return TestObjectFactory.createLoanOffering("Loan",
ApplicableTo.GROUPS, new Date(System.currentTimeMillis()),
status, 300.0, 1.2, 3, InterestType.FLAT, true,
principalAtLastInst, meeting);
}
private List<FeeView> getFeeViews() {
FeeBO fee1 = TestObjectFactory.createOneTimeAmountFee(
"One Time Amount Fee", FeeCategory.LOAN, "120.0",
FeePayment.TIME_OF_DISBURSMENT);
FeeBO fee3 = TestObjectFactory.createPeriodicAmountFee("Periodic Fee",
FeeCategory.LOAN, "10.0", RecurrenceType.WEEKLY, (short) 1);
List<FeeView> feeViews = new ArrayList<FeeView>();
FeeView feeView1 = new FeeView(userContext, fee1);
FeeView feeView2 = new FeeView(userContext, fee3);
feeViews.add(feeView1);
feeViews.add(feeView2);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
return feeViews;
}
private void deleteFee(List<FeeView> feeViews) {
for (FeeView feeView : feeViews) {
TestObjectFactory.cleanUp((FeeBO) TestObjectFactory.getObject(
FeeBO.class, feeView.getFeeIdValue()));
}
}
private AccountBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
createInitialCustomers();
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, center.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
return TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
}
private void createInitialCustomers() {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
}
private void changeFirstInstallmentDateToNextDate(AccountBO accountBO) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day + 1);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private AccountBO applyPaymentandRetrieveAccount() throws AccountException,
SystemException {
Date startDate = new Date(System.currentTimeMillis());
PaymentData paymentData = PaymentData.createPaymentData(new Money(
Configuration.getInstance().getSystemConfig().getCurrency(),
"212.0"), accountBO.getPersonnel(), Short.valueOf("1"),
startDate);
paymentData.setRecieptDate(startDate);
paymentData.setRecieptNum("5435345");
accountBO.applyPaymentWithPersist(paymentData);
HibernateUtil.commitTransaction();
HibernateUtil.getSessionTL().flush();
HibernateUtil.closeSession();
return TestObjectFactory.getObject(AccountBO.class, accountBO
.getAccountId());
}
private AccountBO getLoanAccountWithMiscFeeAndPenalty(AccountState state,
Date startDate, int disbursalType, Money miscFee, Money miscPenalty) {
LoanBO accountBO = getLoanAccount(state, startDate, disbursalType);
for (AccountActionDateEntity accountAction : accountBO
.getAccountActionDates()) {
LoanScheduleEntity accountActionDateEntity = (LoanScheduleEntity) accountAction;
if (accountActionDateEntity.getInstallmentId().equals(
Short.valueOf("1"))) {
accountActionDateEntity.setMiscFee(miscFee);
accountActionDateEntity.setMiscPenalty(miscPenalty);
break;
}
}
LoanSummaryEntity loanSummaryEntity = accountBO.getLoanSummary();
loanSummaryEntity.setOriginalFees(loanSummaryEntity.getOriginalFees()
.add(miscFee));
loanSummaryEntity.setOriginalPenalty(loanSummaryEntity
.getOriginalPenalty().add(miscPenalty));
TestObjectPersistence testObjectPersistence = new TestObjectPersistence();
testObjectPersistence.update(accountBO);
return testObjectPersistence.getObject(LoanBO.class, accountBO
.getAccountId());
}
private void changeInstallmentDate(AccountBO accountBO, int numberOfDays,
Short installmentId) {
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
if (accountActionDateEntity.getInstallmentId()
.equals(installmentId)) {
Calendar dateCalendar = new GregorianCalendar();
dateCalendar.setTimeInMillis(accountActionDateEntity
.getActionDate().getTime());
int year = dateCalendar.get(Calendar.YEAR);
int month = dateCalendar.get(Calendar.MONTH);
int day = dateCalendar.get(Calendar.DAY_OF_MONTH);
dateCalendar = new GregorianCalendar(year, month, day
- numberOfDays);
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(dateCalendar
.getTimeInMillis()));
break;
}
}
}
private AccountBO getLoanAccountWithPerformanceHistory() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
/*((ClientBO) client).getPerformanceHistory().setLoanCycleNumber(1);
TestObjectFactory.updateObject(client);*/
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
accountBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_APPROVED, startDate, loanOffering);
((ClientBO) client).getClientPerformanceHistory().updateLoanCounter(
loanOffering, YesNoFlag.YES);
TestObjectFactory.updateObject(client);
TestObjectFactory.updateObject(accountBO);
return accountBO;
}
private AccountBO getLoanAccountWithPerformanceHistory(AccountState state,
Date startDate, int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
// ((ClientBO) client).getPerformanceHistory().setLoanCycleNumber(1);
accountBO = TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", client, state, startDate, loanOffering,
disbursalType);
((ClientBO) client).getClientPerformanceHistory().updateLoanCounter(
loanOffering, YesNoFlag.YES);
return accountBO;
}
private AccountBO getLoanAccountWithGroupPerformanceHistory(
AccountState state, Date startDate, int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.CLIENTS, startDate, PrdStatus.LOAN_ACTIVE,
300.0, 1.2, 3, InterestType.FLAT, true, true, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
accountBO = TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", group, state, startDate, loanOffering,
disbursalType);
return accountBO;
}
private AccountActionDateEntity getLastInstallmentAccountAction(
LoanBO loanBO) {
AccountActionDateEntity nextAccountAction = null;
if (loanBO.getAccountActionDates() != null
&& loanBO.getAccountActionDates().size() > 0) {
for (AccountActionDateEntity accountAction : loanBO
.getAccountActionDates()) {
if (null == nextAccountAction)
nextAccountAction = accountAction;
else if (nextAccountAction.getInstallmentId() < accountAction
.getInstallmentId())
nextAccountAction = accountAction;
}
}
return nextAccountAction;
}
private void changeFirstInstallmentDate(AccountBO accountBO,
int numberOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day
- numberOfDays);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private void changeFirstInstallmentDate(AccountBO accountBO) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - 1);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private AccountBO saveAndFetch(AccountBO account) throws Exception {
TestObjectFactory.updateObject(account);
HibernateUtil.closeSession();
return accountPersistence.getAccount(account.getAccountId());
}
private java.sql.Date offSetCurrentDate(int noOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays);
return new java.sql.Date(currentDateCalendar.getTimeInMillis());
}
private LoanBO getLoanAccount(AccountState state, Date startDate,
int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
return TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", group, state, startDate, loanOffering,
disbursalType);
}
private Date incrementCurrentDate(int noOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day + noOfDays);
return DateUtils.getDateWithoutTimeStamp(currentDateCalendar
.getTimeInMillis());
}
private void checkLoanScheduleEntity(Date date, String principal,
String interest, String miscFee, String miscPenalty,
String penalty, Map fees, Map feesPaid, String totalFeeDue,
String totalDueWithFees, LoanScheduleEntity entity) {
if (date != null) {
assertDate(date, entity);
}
if (principal != null) {
assertEquals(new Money(principal), entity.getPrincipal());
}
if (interest != null) {
assertEquals(new Money(interest), entity.getInterest());
}
if (miscFee != null) {
assertEquals(new Money(miscFee), entity.getMiscFee());
}
if (miscPenalty != null) {
assertEquals(new Money(miscPenalty), entity.getMiscPenalty());
}
if (penalty != null) {
assertEquals(new Money(penalty), entity.getPenalty());
}
if (fees != null) {
checkFees(fees, entity, false);
}
if (feesPaid != null) {
checkFees(feesPaid, entity, true);
}
if (totalFeeDue != null) {
checkTotalDue(totalFeeDue, entity);
}
if (totalDueWithFees != null) {
checkTotalDueWithFees(totalDueWithFees, entity);
}
}
private void checkTotalDueWithFees(String totalDueWithFees,
LoanScheduleEntity entity) {
assertEquals(new Money(totalDueWithFees), entity.getTotalDueWithFees());
}
private void checkTotalDue(String totalFeeDue, LoanScheduleEntity entity) {
assertEquals(new Money(totalFeeDue), entity.getTotalFeeDue());
}
private void checkLoanScheduleEntity(Date date, String principal,
String interest, Map fees, LoanScheduleEntity entity) {
if (date != null) {
assertDate(date, entity);
}
assertEquals(new Money(principal), entity.getPrincipal());
assertEquals(new Money(interest), entity.getInterest());
checkFees(fees, entity, false);
}
private void assertDate(Date date, LoanScheduleEntity entity) {
assertEquals(DateUtils.getDateWithoutTimeStamp(date.getTime()),
DateUtils.getDateWithoutTimeStamp(entity.getActionDate()
.getTime()));
}
private void checkFees(Map expectedFess, String totalFeeDue,
LoanScheduleEntity entity) {
checkFees(expectedFess, entity, false);
assertEquals(new Money(totalFeeDue), entity.getTotalFeeDue());
}
private void checkPrincipalAndInterest(String principal, String interest,
LoanScheduleEntity entity) {
assertEquals(new Money(principal), entity.getPrincipal());
assertEquals(new Money(interest), entity.getInterest());
}
private void checkFees(Map expected, LoanScheduleEntity loanScheduleEntity,
boolean checkPaid) {
Set<AccountFeesActionDetailEntity> accountFeesActionDetails = loanScheduleEntity
.getAccountFeesActionDetails();
assertEquals("fees were " + feeNames(accountFeesActionDetails),
expected.size(), accountFeesActionDetails.size());
for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : accountFeesActionDetails) {
if (expected.get(accountFeesActionDetailEntity.getFee()
.getFeeName()) != null) {
assertEquals(new Money((String) expected
.get(accountFeesActionDetailEntity.getFee()
.getFeeName())),
checkPaid ? accountFeesActionDetailEntity
.getFeeAmountPaid()
: accountFeesActionDetailEntity.getFeeAmount());
}
else {
assertFalse("Fee amount not found for "
+ accountFeesActionDetailEntity.getFee().getFeeName(),
true);
}
}
}
private String feeNames(Collection<AccountFeesActionDetailEntity> details) {
StringBuilder debugString = new StringBuilder();
for (Iterator<AccountFeesActionDetailEntity> iter = details.iterator(); iter
.hasNext();) {
AccountFeesActionDetailEntity detail = iter.next();
debugString.append(detail.getFee().getFeeName());
if (iter.hasNext()) {
debugString.append(", ");
}
}
return debugString.toString();
}
// altered form protected
public static LoanScheduleEntity[] getSortedAccountActionDateEntity(
Set<AccountActionDateEntity> actionDateCollection, int expectedCount) {
LoanScheduleEntity[] sortedList = new LoanScheduleEntity[actionDateCollection
.size()];
assertEquals(expectedCount, actionDateCollection.size());
for (AccountActionDateEntity actionDateEntity : actionDateCollection) {
sortedList[actionDateEntity.getInstallmentId().intValue() - 1] = (LoanScheduleEntity) actionDateEntity;
}
return sortedList;
}
private void createInitialObjects() {
meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
}
private AccountBO getLoanAccount(CustomerBO customer, MeetingBO meeting) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", customer,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
}
private AccountBO createLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
accountBO = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
return accountBO;
}
private List<CustomFieldView> getCustomFields() {
List<CustomFieldView> fields = new ArrayList<CustomFieldView>();
fields.add(new CustomFieldView(Short.valueOf("5"), "value1",
CustomFieldType.ALPHA_NUMERIC));
return fields;
}
}
| mifos/test/org/mifos/application/accounts/loan/business/LoanCalculationTest.java | package org.mifos.application.accounts.loan.business;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_SECOND_WEEK;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.mifos.application.accounts.business.AccountActionDateEntity;
import org.mifos.application.accounts.business.AccountBO;
import org.mifos.application.accounts.business.AccountFeesActionDetailEntity;
import org.mifos.application.accounts.business.AccountFeesEntity;
import org.mifos.application.accounts.business.TestAccountActionDateEntity;
import org.mifos.application.accounts.business.TestAccountFeesEntity;
import org.mifos.application.accounts.exceptions.AccountException;
import org.mifos.application.accounts.persistence.AccountPersistence;
import org.mifos.application.accounts.util.helpers.AccountState;
import org.mifos.application.accounts.util.helpers.PaymentData;
import org.mifos.application.accounts.util.helpers.PaymentStatus;
import org.mifos.application.customer.business.CustomerBO;
import org.mifos.application.customer.client.business.ClientBO;
import org.mifos.application.customer.util.helpers.CustomerStatus;
import org.mifos.application.fees.business.AmountFeeBO;
import org.mifos.application.fees.business.FeeBO;
import org.mifos.application.fees.business.FeeView;
import org.mifos.application.fees.util.helpers.FeeCategory;
import org.mifos.application.fees.util.helpers.FeePayment;
import org.mifos.application.fund.business.FundBO;
import org.mifos.application.master.business.CustomFieldType;
import org.mifos.application.master.business.CustomFieldView;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.productdefinition.business.LoanOfferingBO;
import org.mifos.application.productdefinition.util.helpers.ApplicableTo;
import org.mifos.application.productdefinition.util.helpers.GraceType;
import org.mifos.application.productdefinition.util.helpers.InterestType;
import org.mifos.application.productdefinition.util.helpers.PrdStatus;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.framework.MifosTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PropertyNotFoundException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.HibernateUtil;
import org.mifos.framework.persistence.TestObjectPersistence;
import org.mifos.framework.security.util.UserContext;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
/*
* LoanCalculationTest is a starting point for defining and exploring
* expected behavior for different loan payment calculations.
*
* This is a work in progress so there is still lots of extraneous junk
* in this file, that will be cleaned up as we go forward.
*/
public class LoanCalculationTest extends MifosTestCase {
LoanOfferingBO loanOffering = null;
// TODO: probably should be of type LoanBO
protected AccountBO accountBO = null;
protected AccountBO badAccountBO = null;
protected CustomerBO center = null;
protected CustomerBO group = null;
private CustomerBO client = null;
private AccountPersistence accountPersistence = null;
private MeetingBO meeting;
private UserContext userContext;
@Override
protected void setUp() throws Exception {
super.setUp();
userContext = TestObjectFactory.getContext();
accountPersistence = new AccountPersistence();
}
@Override
protected void tearDown() throws Exception {
TestObjectFactory.removeObject(loanOffering);
if (accountBO != null)
accountBO = (AccountBO) HibernateUtil.getSessionTL().get(
AccountBO.class, accountBO.getAccountId());
if (badAccountBO != null)
badAccountBO = (AccountBO) HibernateUtil.getSessionTL().get(
AccountBO.class, badAccountBO.getAccountId());
if (group != null)
group = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, group.getCustomerId());
if (center != null)
center = (CustomerBO) HibernateUtil.getSessionTL().get(
CustomerBO.class, center.getCustomerId());
TestObjectFactory.cleanUp(accountBO);
TestObjectFactory.cleanUp(badAccountBO);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
HibernateUtil.closeSession();
super.tearDown();
}
public static void setFeeAmount(
AccountFeesActionDetailEntity accountFeesActionDetailEntity,
Money feeAmount) {
((LoanFeeScheduleEntity) accountFeesActionDetailEntity)
.setFeeAmount(feeAmount);
}
public static void setFeeAmountPaid(
AccountFeesActionDetailEntity accountFeesActionDetailEntity,
Money feeAmountPaid) {
((LoanFeeScheduleEntity) accountFeesActionDetailEntity)
.setFeeAmountPaid(feeAmountPaid);
}
public static void setActionDate(
AccountActionDateEntity accountActionDateEntity,
java.sql.Date actionDate) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(actionDate);
}
public static void setDisbursementDate(AccountBO account,
Date disbursementDate) {
((LoanBO) account).setDisbursementDate(disbursementDate);
}
/**
* Like
* {@link #createLoanAccountWithDisbursement(String, CustomerBO, AccountState, Date, LoanOfferingBO, int, Short)}
* but differs in various ways.
*
* @param globalNum
* Currently ignored (TODO: remove it or honor it)
*/
public static LoanBO createLoanAccount(String globalNum,
CustomerBO customer, AccountState state, Date startDate,
LoanOfferingBO loanOfering) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer
.getCustomerMeeting().getMeeting());
List<Date> meetingDates = TestObjectFactory.getMeetingDates(meeting, 6);
loanOfering.updateLoanOfferingSameForAllLoan(loanOfering);
LoanBO loan;
MifosCurrency currency = TestObjectFactory.getCurrency();
try {
loan = LoanBO.createLoan(TestUtils.makeUser(), loanOfering,
customer, state, new Money(currency, "300.0"), Short
.valueOf("6"), meetingDates.get(0), true, 0.0,
(short) 0, new FundBO(), new ArrayList<FeeView>(), null,
Double.parseDouble(loanOfering.getMaxLoanAmount()
.toString()), Double.parseDouble(loanOfering
.getMinLoanAmount().toString()), loanOfering
.getMaxNoInstallments(), loanOfering
.getMinNoInstallments(),false,null);
}
catch (ApplicationException e) {
throw new RuntimeException(e);
}
FeeBO maintanenceFee = TestObjectFactory.createPeriodicAmountFee(
"Mainatnence Fee", FeeCategory.LOAN, "100",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan,
maintanenceFee, ((AmountFeeBO) maintanenceFee).getFeeAmount()
.getAmountDoubleValue());
TestAccountFeesEntity.addAccountFees(accountPeriodicFee, loan);
loan.setLoanMeeting(meeting);
short i = 0;
for (Date date : meetingDates) {
LoanScheduleEntity actionDate = (LoanScheduleEntity) loan
.getAccountActionDate(++i);
actionDate.setPrincipal(new Money(currency, "100.0"));
actionDate.setInterest(new Money(currency, "12.0"));
actionDate.setActionDate(new java.sql.Date(date.getTime()));
actionDate.setPaymentStatus(PaymentStatus.UNPAID);
TestAccountActionDateEntity.addAccountActionDate(actionDate, loan);
AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(
actionDate, maintanenceFee, accountPeriodicFee, new Money(
currency, "100.0"));
setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
actionDate.addAccountFeesAction(accountFeesaction);
}
loan.setCreatedBy(Short.valueOf("1"));
loan.setCreatedDate(new Date(System.currentTimeMillis()));
setLoanSummary(loan, currency);
return loan;
}
public static LoanBO createIndividualLoanAccount(String globalNum,
CustomerBO customer, AccountState state, Date startDate,
LoanOfferingBO loanOfering) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
MeetingBO meeting = TestObjectFactory.createLoanMeeting(customer
.getCustomerMeeting().getMeeting());
List<Date> meetingDates = TestObjectFactory.getMeetingDates(meeting, 6);
LoanBO loan;
MifosCurrency currency = TestObjectFactory.getCurrency();
try {
loan = LoanBO.createIndividualLoan(TestUtils.makeUser(), loanOfering, customer,
state, new Money(currency, "300.0"), Short.valueOf("6"),
meetingDates.get(0), true,false, 0.0, (short) 0, new FundBO(),
new ArrayList<FeeView>(), null);
}
catch (ApplicationException e) {
throw new RuntimeException(e);
}
FeeBO maintanenceFee = TestObjectFactory.createPeriodicAmountFee(
"Mainatnence Fee", FeeCategory.LOAN, "100",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountPeriodicFee = new AccountFeesEntity(loan,
maintanenceFee, ((AmountFeeBO) maintanenceFee).getFeeAmount()
.getAmountDoubleValue());
TestAccountFeesEntity.addAccountFees(accountPeriodicFee, loan);
loan.setLoanMeeting(meeting);
short i = 0;
for (Date date : meetingDates) {
LoanScheduleEntity actionDate = (LoanScheduleEntity) loan
.getAccountActionDate(++i);
actionDate.setPrincipal(new Money(currency, "100.0"));
actionDate.setInterest(new Money(currency, "12.0"));
actionDate.setActionDate(new java.sql.Date(date.getTime()));
actionDate.setPaymentStatus(PaymentStatus.UNPAID);
TestAccountActionDateEntity.addAccountActionDate(actionDate, loan);
AccountFeesActionDetailEntity accountFeesaction = new LoanFeeScheduleEntity(
actionDate, maintanenceFee, accountPeriodicFee, new Money(
currency, "100.0"));
setFeeAmountPaid(accountFeesaction, new Money(currency, "0.0"));
actionDate.addAccountFeesAction(accountFeesaction);
}
loan.setCreatedBy(Short.valueOf("1"));
loan.setCreatedDate(new Date(System.currentTimeMillis()));
setLoanSummary(loan, currency);
return loan;
}
private static void setLoanSummary(LoanBO loan, MifosCurrency currency) {
LoanSummaryEntity loanSummary = loan.getLoanSummary();
loanSummary.setOriginalPrincipal(new Money(currency, "300.0"));
loanSummary.setOriginalInterest(new Money(currency, "36.0"));
}
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
public static void modifyDisbursmentDate(LoanBO loan, Date disbursmentDate) {
loan.setDisbursementDate(disbursmentDate);
}
/*
* This test case is meant to reproduce issue 1648
*/
public void testIssue1648()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
int digitsRightOfDecimal = 10;
/**
* What should expectedTotalInterest be? From the spreadsheet test
* case we have 956.76. But we are using 1 digit to the right of the
* decimal place, so depending on the rounding mode, it should be
* 956.7 or 956.8.
*/
String expectedTotalInterest = "956.8";
short numberOfInstallments = 50;
double interestRate = 19.0;
InterestType interestType = InterestType.DECLINING;
String loanAmount = "10000";
short gracePeriodDuration = 0;
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 10000.0, interestRate, numberOfInstallments,
interestType, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
loanAmount), numberOfInstallments, startDate, false,
interestRate, gracePeriodDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(numberOfInstallments, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, numberOfInstallments);
int paymentCount = 1;
MathContext context = new MathContext(digitsRightOfDecimal);
BigDecimal totalPrincipal = new BigDecimal(0, context);
BigDecimal totalInterest = new BigDecimal(0, context);
for (LoanScheduleEntity loanEntry : paymentsArray) {
System.out.println(paymentCount + " -- P: " + loanEntry.getPrincipal() + " I: " + loanEntry.getInterest());
totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
++paymentCount;
}
System.out.println("TotalPrincipal: " + totalPrincipal + " TotalInterest: " + totalInterest);
assertEquals(new BigDecimal(loanAmount), totalPrincipal);
assertEquals(new BigDecimal(expectedTotalInterest), totalInterest);
}
public void testIssue1623()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
int digitsRightOfDecimal = 10;
String expectedTotalInterest = "189.86";
short numberOfInstallments = 11;
double interestRate = 36.0;
String loanAmount = "2500";
short gracePeriodDuration = 0;
InterestType interestType = InterestType.FLAT;
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 10000.0, interestRate, numberOfInstallments,
interestType, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
loanAmount), numberOfInstallments, startDate, false,
interestRate, gracePeriodDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(numberOfInstallments, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, numberOfInstallments);
int paymentCount = 1;
MathContext context = new MathContext(digitsRightOfDecimal);
BigDecimal totalPrincipal = new BigDecimal(0, context);
BigDecimal totalInterest = new BigDecimal(0, context);
for (LoanScheduleEntity loanEntry : paymentsArray) {
System.out.println(paymentCount + " -- P: " + loanEntry.getPrincipal() + " I: " + loanEntry.getInterest());
totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
++paymentCount;
}
System.out.println("TotalPrincipal: " + totalPrincipal + " TotalInterest: " + totalInterest);
assertEquals(new BigDecimal(loanAmount), totalPrincipal);
assertEquals(new BigDecimal(expectedTotalInterest), totalInterest);
}
public void testCreateLoanAccountWithDecliningInterestNoGracePeriod()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, (short) 0, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "50.9", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "50.9", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "50.9", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "50.9", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "51.0", "0.0",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "45.6", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestGraceAllRepayments()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * (1 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (2 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (3 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (4 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (5 + graceDuration)),
"51.0", "0.0", fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (6 + graceDuration)),
"45.6", "0.0", fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestGracePrincipalOnly()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING, false, false, center
.getCustomerMeeting().getMeeting(),
GraceType.PRINCIPALONLYGRACE, "1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "75.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "75.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "75.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "75.1", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithDecliningInterestPrincipalDueOnLastInstallment()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "Loan".substring(0, 1), ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING, false, true, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "0.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "0.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "0.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "300.0", "0.1",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestNoGracePeriod()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, (short) 0, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "50.9", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "50.9", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "50.9", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "50.9", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "50.0", "0.0",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "46.4", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestGraceAllRepayments()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * (1 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (2 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (3 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (4 + graceDuration)),
"50.9", "0.1", fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (5 + graceDuration)),
"50.0", "0.0", fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * (6 + graceDuration)),
"46.4", "0.0", fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestGracePrincipalOnly()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "L", ApplicableTo.GROUPS, new Date(System
.currentTimeMillis()), PrdStatus.LOAN_ACTIVE, 300.0,
1.2, (short) 3, InterestType.DECLINING_EPI, false, false, center
.getCustomerMeeting().getMeeting(),
GraceType.PRINCIPALONLYGRACE, "1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), new Date(System
.currentTimeMillis()), false, // 6 installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "75.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "75.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "75.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "75.0", "0.0",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
public void testCreateLoanAccountWithEqualPrincipalDecliningInterestPrincipalDueOnLastInstallment()
throws NumberFormatException, PropertyNotFoundException,
SystemException, ApplicationException {
Date startDate = new Date(System.currentTimeMillis());
short graceDuration = (short) 2;
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_SECOND_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", "Loan".substring(0, 1), ApplicableTo.GROUPS, startDate,
PrdStatus.LOAN_ACTIVE, 300.0, 1.2, (short) 3,
InterestType.DECLINING_EPI, false, true, center
.getCustomerMeeting().getMeeting(), GraceType.NONE,
"1", "1");
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
List<FeeView> feeViewList = new ArrayList<FeeView>();
accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, new Money(
"300.0"), Short.valueOf("6"), startDate, false, // 6
// installments
1.2, graceDuration, new FundBO(), feeViewList, null);
new TestObjectPersistence().persist(accountBO);
assertEquals(6, accountBO.getAccountActionDates().size());
HashMap fees0 = new HashMap();
Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
.getAccountActionDates();
LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities, 6);
checkLoanScheduleEntity(incrementCurrentDate(14 * 1), "0.0", "0.1",
fees0, paymentsArray[0]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 2), "0.0", "0.1",
fees0, paymentsArray[1]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 3), "0.0", "0.1",
fees0, paymentsArray[2]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 4), "0.0", "0.1",
fees0, paymentsArray[3]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 5), "0.0", "0.1",
fees0, paymentsArray[4]);
checkLoanScheduleEntity(incrementCurrentDate(14 * 6), "300.0", "0.1",
fees0, paymentsArray[5]);
LoanSummaryEntity loanSummaryEntity = ((LoanBO) accountBO)
.getLoanSummary();
assertEquals(new Money("300.0"), loanSummaryEntity
.getOriginalPrincipal());
}
private java.sql.Date setDate(int dayUnit, int interval) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(DateUtils.getCurrentDateWithoutTimeStamp());
calendar.add(dayUnit, interval);
return new java.sql.Date(calendar.getTimeInMillis());
}
private LoanBO createAndRetrieveLoanAccount(LoanOfferingBO loanOffering,
boolean isInterestDedAtDisb, List<FeeView> feeViews,
Short noOfinstallments, Double interestRate)
throws NumberFormatException, AccountException, SystemException,
ApplicationException {
LoanBO loan = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
group, AccountState.LOAN_APPROVED, new Money("300.0"),
noOfinstallments, new Date(System.currentTimeMillis()),
isInterestDedAtDisb, interestRate, (short) 0, new FundBO(),
feeViews, null, Double.parseDouble(loanOffering
.getMaxLoanAmount().toString()),
Double.parseDouble(loanOffering.getMinLoanAmount().toString()),
loanOffering.getMaxNoInstallments(), loanOffering
.getMinNoInstallments(),false,null);
loan.save();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
accountBO = TestObjectFactory.getObject(AccountBO.class, loan
.getAccountId());
return (LoanBO) accountBO;
}
private LoanBO createAndRetrieveLoanAccount(LoanOfferingBO loanOffering,
boolean isInterestDedAtDisb, List<FeeView> feeViews,
Short noOfinstallments) throws NumberFormatException,
AccountException, SystemException, ApplicationException {
return createAndRetrieveLoanAccount(loanOffering, isInterestDedAtDisb,
feeViews, noOfinstallments, 10.0);
}
private LoanOfferingBO createLoanOffering(boolean isPrincipalAtLastInst) {
return createLoanOffering(isPrincipalAtLastInst, PrdStatus.LOAN_ACTIVE);
}
private LoanOfferingBO createLoanOffering(boolean principalAtLastInst,
PrdStatus status) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
return TestObjectFactory.createLoanOffering("Loan",
ApplicableTo.GROUPS, new Date(System.currentTimeMillis()),
status, 300.0, 1.2, 3, InterestType.FLAT, true,
principalAtLastInst, meeting);
}
private List<FeeView> getFeeViews() {
FeeBO fee1 = TestObjectFactory.createOneTimeAmountFee(
"One Time Amount Fee", FeeCategory.LOAN, "120.0",
FeePayment.TIME_OF_DISBURSMENT);
FeeBO fee3 = TestObjectFactory.createPeriodicAmountFee("Periodic Fee",
FeeCategory.LOAN, "10.0", RecurrenceType.WEEKLY, (short) 1);
List<FeeView> feeViews = new ArrayList<FeeView>();
FeeView feeView1 = new FeeView(userContext, fee1);
FeeView feeView2 = new FeeView(userContext, fee3);
feeViews.add(feeView1);
feeViews.add(feeView2);
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
return feeViews;
}
private void deleteFee(List<FeeView> feeViews) {
for (FeeView feeView : feeViews) {
TestObjectFactory.cleanUp((FeeBO) TestObjectFactory.getObject(
FeeBO.class, feeView.getFeeIdValue()));
}
}
private AccountBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
createInitialCustomers();
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, center.getCustomerMeeting().getMeeting());
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
return TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
}
private void createInitialCustomers() {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
}
private void changeFirstInstallmentDateToNextDate(AccountBO accountBO) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day + 1);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private AccountBO applyPaymentandRetrieveAccount() throws AccountException,
SystemException {
Date startDate = new Date(System.currentTimeMillis());
PaymentData paymentData = PaymentData.createPaymentData(new Money(
Configuration.getInstance().getSystemConfig().getCurrency(),
"212.0"), accountBO.getPersonnel(), Short.valueOf("1"),
startDate);
paymentData.setRecieptDate(startDate);
paymentData.setRecieptNum("5435345");
accountBO.applyPaymentWithPersist(paymentData);
HibernateUtil.commitTransaction();
HibernateUtil.getSessionTL().flush();
HibernateUtil.closeSession();
return TestObjectFactory.getObject(AccountBO.class, accountBO
.getAccountId());
}
private AccountBO getLoanAccountWithMiscFeeAndPenalty(AccountState state,
Date startDate, int disbursalType, Money miscFee, Money miscPenalty) {
LoanBO accountBO = getLoanAccount(state, startDate, disbursalType);
for (AccountActionDateEntity accountAction : accountBO
.getAccountActionDates()) {
LoanScheduleEntity accountActionDateEntity = (LoanScheduleEntity) accountAction;
if (accountActionDateEntity.getInstallmentId().equals(
Short.valueOf("1"))) {
accountActionDateEntity.setMiscFee(miscFee);
accountActionDateEntity.setMiscPenalty(miscPenalty);
break;
}
}
LoanSummaryEntity loanSummaryEntity = accountBO.getLoanSummary();
loanSummaryEntity.setOriginalFees(loanSummaryEntity.getOriginalFees()
.add(miscFee));
loanSummaryEntity.setOriginalPenalty(loanSummaryEntity
.getOriginalPenalty().add(miscPenalty));
TestObjectPersistence testObjectPersistence = new TestObjectPersistence();
testObjectPersistence.update(accountBO);
return testObjectPersistence.getObject(LoanBO.class, accountBO
.getAccountId());
}
private void changeInstallmentDate(AccountBO accountBO, int numberOfDays,
Short installmentId) {
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
if (accountActionDateEntity.getInstallmentId()
.equals(installmentId)) {
Calendar dateCalendar = new GregorianCalendar();
dateCalendar.setTimeInMillis(accountActionDateEntity
.getActionDate().getTime());
int year = dateCalendar.get(Calendar.YEAR);
int month = dateCalendar.get(Calendar.MONTH);
int day = dateCalendar.get(Calendar.DAY_OF_MONTH);
dateCalendar = new GregorianCalendar(year, month, day
- numberOfDays);
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(dateCalendar
.getTimeInMillis()));
break;
}
}
}
private AccountBO getLoanAccountWithPerformanceHistory() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
/*((ClientBO) client).getPerformanceHistory().setLoanCycleNumber(1);
TestObjectFactory.updateObject(client);*/
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
accountBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_APPROVED, startDate, loanOffering);
((ClientBO) client).getClientPerformanceHistory().updateLoanCounter(
loanOffering, YesNoFlag.YES);
TestObjectFactory.updateObject(client);
TestObjectFactory.updateObject(accountBO);
return accountBO;
}
private AccountBO getLoanAccountWithPerformanceHistory(AccountState state,
Date startDate, int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
// ((ClientBO) client).getPerformanceHistory().setLoanCycleNumber(1);
accountBO = TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", client, state, startDate, loanOffering,
disbursalType);
((ClientBO) client).getClientPerformanceHistory().updateLoanCounter(
loanOffering, YesNoFlag.YES);
return accountBO;
}
private AccountBO getLoanAccountWithGroupPerformanceHistory(
AccountState state, Date startDate, int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
"Loan", ApplicableTo.CLIENTS, startDate, PrdStatus.LOAN_ACTIVE,
300.0, 1.2, 3, InterestType.FLAT, true, true, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
accountBO = TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", group, state, startDate, loanOffering,
disbursalType);
return accountBO;
}
private AccountActionDateEntity getLastInstallmentAccountAction(
LoanBO loanBO) {
AccountActionDateEntity nextAccountAction = null;
if (loanBO.getAccountActionDates() != null
&& loanBO.getAccountActionDates().size() > 0) {
for (AccountActionDateEntity accountAction : loanBO
.getAccountActionDates()) {
if (null == nextAccountAction)
nextAccountAction = accountAction;
else if (nextAccountAction.getInstallmentId() < accountAction
.getInstallmentId())
nextAccountAction = accountAction;
}
}
return nextAccountAction;
}
private void changeFirstInstallmentDate(AccountBO accountBO,
int numberOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day
- numberOfDays);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private void changeFirstInstallmentDate(AccountBO accountBO) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - 1);
for (AccountActionDateEntity accountActionDateEntity : accountBO
.getAccountActionDates()) {
((LoanScheduleEntity) accountActionDateEntity)
.setActionDate(new java.sql.Date(currentDateCalendar
.getTimeInMillis()));
break;
}
}
private AccountBO saveAndFetch(AccountBO account) throws Exception {
TestObjectFactory.updateObject(account);
HibernateUtil.closeSession();
return accountPersistence.getAccount(account.getAccountId());
}
private java.sql.Date offSetCurrentDate(int noOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day - noOfDays);
return new java.sql.Date(currentDateCalendar.getTimeInMillis());
}
private LoanBO getLoanAccount(AccountState state, Date startDate,
int disbursalType) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
return TestObjectFactory.createLoanAccountWithDisbursement(
"99999999999", group, state, startDate, loanOffering,
disbursalType);
}
private Date incrementCurrentDate(int noOfDays) {
Calendar currentDateCalendar = new GregorianCalendar();
int year = currentDateCalendar.get(Calendar.YEAR);
int month = currentDateCalendar.get(Calendar.MONTH);
int day = currentDateCalendar.get(Calendar.DAY_OF_MONTH);
currentDateCalendar = new GregorianCalendar(year, month, day + noOfDays);
return DateUtils.getDateWithoutTimeStamp(currentDateCalendar
.getTimeInMillis());
}
private void checkLoanScheduleEntity(Date date, String principal,
String interest, String miscFee, String miscPenalty,
String penalty, Map fees, Map feesPaid, String totalFeeDue,
String totalDueWithFees, LoanScheduleEntity entity) {
if (date != null) {
assertDate(date, entity);
}
if (principal != null) {
assertEquals(new Money(principal), entity.getPrincipal());
}
if (interest != null) {
assertEquals(new Money(interest), entity.getInterest());
}
if (miscFee != null) {
assertEquals(new Money(miscFee), entity.getMiscFee());
}
if (miscPenalty != null) {
assertEquals(new Money(miscPenalty), entity.getMiscPenalty());
}
if (penalty != null) {
assertEquals(new Money(penalty), entity.getPenalty());
}
if (fees != null) {
checkFees(fees, entity, false);
}
if (feesPaid != null) {
checkFees(feesPaid, entity, true);
}
if (totalFeeDue != null) {
checkTotalDue(totalFeeDue, entity);
}
if (totalDueWithFees != null) {
checkTotalDueWithFees(totalDueWithFees, entity);
}
}
private void checkTotalDueWithFees(String totalDueWithFees,
LoanScheduleEntity entity) {
assertEquals(new Money(totalDueWithFees), entity.getTotalDueWithFees());
}
private void checkTotalDue(String totalFeeDue, LoanScheduleEntity entity) {
assertEquals(new Money(totalFeeDue), entity.getTotalFeeDue());
}
private void checkLoanScheduleEntity(Date date, String principal,
String interest, Map fees, LoanScheduleEntity entity) {
if (date != null) {
assertDate(date, entity);
}
assertEquals(new Money(principal), entity.getPrincipal());
assertEquals(new Money(interest), entity.getInterest());
checkFees(fees, entity, false);
}
private void assertDate(Date date, LoanScheduleEntity entity) {
assertEquals(DateUtils.getDateWithoutTimeStamp(date.getTime()),
DateUtils.getDateWithoutTimeStamp(entity.getActionDate()
.getTime()));
}
private void checkFees(Map expectedFess, String totalFeeDue,
LoanScheduleEntity entity) {
checkFees(expectedFess, entity, false);
assertEquals(new Money(totalFeeDue), entity.getTotalFeeDue());
}
private void checkPrincipalAndInterest(String principal, String interest,
LoanScheduleEntity entity) {
assertEquals(new Money(principal), entity.getPrincipal());
assertEquals(new Money(interest), entity.getInterest());
}
private void checkFees(Map expected, LoanScheduleEntity loanScheduleEntity,
boolean checkPaid) {
Set<AccountFeesActionDetailEntity> accountFeesActionDetails = loanScheduleEntity
.getAccountFeesActionDetails();
assertEquals("fees were " + feeNames(accountFeesActionDetails),
expected.size(), accountFeesActionDetails.size());
for (AccountFeesActionDetailEntity accountFeesActionDetailEntity : accountFeesActionDetails) {
if (expected.get(accountFeesActionDetailEntity.getFee()
.getFeeName()) != null) {
assertEquals(new Money((String) expected
.get(accountFeesActionDetailEntity.getFee()
.getFeeName())),
checkPaid ? accountFeesActionDetailEntity
.getFeeAmountPaid()
: accountFeesActionDetailEntity.getFeeAmount());
}
else {
assertFalse("Fee amount not found for "
+ accountFeesActionDetailEntity.getFee().getFeeName(),
true);
}
}
}
private String feeNames(Collection<AccountFeesActionDetailEntity> details) {
StringBuilder debugString = new StringBuilder();
for (Iterator<AccountFeesActionDetailEntity> iter = details.iterator(); iter
.hasNext();) {
AccountFeesActionDetailEntity detail = iter.next();
debugString.append(detail.getFee().getFeeName());
if (iter.hasNext()) {
debugString.append(", ");
}
}
return debugString.toString();
}
// altered form protected
public static LoanScheduleEntity[] getSortedAccountActionDateEntity(
Set<AccountActionDateEntity> actionDateCollection, int expectedCount) {
LoanScheduleEntity[] sortedList = new LoanScheduleEntity[actionDateCollection
.size()];
assertEquals(expectedCount, actionDateCollection.size());
for (AccountActionDateEntity actionDateEntity : actionDateCollection) {
sortedList[actionDateEntity.getInstallmentId().intValue() - 1] = (LoanScheduleEntity) actionDateEntity;
}
return sortedList;
}
private void createInitialObjects() {
meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client",
CustomerStatus.CLIENT_ACTIVE, group);
}
private AccountBO getLoanAccount(CustomerBO customer, MeetingBO meeting) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", customer,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
}
private AccountBO createLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
.getNewMeetingForToday(WEEKLY, EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createCenter("Center", meeting);
group = TestObjectFactory.createGroupUnderCenter("Group",
CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
startDate, meeting);
accountBO = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate,
loanOffering);
return accountBO;
}
private List<CustomFieldView> getCustomFields() {
List<CustomFieldView> fields = new ArrayList<CustomFieldView>();
fields.add(new CustomFieldView(Short.valueOf("5"), "value1",
CustomFieldType.ALPHA_NUMERIC));
return fields;
}
}
| Added tests to the LoanCalculationTest to read data from files and create loan calculations and verify against the imported data.
git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@12668 a8845c50-7012-0410-95d3-8e1449b9b1e4
| mifos/test/org/mifos/application/accounts/loan/business/LoanCalculationTest.java | Added tests to the LoanCalculationTest to read data from files and create loan calculations and verify against the imported data. | <ide><path>ifos/test/org/mifos/application/accounts/loan/business/LoanCalculationTest.java
<ide>
<ide> import java.math.BigDecimal;
<ide> import java.math.MathContext;
<add>import java.math.RoundingMode;
<ide> import java.util.ArrayList;
<ide> import java.util.Calendar;
<ide> import java.util.Collection;
<ide> import org.mifos.framework.security.util.UserContext;
<ide> import org.mifos.framework.util.helpers.DateUtils;
<ide> import org.mifos.framework.util.helpers.Money;
<add>import org.mifos.framework.util.helpers.StringUtils;
<ide> import org.mifos.framework.util.helpers.TestObjectFactory;
<add>
<add>import java.io.File;
<add>import java.io.FileInputStream;
<add>import java.io.InputStreamReader;
<add>import java.io.BufferedReader;
<add>
<add>
<ide>
<ide> /*
<ide> * LoanCalculationTest is a starting point for defining and exploring
<ide> * in this file, that will be cleaned up as we go forward.
<ide> */
<ide> public class LoanCalculationTest extends MifosTestCase {
<add> // these constants for parsing the spreadsheet
<add> final String principal = "Principal";
<add> final String loanType = "Loan Type";
<add> final String annualInterest = "Annual Interest";
<add> final String numberOfPayments = "Number of Payments";
<add> final String paymentFrequency = "Payment Frequency";
<add> final String initialRoundingMode = "InitialRoundingMode";
<add> final String initialRoundOffMultiple = "InitialRoundOffMultiple";
<add> final String finalRoundingMode = "FinalRoundingMode";
<add> final String finalRoundOffMultiple = "FinalRoundOffMultiple";
<add> final String interestRounding = "InterestRounding";
<add> final String digitsAfterDecimal = "Digits After Decimal";
<add> final String daysInYear = "Days in Year";
<add> final String totals = "Summed Totals";
<add> final String start = "Start";
<add>
<ide>
<ide> LoanOfferingBO loanOffering = null;
<ide>
<ide> private MeetingBO meeting;
<ide>
<ide> private UserContext userContext;
<add>
<ide>
<ide> @Override
<ide> protected void setUp() throws Exception {
<ide> userContext = TestObjectFactory.getContext();
<ide> accountPersistence = new AccountPersistence();
<ide> }
<add>
<ide>
<ide> @Override
<ide> protected void tearDown() throws Exception {
<ide> Date disbursementDate) {
<ide> ((LoanBO) account).setDisbursementDate(disbursementDate);
<ide> }
<del>
<add>
<add>
<ide>
<ide> /**
<ide> * Like
<ide> loanSummary.setOriginalPrincipal(new Money(currency, "300.0"));
<ide> loanSummary.setOriginalInterest(new Money(currency, "36.0"));
<ide> }
<del>
<del>
<del>
<del>
<del>
<del>
<add>
<add> public static void modifyDisbursmentDate(LoanBO loan, Date disbursmentDate) {
<add> loan.setDisbursementDate(disbursmentDate);
<add> }
<add>
<add>
<add> /* This part is for the new financial calculation */
<ide> /****************************************************************************/
<ide> /****************************************************************************/
<ide> /****************************************************************************/
<ide> /****************************************************************************/
<ide>
<del> public static void modifyDisbursmentDate(LoanBO loan, Date disbursmentDate) {
<del> loan.setDisbursementDate(disbursmentDate);
<del> }
<del>
<add>
<add>
<add>
<add> class LoanParameters {
<add> private String principal = null;
<add> private InterestType loanType = null;
<add> private String annualInterest = null;
<add> private short numberOfPayments = 0;
<add> private RecurrenceType paymentFrequency = null;
<add>
<add> public LoanParameters(String principal, InterestType loanType,
<add> String annualInterest, short numberOfPayments,
<add> RecurrenceType paymentFrequency) {
<add> super();
<add> this.principal = principal;
<add> this.loanType = loanType;
<add> this.annualInterest = annualInterest;
<add> this.numberOfPayments = numberOfPayments;
<add> this.paymentFrequency = paymentFrequency;
<add> }
<add>
<add> public LoanParameters()
<add> {
<add> }
<add>
<add> public String getPrincipal() {
<add> return principal;
<add> }
<add>
<add> public void setPrincipal(String principal) {
<add> this.principal = principal;
<add> }
<add>
<add> public InterestType getLoanType() {
<add> return loanType;
<add> }
<add>
<add> public void setLoanType(InterestType loanType) {
<add> this.loanType = loanType;
<add> }
<add>
<add> public String getAnnualInterest() {
<add> return annualInterest;
<add> }
<add>
<add> public void setAnnualInterest(String annualInterest) {
<add> this.annualInterest = annualInterest;
<add> }
<add>
<add> public short getNumberOfPayments() {
<add> return numberOfPayments;
<add> }
<add>
<add> public void setNumberOfPayments(short numberOfPayments) {
<add> this.numberOfPayments = numberOfPayments;
<add> }
<add>
<add> public RecurrenceType getPaymentFrequency() {
<add> return paymentFrequency;
<add> }
<add>
<add> public void setPaymentFrequency(RecurrenceType paymentFrequency) {
<add> this.paymentFrequency = paymentFrequency;
<add> }
<add>
<add> }
<add>
<add> class InternalConfiguration {
<add> private int daysInYear = 0;
<add> // right now we are just supporting CEILING, FLOOR, HALF_UP
<add> private RoundingMode initialRoundingMode = null;
<add> // should this be constrained to .001, .01, .5, .1, 1 as in the spreadsheet?
<add> private String initialRoundOffMultiple = null;
<add> // right now we are just supporting CEILING, FLOOR, HALF_UP
<add> private RoundingMode finalRoundingMode = null;
<add> // should this be constrained to .001, .01, .5, .1, 1 as in the spreadsheet?
<add> private String finalRoundOffMultiple = null;
<add> // right now we are just supporting CEILING, FLOOR, HALF_UP
<add> private RoundingMode interestRoundingMode = null;
<add> // the number of digits to use to the right of the decimal for interal caculations
<add> private int internalPrecision = 13;
<add> // digits after decimal right now is in the application configuration
<add> private int digitsAfterDecimal = 1;
<add>
<add> public int getDigitsAfterDecimal() {
<add> return digitsAfterDecimal;
<add> }
<add>
<add> public void setDigitsAfterDecimal(int digitsAfterDecimal) {
<add> this.digitsAfterDecimal = digitsAfterDecimal;
<add> }
<add>
<add> public InternalConfiguration(int daysInYear,
<add> RoundingMode initialRoundingMode,
<add> String initialRoundOffMultiple, RoundingMode finalRoundingMode,
<add> String finalRoundOffMultiple, RoundingMode interestRoundingMode,
<add> int internalPrecision) {
<add> super();
<add> this.daysInYear = daysInYear;
<add> this.initialRoundingMode = initialRoundingMode;
<add> this.initialRoundOffMultiple = initialRoundOffMultiple;
<add> this.finalRoundingMode = finalRoundingMode;
<add> this.finalRoundOffMultiple = finalRoundOffMultiple;
<add> this.interestRoundingMode = interestRoundingMode;
<add> this.internalPrecision = internalPrecision;
<add> }
<add>
<add> public InternalConfiguration()
<add> {
<add> }
<add>
<add> public int getDaysInYear() {
<add> return daysInYear;
<add> }
<add>
<add> public void setDaysInYear(int daysInYear) {
<add> this.daysInYear = daysInYear;
<add> }
<add>
<add> public RoundingMode getInitialRoundingMode() {
<add> return initialRoundingMode;
<add> }
<add>
<add> public void setInitialRoundingMode(RoundingMode initialRoundingMode) {
<add> this.initialRoundingMode = initialRoundingMode;
<add> }
<add>
<add> public String getInitialRoundOffMultiple() {
<add> return initialRoundOffMultiple;
<add> }
<add>
<add> public void setInitialRoundOffMultiple(String initialRoundOffMultiple) {
<add> this.initialRoundOffMultiple = initialRoundOffMultiple;
<add> }
<add>
<add> public RoundingMode getFinalRoundingMode() {
<add> return finalRoundingMode;
<add> }
<add>
<add> public void setFinalRoundingMode(RoundingMode finalRoundingMode) {
<add> this.finalRoundingMode = finalRoundingMode;
<add> }
<add>
<add> public String getFinalRoundOffMultiple() {
<add> return finalRoundOffMultiple;
<add> }
<add>
<add> public void setFinalRoundOffMultiple(String finalRoundOffMultiple) {
<add> this.finalRoundOffMultiple = finalRoundOffMultiple;
<add> }
<add>
<add> public RoundingMode getInterestRoundingMode() {
<add> return interestRoundingMode;
<add> }
<add>
<add> public void setInterestRoundingMode(RoundingMode interestRoundingMode) {
<add> this.interestRoundingMode = interestRoundingMode;
<add> }
<add>
<add> public int getInternalPrecision() {
<add> return internalPrecision;
<add> }
<add>
<add> public void setInternalPrecision(int internalPrecision) {
<add> this.internalPrecision = internalPrecision;
<add> }
<add>
<add> }
<add>
<add>
<add> class Results {
<add> // each installment has payment = interest + principal
<add> Money totalPayments = null; // sum of all payments
<add> Money totalInterest = null; // sum of all interests for all payments
<add> Money totalPrincipal = null; // sum of all principals for all payments
<add> // detailed list of all payments. Each payment includes payment, interest, principal and balance
<add> List<PaymentDetail> payments = null;
<add>
<add> public List<PaymentDetail> getPayments() {
<add> return payments;
<add> }
<add> public void setPayments(List<PaymentDetail> payments) {
<add> this.payments = payments;
<add> }
<add> public Money getTotalInterest() {
<add> return totalInterest;
<add> }
<add> public void setTotalInterest(Money totalInterest) {
<add> this.totalInterest = totalInterest;
<add> }
<add> public Money getTotalPayments() {
<add> return totalPayments;
<add> }
<add> public void setTotalPayments(Money totalPayments) {
<add> this.totalPayments = totalPayments;
<add> }
<add> public Money getTotalPrincipal() {
<add> return totalPrincipal;
<add> }
<add> public void setTotalPrincipal(Money totalPrincipal) {
<add> this.totalPrincipal = totalPrincipal;
<add> }
<add> }
<add>
<add>class LoanTestCaseData {
<add>
<add> private LoanParameters loanParams = null;
<add> private Results expectedResult = null;
<add> InternalConfiguration internalConfig = null;
<add>
<add> public InternalConfiguration getInternalConfig() {
<add> return internalConfig;
<add> }
<add>
<add> public void setInternalConfig(InternalConfiguration config) {
<add> this.internalConfig = config;
<add> }
<add>
<add> public LoanTestCaseData()
<add> {
<add> }
<add>
<add> public Results getExpectedResult() {
<add> return expectedResult;
<add> }
<add> public void setExpectedResult(Results expectedResult) {
<add> this.expectedResult = expectedResult;
<add> }
<add> public LoanParameters getLoanParams() {
<add> return loanParams;
<add> }
<add> public void setLoanParams(LoanParameters loanParams) {
<add> this.loanParams = loanParams;
<add> }
<add> }
<add>
<add> private void compareResults(Results expectedResult, Results calculatedResult)
<add> {
<add> // this commented code will be the final code when the financial calculation is done
<add> /*assertEquals(expectedResult.getTotalInterest(),
<add> calculatedResult.getTotalInterest());
<add> assertEquals(expectedResult.getTotalPayments(),
<add> calculatedResult.getTotalPayments());
<add> assertEquals(expectedResult.getTotalPrincipal(),
<add> calculatedResult.getTotalPrincipal());
<add> List<PaymentDetail> expectedPayments = expectedResult.getPayments();
<add> List<PaymentDetail> calculatedPayments = calculatedResult.getPayments();
<add> assertEquals(expectedPayments.size(), calculatedPayments.size());
<add> for (int i=0; i < expectedPayments.size(); i++)
<add> {
<add> assertEquals(expectedPayments.get(i).getBalance(),
<add> calculatedPayments.get(i).getBalance());
<add> assertEquals(expectedPayments.get(i).getInterest(),
<add> calculatedPayments.get(i).getInterest());
<add> assertEquals(expectedPayments.get(i).getPayment(),
<add> calculatedPayments.get(i).getPayment());
<add> assertEquals(expectedPayments.get(i).getPrincipal(),
<add> calculatedPayments.get(i).getPrincipal());
<add> }*/
<add>
<add> System.out.println("Expected Total Interest: " + expectedResult.getTotalInterest() +
<add> " - Calculated Total Interest: " + calculatedResult.getTotalInterest());
<add> System.out.println("Expected Total Payments: " + expectedResult.getTotalPayments() +
<add> " - Calculated Total Payments: " + calculatedResult.getTotalPayments());
<add> System.out.println("Expected Total Principal: " + expectedResult.getTotalPrincipal() +
<add> " - Calculated Total Principal: " + calculatedResult.getTotalPrincipal());
<add>
<add> List<PaymentDetail> expectedPayments = expectedResult.getPayments();
<add> List<PaymentDetail> calculatedPayments = calculatedResult.getPayments();
<add> System.out.println("Expected Number of Installments: " + expectedPayments.size() +
<add> " - Calculated Number of Installments: " + calculatedPayments.size());
<add> for (int i=0; i < expectedPayments.size(); i++)
<add> {
<add> System.out.println("Payment #: " + (i+1));
<add> System.out.println("Expected Balance: " + expectedPayments.get(i).getBalance() +
<add> " - Calculated Balance: " + calculatedPayments.get(i).getBalance());
<add> System.out.println("Expected Interest: " + expectedPayments.get(i).getInterest() +
<add> " - Calculated Interest: " + calculatedPayments.get(i).getInterest());
<add> System.out.println("Expected Payment: " + expectedPayments.get(i).getPayment() +
<add> " - Calculated Payment: " + calculatedPayments.get(i).getPayment());
<add> System.out.println("Expected Principal: " + expectedPayments.get(i).getPrincipal() +
<add> " - Calculated Principal: " + calculatedPayments.get(i).getPrincipal());
<add> }
<add>
<add> }
<add>
<add>
<add> private AccountBO setUpLoan(InternalConfiguration config, LoanParameters loanParams) throws
<add> AccountException
<add> {
<add>
<add> /*
<add> * When constructing a "meeting" here, it looks like the frequency
<add> * should be "EVERY_X" for weekly or monthly loan interest posting.
<add> */
<add> // EVERY_WEEK, EVERY_DAY and EVERY_MONTH are defined as 1
<add> MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
<add> .getNewMeetingForToday(loanParams.getPaymentFrequency(), EVERY_WEEK,
<add> CUSTOMER_MEETING));
<add>
<add> center = TestObjectFactory.createCenter("Center", meeting);
<add> group = TestObjectFactory.createGroupUnderCenter("Group",
<add> CustomerStatus.GROUP_ACTIVE, center);
<add>
<add> short gracePeriodDuration = 0;
<add> Date startDate = new Date(System.currentTimeMillis());
<add>
<add> LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(
<add> "Loan", "L", ApplicableTo.GROUPS, startDate,
<add> PrdStatus.LOAN_ACTIVE, Double.parseDouble(loanParams.getPrincipal()),
<add> Double.parseDouble(loanParams.getAnnualInterest()), loanParams.getNumberOfPayments(),
<add> loanParams.getLoanType(), false, false, center
<add> .getCustomerMeeting().getMeeting(), GraceType.NONE,
<add> "1", "1");
<add>
<add> loanOffering.updateLoanOfferingSameForAllLoan(loanOffering);
<add>
<add> List<FeeView> feeViewList = new ArrayList<FeeView>();
<add>
<add> AccountBO accountBO = LoanBO.createLoan(TestUtils.makeUser(), loanOffering,
<add> group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
<add> new Money(loanParams.getPrincipal()), loanParams.getNumberOfPayments(), startDate, false,
<add> Double.parseDouble(loanParams.getAnnualInterest()), gracePeriodDuration,
<add> new FundBO(), feeViewList, null);
<add>
<add> new TestObjectPersistence().persist(accountBO);
<add> return accountBO;
<add> }
<add>
<add> private Results calculatePayments(InternalConfiguration config, AccountBO accountBO, LoanParameters loanParams)
<add> {
<add>
<add>
<add> Set<AccountActionDateEntity> actionDateEntities = ((LoanBO) accountBO)
<add> .getAccountActionDates();
<add> LoanScheduleEntity[] paymentsArray = getSortedAccountActionDateEntity(actionDateEntities,
<add> loanParams.getNumberOfPayments());
<add>
<add>
<add> MathContext context = new MathContext(config.getInternalPrecision());
<add> BigDecimal totalPrincipal = new BigDecimal(0, context);
<add> BigDecimal totalInterest = new BigDecimal(0, context);
<add> Money totalPayments = new Money("0");
<add> Results calculatedResult = new Results();
<add> List<PaymentDetail> payments = new ArrayList<PaymentDetail>();
<add> for (LoanScheduleEntity loanEntry : paymentsArray)
<add> {
<add> PaymentDetail payment = new PaymentDetail();
<add> Money calculatedPayment = new Money(loanEntry.getPrincipal().getAmount().add(loanEntry.getInterest().getAmount()));
<add> payment.setPayment(calculatedPayment);
<add> payment.setInterest(loanEntry.getInterest());
<add> payment.setPrincipal(loanEntry.getPrincipal());
<add> totalPrincipal = totalPrincipal.add(loanEntry.getPrincipal().getAmount());
<add> totalInterest = totalInterest.add(loanEntry.getInterest().getAmount());
<add> totalPayments = totalPayments.add(calculatedPayment);
<add> payments.add(payment);
<add> }
<add> calculatedResult.setPayments(payments);
<add> calculatedResult.setTotalInterest(new Money(totalInterest));
<add> calculatedResult.setTotalPayments(totalPayments);
<add> calculatedResult.setTotalPrincipal(new Money(totalPrincipal));
<add>
<add> // set balance after each payment
<add> Money balance = totalPayments;
<add> for( PaymentDetail paymentDetail : payments)
<add> {
<add> Money onePayment = paymentDetail.getPayment();
<add> balance = balance.subtract(onePayment);
<add> paymentDetail.setBalance(balance);
<add> }
<add>
<add> return calculatedResult;
<add>
<add> }
<add>
<add>
<add>
<add> private void parseLoanParams(String paramType, String line, LoanParameters loanParams)
<add> {
<add> String tempLine = line.substring(paramType.length(), line.length() - 1);
<add> String[] tokens = tempLine.split(",");
<add> for (int i=0; i < tokens.length; i++)
<add> {
<add> String token = tokens[i];
<add> if (StringUtils.isNullAndEmptySafe(token))
<add> {
<add> if ((paramType.indexOf(principal)>= 0) && (loanParams.getPrincipal() == null))
<add> loanParams.setPrincipal(token);
<add> else if (paramType.indexOf(loanType)>= 0)
<add> {
<add> InterestType interestType = InterestType.valueOf(token.toUpperCase());
<add> loanParams.setLoanType(interestType);
<add> }
<add> else if (paramType.indexOf(annualInterest)>= 0)
<add> {
<add> int pos = token.indexOf("%");
<add> String interest = token.substring(0, pos);
<add> loanParams.setAnnualInterest(interest);
<add> }
<add> else if (paramType.indexOf(numberOfPayments) >= 0)
<add> loanParams.setNumberOfPayments(Short.parseShort(token));
<add> else if (paramType.indexOf(paymentFrequency)>= 0)
<add> {
<add> RecurrenceType recurrenceType = RecurrenceType.valueOf(token.toUpperCase());
<add> loanParams.setPaymentFrequency(recurrenceType);
<add> }
<add> break;
<add>
<add> }
<add> }
<add>
<add>
<add> }
<add>
<add>
<add> private void parseConfigParams(String paramType, String line, InternalConfiguration config)
<add> {
<add> String tempLine = line.substring(paramType.length(), line.length() - 1);
<add> String[] tokens = tempLine.split(",");
<add> for (int i=0; i < tokens.length; i++)
<add> {
<add> String token = tokens[i];
<add> if (StringUtils.isNullAndEmptySafe(token))
<add> {
<add> if (paramType.indexOf(initialRoundingMode) >= 0)
<add> {
<add> RoundingMode mode = RoundingMode.valueOf(token);
<add> config.setInitialRoundingMode(mode);
<add> }
<add> else if (paramType.indexOf(initialRoundOffMultiple) >= 0)
<add> {
<add> config.setInitialRoundOffMultiple(token);
<add> }
<add> else if (paramType.indexOf(finalRoundingMode) >= 0)
<add> {
<add> RoundingMode mode = RoundingMode.valueOf(token);
<add> config.setFinalRoundingMode(mode);
<add> }
<add> else if (paramType.indexOf(finalRoundOffMultiple) >= 0)
<add> {
<add> config.setFinalRoundOffMultiple(token);
<add> }
<add> else if (paramType.indexOf(interestRounding)>= 0)
<add> {
<add> RoundingMode mode = RoundingMode.valueOf(token);
<add> config.setInterestRoundingMode(mode);
<add> }
<add> else if (paramType.indexOf(digitsAfterDecimal) >= 0)
<add> {
<add> config.setDigitsAfterDecimal(Short.parseShort(token));
<add> }
<add> else if (paramType.indexOf(daysInYear) >= 0)
<add> {
<add> config.setDaysInYear(Short.parseShort(token));
<add> }
<add> break;
<add>
<add> }
<add> }
<add>
<add>
<add> }
<add>
<add> private void parseTotals(String paramType, String line, Results result)
<add> {
<add> String tempLine = line.substring(paramType.length(), line.length() -1);
<add> int index = tempLine.indexOf(paramType);
<add> tempLine = tempLine.substring(index + paramType.length(), tempLine.length() -1);
<add> String[] tokens = tempLine.split(",");
<add> boolean totalPayments = false;
<add> boolean totalInterests = true;
<add> boolean totalPrincipals = true;
<add> for (int i=0; i < tokens.length; i++)
<add> {
<add> String token = tokens[i].trim();
<add> if (StringUtils.isNullAndEmptySafe(token))
<add> {
<add> if (totalPayments == false)
<add> {
<add> result.setTotalPayments(new Money(token));
<add> totalPayments = true;
<add> totalPrincipals = false;
<add> }
<add> else if (totalInterests == false)
<add> {
<add> result.setTotalInterest(new Money(token));
<add> totalInterests = true;
<add> }
<add> else if (totalPrincipals == false)
<add> {
<add> result.setTotalPrincipal(new Money(token));
<add> totalPrincipals = true;
<add> totalInterests = false;
<add> }
<add> else
<add> return;
<add>
<add> }
<add> }
<add>
<add>
<add> }
<add>
<add> private void parsePaymentDetail(String paramType, String line, Results result)
<add> {
<add>
<add> int index = line.indexOf(",,");
<add> String tempLine = line.substring(index + 1, line.length() -1);
<add> String[] tokens = tempLine.split(",");
<add> boolean paymentIndex = false;
<add> boolean payment = true;
<add> boolean principal = true;
<add> boolean interest = true;
<add> boolean balance = true;
<add> PaymentDetail paymentDetail = new PaymentDetail();
<add> for (int i=0; i < tokens.length; i++)
<add> {
<add> String token = tokens[i].trim();
<add> if (StringUtils.isNullAndEmptySafe(token))
<add> {
<add> if (paymentIndex == false)
<add> {
<add> int paymentNumber = Integer.parseInt(token);
<add> int expectedPaymentNumber = result.getPayments().size() + 1;
<add> if (paymentNumber != expectedPaymentNumber)
<add> throw new RuntimeException("Parsing error. paymentNumber " + paymentNumber + " Expected: " + expectedPaymentNumber);
<add> paymentIndex = true;
<add> payment = false;
<add> }
<add> else if (payment == false)
<add> {
<add> paymentDetail.setPayment(new Money(token));
<add> payment = true;
<add> principal = false;
<add> }
<add> else if (principal == false)
<add> {
<add> paymentDetail.setPrincipal(new Money(token));
<add> principal = true;
<add> interest = false;
<add> }
<add> else if (interest == false)
<add> {
<add> paymentDetail.setInterest(new Money(token));
<add> interest = true;
<add> balance = false;
<add> }
<add> else if (balance == false)
<add> {
<add> paymentDetail.setBalance(new Money(token));
<add> result.getPayments().add(paymentDetail);
<add> return;
<add> }
<add> }
<add> }
<add>
<add>
<add> }
<add>
<add> private LoanTestCaseData loadSpreadSheetData(String fileName)
<add> {
<add>
<add> File file = new File(fileName);
<add> FileInputStream fileInputStream = null;
<add> InputStreamReader inputStreamReader = null;
<add> BufferedReader bufferedReader = null;
<add> LoanTestCaseData testCaseData = new LoanTestCaseData();
<add> boolean startPayment = false;
<add> int paymentIndex = 0;
<add>
<add>
<add> try
<add> {
<add> fileInputStream = new FileInputStream(file);
<add> inputStreamReader = new InputStreamReader(fileInputStream);
<add> bufferedReader = new BufferedReader(inputStreamReader);
<add>
<add> // dataInputStream.available() returns 0 if the file does not have more lines.
<add> String line = null;
<add> LoanParameters loanParams = new LoanParameters();
<add> InternalConfiguration config = new InternalConfiguration();
<add> Results expectedResult = new Results();
<add> List<PaymentDetail> list = new ArrayList<PaymentDetail>();
<add> expectedResult.setPayments(list);
<add> while ((line = bufferedReader.readLine()) != null)
<add> {
<add> String[] tokens = line.split(",");
<add> for (int i=0; i < tokens.length; i++)
<add> {
<add> String token = tokens[i];
<add> if (StringUtils.isNullAndEmptySafe(token))
<add> {
<add> if ((token.indexOf(principal) >= 0) ||( token.indexOf(loanType) >= 0) || (token.indexOf(annualInterest) >=0)
<add> || (token.indexOf(numberOfPayments) >=0) || (token.indexOf(paymentFrequency) >= 0))
<add> {
<add> parseLoanParams(token, line, loanParams);
<add> break;
<add> }
<add> else if ((token.indexOf(initialRoundingMode) >= 0 ) || (token.indexOf(finalRoundingMode)>= 0 )
<add> || (token.indexOf(initialRoundOffMultiple) >= 0 )
<add> || (token.indexOf(finalRoundOffMultiple) >= 0 ) || (token.indexOf(interestRounding)>= 0 )
<add> || (token.indexOf(digitsAfterDecimal) >= 0 ) || (token.indexOf(daysInYear) >= 0 ))
<add> {
<add> parseConfigParams(token, line, config);
<add> break;
<add> }
<add> else if (token.indexOf(totals) >= 0)
<add> parseTotals(token, line, expectedResult);
<add> else if (token.indexOf(start) >= 0)
<add> {
<add> startPayment = true;
<add> break;
<add> }
<add> else if (startPayment)
<add> {
<add> parsePaymentDetail(token, line, expectedResult);
<add> paymentIndex++;
<add> if (paymentIndex >= loanParams.getNumberOfPayments())
<add> {
<add> testCaseData.setExpectedResult(expectedResult);
<add> testCaseData.setInternalConfig(config);
<add> testCaseData.setLoanParams(loanParams);
<add> return testCaseData;
<add> }
<add> break;
<add> }
<add>
<add> }
<add>
<add> }
<add>
<add> }
<add> if (fileInputStream != null)
<add> fileInputStream.close();
<add> if (inputStreamReader != null)
<add> inputStreamReader.close();
<add> if (bufferedReader != null)
<add> bufferedReader.close();
<add>
<add> }
<add> catch (Exception e)
<add> {
<add> throw new RuntimeException(e);
<add> }
<add> return testCaseData;
<add>
<add> }
<add>
<add>
<add>
<add>
<add> /*
<add> * This test case will populate the data classes for a loan test case with data from spreadsheet and
<add> * calculates payments and compares
<add> */
<add> private void runOneTestCaseWithDataFromSpreadSheet(String fileName) throws NumberFormatException, PropertyNotFoundException,
<add> SystemException, ApplicationException
<add> {
<add>
<add> LoanTestCaseData testCaseData = loadSpreadSheetData(fileName);
<add> accountBO = setUpLoan(testCaseData.getInternalConfig(), testCaseData.getLoanParams());
<add> // calculated results
<add> Results calculatedResult = calculatePayments(testCaseData.getInternalConfig(), accountBO, testCaseData.getLoanParams());
<add> compareResults(testCaseData.getExpectedResult(), calculatedResult);
<add>
<add>
<add> }
<add>
<add>
<add> public void testCaseWithDataFromSpreadSheets() throws NumberFormatException, PropertyNotFoundException,
<add> SystemException, ApplicationException
<add> {
<add> String rootPath = "C:\\";
<add> String[] dataFileNames = {"loan-repayment-master-comma.csv"};
<add> for (int i=0; i < dataFileNames.length; i++)
<add> runOneTestCaseWithDataFromSpreadSheet(rootPath + dataFileNames[i]);
<add> }
<add>
<add> /*
<add> * This test case populates data from spreadsheet for loan params and expected results
<add> */
<add> public void testOneExampleOfTestCaseFromSpreadSheet() throws NumberFormatException, PropertyNotFoundException,
<add> SystemException, ApplicationException
<add> {
<add>
<add> // set up config
<add> InternalConfiguration config = new InternalConfiguration();
<add> config.setDaysInYear(365);
<add> config.setFinalRoundingMode(RoundingMode.CEILING);
<add> config.setFinalRoundOffMultiple("0.01");
<add> config.setInitialRoundingMode(RoundingMode.CEILING);
<add> config.setInitialRoundOffMultiple("1");
<add> config.setInterestRoundingMode(RoundingMode.CEILING);
<add> config.setInternalPrecision(13);
<add> // the digits after decimal now has to be set in the applicationConfiguration
<add>
<add>
<add> // set up loan params
<add> LoanParameters loanParams = new LoanParameters();
<add> loanParams.setLoanType(InterestType.FLAT);
<add> loanParams.setNumberOfPayments((short)5);
<add> loanParams.setPaymentFrequency(RecurrenceType.WEEKLY);
<add> loanParams.setAnnualInterest("12.00");
<add> loanParams.setPrincipal("1002");
<add>
<add> // set up expected results
<add> Results expectedResult = new Results();
<add> expectedResult.setTotalInterest(new Money("11.53"));
<add> expectedResult.setTotalPayments(new Money("1013.53"));
<add> expectedResult.setTotalPrincipal(new Money("1002")); // this loan amount
<add> List<PaymentDetail> list = new ArrayList<PaymentDetail>();
<add> // 1st payment
<add> PaymentDetail payment = new PaymentDetail();
<add> payment.setPayment(new Money("203.000"));
<add> payment.setInterest(new Money("2.306"));
<add> payment.setBalance(new Money("810.530"));
<add> payment.setPrincipal(new Money("200.694"));
<add> list.add(payment);
<add> // 2nd payment
<add> payment = new PaymentDetail();
<add> payment.setPayment(new Money("203.000"));
<add> payment.setInterest(new Money("2.306"));
<add> payment.setBalance(new Money("607.530"));
<add> payment.setPrincipal(new Money("200.694"));
<add> list.add(payment);
<add> // 3rd payment
<add> payment = new PaymentDetail();
<add> payment.setPayment(new Money("203.000"));
<add> payment.setInterest(new Money("2.306"));
<add> payment.setBalance(new Money("404.530"));
<add> payment.setPrincipal(new Money("200.694"));
<add> list.add(payment);
<add> // 4th payment
<add> payment = new PaymentDetail();
<add> payment.setPayment(new Money("203.000"));
<add> payment.setInterest(new Money("2.306"));
<add> payment.setBalance(new Money("201.530"));
<add> payment.setPrincipal(new Money("200.694"));
<add> list.add(payment);
<add> // last payment
<add> payment = new PaymentDetail();
<add> payment.setPayment(new Money("201.530"));
<add> payment.setInterest(new Money("2.306"));
<add> payment.setBalance(new Money("0"));
<add> payment.setPrincipal(new Money("199.224"));
<add> list.add(payment);
<add> expectedResult.setPayments(list);
<add>
<add> expectedResult.setPayments(list);
<add>
<add> accountBO = setUpLoan(config, loanParams);
<add>
<add> // calculated results
<add> Results calculatedResult = calculatePayments(config, accountBO, loanParams);
<add> compareResults(expectedResult, calculatedResult);
<add>
<add>
<add> }
<add>
<add>
<add>
<add> /*
<add> * This test case is meant to reproduce issue 1648 using the new data classes
<add> */
<add> public void testIssue1648New() throws NumberFormatException, PropertyNotFoundException,
<add> SystemException, ApplicationException
<add> {
<add> // set up config
<add> InternalConfiguration config = new InternalConfiguration();
<add> config.setDaysInYear(365);
<add> config.setFinalRoundingMode(RoundingMode.HALF_UP);
<add> config.setFinalRoundOffMultiple("0.001");
<add> config.setInitialRoundingMode(RoundingMode.HALF_UP);
<add> config.setInitialRoundOffMultiple("0.001");
<add> config.setInterestRoundingMode(RoundingMode.HALF_UP);
<add> config.setInternalPrecision(10);
<add>
<add> // set up loan params
<add> LoanParameters loanParams = new LoanParameters();
<add> loanParams.setLoanType(InterestType.DECLINING);
<add> loanParams.setNumberOfPayments((short)50);
<add> loanParams.setPaymentFrequency(RecurrenceType.WEEKLY);
<add> loanParams.setAnnualInterest("19.0");
<add> loanParams.setPrincipal("10000");
<add>
<add> // set up expected results
<add> Results expectedResult = new Results();
<add> expectedResult.setTotalInterest(new Money("956.8"));
<add> expectedResult.setTotalPayments(new Money("10000.4")); // this test doesn't compare this, I made this up
<add> expectedResult.setTotalPrincipal(new Money("10000")); // this loan amount
<add> List<PaymentDetail> list = new ArrayList<PaymentDetail>(); // we don't have this info from this test
<add> expectedResult.setPayments(list);
<add>
<add> accountBO = setUpLoan(config, loanParams);
<add>
<add> // calculated results
<add> Results calculatedResult = calculatePayments(config, accountBO, loanParams);
<add> compareResults(expectedResult, calculatedResult);
<add>
<add>
<add> }
<add>
<add> /****************************************************************************************/
<add> /****************************************************************************************/
<add> /****************************************************************************************/
<add>
<ide> /*
<ide> * This test case is meant to reproduce issue 1648
<ide> */
<ide> short gracePeriodDuration = 0;
<ide> Date startDate = new Date(System.currentTimeMillis());
<ide>
<add> /*
<add> * When constructing a "meeting" here, it looks like the frequency
<add> * should be "EVERY_X" for weekly or monthly loan interest posting.
<add> */
<ide> MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory
<ide> .getNewMeetingForToday(WEEKLY, EVERY_WEEK,
<ide> CUSTOMER_MEETING));
<ide> assertEquals(new BigDecimal(expectedTotalInterest), totalInterest);
<ide>
<ide> }
<del>
<add>
<add>
<add>
<add>
<add> class PaymentDetail{
<add> Money payment = null;
<add> Money principal = null;
<add> Money interest = null;
<add> Money balance = null;
<add>
<add> public PaymentDetail(Money payment, Money principal, Money interest, Money balance) {
<add> super();
<add> this.payment = payment;
<add> this.principal = principal;
<add> this.interest = interest;
<add> this.balance = balance;
<add> }
<add>
<add> public PaymentDetail()
<add> {
<add> }
<add>
<add> public Money getBalance() {
<add> return balance;
<add> }
<add>
<add> public void setBalance(Money balance) {
<add> this.balance = balance;
<add> }
<add>
<add> public Money getInterest() {
<add> return interest;
<add> }
<add>
<add> public void setInterest(Money interest) {
<add> this.interest = interest;
<add> }
<add>
<add> public Money getPayment() {
<add> return payment;
<add> }
<add>
<add> public void setPayment(Money payment) {
<add> this.payment = payment;
<add> }
<add>
<add> public Money getPrincipal() {
<add> return principal;
<add> }
<add>
<add> public void setPrincipal(Money principal) {
<add> this.principal = principal;
<add> }
<add>
<add>
<add> }
<add>
<add>
<add>
<ide> public void testIssue1623()
<ide> throws NumberFormatException, PropertyNotFoundException,
<ide> SystemException, ApplicationException { |
|
Java | apache-2.0 | fc1807b8f26b98be1b0b3d257b5a6e5a7c505a04 | 0 | dpocock/camel,NickCis/camel,onders86/camel,igarashitm/camel,w4tson/camel,jmandawg/camel,lburgazzoli/apache-camel,josefkarasek/camel,jonmcewen/camel,CandleCandle/camel,engagepoint/camel,jollygeorge/camel,nboukhed/camel,mike-kukla/camel,sebi-hgdata/camel,davidkarlsen/camel,JYBESSON/camel,jkorab/camel,grgrzybek/camel,w4tson/camel,neoramon/camel,jonmcewen/camel,hqstevenson/camel,anoordover/camel,hqstevenson/camel,akhettar/camel,pax95/camel,dvankleef/camel,arnaud-deprez/camel,lasombra/camel,prashant2402/camel,punkhorn/camel-upstream,RohanHart/camel,arnaud-deprez/camel,salikjan/camel,brreitme/camel,akhettar/camel,snurmine/camel,lowwool/camel,joakibj/camel,woj-i/camel,RohanHart/camel,sverkera/camel,akhettar/camel,erwelch/camel,isavin/camel,tadayosi/camel,NetNow/camel,scranton/camel,stravag/camel,jonmcewen/camel,snurmine/camel,lasombra/camel,akhettar/camel,jarst/camel,qst-jdc-labs/camel,NickCis/camel,manuelh9r/camel,yuruki/camel,grange74/camel,apache/camel,logzio/camel,dkhanolkar/camel,sirlatrom/camel,w4tson/camel,mike-kukla/camel,dpocock/camel,tlehoux/camel,pplatek/camel,maschmid/camel,apache/camel,lasombra/camel,isururanawaka/camel,joakibj/camel,ullgren/camel,Fabryprog/camel,pplatek/camel,dvankleef/camel,satishgummadelli/camel,engagepoint/camel,scranton/camel,MrCoder/camel,pmoerenhout/camel,kevinearls/camel,gautric/camel,isavin/camel,duro1/camel,allancth/camel,mgyongyosi/camel,yury-vashchyla/camel,borcsokj/camel,kevinearls/camel,salikjan/camel,jpav/camel,lburgazzoli/camel,rparree/camel,jarst/camel,dsimansk/camel,tarilabs/camel,dvankleef/camel,yuruki/camel,jarst/camel,pmoerenhout/camel,isururanawaka/camel,jamesnetherton/camel,aaronwalker/camel,woj-i/camel,DariusX/camel,NickCis/camel,sirlatrom/camel,coderczp/camel,koscejev/camel,allancth/camel,bgaudaen/camel,dpocock/camel,brreitme/camel,anoordover/camel,onders86/camel,cunningt/camel,yury-vashchyla/camel,duro1/camel,dpocock/camel,bfitzpat/camel,FingolfinTEK/camel,igarashitm/camel,jpav/camel,jpav/camel,prashant2402/camel,borcsokj/camel,christophd/camel,erwelch/camel,skinzer/camel,anton-k11/camel,koscejev/camel,qst-jdc-labs/camel,skinzer/camel,jlpedrosa/camel,drsquidop/camel,jamesnetherton/camel,nboukhed/camel,pax95/camel,pkletsko/camel,johnpoth/camel,tdiesler/camel,coderczp/camel,partis/camel,ge0ffrey/camel,dkhanolkar/camel,ge0ffrey/camel,sirlatrom/camel,iweiss/camel,JYBESSON/camel,arnaud-deprez/camel,pplatek/camel,allancth/camel,ramonmaruko/camel,qst-jdc-labs/camel,oalles/camel,oalles/camel,pplatek/camel,lburgazzoli/apache-camel,tadayosi/camel,logzio/camel,rmarting/camel,dkhanolkar/camel,royopa/camel,MrCoder/camel,chanakaudaya/camel,sabre1041/camel,sabre1041/camel,zregvart/camel,satishgummadelli/camel,askannon/camel,josefkarasek/camel,ekprayas/camel,snurmine/camel,hqstevenson/camel,CandleCandle/camel,mohanaraosv/camel,stravag/camel,partis/camel,tadayosi/camel,aaronwalker/camel,trohovsky/camel,ssharma/camel,nikvaessen/camel,neoramon/camel,isururanawaka/camel,YoshikiHigo/camel,gilfernandes/camel,mohanaraosv/camel,allancth/camel,jlpedrosa/camel,iweiss/camel,nicolaferraro/camel,borcsokj/camel,veithen/camel,MrCoder/camel,haku/camel,MohammedHammam/camel,joakibj/camel,lburgazzoli/apache-camel,adessaigne/camel,skinzer/camel,snurmine/camel,YoshikiHigo/camel,davidwilliams1978/camel,ge0ffrey/camel,ullgren/camel,sebi-hgdata/camel,chanakaudaya/camel,satishgummadelli/camel,jameszkw/camel,nikvaessen/camel,MohammedHammam/camel,josefkarasek/camel,yury-vashchyla/camel,bgaudaen/camel,trohovsky/camel,woj-i/camel,MohammedHammam/camel,gyc567/camel,jamesnetherton/camel,jameszkw/camel,mike-kukla/camel,tlehoux/camel,MohammedHammam/camel,jkorab/camel,NetNow/camel,JYBESSON/camel,lowwool/camel,mike-kukla/camel,pax95/camel,Fabryprog/camel,kevinearls/camel,manuelh9r/camel,gautric/camel,sirlatrom/camel,MohammedHammam/camel,grgrzybek/camel,driseley/camel,alvinkwekel/camel,atoulme/camel,gyc567/camel,ssharma/camel,ramonmaruko/camel,driseley/camel,iweiss/camel,YoshikiHigo/camel,scranton/camel,johnpoth/camel,sebi-hgdata/camel,duro1/camel,dmvolod/camel,bhaveshdt/camel,yogamaha/camel,woj-i/camel,tdiesler/camel,acartapanis/camel,yuruki/camel,lburgazzoli/camel,Thopap/camel,stalet/camel,drsquidop/camel,jkorab/camel,Thopap/camel,nicolaferraro/camel,veithen/camel,anton-k11/camel,atoulme/camel,dkhanolkar/camel,dmvolod/camel,mgyongyosi/camel,rparree/camel,scranton/camel,gnodet/camel,davidwilliams1978/camel,davidkarlsen/camel,CodeSmell/camel,aaronwalker/camel,MrCoder/camel,ekprayas/camel,haku/camel,jameszkw/camel,mohanaraosv/camel,CodeSmell/camel,tkopczynski/camel,sverkera/camel,yogamaha/camel,jmandawg/camel,jmandawg/camel,tkopczynski/camel,tarilabs/camel,objectiser/camel,RohanHart/camel,yury-vashchyla/camel,isavin/camel,YMartsynkevych/camel,sabre1041/camel,mnki/camel,arnaud-deprez/camel,brreitme/camel,mike-kukla/camel,nboukhed/camel,stalet/camel,eformat/camel,lburgazzoli/apache-camel,chanakaudaya/camel,kevinearls/camel,pmoerenhout/camel,duro1/camel,chirino/camel,yuruki/camel,sverkera/camel,jlpedrosa/camel,jameszkw/camel,coderczp/camel,apache/camel,CandleCandle/camel,dvankleef/camel,mnki/camel,manuelh9r/camel,atoulme/camel,aaronwalker/camel,stalet/camel,onders86/camel,scranton/camel,borcsokj/camel,mnki/camel,isururanawaka/camel,haku/camel,prashant2402/camel,Thopap/camel,qst-jdc-labs/camel,nikhilvibhav/camel,Fabryprog/camel,objectiser/camel,royopa/camel,pax95/camel,dsimansk/camel,neoramon/camel,alvinkwekel/camel,gnodet/camel,josefkarasek/camel,jollygeorge/camel,josefkarasek/camel,veithen/camel,lowwool/camel,MrCoder/camel,mgyongyosi/camel,jmandawg/camel,gyc567/camel,nicolaferraro/camel,tlehoux/camel,lburgazzoli/camel,YMartsynkevych/camel,drsquidop/camel,YMartsynkevych/camel,akhettar/camel,hqstevenson/camel,cunningt/camel,eformat/camel,curso007/camel,YoshikiHigo/camel,isavin/camel,Thopap/camel,sverkera/camel,jkorab/camel,anton-k11/camel,ramonmaruko/camel,pmoerenhout/camel,ge0ffrey/camel,coderczp/camel,acartapanis/camel,curso007/camel,edigrid/camel,mzapletal/camel,bdecoste/camel,trohovsky/camel,johnpoth/camel,tdiesler/camel,drsquidop/camel,christophd/camel,snurmine/camel,royopa/camel,pkletsko/camel,tarilabs/camel,partis/camel,w4tson/camel,tkopczynski/camel,logzio/camel,rmarting/camel,jpav/camel,dvankleef/camel,jlpedrosa/camel,bhaveshdt/camel,coderczp/camel,jollygeorge/camel,neoramon/camel,oscerd/camel,bfitzpat/camel,gautric/camel,manuelh9r/camel,stravag/camel,askannon/camel,dmvolod/camel,dsimansk/camel,cunningt/camel,grgrzybek/camel,koscejev/camel,adessaigne/camel,koscejev/camel,anoordover/camel,royopa/camel,lburgazzoli/camel,allancth/camel,CandleCandle/camel,YoshikiHigo/camel,isururanawaka/camel,oalles/camel,anoordover/camel,rparree/camel,logzio/camel,pax95/camel,sabre1041/camel,oscerd/camel,tlehoux/camel,ssharma/camel,DariusX/camel,oscerd/camel,mohanaraosv/camel,NetNow/camel,bhaveshdt/camel,gnodet/camel,askannon/camel,pplatek/camel,dsimansk/camel,pkletsko/camel,scranton/camel,edigrid/camel,pkletsko/camel,ullgren/camel,yuruki/camel,zregvart/camel,noelo/camel,mzapletal/camel,joakibj/camel,punkhorn/camel-upstream,iweiss/camel,punkhorn/camel-upstream,nicolaferraro/camel,bhaveshdt/camel,rparree/camel,yogamaha/camel,skinzer/camel,grange74/camel,mzapletal/camel,coderczp/camel,satishgummadelli/camel,davidwilliams1978/camel,gautric/camel,gnodet/camel,edigrid/camel,jollygeorge/camel,nikvaessen/camel,onders86/camel,stravag/camel,nikhilvibhav/camel,stalet/camel,NickCis/camel,skinzer/camel,yuruki/camel,RohanHart/camel,JYBESSON/camel,igarashitm/camel,gilfernandes/camel,tarilabs/camel,veithen/camel,dmvolod/camel,acartapanis/camel,neoramon/camel,tdiesler/camel,partis/camel,bdecoste/camel,tdiesler/camel,dmvolod/camel,mcollovati/camel,NetNow/camel,grgrzybek/camel,curso007/camel,kevinearls/camel,onders86/camel,lburgazzoli/camel,bdecoste/camel,mnki/camel,jonmcewen/camel,lburgazzoli/apache-camel,oalles/camel,FingolfinTEK/camel,driseley/camel,edigrid/camel,askannon/camel,punkhorn/camel-upstream,yury-vashchyla/camel,CandleCandle/camel,zregvart/camel,edigrid/camel,tarilabs/camel,FingolfinTEK/camel,edigrid/camel,jameszkw/camel,mgyongyosi/camel,eformat/camel,bdecoste/camel,snadakuduru/camel,jmandawg/camel,sabre1041/camel,iweiss/camel,adessaigne/camel,DariusX/camel,JYBESSON/camel,qst-jdc-labs/camel,tadayosi/camel,CodeSmell/camel,joakibj/camel,MrCoder/camel,jamesnetherton/camel,borcsokj/camel,gnodet/camel,jkorab/camel,neoramon/camel,tlehoux/camel,noelo/camel,w4tson/camel,rmarting/camel,grange74/camel,lasombra/camel,sebi-hgdata/camel,maschmid/camel,acartapanis/camel,maschmid/camel,yogamaha/camel,atoulme/camel,pplatek/camel,jlpedrosa/camel,jollygeorge/camel,grange74/camel,chirino/camel,dkhanolkar/camel,christophd/camel,adessaigne/camel,JYBESSON/camel,adessaigne/camel,rmarting/camel,oscerd/camel,jonmcewen/camel,dpocock/camel,curso007/camel,satishgummadelli/camel,pax95/camel,jarst/camel,nikvaessen/camel,johnpoth/camel,koscejev/camel,maschmid/camel,brreitme/camel,anoordover/camel,jarst/camel,sverkera/camel,trohovsky/camel,bfitzpat/camel,ekprayas/camel,arnaud-deprez/camel,askannon/camel,christophd/camel,NetNow/camel,apache/camel,MohammedHammam/camel,tadayosi/camel,ssharma/camel,gilfernandes/camel,yogamaha/camel,prashant2402/camel,akhettar/camel,dmvolod/camel,RohanHart/camel,mcollovati/camel,stravag/camel,dpocock/camel,eformat/camel,alvinkwekel/camel,manuelh9r/camel,lburgazzoli/apache-camel,ssharma/camel,rparree/camel,sebi-hgdata/camel,chanakaudaya/camel,mnki/camel,davidwilliams1978/camel,gautric/camel,mcollovati/camel,nboukhed/camel,igarashitm/camel,ekprayas/camel,pplatek/camel,brreitme/camel,chirino/camel,Thopap/camel,davidwilliams1978/camel,mzapletal/camel,pmoerenhout/camel,driseley/camel,pkletsko/camel,objectiser/camel,grange74/camel,YMartsynkevych/camel,jollygeorge/camel,stravag/camel,jameszkw/camel,hqstevenson/camel,oalles/camel,sverkera/camel,jkorab/camel,bfitzpat/camel,Fabryprog/camel,stalet/camel,DariusX/camel,royopa/camel,josefkarasek/camel,drsquidop/camel,noelo/camel,sirlatrom/camel,atoulme/camel,tarilabs/camel,curso007/camel,haku/camel,nikhilvibhav/camel,CandleCandle/camel,lowwool/camel,anton-k11/camel,eformat/camel,Thopap/camel,pmoerenhout/camel,driseley/camel,nikhilvibhav/camel,bgaudaen/camel,haku/camel,yury-vashchyla/camel,tkopczynski/camel,NickCis/camel,noelo/camel,FingolfinTEK/camel,snurmine/camel,johnpoth/camel,sabre1041/camel,ekprayas/camel,veithen/camel,mzapletal/camel,FingolfinTEK/camel,manuelh9r/camel,allancth/camel,tkopczynski/camel,mgyongyosi/camel,RohanHart/camel,gyc567/camel,isururanawaka/camel,grange74/camel,aaronwalker/camel,aaronwalker/camel,johnpoth/camel,w4tson/camel,igarashitm/camel,erwelch/camel,snadakuduru/camel,grgrzybek/camel,oscerd/camel,snadakuduru/camel,ekprayas/camel,engagepoint/camel,joakibj/camel,igarashitm/camel,snadakuduru/camel,oalles/camel,gilfernandes/camel,jamesnetherton/camel,sirlatrom/camel,erwelch/camel,lburgazzoli/camel,bgaudaen/camel,onders86/camel,grgrzybek/camel,atoulme/camel,NetNow/camel,woj-i/camel,chirino/camel,mnki/camel,partis/camel,kevinearls/camel,acartapanis/camel,erwelch/camel,stalet/camel,sebi-hgdata/camel,anton-k11/camel,davidwilliams1978/camel,chanakaudaya/camel,cunningt/camel,lasombra/camel,dvankleef/camel,mcollovati/camel,tadayosi/camel,trohovsky/camel,noelo/camel,nboukhed/camel,bdecoste/camel,lasombra/camel,maschmid/camel,nikvaessen/camel,bhaveshdt/camel,mohanaraosv/camel,snadakuduru/camel,alvinkwekel/camel,royopa/camel,bgaudaen/camel,anton-k11/camel,prashant2402/camel,dsimansk/camel,christophd/camel,mzapletal/camel,pkletsko/camel,bhaveshdt/camel,apache/camel,duro1/camel,objectiser/camel,gautric/camel,qst-jdc-labs/camel,ullgren/camel,ge0ffrey/camel,driseley/camel,yogamaha/camel,ramonmaruko/camel,curso007/camel,jpav/camel,prashant2402/camel,snadakuduru/camel,jamesnetherton/camel,anoordover/camel,dkhanolkar/camel,tlehoux/camel,gilfernandes/camel,borcsokj/camel,lowwool/camel,drsquidop/camel,eformat/camel,bfitzpat/camel,FingolfinTEK/camel,rmarting/camel,trohovsky/camel,YMartsynkevych/camel,jmandawg/camel,NickCis/camel,CodeSmell/camel,logzio/camel,dsimansk/camel,logzio/camel,noelo/camel,skinzer/camel,davidkarlsen/camel,koscejev/camel,tdiesler/camel,erwelch/camel,davidkarlsen/camel,askannon/camel,adessaigne/camel,isavin/camel,jarst/camel,cunningt/camel,chanakaudaya/camel,chirino/camel,haku/camel,logzio/camel,brreitme/camel,gilfernandes/camel,acartapanis/camel,isavin/camel,woj-i/camel,chirino/camel,apache/camel,engagepoint/camel,cunningt/camel,gyc567/camel,arnaud-deprez/camel,duro1/camel,rmarting/camel,tkopczynski/camel,jlpedrosa/camel,maschmid/camel,rparree/camel,oscerd/camel,gyc567/camel,partis/camel,bgaudaen/camel,lowwool/camel,nikvaessen/camel,zregvart/camel,ramonmaruko/camel,YMartsynkevych/camel,engagepoint/camel,jonmcewen/camel,bfitzpat/camel,christophd/camel,mgyongyosi/camel,ramonmaruko/camel,bdecoste/camel,mike-kukla/camel,YoshikiHigo/camel,iweiss/camel,jpav/camel,satishgummadelli/camel,hqstevenson/camel,nboukhed/camel,mohanaraosv/camel,ssharma/camel,ge0ffrey/camel,veithen/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.validator;
import java.io.InputStream;
import java.util.Map;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.impl.ProcessorEndpoint;
import org.apache.camel.processor.validation.ValidatingProcessor;
import org.apache.camel.util.ResourceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <a href="http://camel.apache.org/validation.html">Validator Component</a>
* for validating XML against some schema
*/
public class ValidatorComponent extends DefaultComponent {
private static final transient Logger LOG = LoggerFactory.getLogger(ValidatorComponent.class);
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
final String resourceUri = remaining;
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext().getClassResolver(), resourceUri);
StreamSource source = new StreamSource(is);
ValidatingProcessor validator = new ValidatingProcessor();
validator.setSchemaSource(source);
LOG.debug("{} using schema resource: {}", this, resourceUri);
configureValidator(validator, uri, remaining, parameters);
// force loading of schema at create time otherwise concurrent
// processing could cause thread safe issues for the javax.xml.validation.SchemaFactory
validator.loadSchema();
return new ProcessorEndpoint(uri, this, validator);
}
protected void configureValidator(ValidatingProcessor validator, String uri, String remaining, Map<String, Object> parameters) throws Exception {
LSResourceResolver resourceResolver = resolveAndRemoveReferenceParameter(parameters, "resourceResolver", LSResourceResolver.class);
if (resourceResolver != null) {
validator.setResourceResolver(resourceResolver);
} else {
validator.setResourceResolver(new DefaultLSResourceResolver(getCamelContext(), remaining));
}
setProperties(validator, parameters);
}
} | camel-core/src/main/java/org/apache/camel/component/validator/ValidatorComponent.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.validator;
import java.io.InputStream;
import java.util.Map;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.impl.ProcessorEndpoint;
import org.apache.camel.processor.validation.ValidatingProcessor;
import org.apache.camel.util.ResourceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <a href="http://camel.apache.org/validator.html">Validator Component</a>
* for validating XML against some schema
*/
public class ValidatorComponent extends DefaultComponent {
private static final transient Logger LOG = LoggerFactory.getLogger(ValidatorComponent.class);
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
final String resourceUri = remaining;
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext().getClassResolver(), resourceUri);
StreamSource source = new StreamSource(is);
ValidatingProcessor validator = new ValidatingProcessor();
validator.setSchemaSource(source);
LOG.debug("{} using schema resource: {}", this, resourceUri);
configureValidator(validator, uri, remaining, parameters);
// force loading of schema at create time otherwise concurrent
// processing could cause thread safe issues for the javax.xml.validation.SchemaFactory
validator.loadSchema();
return new ProcessorEndpoint(uri, this, validator);
}
protected void configureValidator(ValidatingProcessor validator, String uri, String remaining, Map<String, Object> parameters) throws Exception {
LSResourceResolver resourceResolver = resolveAndRemoveReferenceParameter(parameters, "resourceResolver", LSResourceResolver.class);
if (resourceResolver != null) {
validator.setResourceResolver(resourceResolver);
} else {
validator.setResourceResolver(new DefaultLSResourceResolver(getCamelContext(), remaining));
}
setProperties(validator, parameters);
}
} | Corrected the URL typo inside Javadoc.
git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@1294572 13f79535-47bb-0310-9956-ffa450edef68
| camel-core/src/main/java/org/apache/camel/component/validator/ValidatorComponent.java | Corrected the URL typo inside Javadoc. | <ide><path>amel-core/src/main/java/org/apache/camel/component/validator/ValidatorComponent.java
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> /**
<del> * The <a href="http://camel.apache.org/validator.html">Validator Component</a>
<add> * The <a href="http://camel.apache.org/validation.html">Validator Component</a>
<ide> * for validating XML against some schema
<ide> */
<ide> public class ValidatorComponent extends DefaultComponent { |
|
Java | mit | ed773d91a9f99c435a821d8ec45cc67412a4ce76 | 0 | matthieu-vergne/jMetal | package org.uma.jmetal.problem.multiobjective;
import org.uma.jmetal.problem.ConstrainedProblem;
import org.uma.jmetal.problem.impl.AbstractDoubleProblem;
import org.uma.jmetal.solution.DoubleSolution;
import org.uma.jmetal.util.solutionattribute.impl.NumberOfViolatedConstraints;
import org.uma.jmetal.util.solutionattribute.impl.OverallConstraintViolation;
import java.util.Arrays;
import java.util.List;
/**
* Class representing problem Water
*/
@SuppressWarnings("serial")
public class Water extends AbstractDoubleProblem implements ConstrainedProblem<DoubleSolution> {
public OverallConstraintViolation<DoubleSolution> overallConstraintViolationDegree ;
public NumberOfViolatedConstraints<DoubleSolution> numberOfViolatedConstraints ;
// defining the lower and upper limits
public static final Double [] LOWERLIMIT = {0.01, 0.01, 0.01};
public static final Double [] UPPERLIMIT = {0.45, 0.10, 0.10};
/**
* Constructor.
* Creates a default instance of the Water problem.
*/
public Water() {
setNumberOfVariables(3);
setNumberOfObjectives(5);
setNumberOfConstraints(7);
setName("Water") ;
List<Double> lowerLimit = Arrays.asList(LOWERLIMIT) ;
List<Double> upperLimit = Arrays.asList(UPPERLIMIT) ;
setLowerLimit(lowerLimit);
setUpperLimit(upperLimit);
overallConstraintViolationDegree = new OverallConstraintViolation<DoubleSolution>() ;
numberOfViolatedConstraints = new NumberOfViolatedConstraints<DoubleSolution>() ;
}
/** Evaluate() method */
@Override
public void evaluate(DoubleSolution solution) {
double[] fx = new double[solution.getNumberOfObjectives()];
double[] x = new double[solution.getNumberOfVariables()];
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
x[i] = solution.getVariableValue(i) ;
}
fx[0] = 106780.37 * (x[1] + x[2]) + 61704.67 ;
fx[1] = 3000 * x[0] ;
fx[2] = 305700 * 2289 * x[1] / Math.pow(0.06*2289, 0.65) ;
fx[3] = 250 * 2289 * Math.exp(-39.75*x[1]+9.9*x[2]+2.74) ;
fx[4] = 25 * (1.39 /(x[0]*x[1]) + 4940*x[2] -80) ;
solution.setObjective(0,fx[0]);
solution.setObjective(1,fx[1]);
solution.setObjective(2,fx[2]);
solution.setObjective(3,fx[3]);
solution.setObjective(4,fx[4]);
}
/** EvaluateConstraints() method */
@Override
public void evaluateConstraints(DoubleSolution solution) {
double[] constraint = new double[getNumberOfConstraints()];
double[] x = new double[solution.getNumberOfVariables()];
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
x[i] = solution.getVariableValue(i) ;
}
constraint[0] = 1 - (0.00139/(x[0]*x[1])+4.94*x[2]-0.08) ;
constraint[1] = 1 - (0.000306/(x[0]*x[1])+1.082*x[2]-0.0986) ;
constraint[2] = 50000 - (12.307/(x[0]*x[1]) + 49408.24*x[2]+4051.02) ;
constraint[3] = 16000 - (2.098/(x[0]*x[1])+8046.33*x[2]-696.71) ;
constraint[4] = 10000 - (2.138/(x[0]*x[1])+7883.39*x[2]-705.04) ;
constraint[5] = 2000 - (0.417*x[0]*x[1] + 1721.26*x[2]-136.54) ;
constraint[6] = 550 - (0.164/(x[0]*x[1])+631.13*x[2]-54.48) ;
double overallConstraintViolation = 0.0;
int violatedConstraints = 0;
for (int i = 0; i < getNumberOfConstraints(); i++) {
if (constraint[i]<0.0){
overallConstraintViolation+=constraint[i];
violatedConstraints++;
}
}
overallConstraintViolationDegree.setAttribute(solution, overallConstraintViolation);
numberOfViolatedConstraints.setAttribute(solution, violatedConstraints);
}
}
| jmetal-problem/src/main/java/org/uma/jmetal/problem/multiobjective/Water.java | package org.uma.jmetal.problem.multiobjective;
import org.uma.jmetal.problem.ConstrainedProblem;
import org.uma.jmetal.problem.impl.AbstractDoubleProblem;
import org.uma.jmetal.solution.DoubleSolution;
import org.uma.jmetal.util.solutionattribute.impl.NumberOfViolatedConstraints;
import org.uma.jmetal.util.solutionattribute.impl.OverallConstraintViolation;
import java.util.Arrays;
import java.util.List;
/**
* Class representing problem Water
*/
@SuppressWarnings("serial")
public class Water extends AbstractDoubleProblem implements ConstrainedProblem<DoubleSolution> {
public OverallConstraintViolation<DoubleSolution> overallConstraintViolationDegree ;
public NumberOfViolatedConstraints<DoubleSolution> numberOfViolatedConstraints ;
// defining the lower and upper limits
public static final Double [] LOWERLIMIT = {0.01, 0.01, 0.01};
public static final Double [] UPPERLIMIT = {0.45, 0.10, 0.10};
/**
* Constructor.
* Creates a default instance of the Water problem.
*/
public Water() {
setNumberOfVariables(3);
setNumberOfObjectives(5);
setNumberOfConstraints(7);
setName("Water") ;
List<Double> lowerLimit = Arrays.asList(LOWERLIMIT) ;
List<Double> upperLimit = Arrays.asList(UPPERLIMIT) ;
setLowerLimit(lowerLimit);
setUpperLimit(upperLimit);
overallConstraintViolationDegree = new OverallConstraintViolation<DoubleSolution>() ;
numberOfViolatedConstraints = new NumberOfViolatedConstraints<DoubleSolution>() ;
}
/** Evaluate() method */
@Override
public void evaluate(DoubleSolution solution) {
double[] fx = new double[2];
double[] x = new double[solution.getNumberOfVariables()];
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
x[i] = solution.getVariableValue(i) ;
}
fx[0] = 106780.37 * (x[1] + x[2]) + 61704.67 ;
fx[1] = 3000 * x[0] ;
fx[2] = 305700 * 2289 * x[1] / Math.pow(0.06*2289, 0.65) ;
fx[3] = 250 * 2289 * Math.exp(-39.75*x[1]+9.9*x[2]+2.74) ;
fx[4] = 25 * (1.39 /(x[0]*x[1]) + 4940*x[2] -80) ;
solution.setObjective(0,fx[0]);
solution.setObjective(1,fx[1]);
solution.setObjective(2,fx[2]);
solution.setObjective(3,fx[3]);
solution.setObjective(4,fx[4]);
}
/** EvaluateConstraints() method */
@Override
public void evaluateConstraints(DoubleSolution solution) {
double[] constraint = new double[getNumberOfConstraints()];
double[] x = new double[solution.getNumberOfVariables()];
for (int i = 0; i < solution.getNumberOfVariables(); i++) {
x[i] = solution.getVariableValue(i) ;
}
constraint[0] = 1 - (0.00139/(x[0]*x[1])+4.94*x[2]-0.08) ;
constraint[1] = 1 - (0.000306/(x[0]*x[1])+1.082*x[2]-0.0986) ;
constraint[2] = 50000 - (12.307/(x[0]*x[1]) + 49408.24*x[2]+4051.02) ;
constraint[3] = 16000 - (2.098/(x[0]*x[1])+8046.33*x[2]-696.71) ;
constraint[4] = 10000 - (2.138/(x[0]*x[1])+7883.39*x[2]-705.04) ;
constraint[5] = 2000 - (0.417*x[0]*x[1] + 1721.26*x[2]-136.54) ;
constraint[6] = 550 - (0.164/(x[0]*x[1])+631.13*x[2]-54.48) ;
double overallConstraintViolation = 0.0;
int violatedConstraints = 0;
for (int i = 0; i < getNumberOfConstraints(); i++) {
if (constraint[i]<0.0){
overallConstraintViolation+=constraint[i];
violatedConstraints++;
}
}
overallConstraintViolationDegree.setAttribute(solution, overallConstraintViolation);
numberOfViolatedConstraints.setAttribute(solution, violatedConstraints);
}
}
| Fix a bug in class Water
| jmetal-problem/src/main/java/org/uma/jmetal/problem/multiobjective/Water.java | Fix a bug in class Water | <ide><path>metal-problem/src/main/java/org/uma/jmetal/problem/multiobjective/Water.java
<ide> /** Evaluate() method */
<ide> @Override
<ide> public void evaluate(DoubleSolution solution) {
<del> double[] fx = new double[2];
<add> double[] fx = new double[solution.getNumberOfObjectives()];
<ide> double[] x = new double[solution.getNumberOfVariables()];
<ide> for (int i = 0; i < solution.getNumberOfVariables(); i++) {
<ide> x[i] = solution.getVariableValue(i) ; |
|
JavaScript | mit | eeaa60111925f537fc0f918df423bcf95f386f9f | 0 | wmurphyrd/aframe-physics-extras,wmurphyrd/aframe-physics-extras | /* global assert, process, setup, suite, test */
const helpers = require('../helpers')
const entityFactory = helpers.entityFactory
suite('physics-collider', function () {
setup(function (done) {
var el = this.el = entityFactory()
window.CANNON = {Body: {KINEMATIC: 4}}
el.body = {el: el, id: 2}
this.scene = el.sceneEl
this.el.setAttribute('physics-collider', '')
this.target1 = document.createElement('a-entity')
this.scene.appendChild(this.target1)
this.target1.body = {el: this.target1, id: 1}
this.target2 = document.createElement('a-entity')
this.scene.appendChild(this.target2)
this.target2.body = {el: this.target2, id: 3}
this.scene.addEventListener('loaded', () => {
this.comp = this.el.components['physics-collider']
done()
})
})
suite('lifecyle', function () {
test('component attaches and removes without errors', function (done) {
this.el.removeAttribute('physics-collider')
process.nextTick(done)
})
})
suite('collisions', function () {
test('finds collided entities in contacts array', function () {
const hitSpy = this.sinon.spy()
this.el.addEventListener('collisions', hitSpy)
this.el.body.world = {
bodyOverlapKeeper: {current: [
(this.target1.body.id << 16) + this.el.body.id,
(this.el.body.id << 16) + this.target2.body.id
]},
idToBodyMap: [undefined, this.target1.body, this.el.body, this.target2.body]
}
this.comp.tick()
assert.isTrue(
hitSpy.calledWithMatch({detail: {els: [this.target1, this.target2]}}),
'finds new collisions'
)
this.comp.tick()
assert.strictEqual(this.comp.collisions.size, 2, 'ignores duplicates')
this.el.body.world.bodyOverlapKeeper.current.pop()
this.comp.tick()
assert.isTrue(
hitSpy.calledWithMatch({detail: {els: [], clearedEls: [this.target2]}}),
'clears old collisions and ignores duplicates'
)
assert.strictEqual(this.comp.collisions.size, 1, 'keeps ongoing collisions')
assert.isTrue(this.comp.collisions.has(this.target1), 'keeps ongoing collisions')
})
test('Handles bodies removed while collided', function () {
this.el.body.world = {
bodyOverlapKeeper: {current: [
(this.target1.body.id << 16) + this.el.body.id,
(this.el.body.id << 16) + this.target2.body.id
]},
idToBodyMap: [undefined, this.target1.body, this.el.body, this.target2.body]
}
this.comp.tick()
this.el.body.world.idToBodyMap[3] = undefined
this.comp.tick()
assert.isFalse(this.comp.collisions.has(this.target2), 'lower loop')
this.el.body.world.idToBodyMap[1] = undefined
this.comp.tick()
assert.isFalse(this.comp.collisions.has(this.target1), 'upper loop')
})
})
})
| tests/components/physics-collider.test.js | /* global assert, process, setup, suite, test */
const helpers = require('../helpers')
const entityFactory = helpers.entityFactory
suite('physics-collider', function () {
setup(function (done) {
var el = this.el = entityFactory()
window.CANNON = {Body: {KINEMATIC: 4}}
el.body = {el: el, id: 2}
this.scene = el.sceneEl
this.el.setAttribute('physics-collider', '')
this.target1 = document.createElement('a-entity')
this.scene.appendChild(this.target1)
this.target1.body = {el: this.target1, id: 1}
this.target2 = document.createElement('a-entity')
this.scene.appendChild(this.target2)
this.target2.body = {el: this.target2, id: 3}
this.scene.addEventListener('loaded', () => {
this.comp = this.el.components['physics-collider']
done()
})
})
suite('lifecyle', function () {
test('component attaches and removes without errors', function (done) {
this.el.removeAttribute('physics-collider')
process.nextTick(done)
})
})
suite('collisions', function () {
test('finds collided entities in contacts array', function () {
const hitSpy = this.sinon.spy()
this.el.addEventListener('collisions', hitSpy)
this.el.body.world = {
bodyOverlapKeeper: {current: [
(this.target1.body.id << 16) + this.el.body.id,
(this.el.body.id << 16) + this.target2.body.id
]},
idToBodyMap: [undefined, this.target1.body, this.el.body, this.target2.body]
}
this.comp.tick()
assert.isTrue(
hitSpy.calledWithMatch({detail: {els: [this.target1, this.target2]}}),
'finds new collisions'
)
this.comp.tick()
assert.strictEqual(this.comp.collisions.size, 2, 'ignores duplicates')
this.el.body.world.bodyOverlapKeeper.current.pop()
this.comp.tick()
assert.isTrue(
hitSpy.calledWithMatch({detail: {els: [], clearedEls: [this.target2]}}),
'clears old collisions and ignores duplicates'
)
assert.strictEqual(this.comp.collisions.size, 1, 'keeps ongoing collisions')
assert.isTrue(this.comp.collisions.has(this.target1), 'keeps ongoing collisions')
})
test('Handles bodies removed while collided', function () {
this.el.body.world = {
bodyOverlapKeeper: {current: [
(this.target1.body.id << 16) + this.el.body.id,
(this.el.body.id << 16) + this.target2.body.id
]},
idToBodyMap: [undefined, this.target1.body, this.el.body, this.target2.body]
}
this.comp.tick()
this.el.body.world.idToBodyMap[3] = undefined
this.comp.tick()
assert.isFalse(this.comp.collisions.has(this.target2), 'lower loop')
})
})
})
| Also test removal of collided entities in the upper loop
| tests/components/physics-collider.test.js | Also test removal of collided entities in the upper loop | <ide><path>ests/components/physics-collider.test.js
<ide> this.el.body.world.idToBodyMap[3] = undefined
<ide> this.comp.tick()
<ide> assert.isFalse(this.comp.collisions.has(this.target2), 'lower loop')
<add> this.el.body.world.idToBodyMap[1] = undefined
<add> this.comp.tick()
<add> assert.isFalse(this.comp.collisions.has(this.target1), 'upper loop')
<ide> })
<ide> })
<ide> }) |
|
Java | mit | 2dc23c1b75ef3667ffd17f68e50255874e694ef4 | 0 | silencio-app/app | package io.github.silencio_app.silencio;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaRecorder;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private MediaRecorder mediaRecorder = null;
private final String MSG = "Main Thread Logging";
private TextView amplitude; // TextFiled for showing textual reading
private boolean recording_flag = false; // Boolean to check if graph has to be plot or not
private LineGraphSeries<DataPoint> series;
private int lastX = 0; // Pointer for plotting the amplitude
private static final double amp_ref = 3.27;
private static final String PREVIOUS_X = "Previous x axis point";
private static final String PREVIOUS_dB = "Previous noted decibals ";
private int db_level; // decibel levels
private boolean PLAY_PAUSE_STATUS = false;
private Button play_pause_button;
private ImageView loud_image;
private WifiManager mWifiManager;
private DhcpInfo dhcpInfo;
private TextView current_location;
private String current_ip;
private final String FILENAME = "myFingerprinting";
private EditText location_name;
private boolean canR, canW;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
amplitude = (TextView)findViewById(R.id.amp);
// db_meter = (ProgressBar)findViewById(R.id.db_meter);
play_pause_button = (Button)findViewById(R.id.play_pause_button);
loud_image = (ImageView)findViewById(R.id.loud_image);
current_location = (TextView)findViewById(R.id.current_location);
location_name = (EditText)findViewById(R.id.location_name);
/**
* Initialising the empty graph
*/
GraphView graph = (GraphView) findViewById(R.id.graph);
series = new LineGraphSeries<>();
graph.addSeries(series);
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0); // min value is 0
viewport.setMaxY(100); // max value is 32768
viewport.setMaxX(100); // 10 units frame
viewport.setScalable(true); // auto scroll to right
Thread newT2 = new Thread(new IPMapper()); // New Thread is created to handle the amplitude fetching and plotting graph
newT2.start();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_task_home) {
// Intent intent = new Intent(this, TaskHomeActivity.class);
// startActivity(intent);
} else if (id == R.id.nav_server) {
Intent intent = new Intent(this, ServerListnerActivity.class);
startActivity(intent);
} else if (id == R.id.nav_account_setting) {
// Intent intent = new Intent(this, SettingActivity.class);
// startActivity(intent);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Function called when start button is pressed
* @param view
*/
public void play_pause_handler(View view){
if (!PLAY_PAUSE_STATUS){
// If Mic is not running
startMIC(view);
PLAY_PAUSE_STATUS = true;
play_pause_button.setBackground(getResources().getDrawable(R.drawable.ic_menu_slideshow));
}
else{
// If Mic is running
stopMIC(view);
PLAY_PAUSE_STATUS = false;
play_pause_button.setBackground(getResources().getDrawable(R.drawable.ic_menu_send));
}
}
public void showGraph(View view){
View myView = findViewById(R.id.graph);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the final radius for the clipping circle
float finalRadius = (float) Math.hypot(cx, cy);
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius);
// make the graph and meter visible and start the animation
myView.setVisibility(View.VISIBLE);
// db_meter.setVisibility(View.VISIBLE);
anim.start();
}
public void hideGraph(View view){
TextView tview = (TextView) findViewById(R.id.amp);
tview.setText(getString(R.string.press_start));
// previously visible view
final View myView = findViewById(R.id.graph);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the initial radius for the clipping circle
float initialRadius = (float) Math.hypot(cx, cy);
// create the animation (the final radius is zero)
Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
// make graph and meter invisible
myView.setVisibility(View.INVISIBLE);
// db_meter.setVisibility(View.GONE);
}
});
// start the animation
anim.start();
}
public void startMIC(View view){
/**
* start the MIC if mediaRecorder instance is created else Pops up a message
*/
if(mediaRecorder == null){
mediaRecorder = new MediaRecorder();
mediaRecorder.reset();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile("/dev/null"); // Not saving the audio
try{
mediaRecorder.prepare();
mediaRecorder.start();
recording_flag = true;
Thread newT = new Thread(new AudioListener()); // New Thread is created to handle the amplitude fetching and plotting graph
newT.start();
showGraph(view);
}
catch (IOException e){
Log.d(MSG, "================== EXCEPTION ================");
e.printStackTrace();
}
}
}
public void stopMIC(View view) {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
recording_flag = false; //reset the flag
hideGraph(view);
}
else{
Log.d(MSG, "================== NO MIC LOCKED ================");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt(PREVIOUS_X, lastX);
savedInstanceState.putInt(PREVIOUS_dB, db_level);
super.onSaveInstanceState(savedInstanceState);
}
public boolean isExternalWritable(){
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public boolean isExternalReadable(){
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
public void externalState(){
if (isExternalReadable() && isExternalWritable()){
canR = canW = true;
}
else if (isExternalReadable() && !isExternalWritable()){
canR = true;
canW = false;
}
else{
canR = canW = false;
}
}
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), albumName);
if (!file.mkdirs()) {
file.mkdirs();
}
return file;
}
public void bind_ip_value_to_location(View view){
Log.d(MSG, "======================== YES I HAVE BEEEN CALLED ===============================");
FileOutputStream fos;
String name = location_name.getText().toString();
File file;
externalState();
if(canW && canR){
FileOutputStream outputStream;
try {
file = new File(getAlbumStorageDir("Files Generated"), FILENAME+".txt");
outputStream = new FileOutputStream(file, true);
outputStream.write(name.getBytes());
outputStream.write(" == ".getBytes());
outputStream.write(current_ip.getBytes());
outputStream.write("\n".getBytes());
outputStream.close();
Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(), "Cannot Write to External Now", Toast.LENGTH_SHORT).show();
}
}
private class IPMapper implements Runnable{
public void get_gateway_ip(){
mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if(mWifiManager.isWifiEnabled()){
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
if (wifiInfo.getNetworkId() == -1){
// Not connected to an access point
Toast.makeText(getApplicationContext(), " You are not connected to any access point", Toast.LENGTH_LONG).show();
}
else{
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback()) continue;
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast == null)
continue;
Log.d(" BROADCAST ", broadcast.toString());
current_ip = broadcast.toString();
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
}
else{
Toast.makeText(getApplicationContext(), " Wifi Not Enabled", Toast.LENGTH_LONG).show();
}
}
@Override
public void run() {
while(true){
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
get_gateway_ip();
current_location.setText(current_ip);
}
});
try {
// Sleep for 600 ms for next value
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* private class for fetching amplitude and mapping graph
*/
private class AudioListener implements Runnable{
private final String MSG = "AudioListener Logging: ";
/**
* @return current amplitude if instance of MIC exist
*/
public int getAmplitude() {
if (mediaRecorder != null) {
double y = 20*Math.log10(mediaRecorder.getMaxAmplitude()/amp_ref);
return (int)y;
}
else
{
return -1;
}
}
@Override
public void run(){
// if recording flag is true then keep mapping graph
while(recording_flag){
int raw_amp_val = getAmplitude();
final int amp_val;
if (raw_amp_val < 0){
amp_val = 0;
}
else{
amp_val = raw_amp_val;
}
db_level = amp_val;
final String amp_val_string = amp_val + "";
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
amplitude.setText(amp_val_string);
// db_meter.setProgress(amp_val);
/*
Provide Style to meter according to decibel values
*/
if (amp_val <= 50){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_1));
// db_meter.setProgressDrawable(getDrawable(R.drawable.greenprogress));
}
if (amp_val > 50 && amp_val <= 70){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_2));
// db_meter.setProgressDrawable(getDrawable(R.drawable.orangeprogress));
}
if (amp_val > 70){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_3));
// db_meter.setProgressDrawable(getDrawable(R.drawable.redprogress));
}
series.appendData(new DataPoint(lastX++, amp_val), true, 100);
}
});
Log.d(MSG, " === AMPLITUDE === "+ amp_val_string);
// long startTime = System.nanoTime();
// long endTime = System.nanoTime();
// long duration = (endTime - startTime)/1000000;
// Log.d("MSG", " Time took is ============== "+duration);
try {
// Sleep for 600 ms for next value
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(MSG, "======== Thread Destroyed =========");
}
}
}
| app/src/main/java/io/github/silencio_app/silencio/MainActivity.java | package io.github.silencio_app.silencio;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.Image;
import android.media.MediaRecorder;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Formatter;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private MediaRecorder mediaRecorder = null;
private final String MSG = "Main Thread Logging";
private TextView amplitude; // TextFiled for showing textual reading
private boolean recording_flag = false; // Boolean to check if graph has to be plot or not
private LineGraphSeries<DataPoint> series;
private int lastX = 0; // Pointer for plotting the amplitude
private static final double amp_ref = 3.27;
private static final String PREVIOUS_X = "Previous x axis point";
private static final String PREVIOUS_dB = "Previous noted decibals ";
private int db_level; // decibel levels
private boolean PLAY_PAUSE_STATUS = false;
private Button play_pause_button;
private ImageView loud_image;
private WifiManager mWifiManager;
private DhcpInfo dhcpInfo;
private TextView current_location;
private String current_ip;
private final String FILENAME = "myFingerprinting";
private EditText location_name;
private boolean canR, canW;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
amplitude = (TextView)findViewById(R.id.amp);
// db_meter = (ProgressBar)findViewById(R.id.db_meter);
play_pause_button = (Button)findViewById(R.id.play_pause_button);
loud_image = (ImageView)findViewById(R.id.loud_image);
current_location = (TextView)findViewById(R.id.current_location);
location_name = (EditText)findViewById(R.id.location_name);
/**
* Initialising the empty graph
*/
GraphView graph = (GraphView) findViewById(R.id.graph);
series = new LineGraphSeries<>();
graph.addSeries(series);
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0); // min value is 0
viewport.setMaxY(100); // max value is 32768
viewport.setMaxX(100); // 10 units frame
viewport.setScalable(true); // auto scroll to right
Thread newT2 = new Thread(new IPMapper()); // New Thread is created to handle the amplitude fetching and plotting graph
newT2.start();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_task_home) {
// Intent intent = new Intent(this, TaskHomeActivity.class);
// startActivity(intent);
} else if (id == R.id.nav_server) {
Intent intent = new Intent(this, ServerListnerActivity.class);
startActivity(intent);
} else if (id == R.id.nav_account_setting) {
// Intent intent = new Intent(this, SettingActivity.class);
// startActivity(intent);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Function called when start button is pressed
* @param view
*/
public void play_pause_handler(View view){
if (!PLAY_PAUSE_STATUS){
// If Mic is not running
startMIC(view);
PLAY_PAUSE_STATUS = true;
play_pause_button.setBackground(getResources().getDrawable(R.drawable.ic_menu_slideshow));
}
else{
// If Mic is running
stopMIC(view);
PLAY_PAUSE_STATUS = false;
play_pause_button.setBackground(getResources().getDrawable(R.drawable.ic_menu_send));
}
}
public void showGraph(View view){
View myView = findViewById(R.id.graph);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the final radius for the clipping circle
float finalRadius = (float) Math.hypot(cx, cy);
// create the animator for this view (the start radius is zero)
Animator anim =
ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius);
// make the graph and meter visible and start the animation
myView.setVisibility(View.VISIBLE);
// db_meter.setVisibility(View.VISIBLE);
anim.start();
}
public void hideGraph(View view){
TextView tview = (TextView) findViewById(R.id.amp);
tview.setText(getString(R.string.press_start));
// previously visible view
final View myView = findViewById(R.id.graph);
// get the center for the clipping circle
int cx = myView.getWidth() / 2;
int cy = myView.getHeight() / 2;
// get the initial radius for the clipping circle
float initialRadius = (float) Math.hypot(cx, cy);
// create the animation (the final radius is zero)
Animator anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, initialRadius, 0);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
// make graph and meter invisible
myView.setVisibility(View.INVISIBLE);
// db_meter.setVisibility(View.GONE);
}
});
// start the animation
anim.start();
}
public void startMIC(View view){
/**
* start the MIC if mediaRecorder instance is created else Pops up a message
*/
if(mediaRecorder == null){
mediaRecorder = new MediaRecorder();
mediaRecorder.reset();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile("/dev/null"); // Not saving the audio
try{
mediaRecorder.prepare();
mediaRecorder.start();
recording_flag = true;
Thread newT = new Thread(new AudioListener()); // New Thread is created to handle the amplitude fetching and plotting graph
newT.start();
showGraph(view);
}
catch (IOException e){
Log.d(MSG, "================== EXCEPTION ================");
e.printStackTrace();
}
}
}
public void stopMIC(View view) {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
recording_flag = false; //reset the flag
hideGraph(view);
}
else{
Log.d(MSG, "================== NO MIC LOCKED ================");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt(PREVIOUS_X, lastX);
savedInstanceState.putInt(PREVIOUS_dB, db_level);
super.onSaveInstanceState(savedInstanceState);
}
public boolean isExternalWritable(){
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public boolean isExternalReadable(){
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
public void externalState(){
if (isExternalReadable() && isExternalWritable()){
canR = canW = true;
}
else if (isExternalReadable() && !isExternalWritable()){
canR = true;
canW = false;
}
else{
canR = canW = false;
}
}
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), albumName);
if (!file.mkdirs()) {
file.mkdirs();
}
return file;
}
public void bind_ip_value_to_location(View view){
Log.d(MSG, "======================== YES I HAVE BEEEN CALLED ===============================");
FileOutputStream fos;
String name = location_name.getText().toString();
File file;
externalState();
if(canW && canR){
FileOutputStream outputStream;
try {
file = new File(getAlbumStorageDir("Files Generated"), FILENAME+".txt");
outputStream = new FileOutputStream(file, true);
outputStream.write(name.getBytes());
outputStream.write(" == ".getBytes());
outputStream.write(current_ip.getBytes());
outputStream.write("\n".getBytes());
outputStream.close();
Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(), "Cannot Write to External Now", Toast.LENGTH_SHORT).show();
}
}
private class IPMapper implements Runnable{
public void get_gateway_ip(){
mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if(mWifiManager.isWifiEnabled()){
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
if (wifiInfo.getNetworkId() == -1){
// Not connected to an access point
Toast.makeText(getApplicationContext(), " You are not connected to any access point", Toast.LENGTH_LONG).show();
}
else{
// Connected to access point
dhcpInfo = mWifiManager.getDhcpInfo();
int gateway = dhcpInfo.gateway;
String binary_string = Integer.toBinaryString(gateway);
int len = binary_string.length();
String oct1, oct2, oct3, oct4;
oct1 = binary_string.substring(len - 8, len);
oct2 = binary_string.substring(len - 16, len - 8);
oct3 = binary_string.substring(len - 24, len - 16);
oct4 = binary_string.substring(0, len - 24);
Log.d(" MSG ", " =========== Connected to "+ Integer.parseInt(oct1, 2) +"."+ Integer.parseInt(oct2, 2) + "."+Integer.parseInt(oct3, 2)+"."+Integer.parseInt(oct4, 2));
current_ip = Integer.parseInt(oct1, 2) +"."+ Integer.parseInt(oct2, 2) + "."+Integer.parseInt(oct3, 2)+"."+Integer.parseInt(oct4, 2);
}
}
else{
Toast.makeText(getApplicationContext(), " Wifi Not Enabled", Toast.LENGTH_LONG).show();
}
}
@Override
public void run() {
while(true){
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
get_gateway_ip();
current_location.setText(current_ip);
}
});
try {
// Sleep for 600 ms for next value
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* private class for fetching amplitude and mapping graph
*/
private class AudioListener implements Runnable{
private final String MSG = "AudioListener Logging: ";
/**
* @return current amplitude if instance of MIC exist
*/
public int getAmplitude() {
if (mediaRecorder != null) {
double y = 20*Math.log10(mediaRecorder.getMaxAmplitude()/amp_ref);
return (int)y;
}
else
{
return -1;
}
}
@Override
public void run(){
// if recording flag is true then keep mapping graph
while(recording_flag){
int raw_amp_val = getAmplitude();
final int amp_val;
if (raw_amp_val < 0){
amp_val = 0;
}
else{
amp_val = raw_amp_val;
}
db_level = amp_val;
final String amp_val_string = amp_val + "";
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
amplitude.setText(amp_val_string);
// db_meter.setProgress(amp_val);
/*
Provide Style to meter according to decibel values
*/
if (amp_val <= 50){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_1));
// db_meter.setProgressDrawable(getDrawable(R.drawable.greenprogress));
}
if (amp_val > 50 && amp_val <= 70){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_2));
// db_meter.setProgressDrawable(getDrawable(R.drawable.orangeprogress));
}
if (amp_val > 70){
loud_image.setBackground(getResources().getDrawable(R.drawable.sound_level_3));
// db_meter.setProgressDrawable(getDrawable(R.drawable.redprogress));
}
series.appendData(new DataPoint(lastX++, amp_val), true, 100);
}
});
Log.d(MSG, " === AMPLITUDE === "+ amp_val_string);
// long startTime = System.nanoTime();
// long endTime = System.nanoTime();
// long duration = (endTime - startTime)/1000000;
// Log.d("MSG", " Time took is ============== "+duration);
try {
// Sleep for 600 ms for next value
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(MSG, "======== Thread Destroyed =========");
}
}
}
| Get broadcast address fixed
Signed-off-by: Divay Prakash <[email protected]>
| app/src/main/java/io/github/silencio_app/silencio/MainActivity.java | Get broadcast address fixed | <ide><path>pp/src/main/java/io/github/silencio_app/silencio/MainActivity.java
<ide> import android.content.Context;
<ide> import android.content.Intent;
<ide> import android.content.pm.ActivityInfo;
<del>import android.media.Image;
<ide> import android.media.MediaRecorder;
<ide> import android.net.DhcpInfo;
<ide> import android.net.wifi.WifiInfo;
<ide> import android.net.wifi.WifiManager;
<ide> import android.os.Bundle;
<ide> import android.os.Environment;
<del>import android.support.annotation.NonNull;
<ide> import android.support.design.widget.NavigationView;
<del>import android.support.design.widget.Snackbar;
<ide> import android.support.v4.view.GravityCompat;
<ide> import android.support.v4.widget.DrawerLayout;
<ide> import android.support.v7.app.ActionBarDrawerToggle;
<ide> import android.widget.Button;
<ide> import android.widget.EditText;
<ide> import android.widget.ImageView;
<del>import android.widget.NumberPicker;
<del>import android.widget.ProgressBar;
<ide> import android.widget.TextView;
<ide> import android.widget.Toast;
<ide>
<ide> import java.io.File;
<ide> import java.io.FileOutputStream;
<ide> import java.io.IOException;
<del>import java.util.Formatter;
<add>import java.net.InetAddress;
<add>import java.net.InterfaceAddress;
<add>import java.net.NetworkInterface;
<add>import java.net.SocketException;
<add>import java.util.Enumeration;
<ide>
<ide> public class MainActivity extends AppCompatActivity
<ide> implements NavigationView.OnNavigationItemSelectedListener {
<ide> Toast.makeText(getApplicationContext(), " You are not connected to any access point", Toast.LENGTH_LONG).show();
<ide> }
<ide> else{
<del> // Connected to access point
<del> dhcpInfo = mWifiManager.getDhcpInfo();
<del> int gateway = dhcpInfo.gateway;
<del> String binary_string = Integer.toBinaryString(gateway);
<del> int len = binary_string.length();
<del> String oct1, oct2, oct3, oct4;
<del> oct1 = binary_string.substring(len - 8, len);
<del> oct2 = binary_string.substring(len - 16, len - 8);
<del> oct3 = binary_string.substring(len - 24, len - 16);
<del> oct4 = binary_string.substring(0, len - 24);
<del> Log.d(" MSG ", " =========== Connected to "+ Integer.parseInt(oct1, 2) +"."+ Integer.parseInt(oct2, 2) + "."+Integer.parseInt(oct3, 2)+"."+Integer.parseInt(oct4, 2));
<del> current_ip = Integer.parseInt(oct1, 2) +"."+ Integer.parseInt(oct2, 2) + "."+Integer.parseInt(oct3, 2)+"."+Integer.parseInt(oct4, 2);
<add> Enumeration<NetworkInterface> interfaces = null;
<add> try {
<add> interfaces = NetworkInterface.getNetworkInterfaces();
<add> while (interfaces.hasMoreElements()) {
<add> NetworkInterface networkInterface = interfaces.nextElement();
<add> if (networkInterface.isLoopback()) continue;
<add> for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
<add> InetAddress broadcast = interfaceAddress.getBroadcast();
<add> if (broadcast == null)
<add> continue;
<add> Log.d(" BROADCAST ", broadcast.toString());
<add> current_ip = broadcast.toString();
<add> }
<add> }
<add> } catch (SocketException e) {
<add> e.printStackTrace();
<add> }
<ide> }
<ide> }
<ide> else{ |
|
Java | bsd-3-clause | 9dfdc77f63655c2ca58791e0ad7d48ec2b56b03d | 0 | eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j | /*******************************************************************************
* Copyright (c) 2018 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.shacl.AST;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection;
import org.eclipse.rdf4j.sail.shacl.ShaclSailConnection;
import org.eclipse.rdf4j.sail.shacl.SourceConstraintComponent;
import org.eclipse.rdf4j.sail.shacl.planNodes.BufferedPlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.BulkedExternalInnerJoin;
import org.eclipse.rdf4j.sail.shacl.planNodes.EnrichWithShape;
import org.eclipse.rdf4j.sail.shacl.planNodes.GroupByCount;
import org.eclipse.rdf4j.sail.shacl.planNodes.LoggingNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.MaxCountFilter;
import org.eclipse.rdf4j.sail.shacl.planNodes.PlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.TrimTuple;
import org.eclipse.rdf4j.sail.shacl.planNodes.UnBufferedPlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.UnionNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.Unique;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
/**
* The AST (Abstract Syntax Tree) node that represents a sh:maxCount property nodeShape restriction.
*
* @author Håvard Ottestad
*/
public class MaxCountPropertyShape extends PathPropertyShape {
private static final Logger logger = LoggerFactory.getLogger(MaxCountPropertyShape.class);
private long maxCount;
MaxCountPropertyShape(Resource id, SailRepositoryConnection connection, NodeShape nodeShape, boolean deactivated,
Resource path,
Long maxCount) {
super(id, connection, nodeShape, deactivated, path);
this.maxCount = maxCount;
}
@Override
public String toString() {
return "MaxCountPropertyShape{" + "maxCount=" + maxCount + '}';
}
@Override
public PlanNode getPlan(ShaclSailConnection shaclSailConnection, NodeShape nodeShape, boolean printPlans,
PlanNode overrideTargetNode) {
if (deactivated) {
return null;
}
if (overrideTargetNode != null) {
PlanNode bulkedExternalInnerJoin = new LoggingNode(new BulkedExternalInnerJoin(overrideTargetNode,
shaclSailConnection, path.getQuery("?a", "?c", null), false), "");
PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalInnerJoin), "");
PlanNode directTupleFromFilter = new LoggingNode(
new MaxCountFilter(groupByCount, maxCount).getFalseNode(UnBufferedPlanNode.class), "");
if (printPlans) {
String planAsGraphvizDot = getPlanAsGraphvizDot(directTupleFromFilter, shaclSailConnection);
logger.info(planAsGraphvizDot);
}
return new EnrichWithShape(new LoggingNode(directTupleFromFilter, ""), this);
}
PlanNode planAddedStatements = new LoggingNode(
nodeShape.getPlanAddedStatements(shaclSailConnection, nodeShape, null),
"");
PlanNode planAddedStatements1 = new LoggingNode(
super.getPlanAddedStatements(shaclSailConnection, nodeShape, null),
"");
planAddedStatements1 = new LoggingNode(nodeShape.getTargetFilter(shaclSailConnection, planAddedStatements1),
"");
PlanNode mergeNode = new LoggingNode(new UnionNode(planAddedStatements, planAddedStatements1), "");
PlanNode groupByCount1 = new LoggingNode(new GroupByCount(mergeNode), "");
MaxCountFilter maxCountFilter = new MaxCountFilter(groupByCount1, maxCount);
PlanNode validValues = maxCountFilter.getTrueNode(BufferedPlanNode.class);
PlanNode invalidValues = maxCountFilter.getFalseNode(BufferedPlanNode.class);
PlanNode mergeNode1;
if (!shaclSailConnection.stats.isBaseSailEmpty()) {
PlanNode trimmed = new LoggingNode(new TrimTuple(validValues, 0, 1), "");
PlanNode unique = new LoggingNode(new Unique(trimmed), "");
PlanNode bulkedExternalInnerJoin = new LoggingNode(
new BulkedExternalInnerJoin(unique, shaclSailConnection, path.getQuery("?a", "?c", null), true),
"");
PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalInnerJoin), "");
PlanNode directTupleFromFilter = new MaxCountFilter(groupByCount, maxCount)
.getFalseNode(UnBufferedPlanNode.class);
mergeNode1 = new UnionNode(new LoggingNode(directTupleFromFilter, ""),
new LoggingNode(invalidValues, ""));
} else {
mergeNode1 = invalidValues;
}
if (printPlans) {
String planAsGraphvizDot = getPlanAsGraphvizDot(mergeNode1, shaclSailConnection);
logger.info(planAsGraphvizDot);
}
return new EnrichWithShape(new LoggingNode(mergeNode1, ""), this);
}
@Override
public SourceConstraintComponent getSourceConstraintComponent() {
return SourceConstraintComponent.MaxCountConstraintComponent;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
MaxCountPropertyShape that = (MaxCountPropertyShape) o;
return maxCount == that.maxCount;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), maxCount);
}
}
| shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/AST/MaxCountPropertyShape.java | /*******************************************************************************
* Copyright (c) 2018 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.shacl.AST;
import org.eclipse.rdf4j.model.Resource;
import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection;
import org.eclipse.rdf4j.sail.shacl.ShaclSailConnection;
import org.eclipse.rdf4j.sail.shacl.SourceConstraintComponent;
import org.eclipse.rdf4j.sail.shacl.planNodes.BufferedPlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.BulkedExternalLeftOuterJoin;
import org.eclipse.rdf4j.sail.shacl.planNodes.EnrichWithShape;
import org.eclipse.rdf4j.sail.shacl.planNodes.GroupByCount;
import org.eclipse.rdf4j.sail.shacl.planNodes.LoggingNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.MaxCountFilter;
import org.eclipse.rdf4j.sail.shacl.planNodes.PlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.TrimTuple;
import org.eclipse.rdf4j.sail.shacl.planNodes.UnBufferedPlanNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.UnionNode;
import org.eclipse.rdf4j.sail.shacl.planNodes.Unique;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
/**
* The AST (Abstract Syntax Tree) node that represents a sh:maxCount property nodeShape restriction.
*
* @author Håvard Ottestad
*/
public class MaxCountPropertyShape extends PathPropertyShape {
private static final Logger logger = LoggerFactory.getLogger(MaxCountPropertyShape.class);
private long maxCount;
MaxCountPropertyShape(Resource id, SailRepositoryConnection connection, NodeShape nodeShape, boolean deactivated,
Resource path,
Long maxCount) {
super(id, connection, nodeShape, deactivated, path);
this.maxCount = maxCount;
}
@Override
public String toString() {
return "MaxCountPropertyShape{" + "maxCount=" + maxCount + '}';
}
@Override
public PlanNode getPlan(ShaclSailConnection shaclSailConnection, NodeShape nodeShape, boolean printPlans,
PlanNode overrideTargetNode) {
if (deactivated) {
return null;
}
if (overrideTargetNode != null) {
PlanNode bulkedExternalLeftOuterJoin = new LoggingNode(new BulkedExternalLeftOuterJoin(overrideTargetNode,
shaclSailConnection, path.getQuery("?a", "?c", null), false), "");
PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalLeftOuterJoin), "");
PlanNode directTupleFromFilter = new LoggingNode(
new MaxCountFilter(groupByCount, maxCount).getFalseNode(UnBufferedPlanNode.class), "");
if (printPlans) {
String planAsGraphvizDot = getPlanAsGraphvizDot(directTupleFromFilter, shaclSailConnection);
logger.info(planAsGraphvizDot);
}
return new EnrichWithShape(new LoggingNode(directTupleFromFilter, ""), this);
}
PlanNode planAddedStatements = new LoggingNode(
nodeShape.getPlanAddedStatements(shaclSailConnection, nodeShape, null),
"");
PlanNode planAddedStatements1 = new LoggingNode(
super.getPlanAddedStatements(shaclSailConnection, nodeShape, null),
"");
planAddedStatements1 = new LoggingNode(nodeShape.getTargetFilter(shaclSailConnection, planAddedStatements1),
"");
PlanNode mergeNode = new LoggingNode(new UnionNode(planAddedStatements, planAddedStatements1), "");
PlanNode groupByCount1 = new LoggingNode(new GroupByCount(mergeNode), "");
MaxCountFilter maxCountFilter = new MaxCountFilter(groupByCount1, maxCount);
PlanNode validValues = maxCountFilter.getTrueNode(BufferedPlanNode.class);
PlanNode invalidValues = maxCountFilter.getFalseNode(BufferedPlanNode.class);
PlanNode mergeNode1;
if (!shaclSailConnection.stats.isBaseSailEmpty()) {
PlanNode trimmed = new LoggingNode(new TrimTuple(validValues, 0, 1), "");
PlanNode unique = new LoggingNode(new Unique(trimmed), "");
PlanNode bulkedExternalLeftOuterJoin = new LoggingNode(
new BulkedExternalLeftOuterJoin(unique, shaclSailConnection, path.getQuery("?a", "?c", null), true),
"");
PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalLeftOuterJoin), "");
PlanNode directTupleFromFilter = new MaxCountFilter(groupByCount, maxCount)
.getFalseNode(UnBufferedPlanNode.class);
mergeNode1 = new UnionNode(new LoggingNode(directTupleFromFilter, ""),
new LoggingNode(invalidValues, ""));
} else {
mergeNode1 = invalidValues;
}
if (printPlans) {
String planAsGraphvizDot = getPlanAsGraphvizDot(mergeNode1, shaclSailConnection);
logger.info(planAsGraphvizDot);
}
return new EnrichWithShape(new LoggingNode(mergeNode1, ""), this);
}
@Override
public SourceConstraintComponent getSourceConstraintComponent() {
return SourceConstraintComponent.MaxCountConstraintComponent;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
MaxCountPropertyShape that = (MaxCountPropertyShape) o;
return maxCount == that.maxCount;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), maxCount);
}
}
| eclipse/rdf4j#1380 innerjoin
Signed-off-by: Håvard Ottestad <[email protected]>
| shacl/src/main/java/org/eclipse/rdf4j/sail/shacl/AST/MaxCountPropertyShape.java | eclipse/rdf4j#1380 innerjoin | <ide><path>hacl/src/main/java/org/eclipse/rdf4j/sail/shacl/AST/MaxCountPropertyShape.java
<ide> import org.eclipse.rdf4j.sail.shacl.ShaclSailConnection;
<ide> import org.eclipse.rdf4j.sail.shacl.SourceConstraintComponent;
<ide> import org.eclipse.rdf4j.sail.shacl.planNodes.BufferedPlanNode;
<del>import org.eclipse.rdf4j.sail.shacl.planNodes.BulkedExternalLeftOuterJoin;
<add>import org.eclipse.rdf4j.sail.shacl.planNodes.BulkedExternalInnerJoin;
<ide> import org.eclipse.rdf4j.sail.shacl.planNodes.EnrichWithShape;
<ide> import org.eclipse.rdf4j.sail.shacl.planNodes.GroupByCount;
<ide> import org.eclipse.rdf4j.sail.shacl.planNodes.LoggingNode;
<ide> }
<ide>
<ide> if (overrideTargetNode != null) {
<del> PlanNode bulkedExternalLeftOuterJoin = new LoggingNode(new BulkedExternalLeftOuterJoin(overrideTargetNode,
<add> PlanNode bulkedExternalInnerJoin = new LoggingNode(new BulkedExternalInnerJoin(overrideTargetNode,
<ide> shaclSailConnection, path.getQuery("?a", "?c", null), false), "");
<del> PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalLeftOuterJoin), "");
<add> PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalInnerJoin), "");
<ide>
<ide> PlanNode directTupleFromFilter = new LoggingNode(
<ide> new MaxCountFilter(groupByCount, maxCount).getFalseNode(UnBufferedPlanNode.class), "");
<ide>
<ide> PlanNode unique = new LoggingNode(new Unique(trimmed), "");
<ide>
<del> PlanNode bulkedExternalLeftOuterJoin = new LoggingNode(
<del> new BulkedExternalLeftOuterJoin(unique, shaclSailConnection, path.getQuery("?a", "?c", null), true),
<add> PlanNode bulkedExternalInnerJoin = new LoggingNode(
<add> new BulkedExternalInnerJoin(unique, shaclSailConnection, path.getQuery("?a", "?c", null), true),
<ide> "");
<ide>
<del> PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalLeftOuterJoin), "");
<add> PlanNode groupByCount = new LoggingNode(new GroupByCount(bulkedExternalInnerJoin), "");
<ide>
<ide> PlanNode directTupleFromFilter = new MaxCountFilter(groupByCount, maxCount)
<ide> .getFalseNode(UnBufferedPlanNode.class); |
|
Java | apache-2.0 | 9f249fe0075bb40ed1b4d9288f0c38a0cf7307be | 0 | Linuxea/testUnit | package url.httpclient;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HttpTest {
private String url = "https://www.ibm.com/developerworks/cn/opensource/os-httpclient/index.html";
@Test
public void getMethodTest() throws IOException {
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
int stateCode = 0;
String haha = null; //此变量忽略 只是为了做个demo
try {
haha = "abc";
stateCode = httpClient.executeMethod(getMethod);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(HttpStatus.SC_OK);
System.out.print(stateCode);
System.out.print(haha);
try(BufferedReader reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));){
String line ;
while(null != (line = reader.readLine() )){
System.out.println(line);
}
}finally {
getMethod.releaseConnection();
}
}
@Test
public void postMethodTest() {
String choiceUrl = "http://120.77.77.190:8080/choice-ERP/login";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(choiceUrl);
NameValuePair[] nameValuePairs = { new NameValuePair("username","username"),
new NameValuePair("password","admin")};
postMethod.setRequestBody(nameValuePairs);
int stateCode = 0;
try {
stateCode = httpClient.executeMethod(postMethod);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(stateCode == HttpStatus.SC_OK);
Header location = postMethod.getResponseHeader("location");
String locationVal = location.getValue();
System.out.println(locationVal);
String responseString = null;
try {
responseString = postMethod.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(responseString);
}
}
| src/main/java/url/httpclient/HttpTest.java | package url.httpclient;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HttpTest {
private String url = "https://www.ibm.com/developerworks/cn/opensource/os-httpclient/index.html";
@Test
public void getMethodTest() throws IOException {
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
int stateCode = 0;
String haha = null; //此变量忽略 只是为了做个demo
try {
haha = "abc";
stateCode = httpClient.executeMethod(getMethod);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(HttpStatus.SC_OK);
System.out.print(stateCode);
System.out.print(haha);
try(BufferedReader reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));){
String line ;
while(null != (line = reader.readLine() )){
System.out.println(line);
}
}finally {
getMethod.releaseConnection();
}
}
@Test
public void postMethodTest() {
String choiceUrl = "http://120.77.77.190:8080/choice-ERP/login";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(choiceUrl);
NameValuePair[] nameValuePairs = { new NameValuePair("username","username"),
new NameValuePair("password","Admin201706")};
postMethod.setRequestBody(nameValuePairs);
int stateCode = 0;
try {
stateCode = httpClient.executeMethod(postMethod);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(stateCode == HttpStatus.SC_OK);
Header location = postMethod.getResponseHeader("location");
String locationVal = location.getValue();
System.out.println(locationVal);
String responseString = null;
try {
responseString = postMethod.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(responseString);
}
}
| update
| src/main/java/url/httpclient/HttpTest.java | update | <ide><path>rc/main/java/url/httpclient/HttpTest.java
<ide> HttpClient httpClient = new HttpClient();
<ide> PostMethod postMethod = new PostMethod(choiceUrl);
<ide> NameValuePair[] nameValuePairs = { new NameValuePair("username","username"),
<del> new NameValuePair("password","Admin201706")};
<add> new NameValuePair("password","admin")};
<ide> postMethod.setRequestBody(nameValuePairs);
<ide> int stateCode = 0;
<ide> try { |
|
Java | apache-2.0 | d2cf75be9a7ec9b85dac005ca2622e073bf05ca8 | 0 | vroyer/elasticassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elasticassandra,vroyer/elasticassandra,vroyer/elassandra,vroyer/elassandra,strapdata/elassandra | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.monitor.jvm.JvmInfo;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Version implements Comparable<Version> {
/*
* The logic for ID is: XXYYZZAA, where XX is major version, YY is minor version, ZZ is revision, and AA is alpha/beta/rc indicator AA
* values below 25 are for alpha builder (since 5.0), and above 25 and below 50 are beta builds, and below 99 are RC builds, with 99
* indicating a release the (internal) format of the id is there so we can easily do after/before checks on the id
*/
public static final int V_5_0_0_alpha1_ID = 5000001;
public static final Version V_5_0_0_alpha1 = new Version(V_5_0_0_alpha1_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha2_ID = 5000002;
public static final Version V_5_0_0_alpha2 = new Version(V_5_0_0_alpha2_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha3_ID = 5000003;
public static final Version V_5_0_0_alpha3 = new Version(V_5_0_0_alpha3_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha4_ID = 5000004;
public static final Version V_5_0_0_alpha4 = new Version(V_5_0_0_alpha4_ID, org.apache.lucene.util.Version.LUCENE_6_1_0);
public static final int V_5_0_0_alpha5_ID = 5000005;
public static final Version V_5_0_0_alpha5 = new Version(V_5_0_0_alpha5_ID, org.apache.lucene.util.Version.LUCENE_6_1_0);
public static final int V_5_0_0_beta1_ID = 5000026;
public static final Version V_5_0_0_beta1 = new Version(V_5_0_0_beta1_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_0_rc1_ID = 5000051;
public static final Version V_5_0_0_rc1 = new Version(V_5_0_0_rc1_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_0_ID = 5000099;
public static final Version V_5_0_0 = new Version(V_5_0_0_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_1_ID = 5000199;
public static final Version V_5_0_1 = new Version(V_5_0_1_ID, org.apache.lucene.util.Version.LUCENE_6_2_1);
public static final int V_5_0_2_ID = 5000299;
public static final Version V_5_0_2 = new Version(V_5_0_2_ID, org.apache.lucene.util.Version.LUCENE_6_2_1);
// no version constant for 5.1.0 due to inadvertent release
public static final int V_5_1_1_ID = 5010199;
public static final Version V_5_1_1 = new Version(V_5_1_1_ID, org.apache.lucene.util.Version.LUCENE_6_3_0);
public static final int V_5_1_2_ID = 5010299;
public static final Version V_5_1_2 = new Version(V_5_1_2_ID, org.apache.lucene.util.Version.LUCENE_6_3_0);
public static final int V_5_2_0_ID = 5020099;
public static final Version V_5_2_0 = new Version(V_5_2_0_ID, org.apache.lucene.util.Version.LUCENE_6_4_0);
public static final int V_5_2_1_ID = 5020199;
public static final Version V_5_2_1 = new Version(V_5_2_1_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_2_2_ID = 5020299;
public static final Version V_5_2_2 = new Version(V_5_2_2_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_3_0_ID = 5030099;
public static final Version V_5_3_0 = new Version(V_5_3_0_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_3_1_ID = 5030199;
public static final Version V_5_3_1 = new Version(V_5_3_1_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_3_2_ID = 5030299;
public static final Version V_5_3_2 = new Version(V_5_3_2_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_3_3_ID = 5030399;
public static final Version V_5_3_3 = new Version(V_5_3_3_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_4_0_ID = 5040099;
public static final Version V_5_4_0 = new Version(V_5_4_0_ID, org.apache.lucene.util.Version.LUCENE_6_5_0);
public static final int V_5_4_1_ID = 5040199;
public static final Version V_5_4_1 = new Version(V_5_4_1_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_4_2_ID = 5040299;
public static final Version V_5_4_2 = new Version(V_5_4_2_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_4_3_ID = 5040399;
public static final Version V_5_4_3 = new Version(V_5_4_3_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_5_0_ID = 5050099;
public static final Version V_5_5_0 = new Version(V_5_5_0_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_1_ID = 5050199;
public static final Version V_5_5_1 = new Version(V_5_5_1_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_2_ID = 5050299;
public static final Version V_5_5_2 = new Version(V_5_5_2_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_3_ID = 5050399;
public static final Version V_5_5_3 = new Version(V_5_5_3_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_6_0_ID = 5060099;
public static final Version V_5_6_0 = new Version(V_5_6_0_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_6_1_ID = 5060199;
public static final Version V_5_6_1 = new Version(V_5_6_1_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_2_ID = 5060299;
public static final Version V_5_6_2 = new Version(V_5_6_2_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_3_ID = 5060399;
public static final Version V_5_6_3 = new Version(V_5_6_3_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_4_ID = 5060499;
public static final Version V_5_6_4 = new Version(V_5_6_4_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_5_ID = 5060599;
public static final Version V_5_6_5 = new Version(V_5_6_5_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_6_ID = 5060699;
public static final Version V_5_6_6 = new Version(V_5_6_6_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_6_0_0_alpha1_ID = 6000001;
public static final Version V_6_0_0_alpha1 = new Version(V_6_0_0_alpha1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_alpha2_ID = 6000002;
public static final Version V_6_0_0_alpha2 = new Version(V_6_0_0_alpha2_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_beta1_ID = 6000026;
public static final Version V_6_0_0_beta1 = new Version(V_6_0_0_beta1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_beta2_ID = 6000027;
public static final Version V_6_0_0_beta2 = new Version(V_6_0_0_beta2_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_rc1_ID = 6000051;
public static final Version V_6_0_0_rc1 =
new Version(V_6_0_0_rc1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_rc2_ID = 6000052;
public static final Version V_6_0_0_rc2 =
new Version(V_6_0_0_rc2_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_0_ID = 6000099;
public static final Version V_6_0_0 =
new Version(V_6_0_0_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_1_ID = 6000199;
public static final Version V_6_0_1 =
new Version(V_6_0_1_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_2_ID = 6000299;
public static final Version V_6_0_2 =
new Version(V_6_0_2_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_1_0_ID = 6010099;
public static final Version V_6_1_0 = new Version(V_6_1_0_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
public static final int V_6_1_1_ID = 6010199;
public static final Version V_6_1_1 = new Version(V_6_1_1_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
public static final int V_6_1_2_ID = 6010299;
public static final Version V_6_1_2 = new Version(V_6_1_2_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
public static final int V_6_2_0_ID = 6020099;
public static final Version V_6_2_0 = new Version(V_6_2_0_ID, org.apache.lucene.util.Version.LUCENE_7_2_0);
public static final Version CURRENT = V_6_2_0;
static {
assert CURRENT.luceneVersion.equals(org.apache.lucene.util.Version.LATEST) : "Version must be upgraded to ["
+ org.apache.lucene.util.Version.LATEST + "] is still set to [" + CURRENT.luceneVersion + "]";
}
public static Version readVersion(StreamInput in) throws IOException {
return fromId(in.readVInt());
}
public static Version fromId(int id) {
switch (id) {
case V_6_2_0_ID:
return V_6_2_0;
case V_6_1_2_ID:
return V_6_1_2;
case V_6_1_1_ID:
return V_6_1_1;
case V_6_1_0_ID:
return V_6_1_0;
case V_6_0_2_ID:
return V_6_0_2;
case V_6_0_1_ID:
return V_6_0_1;
case V_6_0_0_ID:
return V_6_0_0;
case V_6_0_0_rc2_ID:
return V_6_0_0_rc2;
case V_6_0_0_rc1_ID:
return V_6_0_0_rc1;
case V_6_0_0_beta2_ID:
return V_6_0_0_beta2;
case V_6_0_0_beta1_ID:
return V_6_0_0_beta1;
case V_6_0_0_alpha2_ID:
return V_6_0_0_alpha2;
case V_6_0_0_alpha1_ID:
return V_6_0_0_alpha1;
case V_5_6_6_ID:
return V_5_6_6;
case V_5_6_5_ID:
return V_5_6_5;
case V_5_6_4_ID:
return V_5_6_4;
case V_5_6_3_ID:
return V_5_6_3;
case V_5_6_2_ID:
return V_5_6_2;
case V_5_6_1_ID:
return V_5_6_1;
case V_5_6_0_ID:
return V_5_6_0;
case V_5_5_3_ID:
return V_5_5_3;
case V_5_5_2_ID:
return V_5_5_2;
case V_5_5_1_ID:
return V_5_5_1;
case V_5_5_0_ID:
return V_5_5_0;
case V_5_4_3_ID:
return V_5_4_3;
case V_5_4_2_ID:
return V_5_4_2;
case V_5_4_1_ID:
return V_5_4_1;
case V_5_4_0_ID:
return V_5_4_0;
case V_5_3_3_ID:
return V_5_3_3;
case V_5_3_2_ID:
return V_5_3_2;
case V_5_3_1_ID:
return V_5_3_1;
case V_5_3_0_ID:
return V_5_3_0;
case V_5_2_2_ID:
return V_5_2_2;
case V_5_2_1_ID:
return V_5_2_1;
case V_5_2_0_ID:
return V_5_2_0;
case V_5_1_2_ID:
return V_5_1_2;
case V_5_1_1_ID:
return V_5_1_1;
case V_5_0_2_ID:
return V_5_0_2;
case V_5_0_1_ID:
return V_5_0_1;
case V_5_0_0_ID:
return V_5_0_0;
case V_5_0_0_rc1_ID:
return V_5_0_0_rc1;
case V_5_0_0_beta1_ID:
return V_5_0_0_beta1;
case V_5_0_0_alpha5_ID:
return V_5_0_0_alpha5;
case V_5_0_0_alpha4_ID:
return V_5_0_0_alpha4;
case V_5_0_0_alpha3_ID:
return V_5_0_0_alpha3;
case V_5_0_0_alpha2_ID:
return V_5_0_0_alpha2;
case V_5_0_0_alpha1_ID:
return V_5_0_0_alpha1;
default:
return new Version(id, org.apache.lucene.util.Version.LATEST);
}
}
/**
* Return the {@link Version} of Elasticsearch that has been used to create an index given its settings.
*
* @throws IllegalStateException if the given index settings doesn't contain a value for the key
* {@value IndexMetaData#SETTING_VERSION_CREATED}
*/
public static Version indexCreated(Settings indexSettings) {
final Version indexVersion = indexSettings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, null);
if (indexVersion == null) {
throw new IllegalStateException(
"[" + IndexMetaData.SETTING_VERSION_CREATED + "] is not present in the index settings for index with uuid: ["
+ indexSettings.get(IndexMetaData.SETTING_INDEX_UUID) + "]");
}
return indexVersion;
}
public static void writeVersion(Version version, StreamOutput out) throws IOException {
out.writeVInt(version.id);
}
/**
* Returns the minimum version between the 2.
*/
public static Version min(Version version1, Version version2) {
return version1.id < version2.id ? version1 : version2;
}
/**
* Returns the maximum version between the 2
*/
public static Version max(Version version1, Version version2) { return version1.id > version2.id ? version1 : version2; }
/**
* Returns the version given its string representation, current version if the argument is null or empty
*/
public static Version fromString(String version) {
if (!Strings.hasLength(version)) {
return Version.CURRENT;
}
final boolean snapshot; // this is some BWC for 2.x and before indices
if (snapshot = version.endsWith("-SNAPSHOT")) {
version = version.substring(0, version.length() - 9);
}
String[] parts = version.split("[.-]");
if (parts.length < 3 || parts.length > 4) {
throw new IllegalArgumentException(
"the version needs to contain major, minor, and revision, and optionally the build: " + version);
}
try {
final int rawMajor = Integer.parseInt(parts[0]);
if (rawMajor >= 5 && snapshot) { // we don't support snapshot as part of the version here anymore
throw new IllegalArgumentException("illegal version format - snapshots are only supported until version 2.x");
}
final int betaOffset = rawMajor < 5 ? 0 : 25;
//we reverse the version id calculation based on some assumption as we can't reliably reverse the modulo
final int major = rawMajor * 1000000;
final int minor = Integer.parseInt(parts[1]) * 10000;
final int revision = Integer.parseInt(parts[2]) * 100;
int build = 99;
if (parts.length == 4) {
String buildStr = parts[3];
if (buildStr.startsWith("alpha")) {
assert rawMajor >= 5 : "major must be >= 5 but was " + major;
build = Integer.parseInt(buildStr.substring(5));
assert build < 25 : "expected a beta build but " + build + " >= 25";
} else if (buildStr.startsWith("Beta") || buildStr.startsWith("beta")) {
build = betaOffset + Integer.parseInt(buildStr.substring(4));
assert build < 50 : "expected a beta build but " + build + " >= 50";
} else if (buildStr.startsWith("RC") || buildStr.startsWith("rc")) {
build = Integer.parseInt(buildStr.substring(2)) + 50;
} else {
throw new IllegalArgumentException("unable to parse version " + version);
}
}
return fromId(major + minor + revision + build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("unable to parse version " + version, e);
}
}
public final int id;
public final byte major;
public final byte minor;
public final byte revision;
public final byte build;
public final org.apache.lucene.util.Version luceneVersion;
Version(int id, org.apache.lucene.util.Version luceneVersion) {
this.id = id;
this.major = (byte) ((id / 1000000) % 100);
this.minor = (byte) ((id / 10000) % 100);
this.revision = (byte) ((id / 100) % 100);
this.build = (byte) (id % 100);
this.luceneVersion = luceneVersion;
}
public boolean after(Version version) {
return version.id < id;
}
public boolean onOrAfter(Version version) {
return version.id <= id;
}
public boolean before(Version version) {
return version.id > id;
}
public boolean onOrBefore(Version version) {
return version.id >= id;
}
@Override
public int compareTo(Version other) {
return Integer.compare(this.id, other.id);
}
/**
* Returns the minimum compatible version based on the current
* version. Ie a node needs to have at least the return version in order
* to communicate with a node running the current version. The returned version
* is in most of the cases the smallest major version release unless the current version
* is a beta or RC release then the version itself is returned.
*/
public Version minimumCompatibilityVersion() {
if (major >= 6) {
// all major versions from 6 onwards are compatible with last minor series of the previous major
final List<Version> declaredVersions = getDeclaredVersions(getClass());
Version bwcVersion = null;
for (int i = declaredVersions.size() - 1; i >= 0; i--) {
final Version candidateVersion = declaredVersions.get(i);
if (candidateVersion.major == major - 1 && candidateVersion.isRelease() && after(candidateVersion)) {
if (bwcVersion != null && candidateVersion.minor < bwcVersion.minor) {
break;
}
bwcVersion = candidateVersion;
}
}
return bwcVersion == null ? this : bwcVersion;
}
return Version.min(this, fromId((int) major * 1000000 + 0 * 10000 + 99));
}
/**
* Returns the minimum created index version that this version supports. Indices created with lower versions
* can't be used with this version. This should also be used for file based serialization backwards compatibility ie. on serialization
* code that is used to read / write file formats like transaction logs, cluster state, and index metadata.
*/
public Version minimumIndexCompatibilityVersion() {
final int bwcMajor;
if (major == 5) {
bwcMajor = 2; // we jumped from 2 to 5
} else {
bwcMajor = major - 1;
}
final int bwcMinor = 0;
return Version.min(this, fromId(bwcMajor * 1000000 + bwcMinor * 10000 + 99));
}
/**
* Returns <code>true</code> iff both version are compatible. Otherwise <code>false</code>
*/
public boolean isCompatible(Version version) {
boolean compatible = onOrAfter(version.minimumCompatibilityVersion())
&& version.onOrAfter(minimumCompatibilityVersion());
assert compatible == false || Math.max(major, version.major) - Math.min(major, version.major) <= 1;
return compatible;
}
@SuppressForbidden(reason = "System.out.*")
public static void main(String[] args) {
System.out.println("Version: " + Version.CURRENT + ", Build: " + Build.CURRENT.shortHash() + "/" + Build.CURRENT.date() + ", JVM: "
+ JvmInfo.jvmInfo().version());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(major).append('.').append(minor).append('.').append(revision);
if (isAlpha()) {
sb.append("-alpha");
sb.append(build);
} else if (isBeta()) {
if (major >= 2) {
sb.append("-beta");
} else {
sb.append(".Beta");
}
sb.append(major < 5 ? build : build-25);
} else if (build < 99) {
if (major >= 2) {
sb.append("-rc");
} else {
sb.append(".RC");
}
sb.append(build - 50);
}
return sb.toString();
}
public static String displayVersion(final Version version, final boolean isSnapshot) {
return version + (isSnapshot ? "-SNAPSHOT" : "");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Version version = (Version) o;
if (id != version.id) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id;
}
public boolean isBeta() {
return major < 5 ? build < 50 : build >= 25 && build < 50;
}
/**
* Returns true iff this version is an alpha version
* Note: This has been introduced in elasticsearch version 5. Previous versions will never
* have an alpha version.
*/
public boolean isAlpha() {
return major < 5 ? false : build < 25;
}
public boolean isRC() {
return build > 50 && build < 99;
}
public boolean isRelease() {
return build == 99;
}
/**
* Extracts a sorted list of declared version constants from a class.
* The argument would normally be Version.class but is exposed for
* testing with other classes-containing-version-constants.
*/
public static List<Version> getDeclaredVersions(final Class<?> versionClass) {
final Field[] fields = versionClass.getFields();
final List<Version> versions = new ArrayList<>(fields.length);
for (final Field field : fields) {
final int mod = field.getModifiers();
if (false == Modifier.isStatic(mod) && Modifier.isFinal(mod) && Modifier.isPublic(mod)) {
continue;
}
if (field.getType() != Version.class) {
continue;
}
if ("CURRENT".equals(field.getName())) {
continue;
}
assert field.getName().matches("V(_\\d+)+(_(alpha|beta|rc)\\d+)?") : field.getName();
try {
versions.add(((Version) field.get(null)));
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Collections.sort(versions);
return versions;
}
}
| core/src/main/java/org/elasticsearch/Version.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.monitor.jvm.JvmInfo;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Version implements Comparable<Version> {
/*
* The logic for ID is: XXYYZZAA, where XX is major version, YY is minor version, ZZ is revision, and AA is alpha/beta/rc indicator AA
* values below 25 are for alpha builder (since 5.0), and above 25 and below 50 are beta builds, and below 99 are RC builds, with 99
* indicating a release the (internal) format of the id is there so we can easily do after/before checks on the id
*/
public static final int V_5_0_0_alpha1_ID = 5000001;
public static final Version V_5_0_0_alpha1 = new Version(V_5_0_0_alpha1_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha2_ID = 5000002;
public static final Version V_5_0_0_alpha2 = new Version(V_5_0_0_alpha2_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha3_ID = 5000003;
public static final Version V_5_0_0_alpha3 = new Version(V_5_0_0_alpha3_ID, org.apache.lucene.util.Version.LUCENE_6_0_0);
public static final int V_5_0_0_alpha4_ID = 5000004;
public static final Version V_5_0_0_alpha4 = new Version(V_5_0_0_alpha4_ID, org.apache.lucene.util.Version.LUCENE_6_1_0);
public static final int V_5_0_0_alpha5_ID = 5000005;
public static final Version V_5_0_0_alpha5 = new Version(V_5_0_0_alpha5_ID, org.apache.lucene.util.Version.LUCENE_6_1_0);
public static final int V_5_0_0_beta1_ID = 5000026;
public static final Version V_5_0_0_beta1 = new Version(V_5_0_0_beta1_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_0_rc1_ID = 5000051;
public static final Version V_5_0_0_rc1 = new Version(V_5_0_0_rc1_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_0_ID = 5000099;
public static final Version V_5_0_0 = new Version(V_5_0_0_ID, org.apache.lucene.util.Version.LUCENE_6_2_0);
public static final int V_5_0_1_ID = 5000199;
public static final Version V_5_0_1 = new Version(V_5_0_1_ID, org.apache.lucene.util.Version.LUCENE_6_2_1);
public static final int V_5_0_2_ID = 5000299;
public static final Version V_5_0_2 = new Version(V_5_0_2_ID, org.apache.lucene.util.Version.LUCENE_6_2_1);
// no version constant for 5.1.0 due to inadvertent release
public static final int V_5_1_1_ID = 5010199;
public static final Version V_5_1_1 = new Version(V_5_1_1_ID, org.apache.lucene.util.Version.LUCENE_6_3_0);
public static final int V_5_1_2_ID = 5010299;
public static final Version V_5_1_2 = new Version(V_5_1_2_ID, org.apache.lucene.util.Version.LUCENE_6_3_0);
public static final int V_5_2_0_ID = 5020099;
public static final Version V_5_2_0 = new Version(V_5_2_0_ID, org.apache.lucene.util.Version.LUCENE_6_4_0);
public static final int V_5_2_1_ID = 5020199;
public static final Version V_5_2_1 = new Version(V_5_2_1_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_2_2_ID = 5020299;
public static final Version V_5_2_2 = new Version(V_5_2_2_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_3_0_ID = 5030099;
public static final Version V_5_3_0 = new Version(V_5_3_0_ID, org.apache.lucene.util.Version.LUCENE_6_4_1);
public static final int V_5_3_1_ID = 5030199;
public static final Version V_5_3_1 = new Version(V_5_3_1_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_3_2_ID = 5030299;
public static final Version V_5_3_2 = new Version(V_5_3_2_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_3_3_ID = 5030399;
public static final Version V_5_3_3 = new Version(V_5_3_3_ID, org.apache.lucene.util.Version.LUCENE_6_4_2);
public static final int V_5_4_0_ID = 5040099;
public static final Version V_5_4_0 = new Version(V_5_4_0_ID, org.apache.lucene.util.Version.LUCENE_6_5_0);
public static final int V_5_4_1_ID = 5040199;
public static final Version V_5_4_1 = new Version(V_5_4_1_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_4_2_ID = 5040299;
public static final Version V_5_4_2 = new Version(V_5_4_2_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_4_3_ID = 5040399;
public static final Version V_5_4_3 = new Version(V_5_4_3_ID, org.apache.lucene.util.Version.LUCENE_6_5_1);
public static final int V_5_5_0_ID = 5050099;
public static final Version V_5_5_0 = new Version(V_5_5_0_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_1_ID = 5050199;
public static final Version V_5_5_1 = new Version(V_5_5_1_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_2_ID = 5050299;
public static final Version V_5_5_2 = new Version(V_5_5_2_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_5_3_ID = 5050399;
public static final Version V_5_5_3 = new Version(V_5_5_3_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_6_0_ID = 5060099;
public static final Version V_5_6_0 = new Version(V_5_6_0_ID, org.apache.lucene.util.Version.LUCENE_6_6_0);
public static final int V_5_6_1_ID = 5060199;
public static final Version V_5_6_1 = new Version(V_5_6_1_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_2_ID = 5060299;
public static final Version V_5_6_2 = new Version(V_5_6_2_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_3_ID = 5060399;
public static final Version V_5_6_3 = new Version(V_5_6_3_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_4_ID = 5060499;
public static final Version V_5_6_4 = new Version(V_5_6_4_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_5_ID = 5060599;
public static final Version V_5_6_5 = new Version(V_5_6_5_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_5_6_6_ID = 5060699;
public static final Version V_5_6_6 = new Version(V_5_6_6_ID, org.apache.lucene.util.Version.LUCENE_6_6_1);
public static final int V_6_0_0_alpha1_ID = 6000001;
public static final Version V_6_0_0_alpha1 = new Version(V_6_0_0_alpha1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_alpha2_ID = 6000002;
public static final Version V_6_0_0_alpha2 = new Version(V_6_0_0_alpha2_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_beta1_ID = 6000026;
public static final Version V_6_0_0_beta1 = new Version(V_6_0_0_beta1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_beta2_ID = 6000027;
public static final Version V_6_0_0_beta2 = new Version(V_6_0_0_beta2_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_rc1_ID = 6000051;
public static final Version V_6_0_0_rc1 =
new Version(V_6_0_0_rc1_ID, org.apache.lucene.util.Version.LUCENE_7_0_0);
public static final int V_6_0_0_rc2_ID = 6000052;
public static final Version V_6_0_0_rc2 =
new Version(V_6_0_0_rc2_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_0_ID = 6000099;
public static final Version V_6_0_0 =
new Version(V_6_0_0_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_1_ID = 6000199;
public static final Version V_6_0_1 =
new Version(V_6_0_1_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_0_2_ID = 6000299;
public static final Version V_6_0_2 =
new Version(V_6_0_2_ID, org.apache.lucene.util.Version.LUCENE_7_0_1);
public static final int V_6_1_0_ID = 6010099;
public static final Version V_6_1_0 = new Version(V_6_1_0_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
public static final int V_6_1_1_ID = 6010199;
public static final Version V_6_1_1 = new Version(V_6_1_1_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
public static final int V_6_2_0_ID = 6020099;
public static final Version V_6_2_0 = new Version(V_6_2_0_ID, org.apache.lucene.util.Version.LUCENE_7_2_0);
public static final Version CURRENT = V_6_2_0;
static {
assert CURRENT.luceneVersion.equals(org.apache.lucene.util.Version.LATEST) : "Version must be upgraded to ["
+ org.apache.lucene.util.Version.LATEST + "] is still set to [" + CURRENT.luceneVersion + "]";
}
public static Version readVersion(StreamInput in) throws IOException {
return fromId(in.readVInt());
}
public static Version fromId(int id) {
switch (id) {
case V_6_2_0_ID:
return V_6_2_0;
case V_6_1_1_ID:
return V_6_1_1;
case V_6_1_0_ID:
return V_6_1_0;
case V_6_0_2_ID:
return V_6_0_2;
case V_6_0_1_ID:
return V_6_0_1;
case V_6_0_0_ID:
return V_6_0_0;
case V_6_0_0_rc2_ID:
return V_6_0_0_rc2;
case V_6_0_0_rc1_ID:
return V_6_0_0_rc1;
case V_6_0_0_beta2_ID:
return V_6_0_0_beta2;
case V_6_0_0_beta1_ID:
return V_6_0_0_beta1;
case V_6_0_0_alpha2_ID:
return V_6_0_0_alpha2;
case V_6_0_0_alpha1_ID:
return V_6_0_0_alpha1;
case V_5_6_6_ID:
return V_5_6_6;
case V_5_6_5_ID:
return V_5_6_5;
case V_5_6_4_ID:
return V_5_6_4;
case V_5_6_3_ID:
return V_5_6_3;
case V_5_6_2_ID:
return V_5_6_2;
case V_5_6_1_ID:
return V_5_6_1;
case V_5_6_0_ID:
return V_5_6_0;
case V_5_5_3_ID:
return V_5_5_3;
case V_5_5_2_ID:
return V_5_5_2;
case V_5_5_1_ID:
return V_5_5_1;
case V_5_5_0_ID:
return V_5_5_0;
case V_5_4_3_ID:
return V_5_4_3;
case V_5_4_2_ID:
return V_5_4_2;
case V_5_4_1_ID:
return V_5_4_1;
case V_5_4_0_ID:
return V_5_4_0;
case V_5_3_3_ID:
return V_5_3_3;
case V_5_3_2_ID:
return V_5_3_2;
case V_5_3_1_ID:
return V_5_3_1;
case V_5_3_0_ID:
return V_5_3_0;
case V_5_2_2_ID:
return V_5_2_2;
case V_5_2_1_ID:
return V_5_2_1;
case V_5_2_0_ID:
return V_5_2_0;
case V_5_1_2_ID:
return V_5_1_2;
case V_5_1_1_ID:
return V_5_1_1;
case V_5_0_2_ID:
return V_5_0_2;
case V_5_0_1_ID:
return V_5_0_1;
case V_5_0_0_ID:
return V_5_0_0;
case V_5_0_0_rc1_ID:
return V_5_0_0_rc1;
case V_5_0_0_beta1_ID:
return V_5_0_0_beta1;
case V_5_0_0_alpha5_ID:
return V_5_0_0_alpha5;
case V_5_0_0_alpha4_ID:
return V_5_0_0_alpha4;
case V_5_0_0_alpha3_ID:
return V_5_0_0_alpha3;
case V_5_0_0_alpha2_ID:
return V_5_0_0_alpha2;
case V_5_0_0_alpha1_ID:
return V_5_0_0_alpha1;
default:
return new Version(id, org.apache.lucene.util.Version.LATEST);
}
}
/**
* Return the {@link Version} of Elasticsearch that has been used to create an index given its settings.
*
* @throws IllegalStateException if the given index settings doesn't contain a value for the key
* {@value IndexMetaData#SETTING_VERSION_CREATED}
*/
public static Version indexCreated(Settings indexSettings) {
final Version indexVersion = indexSettings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, null);
if (indexVersion == null) {
throw new IllegalStateException(
"[" + IndexMetaData.SETTING_VERSION_CREATED + "] is not present in the index settings for index with uuid: ["
+ indexSettings.get(IndexMetaData.SETTING_INDEX_UUID) + "]");
}
return indexVersion;
}
public static void writeVersion(Version version, StreamOutput out) throws IOException {
out.writeVInt(version.id);
}
/**
* Returns the minimum version between the 2.
*/
public static Version min(Version version1, Version version2) {
return version1.id < version2.id ? version1 : version2;
}
/**
* Returns the maximum version between the 2
*/
public static Version max(Version version1, Version version2) { return version1.id > version2.id ? version1 : version2; }
/**
* Returns the version given its string representation, current version if the argument is null or empty
*/
public static Version fromString(String version) {
if (!Strings.hasLength(version)) {
return Version.CURRENT;
}
final boolean snapshot; // this is some BWC for 2.x and before indices
if (snapshot = version.endsWith("-SNAPSHOT")) {
version = version.substring(0, version.length() - 9);
}
String[] parts = version.split("[.-]");
if (parts.length < 3 || parts.length > 4) {
throw new IllegalArgumentException(
"the version needs to contain major, minor, and revision, and optionally the build: " + version);
}
try {
final int rawMajor = Integer.parseInt(parts[0]);
if (rawMajor >= 5 && snapshot) { // we don't support snapshot as part of the version here anymore
throw new IllegalArgumentException("illegal version format - snapshots are only supported until version 2.x");
}
final int betaOffset = rawMajor < 5 ? 0 : 25;
//we reverse the version id calculation based on some assumption as we can't reliably reverse the modulo
final int major = rawMajor * 1000000;
final int minor = Integer.parseInt(parts[1]) * 10000;
final int revision = Integer.parseInt(parts[2]) * 100;
int build = 99;
if (parts.length == 4) {
String buildStr = parts[3];
if (buildStr.startsWith("alpha")) {
assert rawMajor >= 5 : "major must be >= 5 but was " + major;
build = Integer.parseInt(buildStr.substring(5));
assert build < 25 : "expected a beta build but " + build + " >= 25";
} else if (buildStr.startsWith("Beta") || buildStr.startsWith("beta")) {
build = betaOffset + Integer.parseInt(buildStr.substring(4));
assert build < 50 : "expected a beta build but " + build + " >= 50";
} else if (buildStr.startsWith("RC") || buildStr.startsWith("rc")) {
build = Integer.parseInt(buildStr.substring(2)) + 50;
} else {
throw new IllegalArgumentException("unable to parse version " + version);
}
}
return fromId(major + minor + revision + build);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("unable to parse version " + version, e);
}
}
public final int id;
public final byte major;
public final byte minor;
public final byte revision;
public final byte build;
public final org.apache.lucene.util.Version luceneVersion;
Version(int id, org.apache.lucene.util.Version luceneVersion) {
this.id = id;
this.major = (byte) ((id / 1000000) % 100);
this.minor = (byte) ((id / 10000) % 100);
this.revision = (byte) ((id / 100) % 100);
this.build = (byte) (id % 100);
this.luceneVersion = luceneVersion;
}
public boolean after(Version version) {
return version.id < id;
}
public boolean onOrAfter(Version version) {
return version.id <= id;
}
public boolean before(Version version) {
return version.id > id;
}
public boolean onOrBefore(Version version) {
return version.id >= id;
}
@Override
public int compareTo(Version other) {
return Integer.compare(this.id, other.id);
}
/**
* Returns the minimum compatible version based on the current
* version. Ie a node needs to have at least the return version in order
* to communicate with a node running the current version. The returned version
* is in most of the cases the smallest major version release unless the current version
* is a beta or RC release then the version itself is returned.
*/
public Version minimumCompatibilityVersion() {
if (major >= 6) {
// all major versions from 6 onwards are compatible with last minor series of the previous major
final List<Version> declaredVersions = getDeclaredVersions(getClass());
Version bwcVersion = null;
for (int i = declaredVersions.size() - 1; i >= 0; i--) {
final Version candidateVersion = declaredVersions.get(i);
if (candidateVersion.major == major - 1 && candidateVersion.isRelease() && after(candidateVersion)) {
if (bwcVersion != null && candidateVersion.minor < bwcVersion.minor) {
break;
}
bwcVersion = candidateVersion;
}
}
return bwcVersion == null ? this : bwcVersion;
}
return Version.min(this, fromId((int) major * 1000000 + 0 * 10000 + 99));
}
/**
* Returns the minimum created index version that this version supports. Indices created with lower versions
* can't be used with this version. This should also be used for file based serialization backwards compatibility ie. on serialization
* code that is used to read / write file formats like transaction logs, cluster state, and index metadata.
*/
public Version minimumIndexCompatibilityVersion() {
final int bwcMajor;
if (major == 5) {
bwcMajor = 2; // we jumped from 2 to 5
} else {
bwcMajor = major - 1;
}
final int bwcMinor = 0;
return Version.min(this, fromId(bwcMajor * 1000000 + bwcMinor * 10000 + 99));
}
/**
* Returns <code>true</code> iff both version are compatible. Otherwise <code>false</code>
*/
public boolean isCompatible(Version version) {
boolean compatible = onOrAfter(version.minimumCompatibilityVersion())
&& version.onOrAfter(minimumCompatibilityVersion());
assert compatible == false || Math.max(major, version.major) - Math.min(major, version.major) <= 1;
return compatible;
}
@SuppressForbidden(reason = "System.out.*")
public static void main(String[] args) {
System.out.println("Version: " + Version.CURRENT + ", Build: " + Build.CURRENT.shortHash() + "/" + Build.CURRENT.date() + ", JVM: "
+ JvmInfo.jvmInfo().version());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(major).append('.').append(minor).append('.').append(revision);
if (isAlpha()) {
sb.append("-alpha");
sb.append(build);
} else if (isBeta()) {
if (major >= 2) {
sb.append("-beta");
} else {
sb.append(".Beta");
}
sb.append(major < 5 ? build : build-25);
} else if (build < 99) {
if (major >= 2) {
sb.append("-rc");
} else {
sb.append(".RC");
}
sb.append(build - 50);
}
return sb.toString();
}
public static String displayVersion(final Version version, final boolean isSnapshot) {
return version + (isSnapshot ? "-SNAPSHOT" : "");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Version version = (Version) o;
if (id != version.id) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id;
}
public boolean isBeta() {
return major < 5 ? build < 50 : build >= 25 && build < 50;
}
/**
* Returns true iff this version is an alpha version
* Note: This has been introduced in elasticsearch version 5. Previous versions will never
* have an alpha version.
*/
public boolean isAlpha() {
return major < 5 ? false : build < 25;
}
public boolean isRC() {
return build > 50 && build < 99;
}
public boolean isRelease() {
return build == 99;
}
/**
* Extracts a sorted list of declared version constants from a class.
* The argument would normally be Version.class but is exposed for
* testing with other classes-containing-version-constants.
*/
public static List<Version> getDeclaredVersions(final Class<?> versionClass) {
final Field[] fields = versionClass.getFields();
final List<Version> versions = new ArrayList<>(fields.length);
for (final Field field : fields) {
final int mod = field.getModifiers();
if (false == Modifier.isStatic(mod) && Modifier.isFinal(mod) && Modifier.isPublic(mod)) {
continue;
}
if (field.getType() != Version.class) {
continue;
}
if ("CURRENT".equals(field.getName())) {
continue;
}
assert field.getName().matches("V(_\\d+)+(_(alpha|beta|rc)\\d+)?") : field.getName();
try {
versions.add(((Version) field.get(null)));
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Collections.sort(versions);
return versions;
}
}
| Add unreleased v6.1.2 version
| core/src/main/java/org/elasticsearch/Version.java | Add unreleased v6.1.2 version | <ide><path>ore/src/main/java/org/elasticsearch/Version.java
<ide> public static final Version V_6_1_0 = new Version(V_6_1_0_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
<ide> public static final int V_6_1_1_ID = 6010199;
<ide> public static final Version V_6_1_1 = new Version(V_6_1_1_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
<add> public static final int V_6_1_2_ID = 6010299;
<add> public static final Version V_6_1_2 = new Version(V_6_1_2_ID, org.apache.lucene.util.Version.LUCENE_7_1_0);
<ide> public static final int V_6_2_0_ID = 6020099;
<ide> public static final Version V_6_2_0 = new Version(V_6_2_0_ID, org.apache.lucene.util.Version.LUCENE_7_2_0);
<ide> public static final Version CURRENT = V_6_2_0;
<ide> switch (id) {
<ide> case V_6_2_0_ID:
<ide> return V_6_2_0;
<add> case V_6_1_2_ID:
<add> return V_6_1_2;
<ide> case V_6_1_1_ID:
<ide> return V_6_1_1;
<ide> case V_6_1_0_ID: |
|
Java | apache-2.0 | 6fd989db16f49ef0d7330f3ba3dc4b2cf7023e91 | 0 | getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,lqch14102/lantern | package org.lantern;
import static org.junit.Assert.*;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.VCard;
import org.junit.BeforeClass;
import org.junit.Test;
import org.lantern.oauth.LanternSaslGoogleOAuth2Mechanism;
import org.lantern.state.Model;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test for Lantern utilities.
*/
//@Ignore
public class LanternUtilsTest {
private static Logger LOG = LoggerFactory.getLogger(LanternUtilsTest.class);
@BeforeClass
public static void setup() throws Exception {
LOG.debug("Setting up LanternUtilsTests...");
SASLAuthentication.registerSASLMechanism("X-OAUTH2",
LanternSaslGoogleOAuth2Mechanism.class);
TestUtils.load(true);
System.setProperty("javax.net.debug", "ssl");
}
@Test
public void testGetTargetForPath() throws Exception {
final Model model = TestUtils.getModel();
assertFalse(model.isLaunchd());
Object obj = LanternUtils.getTargetForPath(model,
"/version/installed/major");
assertEquals(model.getVersion().getInstalled(), obj);
obj = LanternUtils.getTargetForPath(model, "/settings/mode");
assertEquals(model.getSettings(), obj);
}
@Test
public void testIsJid() throws Exception {
String id = "[email protected]";
assertTrue(!LanternUtils.isAnonymizedGoogleTalkAddress(id));
id = "[email protected]";
assertTrue(!LanternUtils.isAnonymizedGoogleTalkAddress(id));
id = "[email protected]";
assertTrue(LanternUtils.isAnonymizedGoogleTalkAddress(id));
}
@Test
public void testVCard() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing vcard");
final XMPPConnection conn = TestUtils.xmppConnection();
assertTrue(conn.isAuthenticated());
final VCard vcard = XmppUtils.getVCard(conn, TestUtils.getUserName());
assertTrue(vcard != null);
final String full = vcard.getField("FN");
assertTrue(StringUtils.isNotBlank(full));
return null;
}
});
}
@Test
public void testToTypes() throws Exception {
assertEquals(String.class, LanternUtils.toTyped("33fga").getClass());
assertEquals(Integer.class, LanternUtils.toTyped("21314").getClass());
assertEquals(String.class, LanternUtils.toTyped("2a3b").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("true").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("false").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("on").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("off").getClass());
assertEquals(String.class, LanternUtils.toTyped("2222a").getClass());
}
@Test
public void testReplaceInFile() throws Exception {
final File temp = File.createTempFile(String.valueOf(hashCode()), "test");
temp.deleteOnExit();
final String data = "blah blah blah <true/> blah blah";
FileUtils.write(temp, data, "UTF-8");
LanternUtils.replaceInFile(temp, "<true/>", "<false/>");
final String newFile = FileUtils.readFileToString(temp, "UTF-8");
assertEquals("blah blah blah <false/> blah blah", newFile);
}
@Test
public void testGoogleStunServers() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing STUN servers...");
final XMPPConnection conn = TestUtils.xmppConnection();
final Collection<InetSocketAddress> servers =
XmppUtils.googleStunServers(conn);
LOG.debug("Retrieved {} STUN servers", servers.size());
assertTrue(!servers.isEmpty());
final Roster roster = conn.getRoster();
roster.addRosterListener(new RosterListener() {
@Override
public void entriesDeleted(final Collection<String> addresses) {
LOG.debug("Entries deleted");
}
@Override
public void entriesUpdated(final Collection<String> addresses) {
LOG.debug("Entries updated: {}", addresses);
}
@Override
public void presenceChanged(final Presence presence) {
LOG.debug("Processing presence changed: {}", presence);
}
@Override
public void entriesAdded(final Collection<String> addresses) {
LOG.debug("Entries added: "+addresses);
for (final String address : addresses) {
//presences.add(address);
}
}
});
return null;
}
});
}
@Test
public void testOtrMode() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing OTR mode...");
//System.setProperty("javax.net.debug", "ssl");
/*
final File certsFile = new File("src/test/resources/cacerts");
if (!certsFile.isFile()) {
throw new IllegalStateException("COULD NOT FIND CACERTS!!");
}
System.setProperty("javax.net.ssl.trustStore", certsFile.getCanonicalPath());
*/
final XMPPConnection conn = TestUtils.xmppConnection();
//System.setProperty("javax.net.ssl.trustStore", certsFile.getCanonicalPath());
final String activateResponse = LanternUtils.activateOtr(conn).toXML();
LOG.debug("Got response: {}", activateResponse);
final String allOtr = XmppUtils.getOtr(conn).toXML();
LOG.debug("All OTR: {}", allOtr);
assertTrue("Unexpected response: "+allOtr,
allOtr.contains("google:nosave"));
return null;
}
});
}
@Test
public void testToHttpsCandidates() throws Exception {
Collection<String> candidates =
LanternUtils.toHttpsCandidates("http://www.google.com");
assertTrue(candidates.contains("www.google.com"));
assertTrue(candidates.contains("*.google.com"));
assertTrue(candidates.contains("www.*.com"));
assertTrue(candidates.contains("www.google.*"));
assertEquals(4, candidates.size());
candidates =
LanternUtils.toHttpsCandidates("http://test.www.google.com");
assertTrue(candidates.contains("test.www.google.com"));
assertTrue(candidates.contains("*.www.google.com"));
assertTrue(candidates.contains("*.google.com"));
assertTrue(candidates.contains("test.*.google.com"));
assertTrue(candidates.contains("test.www.*.com"));
assertTrue(candidates.contains("test.www.google.*"));
assertEquals(6, candidates.size());
//assertTrue(candidates.contains("*.com"));
//assertTrue(candidates.contains("*"));
}
}
| src/test/java/org/lantern/LanternUtilsTest.java | package org.lantern;
import static org.junit.Assert.*;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.VCard;
import org.junit.BeforeClass;
import org.junit.Test;
import org.lantern.oauth.LanternSaslGoogleOAuth2Mechanism;
import org.lantern.state.Model;
import org.littleshoot.commom.xmpp.XmppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test for Lantern utilities.
*/
//@Ignore
public class LanternUtilsTest {
private static Logger LOG = LoggerFactory.getLogger(LanternUtilsTest.class);
@BeforeClass
public static void setup() throws Exception {
LOG.debug("Setting up LanternUtilsTests...");
SASLAuthentication.registerSASLMechanism("X-OAUTH2",
LanternSaslGoogleOAuth2Mechanism.class);
TestUtils.load(true);
System.setProperty("javax.net.debug", "ssl");
}
@Test
public void testGetTargetForPath() throws Exception {
final Model model = TestUtils.getModel();
assertFalse(model.isLaunchd());
Object obj = LanternUtils.getTargetForPath(model,
"/version/installed/major");
assertEquals(model.getVersion().getInstalled(), obj);
obj = LanternUtils.getTargetForPath(model, "/settings/mode");
assertEquals(model.getSettings(), obj);
}
@Test
public void testIsJid() throws Exception {
String id = "[email protected]";
assertTrue(!LanternUtils.isAnonymizedGoogleTalkAddress(id));
id = "[email protected]";
assertTrue(!LanternUtils.isAnonymizedGoogleTalkAddress(id));
id = "[email protected]";
assertTrue(LanternUtils.isAnonymizedGoogleTalkAddress(id));
}
@Test
public void testVCard() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing vcard");
final XMPPConnection conn = TestUtils.xmppConnection();
assertTrue(conn.isAuthenticated());
final VCard vcard = XmppUtils.getVCard(conn, TestUtils.getUserName());
assertTrue(vcard != null);
final String full = vcard.getField("FN");
assertTrue(StringUtils.isNotBlank(full));
return null;
}
});
}
@Test
public void testToTypes() throws Exception {
assertEquals(String.class, LanternUtils.toTyped("33fga").getClass());
assertEquals(Integer.class, LanternUtils.toTyped("21314").getClass());
assertEquals(String.class, LanternUtils.toTyped("2a3b").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("true").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("false").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("on").getClass());
assertEquals(Boolean.class, LanternUtils.toTyped("off").getClass());
assertEquals(String.class, LanternUtils.toTyped("2222a").getClass());
}
@Test
public void testReplaceInFile() throws Exception {
final File temp = File.createTempFile(String.valueOf(hashCode()), "test");
temp.deleteOnExit();
final String data = "blah blah blah <true/> blah blah";
FileUtils.write(temp, data, "UTF-8");
LanternUtils.replaceInFile(temp, "<true/>", "<false/>");
final String newFile = FileUtils.readFileToString(temp, "UTF-8");
assertEquals("blah blah blah <false/> blah blah", newFile);
}
@Test
public void testInstallPolicyFiles() throws Exception {
String home = System.getProperty("java.home");
try {
File tmp = new File(System.getProperty("java.io.tmpdir"));
File fakeJRE = new File(tmp, "fakejre");
File security = new File(fakeJRE, "lib/security");
if (!security.isDirectory() && !security.mkdirs()) {
fail("Could not make directories...");
return;
}
File export = new File(security, "US_export_policy.jar");
FileUtils.write(export, "test", "UTF-8");
File local = new File(security, "local_policy.jar");
FileUtils.write(local, "test", "UTF-8");
System.setProperty("java.home", fakeJRE.toString());
LanternUtils.installPolicyFiles();
byte[] export_read = FileUtils.readFileToByteArray(export);
//jars are zips and so always start with PK
final char first = (char)export_read[0];
assertEquals("Expected 'P' but was '"+first+"'", 'P', (char)export_read[0]);
byte[] local_read = FileUtils.readFileToByteArray(export);
assertEquals('P', local_read[0]);
} finally {
System.setProperty("java.home", home);
}
}
@Test
public void testGoogleStunServers() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing STUN servers...");
final XMPPConnection conn = TestUtils.xmppConnection();
final Collection<InetSocketAddress> servers =
XmppUtils.googleStunServers(conn);
LOG.debug("Retrieved {} STUN servers", servers.size());
assertTrue(!servers.isEmpty());
final Roster roster = conn.getRoster();
roster.addRosterListener(new RosterListener() {
@Override
public void entriesDeleted(final Collection<String> addresses) {
LOG.debug("Entries deleted");
}
@Override
public void entriesUpdated(final Collection<String> addresses) {
LOG.debug("Entries updated: {}", addresses);
}
@Override
public void presenceChanged(final Presence presence) {
LOG.debug("Processing presence changed: {}", presence);
}
@Override
public void entriesAdded(final Collection<String> addresses) {
LOG.debug("Entries added: "+addresses);
for (final String address : addresses) {
//presences.add(address);
}
}
});
return null;
}
});
}
@Test
public void testOtrMode() throws Exception {
TestingUtils.doWithWithGetModeProxy(new Callable<Void>() {
@Override
public Void call() throws Exception {
LOG.debug(System.getProperty("javax.net.ssl.trustStore")+" Testing OTR mode...");
//System.setProperty("javax.net.debug", "ssl");
/*
final File certsFile = new File("src/test/resources/cacerts");
if (!certsFile.isFile()) {
throw new IllegalStateException("COULD NOT FIND CACERTS!!");
}
System.setProperty("javax.net.ssl.trustStore", certsFile.getCanonicalPath());
*/
final XMPPConnection conn = TestUtils.xmppConnection();
//System.setProperty("javax.net.ssl.trustStore", certsFile.getCanonicalPath());
final String activateResponse = LanternUtils.activateOtr(conn).toXML();
LOG.debug("Got response: {}", activateResponse);
final String allOtr = XmppUtils.getOtr(conn).toXML();
LOG.debug("All OTR: {}", allOtr);
assertTrue("Unexpected response: "+allOtr,
allOtr.contains("google:nosave"));
return null;
}
});
}
@Test
public void testToHttpsCandidates() throws Exception {
Collection<String> candidates =
LanternUtils.toHttpsCandidates("http://www.google.com");
assertTrue(candidates.contains("www.google.com"));
assertTrue(candidates.contains("*.google.com"));
assertTrue(candidates.contains("www.*.com"));
assertTrue(candidates.contains("www.google.*"));
assertEquals(4, candidates.size());
candidates =
LanternUtils.toHttpsCandidates("http://test.www.google.com");
assertTrue(candidates.contains("test.www.google.com"));
assertTrue(candidates.contains("*.www.google.com"));
assertTrue(candidates.contains("*.google.com"));
assertTrue(candidates.contains("test.*.google.com"));
assertTrue(candidates.contains("test.www.*.com"));
assertTrue(candidates.contains("test.www.google.*"));
assertEquals(6, candidates.size());
//assertTrue(candidates.contains("*.com"));
//assertTrue(candidates.contains("*"));
}
}
| removed unlimited strength test
| src/test/java/org/lantern/LanternUtilsTest.java | removed unlimited strength test | <ide><path>rc/test/java/org/lantern/LanternUtilsTest.java
<ide> LanternUtils.replaceInFile(temp, "<true/>", "<false/>");
<ide> final String newFile = FileUtils.readFileToString(temp, "UTF-8");
<ide> assertEquals("blah blah blah <false/> blah blah", newFile);
<del> }
<del>
<del>
<del> @Test
<del> public void testInstallPolicyFiles() throws Exception {
<del> String home = System.getProperty("java.home");
<del> try {
<del> File tmp = new File(System.getProperty("java.io.tmpdir"));
<del> File fakeJRE = new File(tmp, "fakejre");
<del> File security = new File(fakeJRE, "lib/security");
<del> if (!security.isDirectory() && !security.mkdirs()) {
<del> fail("Could not make directories...");
<del> return;
<del> }
<del>
<del> File export = new File(security, "US_export_policy.jar");
<del> FileUtils.write(export, "test", "UTF-8");
<del>
<del> File local = new File(security, "local_policy.jar");
<del> FileUtils.write(local, "test", "UTF-8");
<del>
<del> System.setProperty("java.home", fakeJRE.toString());
<del> LanternUtils.installPolicyFiles();
<del>
<del> byte[] export_read = FileUtils.readFileToByteArray(export);
<del> //jars are zips and so always start with PK
<del> final char first = (char)export_read[0];
<del>
<del> assertEquals("Expected 'P' but was '"+first+"'", 'P', (char)export_read[0]);
<del>
<del> byte[] local_read = FileUtils.readFileToByteArray(export);
<del> assertEquals('P', local_read[0]);
<del>
<del> } finally {
<del> System.setProperty("java.home", home);
<del> }
<ide> }
<ide>
<ide> @Test |
|
JavaScript | mit | 5e82667b9d76a156741ccc36faf0ac24dabd9359 | 0 | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 | $(document).ready(function() {
// Defining all the navs on the frontpage
var navs = {
'#events': $('#events').offset().top,
'#articles': $('#articles').offset().top,
'#about': $('#about').offset().top,
'#business': $('#business').offset().top,
'#offline': $('#offline').offset().top
};
// On scroll, loop the navs and swap active (if it needs to)
function scrollspy() {
var current = $(window).scrollTop();
for (nav in navs) {
var diff = current - navs[nav];
if (diff > -20) {
$(".top-menu-link a.active").removeClass('active');
$(".nav a[href='/"+nav+"']").addClass('active');
}
}
}
// Clicking the links in the topnav
$('.nav a').on('click',function(e) {
e.preventDefault();
var $that = $(this);
var jumpto_section = $that.data('section');
if (typeof jumpto_section !== 'undefined') {
var top_position = navs['#'+jumpto_section];
$('html, body').animate({scrollTop: top_position}, 250);
}
});
// TODO: heavy shit? Find a reliable way to setnavs instead of doing it fucking all the time.
$(window).scroll(scrollspy);
// On load highlight the current menu-item if an anchor is represented
scrollspy();
});
| static/js/scroller.js | $(document).ready(function() {
function setnavs() {
navs = {
'#events': jQuery('#events').offset().top - 50,
'#articles': jQuery('#articles').offset().top - 50,
'#about': jQuery('#about').offset().top - 50,
'#business': jQuery('#business').offset().top - 50,
'#offline': jQuery('#offline').offset().top - 50
};
return navs;
}
function setactive() {
$('a[href="/#events"]').addClass('active');
}
setactive();
var navs = setnavs();
function scrolltothis(from, to) {
$("a[href='/"+from+"']").click(function(event) {
event.preventDefault();
var topPosition = jQuery(to).offset().top - 50; // See body margin
jQuery('html, body').animate({scrollTop:topPosition}, 250);
});
}
for (nav in navs) {
scrolltothis(nav, nav)
};
function scrollspy() {
var current = $(window).scrollTop();
for (nav in navs) {
var diff = current - navs[nav];
if (diff > -20) {
$(".top-menu-link a").removeClass('active');
$("a[href='/"+nav+"']").addClass('active');
}
}
}
// TODO: heavy shit? Find a reliable way to setnavs instead of doing it fucking all the time.
$(window).scroll(function() {
navs = setnavs();
scrollspy();
});
});
| Attempt to clean up the scrolling-code
| static/js/scroller.js | Attempt to clean up the scrolling-code | <ide><path>tatic/js/scroller.js
<ide> $(document).ready(function() {
<del>
<del> function setnavs() {
<del> navs = {
<del> '#events': jQuery('#events').offset().top - 50,
<del> '#articles': jQuery('#articles').offset().top - 50,
<del> '#about': jQuery('#about').offset().top - 50,
<del> '#business': jQuery('#business').offset().top - 50,
<del> '#offline': jQuery('#offline').offset().top - 50
<del> };
<del> return navs;
<del> }
<del> function setactive() {
<del> $('a[href="/#events"]').addClass('active');
<del> }
<del> setactive();
<del>
<del> var navs = setnavs();
<del>
<del> function scrolltothis(from, to) {
<del> $("a[href='/"+from+"']").click(function(event) {
<del> event.preventDefault();
<del> var topPosition = jQuery(to).offset().top - 50; // See body margin
<del> jQuery('html, body').animate({scrollTop:topPosition}, 250);
<del> });
<del> }
<del>
<del> for (nav in navs) {
<del> scrolltothis(nav, nav)
<add> // Defining all the navs on the frontpage
<add> var navs = {
<add> '#events': $('#events').offset().top,
<add> '#articles': $('#articles').offset().top,
<add> '#about': $('#about').offset().top,
<add> '#business': $('#business').offset().top,
<add> '#offline': $('#offline').offset().top
<ide> };
<del>
<add>
<add> // On scroll, loop the navs and swap active (if it needs to)
<ide> function scrollspy() {
<ide> var current = $(window).scrollTop();
<ide> for (nav in navs) {
<ide> var diff = current - navs[nav];
<ide> if (diff > -20) {
<del> $(".top-menu-link a").removeClass('active');
<del> $("a[href='/"+nav+"']").addClass('active');
<add> $(".top-menu-link a.active").removeClass('active');
<add> $(".nav a[href='/"+nav+"']").addClass('active');
<ide> }
<ide> }
<ide> }
<del>
<add>
<add> // Clicking the links in the topnav
<add> $('.nav a').on('click',function(e) {
<add> e.preventDefault();
<add> var $that = $(this);
<add> var jumpto_section = $that.data('section');
<add> if (typeof jumpto_section !== 'undefined') {
<add> var top_position = navs['#'+jumpto_section];
<add> $('html, body').animate({scrollTop: top_position}, 250);
<add> }
<add> });
<add>
<ide> // TODO: heavy shit? Find a reliable way to setnavs instead of doing it fucking all the time.
<del> $(window).scroll(function() {
<del> navs = setnavs();
<del> scrollspy();
<del> });
<del>
<add> $(window).scroll(scrollspy);
<add>
<add> // On load highlight the current menu-item if an anchor is represented
<add> scrollspy();
<ide> }); |
|
Java | epl-1.0 | error: pathspec 'src/main/java/eu/jpereira/trainings/designpatterns/structural/adapter/thirdparty/ThirdParyDoorObjectAdapter.java' did not match any file(s) known to git
| 177ff2c463f346aac6c3648059d5c67fa2952e39 | 1 | magiclud/adapter | package eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty;
import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.CodeMismatchException;
import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.IncorrectDoorCodeException;
import eu.jpereira.trainings.designpatterns.structural.adapter.model.Door;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.DoorState;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.LockStatus;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeCodeForUnlockedDoor;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeStateOfLockedDoor;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotUnlockDoorException;
public class ThirdParyDoorObjectAdapter implements Door {
ThirdPartyDoor door = new ThirdPartyDoor();
@Override
public void open(String code) throws IncorrectDoorCodeException {
// TODO Auto-generated method stub
if (!isOpen()) {
try {
door.unlock(code);
if (door.getLockStatus().equals(LockStatus.UNLOCKED)) {
door.setState(DoorState.OPEN);
}
} catch (CannotUnlockDoorException e) {
// TODO Auto-generated catch block
throw new IncorrectDoorCodeException();
} catch (CannotChangeStateOfLockedDoor e) {
// TODO Auto-generated catch block
throw new IncorrectDoorCodeException();
}
}
}
@Override
public void close() {
try {
if (isOpen()) {
// TODO Auto-generated method stub
door.setState(DoorState.CLOSED);
}
} catch (CannotChangeStateOfLockedDoor e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean isOpen() {
// TODO Auto-generated method stub
if (door.getState().equals(DoorState.OPEN)) {
return true;
}
return false;
}
@Override
public void changeCode(String oldCode, String newCode, String newCodeConfirmation) throws IncorrectDoorCodeException,
CodeMismatchException {
// TODO Auto-generated method stub
try {
if (door.getLockStatus().equals(LockStatus.LOCKED)) {
door.unlock(oldCode);
}
if (!newCode.equals(newCodeConfirmation)) {
door.lock();
}
door.setNewLockCode(newCode);
} catch (CannotChangeCodeForUnlockedDoor e) {
// TODO Auto-generated catch block
throw new CodeMismatchException();
} catch (CannotUnlockDoorException e) {
// TODO Auto-generated catch block
throw new IncorrectDoorCodeException();
}
}
@Override
public boolean testCode(String code) {
// TODO Auto-generated method stub
try {
door.setNewLockCode(code);
return true;
} catch (CannotChangeCodeForUnlockedDoor e) {
// TODO Auto-generated catch block
return false;
}
}
}
| src/main/java/eu/jpereira/trainings/designpatterns/structural/adapter/thirdparty/ThirdParyDoorObjectAdapter.java | zadanie 1.3 z samym implements
| src/main/java/eu/jpereira/trainings/designpatterns/structural/adapter/thirdparty/ThirdParyDoorObjectAdapter.java | zadanie 1.3 z samym implements | <ide><path>rc/main/java/eu/jpereira/trainings/designpatterns/structural/adapter/thirdparty/ThirdParyDoorObjectAdapter.java
<add>package eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty;
<add>
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.CodeMismatchException;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.IncorrectDoorCodeException;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.model.Door;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.DoorState;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.LockStatus;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeCodeForUnlockedDoor;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeStateOfLockedDoor;
<add>import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotUnlockDoorException;
<add>
<add>public class ThirdParyDoorObjectAdapter implements Door {
<add>
<add> ThirdPartyDoor door = new ThirdPartyDoor();
<add>
<add> @Override
<add> public void open(String code) throws IncorrectDoorCodeException {
<add> // TODO Auto-generated method stub
<add> if (!isOpen()) {
<add> try {
<add> door.unlock(code);
<add> if (door.getLockStatus().equals(LockStatus.UNLOCKED)) {
<add> door.setState(DoorState.OPEN);
<add> }
<add>
<add> } catch (CannotUnlockDoorException e) {
<add> // TODO Auto-generated catch block
<add> throw new IncorrectDoorCodeException();
<add> } catch (CannotChangeStateOfLockedDoor e) {
<add> // TODO Auto-generated catch block
<add> throw new IncorrectDoorCodeException();
<add> }
<add> }
<add> }
<add>
<add> @Override
<add> public void close() {
<add> try {
<add> if (isOpen()) {
<add> // TODO Auto-generated method stub
<add> door.setState(DoorState.CLOSED);
<add> }
<add> } catch (CannotChangeStateOfLockedDoor e) {
<add> // TODO Auto-generated catch block
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> @Override
<add> public boolean isOpen() {
<add> // TODO Auto-generated method stub
<add> if (door.getState().equals(DoorState.OPEN)) {
<add> return true;
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public void changeCode(String oldCode, String newCode, String newCodeConfirmation) throws IncorrectDoorCodeException,
<add> CodeMismatchException {
<add> // TODO Auto-generated method stub
<add> try {
<add> if (door.getLockStatus().equals(LockStatus.LOCKED)) {
<add> door.unlock(oldCode);
<add> }
<add> if (!newCode.equals(newCodeConfirmation)) {
<add> door.lock();
<add> }
<add>
<add> door.setNewLockCode(newCode);
<add> } catch (CannotChangeCodeForUnlockedDoor e) {
<add> // TODO Auto-generated catch block
<add> throw new CodeMismatchException();
<add> } catch (CannotUnlockDoorException e) {
<add> // TODO Auto-generated catch block
<add> throw new IncorrectDoorCodeException();
<add> }
<add>
<add> }
<add>
<add> @Override
<add> public boolean testCode(String code) {
<add> // TODO Auto-generated method stub
<add> try {
<add> door.setNewLockCode(code);
<add> return true;
<add> } catch (CannotChangeCodeForUnlockedDoor e) {
<add> // TODO Auto-generated catch block
<add> return false;
<add> }
<add> }
<add>
<add>} |
|
Java | epl-1.0 | 170449f74541614c7b893b86fa348659618254a7 | 0 | davidfestal/che,codenvy/che,codenvy/che,davidfestal/che,davidfestal/che,davidfestal/che,akervern/che,akervern/che,akervern/che,davidfestal/che,akervern/che,davidfestal/che,akervern/che,davidfestal/che,codenvy/che,davidfestal/che,davidfestal/che,akervern/che,codenvy/che,davidfestal/che,akervern/che,akervern/che,akervern/che | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.miscellaneous;
import static java.lang.String.valueOf;
import static org.eclipse.che.selenium.pageobject.PanelSelector.PanelTypes.LEFT_BOTTOM_ID;
import static org.testng.Assert.fail;
import com.google.inject.Inject;
import java.net.URL;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import org.eclipse.che.commons.lang.NameGenerator;
import org.eclipse.che.selenium.core.client.TestProjectServiceClient;
import org.eclipse.che.selenium.core.constant.TestBuildConstants;
import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants;
import org.eclipse.che.selenium.core.project.ProjectTemplates;
import org.eclipse.che.selenium.core.utils.WaitUtils;
import org.eclipse.che.selenium.core.workspace.TestWorkspace;
import org.eclipse.che.selenium.pageobject.CheTerminal;
import org.eclipse.che.selenium.pageobject.Consoles;
import org.eclipse.che.selenium.pageobject.Ide;
import org.eclipse.che.selenium.pageobject.Loader;
import org.eclipse.che.selenium.pageobject.PanelSelector;
import org.eclipse.che.selenium.pageobject.ProjectExplorer;
import org.openqa.selenium.Keys;
import org.openqa.selenium.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Aleksandr Shmaraev
* @author Alexander Andrienko
*/
public class WorkingWithTerminalTest {
private static final String PROJECT_NAME = NameGenerator.generate("project", 4);
private static final Logger LOG = LoggerFactory.getLogger(WorkingWithTerminalTest.class);
private static final String[] CHECK_MC_OPENING = {
"Left", "File", "Command", "Options", "Right", "Name", "bin", "dev", "etc", "home",
"lib", "lib64", "bin", "1Help", "2Menu", "3View", "4Edit", "5Copy", "6RenMov", "7Mkdir",
"8Delete", "9PullDn", "10Quit"
};
private static final String MESS_IN_CONSOLE =
"Installing /projects/" + PROJECT_NAME + "/target/qa-spring-sample-1.0-SNAPSHOT.war";
private static final String WAR_NAME = "qa-spring-sample-1.0-SNAPSHOT.war";
private static final String BASH_SCRIPT =
"for i in `seq 1 10`; do sleep 1; echo \"test=$i\"; done";
private static final String MC_HELP_DIALOG =
"This is the main help screen for GNU Midnight Commander.";
private static final String MC_USER_MENU_DIALOG = "User menu";
private static final String[] VIEW_BIN_FOLDER = {"bash", "chmod", "date"};
@Inject private TestWorkspace workspace;
@Inject private Ide ide;
@Inject private ProjectExplorer projectExplorer;
@Inject private Loader loader;
@Inject private CheTerminal terminal;
@Inject private Consoles consoles;
@Inject private TestProjectServiceClient testProjectServiceClient;
@Inject private PanelSelector panelSelector;
@BeforeClass
public void setUp() throws Exception {
URL resource = getClass().getResource("/projects/guess-project");
testProjectServiceClient.importProject(
workspace.getId(),
Paths.get(resource.toURI()),
PROJECT_NAME,
ProjectTemplates.MAVEN_SPRING);
ide.open(workspace);
ide.waitOpenedWorkspaceIsReadyToUse();
}
@BeforeMethod
private void prepareNewTerminal() {
panelSelector.selectPanelTypeFromPanelSelector(LEFT_BOTTOM_ID);
projectExplorer.waitItem(PROJECT_NAME);
if (terminal.terminalIsPresent()) {
consoles.closeTerminalIntoConsoles();
terminal.waitTerminalIsNotPresent(1);
}
consoles.clickOnPlusMenuButton();
consoles.clickOnTerminalItemInContextMenu();
terminal.selectFirstTerminalTab();
terminal.waitTerminalConsole();
terminal.waitFirstTerminalIsNotEmpty();
}
@Test
public void shouldLaunchCommandWithBigOutput() {
// build the web java application
projectExplorer.waitProjectExplorer();
loader.waitOnClosed();
projectExplorer.waitItem(PROJECT_NAME);
terminal.waitTerminalConsole(1);
terminal.typeIntoActiveTerminal("cd /projects/" + PROJECT_NAME + Keys.ENTER);
terminal.waitTextInFirstTerminal("/projects/" + PROJECT_NAME);
terminal.typeIntoActiveTerminal("mvn clean install" + Keys.ENTER);
terminal.waitTextInTerminal(
TestBuildConstants.BUILD_SUCCESS, TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC);
terminal.waitTextInFirstTerminal(MESS_IN_CONSOLE);
// check the target folder
projectExplorer.openItemByPath(PROJECT_NAME);
projectExplorer.openItemByPath(PROJECT_NAME + "/target");
projectExplorer.waitItem(PROJECT_NAME + "/target/" + WAR_NAME);
}
@Test
public void shouldScrollAndAppearMCDialogs() {
terminal.typeIntoActiveTerminal("cd ~ && touch -f testfile.txt" + Keys.ENTER);
openMC("~");
// check END + F5
terminal.typeIntoActiveTerminal("" + Keys.END + Keys.F5);
terminal.waitTextInFirstTerminal("Copy file \"testfile.txt\" with source mask");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check HOME + F6
// we need to press END, HOME or PAGE_DOWN.. keys before functional key because click in MC
// moves
// selection to another file in panel
terminal.typeIntoActiveTerminal("" + Keys.HOME + Keys.F6.toString());
terminal.waitTextInFirstTerminal("Cannot operate on \"..\"!");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F7
terminal.typeIntoActiveTerminal(Keys.F7.toString());
terminal.waitTextInFirstTerminal("Enter directory name:");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check PAGE_DOWN + F8
terminal.typeIntoActiveTerminal(
""
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.F8.toString());
terminal.waitTextInFirstTerminal("Delete file");
terminal.waitTextInFirstTerminal("\"testfile.txt\"?");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F9 - Select menu in MC
terminal.typeIntoActiveTerminal("" + Keys.F9 + Keys.ENTER);
terminal.waitTextInFirstTerminal("File listing");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
}
@Test
public void shouldResizeTerminal() {
openMC("/");
try {
// check the root content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.waitNoTextInFirstTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
// check resize of the terminal
for (String partOfContent : CHECK_MC_OPENING) {
try {
terminal.waitTextInFirstTerminal(partOfContent);
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57");
}
}
terminal.waitTextInFirstTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
terminal.waitNoTextInFirstTerminal(".dockerenv");
}
@Test
public void shouldNavigateToMC() {
openMC("/");
// navigate to midnight commander tree
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
try {
// check the home content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.typeIntoActiveTerminal(Keys.F10.toString());
}
@Test
public void shouldCreateFileTest() {
terminal.typeIntoActiveTerminal("cd ~" + Keys.ENTER);
terminal.typeIntoActiveTerminal("ls" + Keys.ENTER);
terminal.waitTextInFirstTerminal("che");
terminal.typeIntoActiveTerminal("touch a.txt" + Keys.ENTER);
terminal.typeIntoActiveTerminal("ls" + Keys.ENTER);
terminal.waitTextInFirstTerminal("che");
terminal.waitTextInFirstTerminal("a.txt");
terminal.waitTextInFirstTerminal("tomcat8");
}
@Test
public void shouldCancelProcessByCtrlC() {
terminal.typeIntoActiveTerminal("cd /" + Keys.ENTER);
// launch bash script
terminal.typeIntoActiveTerminal(BASH_SCRIPT + Keys.ENTER);
terminal.waitTextInFirstTerminal("test=1");
// cancel script
terminal.typeIntoActiveTerminal(Keys.CONTROL + "c");
// wait 1 sec. If process was really stopped we should not get text "test=2"
WaitUtils.sleepQuietly(1);
try {
terminal.waitNoTextInFirstTerminal("test=2");
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che/issues/8390");
}
}
@Test
public void shouldBeClear() throws ExecutionException, InterruptedException {
terminal.typeIntoActiveTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoActiveTerminal("clear" + Keys.ENTER);
terminal.waitNoTextInFirstTerminal("clear");
terminal.waitTextInFirstTerminal("@");
}
@Test
public void shouldBeReset() throws ExecutionException, InterruptedException {
terminal.typeIntoActiveTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoActiveTerminal("reset" + Keys.ENTER.toString());
terminal.waitNoTextInFirstTerminal("reset");
terminal.waitTextInFirstTerminal("@");
}
@Test
public void shouldTurnToNormalModeFromAlternativeScreenModeAndOtherwise() {
// open MC - terminal will switch off from normal mode to alternative screen with text user
// interface (pseudo user graphics).
openMC("/");
// turn back to "normal" mode
terminal.typeIntoActiveTerminal(Keys.CONTROL + "o");
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitNoTextInFirstTerminal(partOfContent);
}
terminal.typeIntoActiveTerminal(Keys.CONTROL + "o" + Keys.ENTER);
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
}
@Test
public void shouldOpenMCHelpDialogAndUserMenuDialog() {
openMC("/");
// check "F1"
terminal.typeIntoActiveTerminal(Keys.F1.toString());
terminal.waitTextInFirstTerminal(MC_HELP_DIALOG);
terminal.typeIntoActiveTerminal(Keys.F10.toString());
terminal.waitNoTextInFirstTerminal(MC_HELP_DIALOG);
// check "F2" key
terminal.typeIntoActiveTerminal(Keys.F2.toString());
terminal.waitTextInFirstTerminal(MC_USER_MENU_DIALOG);
terminal.typeIntoActiveTerminal(Keys.F10.toString());
terminal.waitNoTextInFirstTerminal(MC_USER_MENU_DIALOG);
}
@Test
public void shouldViewFolderIntoMC() {
terminal.waitFirstTerminalTab();
consoles.clickOnMaximizePanelIcon();
openMC("/");
// select bin folder and view this folder by "F3" key
terminal.waitTextInFirstTerminal("bin");
terminal.typeIntoActiveTerminal(Keys.HOME.toString() + Keys.F3.toString());
for (String partOfContent : VIEW_BIN_FOLDER) {
terminal.waitTextInFirstTerminal(partOfContent);
}
terminal.typeIntoActiveTerminal("cd ~" + Keys.ENTER);
terminal.waitTextInFirstTerminal("che");
consoles.clickOnMaximizePanelIcon();
}
@Test
public void closeTerminalByExitCommand() {
terminal.waitTerminalConsole();
terminal.typeIntoActiveTerminal("exit" + Keys.ENTER);
terminal.waitTerminalIsNotPresent(1);
}
@Test
public void shouldEditFileIntoMCEdit() {
openMC("/projects/" + PROJECT_NAME);
// check End, Home, F4, Delete keys
terminal.typeIntoActiveTerminal(
"" + Keys.END + Keys.ENTER + Keys.END + Keys.ARROW_UP + Keys.F4);
// select editor
terminal.typeIntoActiveTerminal(valueOf(1) + Keys.ENTER);
terminal.waitTextInFirstTerminal("README.md");
terminal.typeIntoActiveTerminal("<!-some comment->");
terminal.typeIntoActiveTerminal(
"" + Keys.HOME + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.DELETE);
terminal.waitTextInFirstTerminal("<!-ome comment->");
}
@Test
public void checkDeleteAction() {
// if the bug exists -> the dialog appears and the terminal lose focus
terminal.typeIntoActiveTerminal(Keys.DELETE.toString());
terminal.typeIntoActiveTerminal("pwd");
}
private void openMC(String currentLocation) {
// launch mc from root directory
loader.waitOnClosed();
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoActiveTerminal("cd " + currentLocation);
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.typeIntoActiveTerminal("mc");
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.waitTextInFirstTerminal("Modify time");
}
}
| selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/miscellaneous/WorkingWithTerminalTest.java | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.selenium.miscellaneous;
import static java.lang.String.valueOf;
import static org.eclipse.che.selenium.pageobject.PanelSelector.PanelTypes.LEFT_BOTTOM_ID;
import static org.testng.Assert.fail;
import com.google.inject.Inject;
import java.net.URL;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import org.eclipse.che.commons.lang.NameGenerator;
import org.eclipse.che.selenium.core.client.TestProjectServiceClient;
import org.eclipse.che.selenium.core.constant.TestBuildConstants;
import org.eclipse.che.selenium.core.constant.TestTimeoutsConstants;
import org.eclipse.che.selenium.core.project.ProjectTemplates;
import org.eclipse.che.selenium.core.utils.WaitUtils;
import org.eclipse.che.selenium.core.workspace.TestWorkspace;
import org.eclipse.che.selenium.pageobject.CheTerminal;
import org.eclipse.che.selenium.pageobject.Consoles;
import org.eclipse.che.selenium.pageobject.Ide;
import org.eclipse.che.selenium.pageobject.Loader;
import org.eclipse.che.selenium.pageobject.PanelSelector;
import org.eclipse.che.selenium.pageobject.ProjectExplorer;
import org.openqa.selenium.Keys;
import org.openqa.selenium.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Aleksandr Shmaraev
* @author Alexander Andrienko
*/
public class WorkingWithTerminalTest {
private static final String PROJECT_NAME = NameGenerator.generate("project", 4);
private static final Logger LOG = LoggerFactory.getLogger(WorkingWithTerminalTest.class);
private static final String[] CHECK_MC_OPENING = {
"Left", "File", "Command", "Options", "Right", "Name", "bin", "dev", "etc", "home",
"lib", "lib64", "bin", "1Help", "2Menu", "3View", "4Edit", "5Copy", "6RenMov", "7Mkdir",
"8Delete", "9PullDn", "10Quit"
};
private static final String MESS_IN_CONSOLE =
"Installing /projects/" + PROJECT_NAME + "/target/qa-spring-sample-1.0-SNAPSHOT.war";
private static final String WAR_NAME = "qa-spring-sample-1.0-SNAPSHOT.war";
private static final String BASH_SCRIPT =
"for i in `seq 1 10`; do sleep 1; echo \"test=$i\"; done";
private static final String MC_HELP_DIALOG =
"This is the main help screen for GNU Midnight Commander.";
private static final String MC_USER_MENU_DIALOG = "User menu";
private static final String[] VIEW_BIN_FOLDER = {"bash", "chmod", "date"};
@Inject private TestWorkspace workspace;
@Inject private Ide ide;
@Inject private ProjectExplorer projectExplorer;
@Inject private Loader loader;
@Inject private CheTerminal terminal;
@Inject private Consoles consoles;
@Inject private TestProjectServiceClient testProjectServiceClient;
@Inject private PanelSelector panelSelector;
@BeforeClass
public void setUp() throws Exception {
URL resource = getClass().getResource("/projects/guess-project");
testProjectServiceClient.importProject(
workspace.getId(),
Paths.get(resource.toURI()),
PROJECT_NAME,
ProjectTemplates.MAVEN_SPRING);
ide.open(workspace);
ide.waitOpenedWorkspaceIsReadyToUse();
}
@BeforeMethod
private void prepareNewTerminal() {
try {
panelSelector.selectPanelTypeFromPanelSelector(LEFT_BOTTOM_ID);
projectExplorer.waitItem(PROJECT_NAME);
if (terminal.terminalIsPresent()) {
consoles.closeTerminalIntoConsoles();
terminal.waitTerminalIsNotPresent(1);
}
consoles.clickOnPlusMenuButton();
consoles.clickOnTerminalItemInContextMenu();
terminal.selectFirstTerminalTab();
terminal.waitTerminalConsole();
terminal.waitFirstTerminalIsNotEmpty();
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
@Test
public void shouldLaunchCommandWithBigOutput() {
// build the web java application
projectExplorer.waitProjectExplorer();
loader.waitOnClosed();
projectExplorer.waitItem(PROJECT_NAME);
terminal.waitTerminalConsole(1);
terminal.typeIntoActiveTerminal("cd /projects/" + PROJECT_NAME + Keys.ENTER);
terminal.waitTextInFirstTerminal("/projects/" + PROJECT_NAME);
terminal.typeIntoActiveTerminal("mvn clean install" + Keys.ENTER);
terminal.waitTextInTerminal(
TestBuildConstants.BUILD_SUCCESS, TestTimeoutsConstants.EXPECTED_MESS_IN_CONSOLE_SEC);
terminal.waitTextInFirstTerminal(MESS_IN_CONSOLE);
// check the target folder
projectExplorer.openItemByPath(PROJECT_NAME);
projectExplorer.openItemByPath(PROJECT_NAME + "/target");
projectExplorer.waitItem(PROJECT_NAME + "/target/" + WAR_NAME);
}
@Test
public void shouldScrollAndAppearMCDialogs() {
terminal.typeIntoActiveTerminal("cd ~ && touch -f testfile.txt" + Keys.ENTER);
openMC("~");
// check END + F5
terminal.typeIntoActiveTerminal("" + Keys.END + Keys.F5);
terminal.waitTextInFirstTerminal("Copy file \"testfile.txt\" with source mask");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check HOME + F6
// we need to press END, HOME or PAGE_DOWN.. keys before functional key because click in MC
// moves
// selection to another file in panel
terminal.typeIntoActiveTerminal("" + Keys.HOME + Keys.F6.toString());
terminal.waitTextInFirstTerminal("Cannot operate on \"..\"!");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F7
terminal.typeIntoActiveTerminal(Keys.F7.toString());
terminal.waitTextInFirstTerminal("Enter directory name:");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check PAGE_DOWN + F8
terminal.typeIntoActiveTerminal(
""
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.PAGE_DOWN
+ Keys.F8.toString());
terminal.waitTextInFirstTerminal("Delete file");
terminal.waitTextInFirstTerminal("\"testfile.txt\"?");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
// check F9 - Select menu in MC
terminal.typeIntoActiveTerminal("" + Keys.F9 + Keys.ENTER);
terminal.waitTextInFirstTerminal("File listing");
terminal.typeIntoActiveTerminal("" + Keys.ESCAPE + Keys.ESCAPE);
}
@Test
public void shouldResizeTerminal() {
openMC("/");
try {
// check the root content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.waitNoTextInFirstTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
// check resize of the terminal
for (String partOfContent : CHECK_MC_OPENING) {
try {
terminal.waitTextInFirstTerminal(partOfContent);
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57");
}
}
terminal.waitTextInFirstTerminal(".dockerenv");
consoles.clickOnMaximizePanelIcon();
loader.waitOnClosed();
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
terminal.waitNoTextInFirstTerminal(".dockerenv");
}
@Test
public void shouldNavigateToMC() {
openMC("/");
// navigate to midnight commander tree
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.typeIntoActiveTerminal(Keys.ARROW_DOWN.toString());
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
try {
// check the home content of the midnight commander
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che-lib/issues/57", ex);
}
terminal.typeIntoActiveTerminal(Keys.F10.toString());
}
@Test
public void shouldCreateFileTest() {
terminal.typeIntoActiveTerminal("cd ~" + Keys.ENTER);
terminal.typeIntoActiveTerminal("ls" + Keys.ENTER);
terminal.waitFirstTerminalIsNotEmpty();
terminal.waitTextInFirstTerminal("che");
terminal.typeIntoActiveTerminal("touch a.txt" + Keys.ENTER);
terminal.typeIntoActiveTerminal("ls" + Keys.ENTER);
terminal.waitTextInFirstTerminal("che");
terminal.waitTextInFirstTerminal("a.txt");
terminal.waitTextInFirstTerminal("tomcat8");
}
@Test
public void shouldCancelProcessByCtrlC() {
terminal.typeIntoActiveTerminal("cd /" + Keys.ENTER);
// launch bash script
terminal.typeIntoActiveTerminal(BASH_SCRIPT + Keys.ENTER);
terminal.waitTextInFirstTerminal("test=1");
// cancel script
terminal.typeIntoActiveTerminal(Keys.CONTROL + "c");
// wait 1 sec. If process was really stopped we should not get text "test=2"
WaitUtils.sleepQuietly(1);
try {
terminal.waitNoTextInFirstTerminal("test=2");
} catch (TimeoutException ex) {
// remove try-catch block after issue has been resolved
fail("Known issue https://github.com/eclipse/che/issues/8390");
}
}
@Test
public void shouldBeClear() throws ExecutionException, InterruptedException {
terminal.typeIntoActiveTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoActiveTerminal("clear" + Keys.ENTER);
terminal.waitNoTextInFirstTerminal("clear");
terminal.waitFirstTerminalIsNotEmpty();
terminal.waitTextInFirstTerminal(workspace.getId());
}
@Test
public void shouldBeReset() throws ExecutionException, InterruptedException {
terminal.typeIntoActiveTerminal("cd / && ls -l" + Keys.ENTER);
// clear terminal
terminal.typeIntoActiveTerminal("reset" + Keys.ENTER.toString());
terminal.waitNoTextInFirstTerminal("reset");
terminal.waitFirstTerminalIsNotEmpty();
terminal.waitTextInFirstTerminal(workspace.getId());
}
@Test
public void shouldTurnToNormalModeFromAlternativeScreenModeAndOtherwise() {
// open MC - terminal will switch off from normal mode to alternative screen with text user
// interface (pseudo user graphics).
openMC("/");
// turn back to "normal" mode
terminal.typeIntoActiveTerminal(Keys.CONTROL + "o");
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitNoTextInFirstTerminal(partOfContent);
}
terminal.typeIntoActiveTerminal(Keys.CONTROL + "o" + Keys.ENTER);
for (String partOfContent : CHECK_MC_OPENING) {
terminal.waitTextInFirstTerminal(partOfContent);
}
}
@Test
public void shouldOpenMCHelpDialogAndUserMenuDialog() {
openMC("/");
// check "F1"
terminal.typeIntoActiveTerminal(Keys.F1.toString());
terminal.waitFirstTerminalIsNotEmpty();
terminal.waitTextInFirstTerminal(MC_HELP_DIALOG);
terminal.typeIntoActiveTerminal(Keys.F10.toString());
terminal.waitNoTextInFirstTerminal(MC_HELP_DIALOG);
// check "F2" key
terminal.typeIntoActiveTerminal(Keys.F2.toString());
terminal.waitTextInFirstTerminal(MC_USER_MENU_DIALOG);
terminal.typeIntoActiveTerminal(Keys.F10.toString());
terminal.waitNoTextInFirstTerminal(MC_USER_MENU_DIALOG);
}
@Test
public void shouldViewFolderIntoMC() {
terminal.waitFirstTerminalTab();
consoles.clickOnMaximizePanelIcon();
openMC("/");
// select bin folder and view this folder by "F3" key
terminal.waitTextInFirstTerminal("bin");
terminal.typeIntoActiveTerminal(Keys.HOME.toString() + Keys.F3.toString());
for (String partOfContent : VIEW_BIN_FOLDER) {
terminal.waitTextInFirstTerminal(partOfContent);
}
terminal.typeIntoActiveTerminal("cd ~" + Keys.ENTER);
terminal.waitTextInFirstTerminal("che");
consoles.clickOnMaximizePanelIcon();
}
@Test
public void closeTerminalByExitCommand() {
terminal.waitTerminalConsole();
terminal.typeIntoActiveTerminal("exit" + Keys.ENTER);
terminal.waitTerminalIsNotPresent(1);
}
@Test
public void shouldEditFileIntoMCEdit() {
openMC("/projects/" + PROJECT_NAME);
// check End, Home, F4, Delete keys
terminal.typeIntoActiveTerminal(
"" + Keys.END + Keys.ENTER + Keys.END + Keys.ARROW_UP + Keys.F4);
// select editor
terminal.typeIntoActiveTerminal(valueOf(1) + Keys.ENTER);
terminal.waitTextInFirstTerminal("README.md");
terminal.typeIntoActiveTerminal("<!-some comment->");
terminal.typeIntoActiveTerminal(
"" + Keys.HOME + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.ARROW_RIGHT + Keys.DELETE);
terminal.waitTextInFirstTerminal("<!-ome comment->");
}
@Test
public void checkDeleteAction() {
// if the bug exists -> the dialog appears and the terminal lose focus
terminal.typeIntoActiveTerminal(Keys.DELETE.toString());
terminal.typeIntoActiveTerminal("pwd");
}
private void openMC(String currentLocation) {
// launch mc from root directory
loader.waitOnClosed();
consoles.selectProcessByTabName("Terminal");
terminal.typeIntoActiveTerminal("cd " + currentLocation);
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.typeIntoActiveTerminal("mc");
terminal.typeIntoActiveTerminal(Keys.ENTER.toString());
terminal.waitTextInFirstTerminal("Modify time");
}
}
| Fix WorkingWithTerminalTest not to depend on 'workspaceId' in CLI prompt (#10846)
Signed-off-by: Dmytro Nochevnov <[email protected]> | selenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/miscellaneous/WorkingWithTerminalTest.java | Fix WorkingWithTerminalTest not to depend on 'workspaceId' in CLI prompt (#10846) | <ide><path>elenium/che-selenium-test/src/test/java/org/eclipse/che/selenium/miscellaneous/WorkingWithTerminalTest.java
<ide>
<ide> @BeforeMethod
<ide> private void prepareNewTerminal() {
<del> try {
<del> panelSelector.selectPanelTypeFromPanelSelector(LEFT_BOTTOM_ID);
<del>
<del> projectExplorer.waitItem(PROJECT_NAME);
<del>
<del> if (terminal.terminalIsPresent()) {
<del> consoles.closeTerminalIntoConsoles();
<del> terminal.waitTerminalIsNotPresent(1);
<del> }
<del>
<del> consoles.clickOnPlusMenuButton();
<del> consoles.clickOnTerminalItemInContextMenu();
<del>
<del> terminal.selectFirstTerminalTab();
<del> terminal.waitTerminalConsole();
<del> terminal.waitFirstTerminalIsNotEmpty();
<del> } catch (Exception e) {
<del> LOG.error(e.getLocalizedMessage(), e);
<del> }
<add> panelSelector.selectPanelTypeFromPanelSelector(LEFT_BOTTOM_ID);
<add>
<add> projectExplorer.waitItem(PROJECT_NAME);
<add>
<add> if (terminal.terminalIsPresent()) {
<add> consoles.closeTerminalIntoConsoles();
<add> terminal.waitTerminalIsNotPresent(1);
<add> }
<add>
<add> consoles.clickOnPlusMenuButton();
<add> consoles.clickOnTerminalItemInContextMenu();
<add>
<add> terminal.selectFirstTerminalTab();
<add> terminal.waitTerminalConsole();
<add> terminal.waitFirstTerminalIsNotEmpty();
<ide> }
<ide>
<ide> @Test
<ide> public void shouldCreateFileTest() {
<ide> terminal.typeIntoActiveTerminal("cd ~" + Keys.ENTER);
<ide> terminal.typeIntoActiveTerminal("ls" + Keys.ENTER);
<del> terminal.waitFirstTerminalIsNotEmpty();
<ide> terminal.waitTextInFirstTerminal("che");
<ide> terminal.typeIntoActiveTerminal("touch a.txt" + Keys.ENTER);
<ide>
<ide> // clear terminal
<ide> terminal.typeIntoActiveTerminal("clear" + Keys.ENTER);
<ide> terminal.waitNoTextInFirstTerminal("clear");
<del>
<del> terminal.waitFirstTerminalIsNotEmpty();
<del> terminal.waitTextInFirstTerminal(workspace.getId());
<add> terminal.waitTextInFirstTerminal("@");
<ide> }
<ide>
<ide> @Test
<ide> // clear terminal
<ide> terminal.typeIntoActiveTerminal("reset" + Keys.ENTER.toString());
<ide> terminal.waitNoTextInFirstTerminal("reset");
<del>
<del> terminal.waitFirstTerminalIsNotEmpty();
<del> terminal.waitTextInFirstTerminal(workspace.getId());
<add> terminal.waitTextInFirstTerminal("@");
<ide> }
<ide>
<ide> @Test
<ide>
<ide> // check "F1"
<ide> terminal.typeIntoActiveTerminal(Keys.F1.toString());
<del> terminal.waitFirstTerminalIsNotEmpty();
<ide> terminal.waitTextInFirstTerminal(MC_HELP_DIALOG);
<ide> terminal.typeIntoActiveTerminal(Keys.F10.toString());
<ide> terminal.waitNoTextInFirstTerminal(MC_HELP_DIALOG); |
|
Java | mit | 91137e922e6e7c3546408c1d32930a204aff5101 | 0 | seanhold3n/sleep-analytics,seanhold3n/sleep-analytics | package model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author sean
*/
public final class DaySleepDurationMap extends DayValuesMap {
private static final long serialVersionUID = -4755148060348935227L;
private static DaySleepDurationMap singleMap;
private DaySleepDurationMap(){
}
public static DaySleepDurationMap getInstance(){
if (singleMap == null){
singleMap = new DaySleepDurationMap();
}
return singleMap;
}
/** Add sleep time to the current map. Use this over {@link #put(SimpleDay, Double)}
* to avoid accidentally overwriting data
* @param day
* @param increment
*/
public void addToDay(SimpleDay day, double increment){
// If the key doesn't exist, add it
if (!containsKey(day)){
put(day, increment);
}
else {
put(day, Double.sum(get(day), increment));
}
}
/** Get the simple moving averages for each day (that is, the unweighted mean of the previous nDays of data).
* @param nDays The number of days over which to compute the average
* @return A map of all day/SMA pairings
*/
public DayValuesMap getSimpleMovingAverage(final int nDays){
// Create the map
DayValuesMap smaMap = new DayValuesMap();
double sma = 0;
boolean firstSMA = true;
List<Map.Entry<SimpleDay, Double>> smaActiveSet = new ArrayList<Map.Entry<SimpleDay, Double>>(nDays);
for (Map.Entry<SimpleDay, Double> todayEntry : this.entrySet()){
// Add the entry to the active set
smaActiveSet.add(todayEntry);
// If reached the first nDays (i.e. enough items have been added to the set), compute SMA
if (smaActiveSet.size() >= nDays){
if (firstSMA){
// Set baseline SMA
for (Map.Entry<SimpleDay, Double> activeEntry : smaActiveSet){
sma += activeEntry.getValue();
}
sma /= nDays;
firstSMA = false;
}
else{
// Augment the SMA
// Get the nth-back element (i.e. the first one in the list)
Map.Entry<SimpleDay, Double> nthElementBack = smaActiveSet.get(0);
// Get new SMA based on old one
sma = sma + todayEntry.getValue()/nDays - nthElementBack.getValue()/nDays;
// Remove the nth-back element
smaActiveSet.remove(0);
}
smaMap.put(todayEntry.getKey(), sma);
}
}
return smaMap;
}
}
| src/main/java/model/DaySleepDurationMap.java | package model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author sean
*/
public final class DaySleepDurationMap extends DayValuesMap {
private static final long serialVersionUID = -4755148060348935227L;
private static DaySleepDurationMap singleMap;
private DaySleepDurationMap(){
}
public static DaySleepDurationMap getInstance(){
if (singleMap == null){
singleMap = new DaySleepDurationMap();
}
return singleMap;
}
/** Add sleep time to the current map. Use this over {@link #put(SimpleDay, Double)}
* to avoid accidentally overwriting data
* @param day
* @param increment
*/
public void addToDay(SimpleDay day, double increment){
// If the key doesn't exist, add it
if (!containsKey(day)){
put(day, increment);
}
else {
put(day, Double.sum(get(day), increment));
}
}
/** Get the simple moving averages for each day (that is, the unweighted mean of the previous nDays of data).
* @param nDays The number of days over which to compute the average
* @return A map of all day/SMA pairings
*/
public DayValuesMap getSimpleMovingAverage(final int nDays){
// Create the map
DayValuesMap smaMap = new DayValuesMap();
double sma = 0;
boolean firstSMA = true;
List<Map.Entry<SimpleDay, Double>> smaActiveSet = new ArrayList<Map.Entry<SimpleDay, Double>>(nDays);
for (Map.Entry<SimpleDay, Double> todayEntry : this.entrySet()){
// If in the first nDays (i.e. not enough items have been added to the set yet), just add them
if (smaActiveSet.size() < nDays){
smaActiveSet.add(todayEntry);
}
// Compute SMA
else{
if (firstSMA){
// Use the values in the set
for (Map.Entry<SimpleDay, Double> activeEntry : smaActiveSet){
sma += activeEntry.getValue();
}
sma /= nDays;
firstSMA = false;
}
else{
// Augment the SMA
// Get the nth-back element (i.e. the first one in the list)
Map.Entry<SimpleDay, Double> nthElementBack = smaActiveSet.get(0);
// Get new SMA based on old one
sma = sma + todayEntry.getValue()/nDays - nthElementBack.getValue()/nDays;
// Remove the nth-back element and load the new value
smaActiveSet.remove(0);
smaActiveSet.add(todayEntry);
}
smaMap.put(todayEntry.getKey(), sma);
}
}
return smaMap;
}
}
| Fixed moving behavior for statistical analysis.
| src/main/java/model/DaySleepDurationMap.java | Fixed moving behavior for statistical analysis. | <ide><path>rc/main/java/model/DaySleepDurationMap.java
<ide>
<ide> for (Map.Entry<SimpleDay, Double> todayEntry : this.entrySet()){
<ide>
<del> // If in the first nDays (i.e. not enough items have been added to the set yet), just add them
<del> if (smaActiveSet.size() < nDays){
<del> smaActiveSet.add(todayEntry);
<del> }
<del> // Compute SMA
<del> else{
<add> // Add the entry to the active set
<add> smaActiveSet.add(todayEntry);
<add>
<add> // If reached the first nDays (i.e. enough items have been added to the set), compute SMA
<add> if (smaActiveSet.size() >= nDays){
<ide> if (firstSMA){
<del> // Use the values in the set
<add> // Set baseline SMA
<ide> for (Map.Entry<SimpleDay, Double> activeEntry : smaActiveSet){
<ide> sma += activeEntry.getValue();
<ide> }
<ide> // Get new SMA based on old one
<ide> sma = sma + todayEntry.getValue()/nDays - nthElementBack.getValue()/nDays;
<ide>
<del> // Remove the nth-back element and load the new value
<add> // Remove the nth-back element
<ide> smaActiveSet.remove(0);
<del> smaActiveSet.add(todayEntry);
<ide>
<ide> }
<ide> smaMap.put(todayEntry.getKey(), sma); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.