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 | 3084c6625ba7bca4cde25c119657b6a6038b5b3c | 0 | ebonnet/Silverpeas-Core,SilverYoCha/Silverpeas-Core,stephaneperry/Silverpeas-Core,mmoqui/Silverpeas-Core,SilverYoCha/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,SilverYoCha/Silverpeas-Core,auroreallibe/Silverpeas-Core,SilverDav/Silverpeas-Core,auroreallibe/Silverpeas-Core,stephaneperry/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,CecileBONIN/Silverpeas-Core,stephaneperry/Silverpeas-Core,stephaneperry/Silverpeas-Core,CecileBONIN/Silverpeas-Core,Silverpeas/Silverpeas-Core,ebonnet/Silverpeas-Core,ebonnet/Silverpeas-Core,auroreallibe/Silverpeas-Core,ebonnet/Silverpeas-Core,SilverDav/Silverpeas-Core,Silverpeas/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,CecileBONIN/Silverpeas-Core,SilverDav/Silverpeas-Core,NicolasEYSSERIC/Silverpeas-Core,mmoqui/Silverpeas-Core,mmoqui/Silverpeas-Core,SilverTeamWork/Silverpeas-Core,CecileBONIN/Silverpeas-Core,CecileBONIN/Silverpeas-Core,Silverpeas/Silverpeas-Core | /**
* Copyright (C) 2000 - 2009 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.lookV5;
import static com.stratelia.silverpeas.util.SilverpeasSettings.readBoolean;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.silverpeas.external.filesharing.model.FileSharingInterface;
import com.silverpeas.external.filesharing.model.FileSharingInterfaceImpl;
import com.silverpeas.external.webConnections.dao.WebConnectionsImpl;
import com.silverpeas.external.webConnections.model.WebConnectionsInterface;
import com.silverpeas.jobStartPagePeas.JobStartPagePeasSettings;
import com.silverpeas.look.LookHelper;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.StringUtil;
import com.stratelia.silverpeas.pdc.control.PdcBm;
import com.stratelia.silverpeas.pdc.control.PdcBmImpl;
import com.stratelia.silverpeas.pdc.model.PdcException;
import com.stratelia.silverpeas.pdc.model.SearchAxis;
import com.stratelia.silverpeas.pdc.model.SearchContext;
import com.stratelia.silverpeas.pdc.model.Value;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.beans.admin.Admin;
import com.stratelia.webactiv.beans.admin.ComponentInst;
import com.stratelia.webactiv.beans.admin.OrganizationController;
import com.stratelia.webactiv.beans.admin.PersonalSpaceController;
import com.stratelia.webactiv.beans.admin.SpaceInst;
import com.stratelia.webactiv.beans.admin.SpaceInstLight;
import com.stratelia.webactiv.beans.admin.UserFavoriteSpaceManager;
import com.stratelia.webactiv.beans.admin.instance.control.Instanciateur;
import com.stratelia.webactiv.beans.admin.instance.control.WAComponent;
import com.stratelia.webactiv.organization.DAOFactory;
import com.stratelia.webactiv.organization.UserFavoriteSpaceDAO;
import com.stratelia.webactiv.organization.UserFavoriteSpaceVO;
import com.stratelia.webactiv.util.FileRepositoryManager;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.viewGenerator.html.GraphicElementFactory;
public class AjaxServletLookV5 extends HttpServlet {
private static final String DISABLE = "DISABLE";
private static final String ALL = "ALL";
private static final String BOOKMARKS = "BOOKMARKS";
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute(
"SilverSessionController");
GraphicElementFactory gef = (GraphicElementFactory) session.getAttribute(
"SessionGraphicElementFactory");
LookHelper helper = (LookHelper) session.getAttribute("Silverpeas_LookHelper");
OrganizationController orgaController = m_MainSessionCtrl.getOrganizationController();
String userId = m_MainSessionCtrl.getUserId();
String language = m_MainSessionCtrl.getFavoriteLanguage();
// Get ajax action
String responseId = req.getParameter("ResponseId");
String init = req.getParameter("Init");
String spaceId = req.getParameter("SpaceId");
String componentId = req.getParameter("ComponentId");
String axisId = req.getParameter("AxisId");
String valuePath = req.getParameter("ValuePath");
String getPDC = req.getParameter("GetPDC");
String pdc = req.getParameter("Pdc");
// New request parameter to manage Bookmarks view or classical view
String userMenuDisplayMode = req.getParameter("UserMenuDisplayMode");
String defaultLook = gef.getCurrentLookName();
boolean displayContextualPDC = helper.displayContextualPDC();
boolean displayPDC = "true".equalsIgnoreCase(getPDC);
// User favorite space DAO
List<UserFavoriteSpaceVO> listUserFS = new ArrayList<UserFavoriteSpaceVO>();
if (!DISABLE.equalsIgnoreCase(helper.getDisplayUserFavoriteSpace())) {
UserFavoriteSpaceDAO ufsDAO = DAOFactory.getUserFavoriteSpaceDAO();
listUserFS = ufsDAO.getListUserFavoriteSpace(userId);
}
if (StringUtil.isDefined(componentId)) {
helper.setComponentIdAndSpaceIds(null, null, componentId);
} else if (StringUtil.isDefined(spaceId) && !isPersonnalSpace(spaceId)) {
helper.setSpaceIdAndSubSpaceId(spaceId);
}
if (StringUtil.isDefined(userMenuDisplayMode)) {
helper.setDisplayUserFavoriteSpace(userMenuDisplayMode);
} else {
userMenuDisplayMode = helper.getDisplayUserFavoriteSpace();
}
res.setContentType("text/xml");
res.setHeader("charset", "UTF-8");
Writer writer = res.getWriter();
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.write("<ajax-response>");
writer.write("<response type=\"object\" id=\"" + responseId + "\">");
if ("1".equals(init)) {
if (!StringUtil.isDefined(spaceId) && !StringUtil.isDefined(componentId)) {
displayFirstLevelSpaces(userId, language, defaultLook, orgaController,
helper, writer, listUserFS, userMenuDisplayMode);
} else {
// First get space's path cause it can be a subspace
List<String> spaceIdsPath = getSpaceIdsPath(spaceId, componentId,
orgaController);
// space transverse
displaySpace(spaceId, componentId, spaceIdsPath, userId, language,
defaultLook, displayPDC, true, orgaController, helper, writer, listUserFS,
userMenuDisplayMode);
// other spaces
displayTree(userId, componentId, spaceIdsPath, language,
defaultLook, orgaController, helper, writer, listUserFS, userMenuDisplayMode);
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC,
m_MainSessionCtrl, writer);
}
} else if (StringUtil.isDefined(axisId) && StringUtil.isDefined(valuePath)) {
try {
writer.write("<pdc>");
getPertinentValues(spaceId, componentId, userId, axisId, valuePath,
displayContextualPDC, m_MainSessionCtrl, writer);
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
} else if (StringUtil.isDefined(spaceId)) {
if (isPersonnalSpace(spaceId)) {
// Affichage de l'espace perso
ResourceLocator settings = gef.getFavoriteLookSettings();
ResourceLocator message = new ResourceLocator(
"com.stratelia.webactiv.homePage.multilang.homePageBundle", language);
serializePersonalSpace(writer, userId, language, orgaController, helper, settings, message);
} else {
// First get space's path cause it can be a subspace
List<String> spaceIdsPath = getSpaceIdsPath(spaceId, componentId, orgaController);
displaySpace(spaceId, componentId, spaceIdsPath, userId, language, defaultLook, displayPDC,
false, orgaController, helper, writer, listUserFS, userMenuDisplayMode);
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC, m_MainSessionCtrl,
writer);
}
} else if (StringUtil.isDefined(componentId)) {
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC, m_MainSessionCtrl,
writer);
} else if (StringUtil.isDefined(pdc)) {
displayNotContextualPDC(userId, m_MainSessionCtrl, writer);
}
writer.write("</response>");
writer.write("</ajax-response>");
}
private void displayNotContextualPDC(String userId,
MainSessionController mainSC, Writer writer) throws IOException {
try {
writer.write("<pdc>");
getPertinentAxis(null, null, userId, mainSC, writer);
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
}
private void displayPDC(String getPDC, String spaceId, String componentId,
String userId, boolean displayContextualPDC, MainSessionController mainSC, Writer writer)
throws IOException {
try {
writer.write("<pdc>");
if ("true".equalsIgnoreCase(getPDC)) {
getPertinentAxis(spaceId, componentId, userId, mainSC, writer);
}
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
}
private List<String> getSpaceIdsPath(String spaceId, String componentId,
OrganizationController orgaController) {
List<SpaceInst> spacePath = null;
if (StringUtil.isDefined(spaceId)) {
spacePath = orgaController.getSpacePath(spaceId);
} else if (StringUtil.isDefined(componentId)) {
spacePath = orgaController.getSpacePathToComponent(componentId);
}
List<String> spaceIdsPath = null;
for (int s = 0; s < spacePath.size(); s++) {
SpaceInst space = spacePath.get(s);
if (spaceIdsPath == null) {
spaceIdsPath = new ArrayList<String>();
}
if (!space.getId().startsWith(Admin.SPACE_KEY_PREFIX)) {
spaceIdsPath.add(Admin.SPACE_KEY_PREFIX + space.getId());
} else {
spaceIdsPath.add(space.getId());
}
}
return spaceIdsPath;
}
/**
* @param spaceId : space identifier
* @param listUFS : the list of user favorite space
* @param orgaController : the OrganizationController object
* @return true if the current space contains user favorites sub space, false else if
*/
private boolean containsFavoriteSubSpace(String spaceId, List<UserFavoriteSpaceVO> listUFS,
OrganizationController orgaController, String userId) {
return UserFavoriteSpaceManager.containsFavoriteSubSpace(spaceId, listUFS, orgaController,
userId);
}
/**
* @param listUFS : the list of user favorite space
* @param spaceId : space identifier
* @return true if list of user favorites space contains spaceId identifier, false else if
*/
private boolean isUserFavoriteSpace(List<UserFavoriteSpaceVO> listUFS, String spaceId) {
return UserFavoriteSpaceManager.isUserFavoriteSpace(listUFS, spaceId);
}
/**
* displaySpace build XML response tree of current spaceId
* @param spaceId
* @param componentId
* @param spacePath
* @param userId
* @param language
* @param defaultLook
* @param displayPDC
* @param displayTransverse
* @param orgaController
* @param helper
* @param writer
* @param listUFS
* @param userMenuDisplayMode TODO
* @throws IOException
*/
private void displaySpace(String spaceId, String componentId, List<String> spacePath,
String userId, String language, String defaultLook,
boolean displayPDC, boolean displayTransverse,
OrganizationController orgaController, LookHelper helper, Writer writer,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode) throws IOException {
boolean isTransverse = false;
int i = 0;
while (!isTransverse && i < spacePath.size()) {
String spaceIdInPath = spacePath.get(i);
isTransverse = helper.getTopSpaceIds().contains(spaceIdInPath);
i++;
}
if (displayTransverse && !isTransverse) {
return;
}
boolean open = (spacePath != null && spacePath.contains(spaceId));
if (open) {
spaceId = spacePath.remove(0);
}
// Affichage de l'espace collaboratif
SpaceInstLight space = orgaController.getSpaceInstLightById(spaceId);
if (space != null && isSpaceVisible(userId, spaceId, orgaController)) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item open=\"").append(open).append("\" ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append(">");
writer.write(itemSB.toString());
if (open) {
// Default display configuration
boolean spaceBeforeComponent = isSpaceBeforeComponentNeeded(space);
if (spaceBeforeComponent) {
getSubSpaces(spaceId, userId, spacePath, componentId, language,
defaultLook, orgaController, helper, writer, listUFS, userMenuDisplayMode);
getComponents(spaceId, componentId, userId, language, orgaController,
writer, userMenuDisplayMode, listUFS);
} else {
getComponents(spaceId, componentId, userId, language, orgaController,
writer, userMenuDisplayMode, listUFS);
getSubSpaces(spaceId, userId, spacePath, componentId, language,
defaultLook, orgaController, helper, writer, listUFS, userMenuDisplayMode);
}
}
}
writer.write("</item>");
}
/**
* @param userId
* @param orgaController
* @param listUFS
* @param space
* @param helper
* @return an XML user favorite space attribute only if User Favorite Space is enable
*/
private String getFavoriteSpaceAttribute(String userId, OrganizationController orgaController,
List<UserFavoriteSpaceVO> listUFS, SpaceInstLight space, LookHelper helper) {
StringBuilder favSpace = new StringBuilder(20);
if (!DISABLE.equalsIgnoreCase(helper.getDisplayUserFavoriteSpace())) {
favSpace.append(" favspace=\"");
if (isUserFavoriteSpace(listUFS, space.getShortId())) {
favSpace.append("true");
} else {
if (helper.isEnableUFSContainsState()) {
if (containsFavoriteSubSpace(space.getShortId(), listUFS, orgaController, userId)) {
favSpace.append("contains");
} else {
favSpace.append("false");
}
} else {
favSpace.append("false");
}
}
favSpace.append("\"");
}
return favSpace.toString();
}
private void displayTree(String userId, String targetComponentId,
List<String> spacePath, String language, String defaultLook,
OrganizationController orgaController, LookHelper helper, Writer out,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode) throws IOException {
// Then get all first level spaces
String[] availableSpaceIds = getRootSpaceIds(userId, orgaController, helper);
out.write("<spaces menu=\"" + helper.getDisplayUserFavoriteSpace() + "\">");
String spaceId = null;
for (int nI = 0; nI < availableSpaceIds.length; nI++) {
spaceId = availableSpaceIds[nI];
boolean loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, spaceId, orgaController)) {
displaySpace(spaceId, targetComponentId, spacePath, userId, language,
defaultLook, false, false, orgaController, helper, out, listUFS, userMenuDisplayMode);
}
loadCurSpace = false;
}
out.write("</spaces>");
}
private String getSpaceAttributes(SpaceInstLight space, String language,
String defaultLook, LookHelper helper) {
String spaceLook = space.getLook();
if (!StringUtil.isDefined(spaceLook)) {
spaceLook = defaultLook;
}
String spaceWallpaper = getWallPaper(space.getFullId());
boolean isTransverse = helper.getTopSpaceIds().contains(space.getFullId());
String attributeType = "space";
if (isTransverse) {
attributeType = "spaceTransverse";
}
return "id=\"" + space.getFullId() + "\" name=\""
+ EncodeHelper.escapeXml(space.getName(language)) + "\" description=\""
+ EncodeHelper.escapeXml(space.getDescription()) + "\" type=\""
+ attributeType + "\" kind=\"space\" level=\"" + space.getLevel()
+ "\" look=\"" + spaceLook + "\" wallpaper=\"" + spaceWallpaper + "\"";
}
private void displayFirstLevelSpaces(String userId, String language,
String defaultLook, OrganizationController orgaController, LookHelper helper,
Writer out, List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode)
throws IOException {
String[] availableSpaceIds = getRootSpaceIds(userId, orgaController, helper);
// Loop variable declaration
SpaceInstLight space = null;
String spaceId = null;
// Start writing XML spaces node
out.write("<spaces menu=\"" + helper.getDisplayUserFavoriteSpace() + "\">");
for (int nI = 0; nI < availableSpaceIds.length; nI++) {
spaceId = availableSpaceIds[nI];
boolean loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, spaceId, orgaController)) {
space = orgaController.getSpaceInstLightById(spaceId);
if (space != null) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append("/>");
out.write(itemSB.toString());
}
}
loadCurSpace = false;
}
out.write("</spaces>");
}
private void getSubSpaces(String spaceId, String userId, List<String> spacePath,
String targetComponentId, String language, String defaultLook,
OrganizationController orgaController, LookHelper helper, Writer out,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode)
throws IOException {
String[] spaceIds = orgaController.getAllSubSpaceIds(spaceId, userId);
String subSpaceId = null;
boolean open = false;
boolean loadCurSpace = false;
for (int nI = 0; nI < spaceIds.length; nI++) {
subSpaceId = spaceIds[nI];
SpaceInstLight space = orgaController.getSpaceInstLightById(subSpaceId);
if (space != null) {
open = (spacePath != null && spacePath.contains(subSpaceId));
// Check user favorite space
loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, subSpaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, subSpaceId, orgaController)) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(" open=\"").append(open).append("\"");
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append(">");
out.write(itemSB.toString());
if (open) {
// Default display configuration
boolean spaceBeforeComponent = isSpaceBeforeComponentNeeded(space);
// the subtree must be displayed
// components of expanded space must be displayed too
if (spaceBeforeComponent) {
getSubSpaces(subSpaceId, userId, spacePath, targetComponentId,
language, defaultLook, orgaController, helper, out, listUFS, userMenuDisplayMode);
getComponents(subSpaceId, targetComponentId, userId, language,
orgaController, out, userMenuDisplayMode, listUFS);
} else {
getComponents(subSpaceId, targetComponentId, userId, language,
orgaController, out, userMenuDisplayMode, listUFS);
getSubSpaces(subSpaceId, userId, spacePath, targetComponentId,
language, defaultLook, orgaController, helper, out, listUFS, userMenuDisplayMode);
}
}
out.write("</item>");
}
loadCurSpace = false;
}
}
}
private void getComponents(String spaceId, String targetComponentId,
String userId, String language, OrganizationController orgaController,
Writer out, String userMenuDisplayMode, List<UserFavoriteSpaceVO> listUFS) throws IOException {
boolean loadCurComponent = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurComponent) {
String[] componentIds = orgaController.getAvailCompoIdsAtRoot(spaceId, userId);
SpaceInstLight space = orgaController.getSpaceInstLightById(spaceId);
int level = space.getLevel() + 1;
ComponentInst component = null;
boolean open = false;
String url = null;
String kind = null;
for (int c = 0; componentIds != null && c < componentIds.length; c++) {
component = orgaController.getComponentInst(componentIds[c]);
if (component != null && !component.isHidden()) {
open = (targetComponentId != null && component.getId().equals(
targetComponentId));
url = URLManager.getURL(component.getName(), null, component.getId()) + "Main";
kind = component.getName();
WAComponent descriptor = Instanciateur.getWAComponent(component.getName());
if (descriptor != null
&& "RprocessManager".equalsIgnoreCase(descriptor.getRequestRouter())) {
kind = "processManager";
}
out.write("<item id=\"" + component.getId() + "\" name=\""
+ EncodeHelper.escapeXml(component.getLabel(language))
+ "\" description=\""
+ EncodeHelper.escapeXml(component.getDescription(language))
+ "\" type=\"component\" kind=\"" + EncodeHelper.escapeXml(kind)
+ "\" level=\"" + level + "\" open=\"" + open + "\" url=\"" + url
+ "\"/>");
}
}
}
}
private void getPertinentAxis(String spaceId, String componentId,
String userId, MainSessionController mainSC, Writer out)
throws PdcException, IOException {
List<SearchAxis> primaryAxis = null;
SearchContext searchContext = new SearchContext();
PdcBm pdc = new PdcBmImpl();
if (StringUtil.isDefined(componentId)) {
// L'item courant est un composant
primaryAxis = pdc.getPertinentAxisByInstanceId(searchContext, "P",
componentId);
} else {
List<String> cmps = null;
if (StringUtil.isDefined(spaceId)) {
// L'item courant est un espace
cmps = getAvailableComponents(spaceId, userId, mainSC.getOrganizationController());
} else {
cmps = Arrays.asList(mainSC.getUserAvailComponentIds());
}
if (cmps != null && cmps.size() > 0) {
primaryAxis = pdc.getPertinentAxisByInstanceIds(searchContext, "P",
cmps);
}
}
SearchAxis axis = null;
if (primaryAxis != null) {
for (int a = 0; a < primaryAxis.size(); a++) {
axis = primaryAxis.get(a);
if (axis != null && axis.getNbObjects() > 0) {
out.write("<axis id=\"" + axis.getAxisId() + "\" name=\""
+ EncodeHelper.escapeXml(axis.getAxisName())
+ "\" description=\"\" level=\"0\" open=\"false\" nbObjects=\""
+ axis.getNbObjects() + "\"/>");
}
}
}
pdc = null;
primaryAxis = null;
}
private List<String> getAvailableComponents(String spaceId, String userId,
OrganizationController orgaController) {
String a[] = orgaController.getAvailCompoIds(spaceId, userId);
return Arrays.asList(a);
}
private String getValueId(String valuePath) {
// cherche l'id de la valeur
// valuePath est de la forme /0/1/2/
String valueId = valuePath;
int len = valuePath.length();
valueId = valuePath.substring(0, len - 1); // on retire le slash
if ("/".equals(valuePath)) {
valueId = valueId.substring(1);// on retire le slash
} else {
int lastIdx = valueId.lastIndexOf('/');
valueId = valueId.substring(lastIdx + 1);
}
return valueId;
}
private List<Value> getPertinentValues(String spaceId, String componentId,
String userId, String axisId, String valuePath,
boolean displayContextualPDC, MainSessionController mainSC, Writer out) throws IOException,
PdcException {
List<Value> daughters = null;
SearchContext searchContext = new SearchContext();
searchContext.setUserId(userId);
if (StringUtil.isDefined(axisId)) {
PdcBm pdc = new PdcBmImpl();
// TODO : some improvements can be made here !
// daughters contains all pertinent values of axis instead of pertinent
// daughters only
if (displayContextualPDC) {
if (StringUtil.isDefined(componentId)) {
daughters = pdc.getPertinentDaughterValuesByInstanceId(searchContext,
axisId, valuePath, componentId);
} else {
List<String> cmps = getAvailableComponents(spaceId, userId, mainSC.
getOrganizationController());
daughters = pdc.getPertinentDaughterValuesByInstanceIds(
searchContext, axisId, valuePath, cmps);
}
} else {
List<String> cmps = Arrays.asList(mainSC.getUserAvailComponentIds());
daughters = pdc.getPertinentDaughterValuesByInstanceIds(searchContext,
axisId, valuePath, cmps);
}
String valueId = getValueId(valuePath);
Value value = null;
for (int v = 0; v < daughters.size(); v++) {
value = daughters.get(v);
if (value != null && value.getMotherId().equals(valueId)) {
out.write("<value id=\"" + value.getFullPath() + "\" name=\""
+ EncodeHelper.escapeXml(value.getName())
+ "\" description=\"\" level=\"" + value.getLevelNumber()
+ "\" open=\"false\" nbObjects=\"" + value.getNbObjects()
+ "\"/>");
}
}
pdc = null;
}
return daughters;
}
private String getWallPaper(String spaceId) {
String path = FileRepositoryManager.getAbsolutePath("Space" + spaceId.substring(2),
new String[]{"look"});
File file = new File(path + "wallPaper.jpg");
if (file.isFile()) {
return "1";
} else {
file = new File(path + "wallPaper.gif");
if (file.isFile()) {
return "1";
}
}
return "0";
}
private String[] getRootSpaceIds(String userId, OrganizationController orgaController,
LookHelper helper) {
List<String> rootSpaceIds = new ArrayList<String>();
List<String> topSpaceIds = helper.getTopSpaceIds();
String[] availableSpaceIds = orgaController.getAllRootSpaceIds(userId);
for (int i = 0; i < availableSpaceIds.length; i++) {
if (!topSpaceIds.contains(availableSpaceIds[i])) {
rootSpaceIds.add(availableSpaceIds[i]);
}
}
return rootSpaceIds.toArray(new String[rootSpaceIds.size()]);
}
protected boolean isPersonnalSpace(String spaceId) {
return "spacePerso".equalsIgnoreCase(spaceId);
}
protected void serializePersonalSpace(Writer writer, String userId, String language,
OrganizationController orgaController, LookHelper helper, ResourceLocator settings,
ResourceLocator message) throws IOException {
// Affichage de l'espace perso
writer.write("<spacePerso id=\"spacePerso\" type=\"space\" level=\"0\">");
boolean isAnonymousAccess = helper.isAnonymousAccess();
if (!isAnonymousAccess && readBoolean(settings, "personnalSpaceVisible", true)) {
if (readBoolean(settings, "agendaVisible", true)) {
writer.write("<item id=\"agenda\" name=\""
+ EncodeHelper.escapeXml(message.getString("Diary"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_AGENDA) + "Main\"/>");
}
if (readBoolean(settings, "todoVisible", true)) {
writer.write("<item id=\"todo\" name=\""
+ EncodeHelper.escapeXml(message.getString("ToDo"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_TODO) + "todo.jsp\"/>");
}
if (readBoolean(settings, "notificationVisible", true)) {
writer.write("<item id=\"notification\" name=\""
+ EncodeHelper.escapeXml(message.getString("Mail"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_SILVERMAIL) + "Main\"/>");
}
if (readBoolean(settings, "interestVisible", true)) {
writer.write("<item id=\"subscriptions\" name=\""
+ EncodeHelper.escapeXml(message.getString("MyInterestCenters"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_PDCSUBSCRIPTION)
+ "subscriptionList.jsp\"/>");
}
if (readBoolean(settings, "favRequestVisible", true)) {
writer.write("<item id=\"requests\" name=\""
+ EncodeHelper.escapeXml(message.getString("FavRequests"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_INTERESTCENTERPEAS)
+ "iCenterList.jsp\"/>");
}
if (readBoolean(settings, "linksVisible", true)) {
writer.write("<item id=\"links\" name=\""
+ EncodeHelper.escapeXml(message.getString("FavLinks"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_MYLINKSPEAS)
+ "Main\"/>");
}
if (readBoolean(settings, "fileSharingVisible", true)) {
FileSharingInterface fileSharing = new FileSharingInterfaceImpl();
if (!fileSharing.getTicketsByUser(userId).isEmpty()) {
writer.write("<item id=\"fileSharing\" name=\""
+ EncodeHelper.escapeXml(message.getString("FileSharing"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_FILESHARING)
+ "Main\"/>");
}
}
// mes connexions
if (readBoolean(settings, "webconnectionsVisible", true)) {
WebConnectionsInterface webConnections = new WebConnectionsImpl();
if (webConnections.getConnectionsByUser(userId).size() > 0) {
writer.write("<item id=\"webConnections\" name=\""
+ EncodeHelper.escapeXml(message.getString("WebConnections"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_WEBCONNECTIONS)
+ "Main\"/>");
}
}
if (readBoolean(settings, "customVisible", true)) {
writer.write("<item id=\"personalize\" name=\""
+ EncodeHelper.escapeXml(message.getString("Personalization"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_MYPROFILE)
+ "Main\"/>");
}
if (readBoolean(settings, "mailVisible", true)) {
writer.write(
"<item id=\"notifAdmins\" name=\""
+ EncodeHelper.escapeXml(message.getString("Feedback"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:notifyAdministrators()\"/>");
}
if (readBoolean(settings, "clipboardVisible", true)) {
writer.write(
"<item id=\"clipboard\" name=\""
+ EncodeHelper.escapeXml(message.getString("Clipboard"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:openClipboard()\"/>");
}
// fonctionnalité "Trouver une date"
if (readBoolean(settings, "scheduleEventVisible", false)) {
writer.write("<item id=\"scheduleevent\" name=\""
+ EncodeHelper.escapeXml(message.getString("ScheduleEvent"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT) + "Main\"/>");
}
if (readBoolean(settings, "PersonalSpaceAddingsEnabled", true)) {
PersonalSpaceController psc = new PersonalSpaceController();
SpaceInst personalSpace = psc.getPersonalSpace(userId);
if (personalSpace != null) {
for (ComponentInst component : personalSpace.getAllComponentsInst()) {
String label =
helper.getString("lookSilverpeasV5.personalSpace." + component.getName());
if (!StringUtil.isDefined(label)) {
label = component.getName();
}
String url = URLManager.getURL(component.getName(), null, component.getName()
+ component.getId()) + "Main";
writer.write("<item id=\""
+ component.getName()
+ component.getId()
+ "\" name=\""
+ EncodeHelper.escapeXml(label)
+ "\" description=\"\" type=\"component\" kind=\"personalComponent\" level=\"1\" open=\"false\" url=\""
+ url + "\"/>");
}
}
int nbComponentAvailables = psc.getVisibleComponents(orgaController).size();
if (nbComponentAvailables > 0) {
if (personalSpace == null
|| personalSpace.getAllComponentsInst().size() < nbComponentAvailables) {
writer.write(
"<item id=\"addComponent\" name=\""
+ EncodeHelper.escapeXml(helper.getString("lookSilverpeasV5.personalSpace.add"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:listComponents()\"/>");
}
}
}
}
writer.write("</spacePerso>");
}
protected boolean isLoadingContentNeeded(String userMenuDisplayMode, String userId, String spaceId,
List<UserFavoriteSpaceVO> listUFS, OrganizationController orgaController) {
if (DISABLE.equalsIgnoreCase(userMenuDisplayMode) || ALL.equalsIgnoreCase(userMenuDisplayMode)) {
return true;
} else if (BOOKMARKS.equalsIgnoreCase(userMenuDisplayMode)) {
if (isUserFavoriteSpace(listUFS, spaceId)
|| containsFavoriteSubSpace(spaceId, listUFS, orgaController, userId)) {
return true;
}
}
return false;
}
/**
* a Space is visible if at least one of its items is visible for the currentUser
* @param userId
* @param spaceId
* @param orgaController
* @return true or false
*/
protected boolean isSpaceVisible(String userId, String spaceId, OrganizationController orgaController) {
String compoIds[] = orgaController.getAvailCompoIds(spaceId, userId);
for (String id : compoIds) {
ComponentInst compInst = orgaController.getComponentInst(id);
if (!compInst.isHidden()) {
return true;
}
}
return false;
}
protected boolean isSpaceBeforeComponentNeeded(SpaceInstLight space) {
// Display computing : First look at global configuration
if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_BEFORE)) {
return true;
} else if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_AFTER)) {
return false;
} else if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_TODEFINE)) {
return space.isDisplaySpaceFirst();
}
return true;
}
}
| war-core/src/main/java/com/silverpeas/lookV5/AjaxServletLookV5.java | /**
* Copyright (C) 2000 - 2009 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.lookV5;
import static com.stratelia.silverpeas.util.SilverpeasSettings.readBoolean;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.silverpeas.external.filesharing.model.FileSharingInterface;
import com.silverpeas.external.filesharing.model.FileSharingInterfaceImpl;
import com.silverpeas.external.webConnections.dao.WebConnectionsImpl;
import com.silverpeas.external.webConnections.model.WebConnectionsInterface;
import com.silverpeas.jobStartPagePeas.JobStartPagePeasSettings;
import com.silverpeas.look.LookHelper;
import com.silverpeas.util.EncodeHelper;
import com.silverpeas.util.StringUtil;
import com.stratelia.silverpeas.pdc.control.PdcBm;
import com.stratelia.silverpeas.pdc.control.PdcBmImpl;
import com.stratelia.silverpeas.pdc.model.PdcException;
import com.stratelia.silverpeas.pdc.model.SearchAxis;
import com.stratelia.silverpeas.pdc.model.SearchContext;
import com.stratelia.silverpeas.pdc.model.Value;
import com.stratelia.silverpeas.peasCore.MainSessionController;
import com.stratelia.silverpeas.peasCore.URLManager;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
import com.stratelia.webactiv.beans.admin.Admin;
import com.stratelia.webactiv.beans.admin.ComponentInst;
import com.stratelia.webactiv.beans.admin.OrganizationController;
import com.stratelia.webactiv.beans.admin.PersonalSpaceController;
import com.stratelia.webactiv.beans.admin.SpaceInst;
import com.stratelia.webactiv.beans.admin.SpaceInstLight;
import com.stratelia.webactiv.beans.admin.UserFavoriteSpaceManager;
import com.stratelia.webactiv.beans.admin.instance.control.Instanciateur;
import com.stratelia.webactiv.beans.admin.instance.control.WAComponent;
import com.stratelia.webactiv.organization.DAOFactory;
import com.stratelia.webactiv.organization.UserFavoriteSpaceDAO;
import com.stratelia.webactiv.organization.UserFavoriteSpaceVO;
import com.stratelia.webactiv.util.FileRepositoryManager;
import com.stratelia.webactiv.util.ResourceLocator;
import com.stratelia.webactiv.util.viewGenerator.html.GraphicElementFactory;
public class AjaxServletLookV5 extends HttpServlet {
private static final String DISABLE = "DISABLE";
private static final String ALL = "ALL";
private static final String BOOKMARKS = "BOOKMARKS";
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
MainSessionController m_MainSessionCtrl = (MainSessionController) session.getAttribute(
"SilverSessionController");
GraphicElementFactory gef = (GraphicElementFactory) session.getAttribute(
"SessionGraphicElementFactory");
LookHelper helper = (LookHelper) session.getAttribute("Silverpeas_LookHelper");
OrganizationController orgaController = m_MainSessionCtrl.getOrganizationController();
String userId = m_MainSessionCtrl.getUserId();
String language = m_MainSessionCtrl.getFavoriteLanguage();
// Get ajax action
String responseId = req.getParameter("ResponseId");
String init = req.getParameter("Init");
String spaceId = req.getParameter("SpaceId");
String componentId = req.getParameter("ComponentId");
String axisId = req.getParameter("AxisId");
String valuePath = req.getParameter("ValuePath");
String getPDC = req.getParameter("GetPDC");
String pdc = req.getParameter("Pdc");
// New request parameter to manage Bookmarks view or classical view
String userMenuDisplayMode = req.getParameter("UserMenuDisplayMode");
String defaultLook = gef.getCurrentLookName();
boolean displayContextualPDC = helper.displayContextualPDC();
boolean displayPDC = "true".equalsIgnoreCase(getPDC);
// User favorite space DAO
List<UserFavoriteSpaceVO> listUserFS = new ArrayList<UserFavoriteSpaceVO>();
if (!DISABLE.equalsIgnoreCase(helper.getDisplayUserFavoriteSpace())) {
UserFavoriteSpaceDAO ufsDAO = DAOFactory.getUserFavoriteSpaceDAO();
listUserFS = ufsDAO.getListUserFavoriteSpace(userId);
}
if (StringUtil.isDefined(componentId)) {
helper.setComponentIdAndSpaceIds(null, null, componentId);
} else if (StringUtil.isDefined(spaceId) && !isPersonnalSpace(spaceId)) {
helper.setSpaceIdAndSubSpaceId(spaceId);
}
if (StringUtil.isDefined(userMenuDisplayMode)) {
helper.setDisplayUserFavoriteSpace(userMenuDisplayMode);
} else {
userMenuDisplayMode = helper.getDisplayUserFavoriteSpace();
}
res.setContentType("text/xml");
res.setHeader("charset", "UTF-8");
Writer writer = res.getWriter();
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writer.write("<ajax-response>");
writer.write("<response type=\"object\" id=\"" + responseId + "\">");
if ("1".equals(init)) {
if (!StringUtil.isDefined(spaceId) && !StringUtil.isDefined(componentId)) {
displayFirstLevelSpaces(userId, language, defaultLook, orgaController,
helper, writer, listUserFS, userMenuDisplayMode);
} else {
// First get space's path cause it can be a subspace
List<String> spaceIdsPath = getSpaceIdsPath(spaceId, componentId,
orgaController);
// space transverse
displaySpace(spaceId, componentId, spaceIdsPath, userId, language,
defaultLook, displayPDC, true, orgaController, helper, writer, listUserFS,
userMenuDisplayMode);
// other spaces
displayTree(userId, componentId, spaceIdsPath, language,
defaultLook, orgaController, helper, writer, listUserFS, userMenuDisplayMode);
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC,
m_MainSessionCtrl, writer);
}
} else if (StringUtil.isDefined(axisId) && StringUtil.isDefined(valuePath)) {
try {
writer.write("<pdc>");
getPertinentValues(spaceId, componentId, userId, axisId, valuePath,
displayContextualPDC, m_MainSessionCtrl, writer);
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
} else if (StringUtil.isDefined(spaceId)) {
if (isPersonnalSpace(spaceId)) {
// Affichage de l'espace perso
ResourceLocator settings = gef.getFavoriteLookSettings();
ResourceLocator message = new ResourceLocator(
"com.stratelia.webactiv.homePage.multilang.homePageBundle", language);
serializePersonalSpace(writer, userId, language, orgaController, helper, settings, message);
} else {
// First get space's path cause it can be a subspace
List<String> spaceIdsPath = getSpaceIdsPath(spaceId, componentId, orgaController);
displaySpace(spaceId, componentId, spaceIdsPath, userId, language, defaultLook, displayPDC,
false, orgaController, helper, writer, listUserFS, userMenuDisplayMode);
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC, m_MainSessionCtrl,
writer);
}
} else if (StringUtil.isDefined(componentId)) {
displayPDC(getPDC, spaceId, componentId, userId, displayContextualPDC, m_MainSessionCtrl,
writer);
} else if (StringUtil.isDefined(pdc)) {
displayNotContextualPDC(userId, m_MainSessionCtrl, writer);
}
writer.write("</response>");
writer.write("</ajax-response>");
}
private void displayNotContextualPDC(String userId,
MainSessionController mainSC, Writer writer) throws IOException {
try {
writer.write("<pdc>");
getPertinentAxis(null, null, userId, mainSC, writer);
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
}
private void displayPDC(String getPDC, String spaceId, String componentId,
String userId, boolean displayContextualPDC, MainSessionController mainSC, Writer writer)
throws IOException {
try {
writer.write("<pdc>");
if ("true".equalsIgnoreCase(getPDC)) {
getPertinentAxis(spaceId, componentId, userId, mainSC, writer);
}
writer.write("</pdc>");
} catch (PdcException e) {
SilverTrace.error("lookSilverpeasV5", "Ajax", "root.ERROR");
}
}
private List<String> getSpaceIdsPath(String spaceId, String componentId,
OrganizationController orgaController) {
List<SpaceInst> spacePath = null;
if (StringUtil.isDefined(spaceId)) {
spacePath = orgaController.getSpacePath(spaceId);
} else if (StringUtil.isDefined(componentId)) {
spacePath = orgaController.getSpacePathToComponent(componentId);
}
List<String> spaceIdsPath = null;
for (int s = 0; s < spacePath.size(); s++) {
SpaceInst space = spacePath.get(s);
if (spaceIdsPath == null) {
spaceIdsPath = new ArrayList<String>();
}
if (!space.getId().startsWith(Admin.SPACE_KEY_PREFIX)) {
spaceIdsPath.add(Admin.SPACE_KEY_PREFIX + space.getId());
} else {
spaceIdsPath.add(space.getId());
}
}
return spaceIdsPath;
}
/**
* @param spaceId : space identifier
* @param listUFS : the list of user favorite space
* @param orgaController : the OrganizationController object
* @return true if the current space contains user favorites sub space, false else if
*/
private boolean containsFavoriteSubSpace(String spaceId, List<UserFavoriteSpaceVO> listUFS,
OrganizationController orgaController, String userId) {
return UserFavoriteSpaceManager.containsFavoriteSubSpace(spaceId, listUFS, orgaController,
userId);
}
/**
* @param listUFS : the list of user favorite space
* @param spaceId : space identifier
* @return true if list of user favorites space contains spaceId identifier, false else if
*/
private boolean isUserFavoriteSpace(List<UserFavoriteSpaceVO> listUFS, String spaceId) {
return UserFavoriteSpaceManager.isUserFavoriteSpace(listUFS, spaceId);
}
/**
* displaySpace build XML response tree of current spaceId
* @param spaceId
* @param componentId
* @param spacePath
* @param userId
* @param language
* @param defaultLook
* @param displayPDC
* @param displayTransverse
* @param orgaController
* @param helper
* @param writer
* @param listUFS
* @param userMenuDisplayMode TODO
* @throws IOException
*/
private void displaySpace(String spaceId, String componentId, List<String> spacePath,
String userId, String language, String defaultLook,
boolean displayPDC, boolean displayTransverse,
OrganizationController orgaController, LookHelper helper, Writer writer,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode) throws IOException {
boolean isTransverse = false;
int i = 0;
while (!isTransverse && i < spacePath.size()) {
String spaceIdInPath = spacePath.get(i);
isTransverse = helper.getTopSpaceIds().contains(spaceIdInPath);
i++;
}
if (displayTransverse && !isTransverse) {
return;
}
boolean open = (spacePath != null && spacePath.contains(spaceId));
if (open) {
spaceId = spacePath.remove(0);
}
// Affichage de l'espace collaboratif
SpaceInstLight space = orgaController.getSpaceInstLightById(spaceId);
if (space != null && isSpaceVisible(userId, spaceId, orgaController)) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item open=\"").append(open).append("\" ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append(">");
writer.write(itemSB.toString());
if (open) {
// Default display configuration
boolean spaceBeforeComponent = isSpaceBeforeComponentNeeded(space);
if (spaceBeforeComponent) {
getSubSpaces(spaceId, userId, spacePath, componentId, language,
defaultLook, orgaController, helper, writer, listUFS, userMenuDisplayMode);
getComponents(spaceId, componentId, userId, language, orgaController,
writer, userMenuDisplayMode, listUFS);
} else {
getComponents(spaceId, componentId, userId, language, orgaController,
writer, userMenuDisplayMode, listUFS);
getSubSpaces(spaceId, userId, spacePath, componentId, language,
defaultLook, orgaController, helper, writer, listUFS, userMenuDisplayMode);
}
}
}
writer.write("</item>");
}
/**
* @param userId
* @param orgaController
* @param listUFS
* @param space
* @param helper
* @return an XML user favorite space attribute only if User Favorite Space is enable
*/
private String getFavoriteSpaceAttribute(String userId, OrganizationController orgaController,
List<UserFavoriteSpaceVO> listUFS, SpaceInstLight space, LookHelper helper) {
StringBuilder favSpace = new StringBuilder(20);
if (!DISABLE.equalsIgnoreCase(helper.getDisplayUserFavoriteSpace())) {
favSpace.append(" favspace=\"");
if (isUserFavoriteSpace(listUFS, space.getShortId())) {
favSpace.append("true");
} else {
if (helper.isEnableUFSContainsState()) {
if (containsFavoriteSubSpace(space.getShortId(), listUFS, orgaController, userId)) {
favSpace.append("contains");
} else {
favSpace.append("false");
}
} else {
favSpace.append("false");
}
}
favSpace.append("\"");
}
return favSpace.toString();
}
private void displayTree(String userId, String targetComponentId,
List<String> spacePath, String language, String defaultLook,
OrganizationController orgaController, LookHelper helper, Writer out,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode) throws IOException {
// Then get all first level spaces
String[] availableSpaceIds = getRootSpaceIds(userId, orgaController, helper);
out.write("<spaces menu=\"" + helper.getDisplayUserFavoriteSpace() + "\">");
String spaceId = null;
for (int nI = 0; nI < availableSpaceIds.length; nI++) {
spaceId = availableSpaceIds[nI];
boolean loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, spaceId, orgaController)) {
displaySpace(spaceId, targetComponentId, spacePath, userId, language,
defaultLook, false, false, orgaController, helper, out, listUFS, userMenuDisplayMode);
}
loadCurSpace = false;
}
out.write("</spaces>");
}
private String getSpaceAttributes(SpaceInstLight space, String language,
String defaultLook, LookHelper helper) {
String spaceLook = space.getLook();
if (!StringUtil.isDefined(spaceLook)) {
spaceLook = defaultLook;
}
String spaceWallpaper = getWallPaper(space.getFullId());
boolean isTransverse = helper.getTopSpaceIds().contains(space.getFullId());
String attributeType = "space";
if (isTransverse) {
attributeType = "spaceTransverse";
}
return "id=\"" + space.getFullId() + "\" name=\""
+ EncodeHelper.escapeXml(space.getName(language)) + "\" description=\""
+ EncodeHelper.escapeXml(space.getDescription()) + "\" type=\""
+ attributeType + "\" kind=\"space\" level=\"" + space.getLevel()
+ "\" look=\"" + spaceLook + "\" wallpaper=\"" + spaceWallpaper + "\"";
}
private void displayFirstLevelSpaces(String userId, String language,
String defaultLook, OrganizationController orgaController, LookHelper helper,
Writer out, List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode)
throws IOException {
String[] availableSpaceIds = getRootSpaceIds(userId, orgaController, helper);
// Loop variable declaration
SpaceInstLight space = null;
String spaceId = null;
// Start writing XML spaces node
out.write("<spaces menu=\"" + helper.getDisplayUserFavoriteSpace() + "\">");
for (int nI = 0; nI < availableSpaceIds.length; nI++) {
spaceId = availableSpaceIds[nI];
boolean loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, spaceId, orgaController)) {
space = orgaController.getSpaceInstLightById(spaceId);
if (space != null) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append("/>");
out.write(itemSB.toString());
}
}
loadCurSpace = false;
}
out.write("</spaces>");
}
private void getSubSpaces(String spaceId, String userId, List<String> spacePath,
String targetComponentId, String language, String defaultLook,
OrganizationController orgaController, LookHelper helper, Writer out,
List<UserFavoriteSpaceVO> listUFS, String userMenuDisplayMode)
throws IOException {
String[] spaceIds = orgaController.getAllSubSpaceIds(spaceId, userId);
String subSpaceId = null;
boolean open = false;
boolean loadCurSpace = false;
for (int nI = 0; nI < spaceIds.length; nI++) {
subSpaceId = spaceIds[nI];
SpaceInstLight space = orgaController.getSpaceInstLightById(subSpaceId);
if (space != null) {
open = (spacePath != null && spacePath.contains(subSpaceId));
// Check user favorite space
loadCurSpace = isLoadingContentNeeded(userMenuDisplayMode, userId, subSpaceId, listUFS,
orgaController);
if (loadCurSpace && isSpaceVisible(userId, subSpaceId, orgaController)) {
StringBuilder itemSB = new StringBuilder(200);
itemSB.append("<item ");
itemSB.append(getSpaceAttributes(space, language, defaultLook, helper));
itemSB.append(" open=\"").append(open).append("\"");
itemSB.append(getFavoriteSpaceAttribute(userId, orgaController, listUFS, space, helper));
itemSB.append(">");
out.write(itemSB.toString());
if (open) {
// Default display configuration
boolean spaceBeforeComponent = isSpaceBeforeComponentNeeded(space);
// the subtree must be displayed
// components of expanded space must be displayed too
if (spaceBeforeComponent) {
getSubSpaces(subSpaceId, userId, spacePath, targetComponentId,
language, defaultLook, orgaController, helper, out, listUFS, userMenuDisplayMode);
getComponents(subSpaceId, targetComponentId, userId, language,
orgaController, out, userMenuDisplayMode, listUFS);
} else {
getComponents(subSpaceId, targetComponentId, userId, language,
orgaController, out, userMenuDisplayMode, listUFS);
getSubSpaces(subSpaceId, userId, spacePath, targetComponentId,
language, defaultLook, orgaController, helper, out, listUFS, userMenuDisplayMode);
}
}
out.write("</item>");
}
loadCurSpace = false;
}
}
}
private void getComponents(String spaceId, String targetComponentId,
String userId, String language, OrganizationController orgaController,
Writer out, String userMenuDisplayMode, List<UserFavoriteSpaceVO> listUFS) throws IOException {
boolean loadCurComponent = isLoadingContentNeeded(userMenuDisplayMode, userId, spaceId, listUFS,
orgaController);
if (loadCurComponent) {
String[] componentIds = orgaController.getAvailCompoIdsAtRoot(spaceId, userId);
SpaceInstLight space = orgaController.getSpaceInstLightById(spaceId);
int level = space.getLevel() + 1;
ComponentInst component = null;
boolean open = false;
String url = null;
String kind = null;
for (int c = 0; componentIds != null && c < componentIds.length; c++) {
component = orgaController.getComponentInst(componentIds[c]);
if (component != null && !component.isHidden()) {
open = (targetComponentId != null && component.getId().equals(
targetComponentId));
url = URLManager.getURL(component.getName(), null, component.getId()) + "Main";
kind = component.getName();
WAComponent descriptor = Instanciateur.getWAComponent(component.getName());
if (descriptor != null
&& "RprocessManager".equalsIgnoreCase(descriptor.getRequestRouter())) {
kind = "processManager";
}
out.write("<item id=\"" + component.getId() + "\" name=\""
+ EncodeHelper.escapeXml(component.getLabel(language))
+ "\" description=\""
+ EncodeHelper.escapeXml(component.getDescription(language))
+ "\" type=\"component\" kind=\"" + EncodeHelper.escapeXml(kind)
+ "\" level=\"" + level + "\" open=\"" + open + "\" url=\"" + url
+ "\"/>");
}
}
}
}
private void getPertinentAxis(String spaceId, String componentId,
String userId, MainSessionController mainSC, Writer out)
throws PdcException, IOException {
List<SearchAxis> primaryAxis = null;
SearchContext searchContext = new SearchContext();
PdcBm pdc = new PdcBmImpl();
if (StringUtil.isDefined(componentId)) {
// L'item courant est un composant
primaryAxis = pdc.getPertinentAxisByInstanceId(searchContext, "P",
componentId);
} else {
List<String> cmps = null;
if (StringUtil.isDefined(spaceId)) {
// L'item courant est un espace
cmps = getAvailableComponents(spaceId, userId, mainSC.getOrganizationController());
} else {
cmps = Arrays.asList(mainSC.getUserAvailComponentIds());
}
if (cmps != null && cmps.size() > 0) {
primaryAxis = pdc.getPertinentAxisByInstanceIds(searchContext, "P",
cmps);
}
}
SearchAxis axis = null;
if (primaryAxis != null) {
for (int a = 0; a < primaryAxis.size(); a++) {
axis = primaryAxis.get(a);
if (axis != null && axis.getNbObjects() > 0) {
out.write("<axis id=\"" + axis.getAxisId() + "\" name=\""
+ EncodeHelper.escapeXml(axis.getAxisName())
+ "\" description=\"\" level=\"0\" open=\"false\" nbObjects=\""
+ axis.getNbObjects() + "\"/>");
}
}
}
pdc = null;
primaryAxis = null;
}
private List<String> getAvailableComponents(String spaceId, String userId,
OrganizationController orgaController) {
String a[] = orgaController.getAvailCompoIds(spaceId, userId);
return Arrays.asList(a);
}
private String getValueId(String valuePath) {
// cherche l'id de la valeur
// valuePath est de la forme /0/1/2/
String valueId = valuePath;
int len = valuePath.length();
valueId = valuePath.substring(0, len - 1); // on retire le slash
if ("/".equals(valuePath)) {
valueId = valueId.substring(1);// on retire le slash
} else {
int lastIdx = valueId.lastIndexOf('/');
valueId = valueId.substring(lastIdx + 1);
}
return valueId;
}
private List<Value> getPertinentValues(String spaceId, String componentId,
String userId, String axisId, String valuePath,
boolean displayContextualPDC, MainSessionController mainSC, Writer out) throws IOException,
PdcException {
List<Value> daughters = null;
SearchContext searchContext = new SearchContext();
searchContext.setUserId(userId);
if (StringUtil.isDefined(axisId)) {
PdcBm pdc = new PdcBmImpl();
// TODO : some improvements can be made here !
// daughters contains all pertinent values of axis instead of pertinent
// daughters only
if (displayContextualPDC) {
if (StringUtil.isDefined(componentId)) {
daughters = pdc.getPertinentDaughterValuesByInstanceId(searchContext,
axisId, valuePath, componentId);
} else {
List<String> cmps = getAvailableComponents(spaceId, userId, mainSC.
getOrganizationController());
daughters = pdc.getPertinentDaughterValuesByInstanceIds(
searchContext, axisId, valuePath, cmps);
}
} else {
List<String> cmps = Arrays.asList(mainSC.getUserAvailComponentIds());
daughters = pdc.getPertinentDaughterValuesByInstanceIds(searchContext,
axisId, valuePath, cmps);
}
String valueId = getValueId(valuePath);
Value value = null;
for (int v = 0; v < daughters.size(); v++) {
value = daughters.get(v);
if (value != null && value.getMotherId().equals(valueId)) {
out.write("<value id=\"" + value.getFullPath() + "\" name=\""
+ EncodeHelper.escapeXml(value.getName())
+ "\" description=\"\" level=\"" + value.getLevelNumber()
+ "\" open=\"false\" nbObjects=\"" + value.getNbObjects()
+ "\"/>");
}
}
pdc = null;
}
return daughters;
}
private String getWallPaper(String spaceId) {
String path = FileRepositoryManager.getAbsolutePath("Space" + spaceId.substring(2),
new String[]{"look"});
File file = new File(path + "wallPaper.jpg");
if (file.isFile()) {
return "1";
} else {
file = new File(path + "wallPaper.gif");
if (file.isFile()) {
return "1";
}
}
return "0";
}
private String[] getRootSpaceIds(String userId, OrganizationController orgaController,
LookHelper helper) {
List<String> rootSpaceIds = new ArrayList<String>();
List<String> topSpaceIds = helper.getTopSpaceIds();
String[] availableSpaceIds = orgaController.getAllRootSpaceIds(userId);
for (int i = 0; i < availableSpaceIds.length; i++) {
if (!topSpaceIds.contains(availableSpaceIds[i])) {
rootSpaceIds.add(availableSpaceIds[i]);
}
}
return rootSpaceIds.toArray(new String[rootSpaceIds.size()]);
}
protected boolean isPersonnalSpace(String spaceId) {
return "spacePerso".equalsIgnoreCase(spaceId);
}
protected void serializePersonalSpace(Writer writer, String userId, String language,
OrganizationController orgaController, LookHelper helper, ResourceLocator settings,
ResourceLocator message) throws IOException {
// Affichage de l'espace perso
writer.write("<spacePerso id=\"spacePerso\" type=\"space\" level=\"0\">");
boolean isAnonymousAccess = helper.isAnonymousAccess();
if (!isAnonymousAccess && readBoolean(settings, "personnalSpaceVisible", true)) {
if (readBoolean(settings, "agendaVisible", true)) {
writer.write("<item id=\"agenda\" name=\""
+ EncodeHelper.escapeXml(message.getString("Diary"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_AGENDA) + "Main\"/>");
}
if (readBoolean(settings, "todoVisible", true)) {
writer.write("<item id=\"todo\" name=\""
+ EncodeHelper.escapeXml(message.getString("ToDo"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_TODO) + "todo.jsp\"/>");
}
if (readBoolean(settings, "notificationVisible", true)) {
writer.write("<item id=\"notification\" name=\""
+ EncodeHelper.escapeXml(message.getString("Mail"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_SILVERMAIL) + "Main\"/>");
}
if (readBoolean(settings, "interestVisible", true)) {
writer.write("<item id=\"subscriptions\" name=\""
+ EncodeHelper.escapeXml(message.getString("MyInterestCenters"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_PDCSUBSCRIPTION)
+ "subscriptionList.jsp\"/>");
}
if (readBoolean(settings, "favRequestVisible", true)) {
writer.write("<item id=\"requests\" name=\""
+ EncodeHelper.escapeXml(message.getString("FavRequests"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_INTERESTCENTERPEAS)
+ "iCenterList.jsp\"/>");
}
if (readBoolean(settings, "linksVisible", true)) {
writer.write("<item id=\"links\" name=\""
+ EncodeHelper.escapeXml(message.getString("FavLinks"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_MYLINKSPEAS)
+ "Main\"/>");
}
if (readBoolean(settings, "fileSharingVisible", true)) {
FileSharingInterface fileSharing = new FileSharingInterfaceImpl();
if (!fileSharing.getTicketsByUser(userId).isEmpty()) {
writer.write("<item id=\"fileSharing\" name=\""
+ EncodeHelper.escapeXml(message.getString("FileSharing"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_FILESHARING)
+ "Main\"/>");
}
}
// mes connexions
if (readBoolean(settings, "webconnectionsVisible", true)) {
WebConnectionsInterface webConnections = new WebConnectionsImpl();
if (webConnections.getConnectionsByUser(userId).size() > 0) {
writer.write("<item id=\"webConnections\" name=\""
+ EncodeHelper.escapeXml(message.getString("WebConnections"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_WEBCONNECTIONS)
+ "Main\"/>");
}
}
if (readBoolean(settings, "customVisible", true)) {
writer.write("<item id=\"personalize\" name=\""
+ EncodeHelper.escapeXml(message.getString("Personalization"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_MYPROFILE)
+ "Main\"/>");
}
if (readBoolean(settings, "mailVisible", true)) {
writer.write(
"<item id=\"notifAdmins\" name=\""
+ EncodeHelper.escapeXml(message.getString("Feedback"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:notifyAdministrators()\"/>");
}
if (readBoolean(settings, "clipboardVisible", true)) {
writer.write(
"<item id=\"clipboard\" name=\""
+ EncodeHelper.escapeXml(message.getString("Clipboard"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:openClipboard()\"/>");
}
// fonctionnalité "Trouver une date"
if (readBoolean(settings, "scheduleEventVisible", true)) {
writer.write("<item id=\"scheduleevent\" name=\""
+ EncodeHelper.escapeXml(message.getString("ScheduleEvent"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\""
+ URLManager.getURL(URLManager.CMP_SCHEDULE_EVENT) + "Main\"/>");
}
if (readBoolean(settings, "PersonalSpaceAddingsEnabled", true)) {
PersonalSpaceController psc = new PersonalSpaceController();
SpaceInst personalSpace = psc.getPersonalSpace(userId);
if (personalSpace != null) {
for (ComponentInst component : personalSpace.getAllComponentsInst()) {
String label =
helper.getString("lookSilverpeasV5.personalSpace." + component.getName());
if (!StringUtil.isDefined(label)) {
label = component.getName();
}
String url = URLManager.getURL(component.getName(), null, component.getName()
+ component.getId()) + "Main";
writer.write("<item id=\""
+ component.getName()
+ component.getId()
+ "\" name=\""
+ EncodeHelper.escapeXml(label)
+ "\" description=\"\" type=\"component\" kind=\"personalComponent\" level=\"1\" open=\"false\" url=\""
+ url + "\"/>");
}
}
int nbComponentAvailables = psc.getVisibleComponents(orgaController).size();
if (nbComponentAvailables > 0) {
if (personalSpace == null
|| personalSpace.getAllComponentsInst().size() < nbComponentAvailables) {
writer.write(
"<item id=\"addComponent\" name=\""
+ EncodeHelper.escapeXml(helper.getString("lookSilverpeasV5.personalSpace.add"))
+ "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:listComponents()\"/>");
}
}
}
}
writer.write("</spacePerso>");
}
protected boolean isLoadingContentNeeded(String userMenuDisplayMode, String userId, String spaceId,
List<UserFavoriteSpaceVO> listUFS, OrganizationController orgaController) {
if (DISABLE.equalsIgnoreCase(userMenuDisplayMode) || ALL.equalsIgnoreCase(userMenuDisplayMode)) {
return true;
} else if (BOOKMARKS.equalsIgnoreCase(userMenuDisplayMode)) {
if (isUserFavoriteSpace(listUFS, spaceId)
|| containsFavoriteSubSpace(spaceId, listUFS, orgaController, userId)) {
return true;
}
}
return false;
}
/**
* a Space is visible if at least one of its items is visible for the currentUser
* @param userId
* @param spaceId
* @param orgaController
* @return true or false
*/
protected boolean isSpaceVisible(String userId, String spaceId, OrganizationController orgaController) {
String compoIds[] = orgaController.getAvailCompoIds(spaceId, userId);
for (String id : compoIds) {
ComponentInst compInst = orgaController.getComponentInst(id);
if (!compInst.isHidden()) {
return true;
}
}
return false;
}
protected boolean isSpaceBeforeComponentNeeded(SpaceInstLight space) {
// Display computing : First look at global configuration
if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_BEFORE)) {
return true;
} else if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_AFTER)) {
return false;
} else if (JobStartPagePeasSettings.SPACEDISPLAYPOSITION_CONFIG.equalsIgnoreCase(
JobStartPagePeasSettings.SPACEDISPLAYPOSITION_TODEFINE)) {
return space.isDisplaySpaceFirst();
}
return true;
}
}
| By default, "Schedule an event" tool is not visible...
git-svn-id: 95dd7209ec50d6c3a4c961d97f2c75f69cb97ab1@2839 a8e77078-a1c7-4fa5-b8fc-53c5178a176c
| war-core/src/main/java/com/silverpeas/lookV5/AjaxServletLookV5.java | By default, "Schedule an event" tool is not visible... | <ide><path>ar-core/src/main/java/com/silverpeas/lookV5/AjaxServletLookV5.java
<ide> + "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"javascript:openClipboard()\"/>");
<ide> }
<ide> // fonctionnalité "Trouver une date"
<del> if (readBoolean(settings, "scheduleEventVisible", true)) {
<add> if (readBoolean(settings, "scheduleEventVisible", false)) {
<ide> writer.write("<item id=\"scheduleevent\" name=\""
<ide> + EncodeHelper.escapeXml(message.getString("ScheduleEvent"))
<ide> + "\" description=\"\" type=\"component\" kind=\"\" level=\"1\" open=\"false\" url=\"" |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/sproutigy/commons/basement/collections/LazyIterator.java' did not match any file(s) known to git
| d592179077677f42bf92e5ec5cd5214e479233b3 | 1 | Sproutigy/Java-Commons-Basement | package com.sproutigy.commons.basement.collections;
import java.util.Iterator;
/**
* LazyIterator keeps reference to Iterable source
* and calls its iterator() method when it is needed
* @param <E> element type
*/
public final class LazyIterator<E> implements Iterator<E> {
private Iterable<E> source;
private Iterator<E> innerIterator;
public LazyIterator(Iterable<E> source) {
this.source = source;
}
@Override
public boolean hasNext() {
if (innerIterator == null) {
innerIterator = source.iterator();
}
return innerIterator.hasNext();
}
@Override
public E next() {
if (innerIterator == null) {
innerIterator = source.iterator();
}
return innerIterator.next();
}
@Override
public void remove() {
if (innerIterator == null) {
innerIterator = source.iterator();
}
innerIterator.remove();
}
}
| src/main/java/com/sproutigy/commons/basement/collections/LazyIterator.java | LazyIterator
| src/main/java/com/sproutigy/commons/basement/collections/LazyIterator.java | LazyIterator | <ide><path>rc/main/java/com/sproutigy/commons/basement/collections/LazyIterator.java
<add>package com.sproutigy.commons.basement.collections;
<add>
<add>import java.util.Iterator;
<add>
<add>/**
<add> * LazyIterator keeps reference to Iterable source
<add> * and calls its iterator() method when it is needed
<add> * @param <E> element type
<add> */
<add>public final class LazyIterator<E> implements Iterator<E> {
<add>
<add> private Iterable<E> source;
<add> private Iterator<E> innerIterator;
<add>
<add> public LazyIterator(Iterable<E> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> public boolean hasNext() {
<add> if (innerIterator == null) {
<add> innerIterator = source.iterator();
<add> }
<add> return innerIterator.hasNext();
<add> }
<add>
<add> @Override
<add> public E next() {
<add> if (innerIterator == null) {
<add> innerIterator = source.iterator();
<add> }
<add> return innerIterator.next();
<add> }
<add>
<add> @Override
<add> public void remove() {
<add> if (innerIterator == null) {
<add> innerIterator = source.iterator();
<add> }
<add> innerIterator.remove();
<add> }
<add>} |
|
Java | apache-2.0 | 1595252f580bf261f573ed3a3d973f2a53da286f | 0 | ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp,ilscipio/scipio-erp | package org.ofbiz.order.shoppingcart;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.service.LocalDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
* SCIPIO: Cart factory to replace hardcoded ShoppingCart and WebShoppingCart constructors.
* <p>
* NOTE: The actual instance is represented by {@link ShoppingCartFactory.Factory}, due to the static
* methods being the exact same as the instance methods which will lead to obscure-bug-making-errors
* if try to put both in same class with slightly different names (this way the compiler will catch everything).
* <p>
* To use this class, create a file named <code>orderstoreconfig.properties</code> in your component's config folder
* and the following entry using your store's ID (the default factory class is given here):
* <ul>
* <li>Per-store config: <code>store.PRODUCT_STORE_ID.cart.factoryClass=org.ofbiz.order.shoppingcart.ShoppingCartFactory$DefaultShoppingCartFactory</code></li>
* <li>Global default config: <code>store.DEFAULT.cart.factoryClass=org.ofbiz.order.shoppingcart.ShoppingCartFactory$DefaultShoppingCartFactory</code></li>
* </ul>
*/
public abstract class ShoppingCartFactory {
public static final String ORDER_STORE_CONFIG_PROPFILE = "orderstoreconfig";
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static final Map<String, Factory> storeIdCache = readInstances();
private static final Factory defaultFactory = readDefaultInstance(storeIdCache);
/** The instance is represented by {@link Factory} nested class. */
private ShoppingCartFactory() {}
public static Factory get(Delegator delegator, String productStoreId) {
Factory factory = storeIdCache.get(productStoreId);
return (factory != null) ? factory : defaultFactory;
}
public static Factory get(HttpServletRequest request) {
return get(null, ProductStoreWorker.getProductStoreId(request));
}
/** @deprecated Not passing delegator was a bad idea */
@Deprecated
public static Factory get(String productStoreId) {
return get(null, productStoreId);
}
private static Map<String, Factory> readInstances() {
Map<String, Factory> factoryMap = new HashMap<>();
Properties props = UtilProperties.readMergedPropertiesFromAllComponents(ORDER_STORE_CONFIG_PROPFILE);
Map<String, Map<String, String>> configs = new LinkedHashMap<>();
UtilProperties.extractPropertiesWithPrefixAndId(configs, props, "store.");
for(Map.Entry<String, Map<String, String>> entry : configs.entrySet()) {
String productStoreId = entry.getKey();
String factoryClsName = entry.getValue().get("cart.factoryClass");
if (UtilValidate.isNotEmpty(factoryClsName)) {
try {
Class<? extends Factory> factoryCls = (Class<? extends Factory>) Thread.currentThread().getContextClassLoader().loadClass(factoryClsName);
Factory factory = factoryCls.newInstance();
factoryMap.put(productStoreId, factory);
} catch(Exception e) {
Debug.logError("Could not load factory [" + factoryClsName + "] for store [" + productStoreId + "]", module);
}
}
}
Debug.logInfo("Read shopping cart factories: " + factoryMap, module);
return factoryMap;
}
private static Factory readDefaultInstance(Map<String, Factory> storeIdCache) {
Factory factory = storeIdCache.get("DEFAULT");
if (factory == null) {
factory = DefaultFactory.INSTANCE;
}
Debug.logInfo("Read default shopping cart factory: " + factory, module);
return factory;
}
// Static standard helper wrapper methods around the Factory methods, to help simplify code
// (the get() calls are unnecessary to write manually in code in all known cases, because delegator and productStoreId are always already known to the factory methods)
/** Creates new empty (non-web) ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
}
/** Creates new empty (non-web) ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
}
/** Creates a new empty (non-web) ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, locale, currencyUom);
}
/** Creates a new cloned (non-web) ShoppingCart Object, using legacy (partial) cloning. */
public static ShoppingCart copyShoppingCart(ShoppingCart cart) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart);
}
/** Creates a new cloned (non-web) ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
public static ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart, exactCopy);
}
/**
* Creates a new web ShoppingCart Object - full web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
public static ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return get(request).createWebShoppingCart(request, locale, currencyUom);
}
/**
* Creates a new web ShoppingCart Object - common web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
public static ShoppingCart createWebShoppingCart(HttpServletRequest request) {
return get(request).createWebShoppingCart(request);
}
/** Creates a new cloned web ShoppingCart Object, using legacy (partial) cloning. */
public static ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart);
}
/** Creates a new cloned web ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
public static ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart, exactCopy);
}
/** Creates a new cloned web ShoppingCart Object - performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
public static ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return get(request).copyWebShoppingCart(request, locale, currencyUom);
}
/** Creates a new empty (web) ShoppingCartHelper object. */
public static ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
return get(delegator, cart.getProductStoreId()).createShoppingCartHelper(delegator, dispatcher, cart);
}
// Instance methods and interfaces
/** Actual ShoppingCart factory and instance methods (mostly identical to the static methods) */
public interface Factory extends Serializable {
/** Creates new empty (non-web) ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId);
/** Creates new empty (non-web) ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom);
/** Creates a new empty (non-web) ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom);
/** Creates a new cloned (non-web) ShoppingCart Object, using legacy (partial) cloning. */
ShoppingCart copyShoppingCart(ShoppingCart cart);
/** Creates a new cloned (non-web) ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy);
/**
* Creates a new web ShoppingCart Object - full web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
/**
* Creates a new web ShoppingCart Object - common web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
ShoppingCart createWebShoppingCart(HttpServletRequest request);
/** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
ShoppingCart copyWebShoppingCart(ShoppingCart cart);
/** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy);
/** Creates a new cloned web ShoppingCart Object - performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
/** Creates a new empty (web) ShoppingCartHelper object. */
ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart);
}
public static abstract class BasicFactory implements Factory {
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
}
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
}
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
return new ShoppingCart(delegator, productStoreId, locale, currencyUom);
}
@Override
public ShoppingCart copyShoppingCart(ShoppingCart cart) {
return new ShoppingCart(cart);
}
@Override
public ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
return new ShoppingCart(cart, exactCopy);
}
@Override
public ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
return new ShoppingCartHelper(delegator, dispatcher, cart);
}
}
public static class DefaultFactory extends BasicFactory {
private static final DefaultFactory INSTANCE = new DefaultFactory();
@Override
public ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return new WebShoppingCart(request, locale, currencyUom);
}
@Override
public ShoppingCart createWebShoppingCart(HttpServletRequest request) {
return new WebShoppingCart(request);
}
@Override
public ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
return new WebShoppingCart(cart);
}
@Override
public ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
return new WebShoppingCart(cart, exactCopy);
}
@Override
public ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return new WebShoppingCart(request, locale, currencyUom);
}
}
}
| applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartFactory.java | package org.ofbiz.order.shoppingcart;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.service.LocalDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
/**
* SCIPIO: Cart factory to replace hardcoded ShoppingCart and WebShoppingCart constructors.
* <p>
* To use this class, create a file named <code>orderstoreconfig.properties</code> in your component's config folder
* and the following entry using your store's ID (the default factory class is given here):
* <ul>
* <li>Per-store config: <code>store.PRODUCT_STORE_ID.cart.factoryClass=org.ofbiz.order.shoppingcart.ShoppingCartFactory$DefaultShoppingCartFactory</code></li>
* <li>Global default config: <code>store.DEFAULT.cart.factoryClass=org.ofbiz.order.shoppingcart.ShoppingCartFactory$DefaultShoppingCartFactory</code></li>
* </ul>
*/
public abstract class ShoppingCartFactory {
public static final String ORDER_STORE_CONFIG_PROPFILE = "orderstoreconfig";
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static final Map<String, Factory> storeIdCache = readInstances();
private static final Factory defaultFactory = readDefaultInstance(storeIdCache);
public static Factory get(Delegator delegator, String productStoreId) {
Factory factory = storeIdCache.get(productStoreId);
return (factory != null) ? factory : defaultFactory;
}
public static Factory get(HttpServletRequest request) {
return get(null, ProductStoreWorker.getProductStoreId(request));
}
/** @deprecated Not passing delegator was a bad idea */
@Deprecated
public static Factory get(String productStoreId) {
return get(null, productStoreId);
}
// Static helper wrapper methods around the factory methods to help simplify code (the get() calls are unnecessary overhead almost every time)
/**
* Full web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
public static ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return get(request).createWebShoppingCart(request, locale, currencyUom);
}
/**
* Common web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
public static ShoppingCart createWebShoppingCart(HttpServletRequest request) {
return get(request).createWebShoppingCart(request);
}
/** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
public static ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart);
}
/** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
public static ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart, exactCopy);
}
/** Performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
public static ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return get(request).copyWebShoppingCart(request, locale, currencyUom);
}
/** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
public static ShoppingCart copyShoppingCart(ShoppingCart cart) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart);
}
/** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
public static ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart, exactCopy);
}
/** Creates new empty ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
}
/** Creates new empty ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
}
/** Creates a new empty ShoppingCart object. */
public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, locale, currencyUom);
}
/** Creates a new empty ShoppingCartHelper object. */
public static ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
return get(delegator, cart.getProductStoreId()).createShoppingCartHelper(delegator, dispatcher, cart);
}
/** The actual factory methods (mostly identical to the static methods) */
public interface Factory extends Serializable {
/**
* Full web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
/**
* Common web shopping cart constructor.
* <p>
* SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
* block, because it modifies session variables that must match the cart contents.
*/
ShoppingCart createWebShoppingCart(HttpServletRequest request);
/** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
ShoppingCart copyWebShoppingCart(ShoppingCart cart);
/** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy);
/** Performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
/** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
ShoppingCart copyShoppingCart(ShoppingCart cart);
/** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy);
/** Creates new empty ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId);
/** Creates new empty ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom);
/** Creates a new empty ShoppingCart object. */
ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom);
/** Creates a new empty ShoppingCartHelper object. */
ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart);
}
private static Map<String, Factory> readInstances() {
Map<String, Factory> factoryMap = new HashMap<>();
Properties props = UtilProperties.readMergedPropertiesFromAllComponents(ORDER_STORE_CONFIG_PROPFILE);
Map<String, Map<String, String>> configs = new LinkedHashMap<>();
UtilProperties.extractPropertiesWithPrefixAndId(configs, props, "store.");
for(Map.Entry<String, Map<String, String>> entry : configs.entrySet()) {
String productStoreId = entry.getKey();
String factoryClsName = entry.getValue().get("cart.factoryClass");
if (UtilValidate.isNotEmpty(factoryClsName)) {
try {
Class<? extends Factory> factoryCls = (Class<? extends Factory>) Thread.currentThread().getContextClassLoader().loadClass(factoryClsName);
Factory factory = factoryCls.newInstance();
factoryMap.put(productStoreId, factory);
} catch(Exception e) {
Debug.logError("Could not load factory [" + factoryClsName + "] for store [" + productStoreId + "]", module);
}
}
}
Debug.logInfo("Read shopping cart factories: " + factoryMap, module);
return factoryMap;
}
private static Factory readDefaultInstance(Map<String, Factory> storeIdCache) {
Factory factory = storeIdCache.get("DEFAULT");
if (factory == null) {
factory = DefaultFactory.INSTANCE;
}
Debug.logInfo("Read default shopping cart factory: " + factory, module);
return factory;
}
public static abstract class BasicFactory implements Factory {
@Override
public ShoppingCart copyShoppingCart(ShoppingCart cart) {
return new ShoppingCart(cart);
}
@Override
public ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
return new ShoppingCart(cart, exactCopy);
}
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
}
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
}
@Override
public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
return new ShoppingCart(delegator, productStoreId, locale, currencyUom);
}
@Override
public ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
return new ShoppingCartHelper(delegator, dispatcher, cart);
}
}
public static class DefaultFactory extends BasicFactory {
private static final DefaultFactory INSTANCE = new DefaultFactory();
@Override
public ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return new WebShoppingCart(request, locale, currencyUom);
}
@Override
public ShoppingCart createWebShoppingCart(HttpServletRequest request) {
return new WebShoppingCart(request);
}
@Override
public ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
return new WebShoppingCart(cart);
}
@Override
public ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
return new WebShoppingCart(cart, exactCopy);
}
@Override
public ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
return new WebShoppingCart(request, locale, currencyUom);
}
}
}
| ShoppingCartFactory: cleanups
| applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartFactory.java | ShoppingCartFactory: cleanups | <ide><path>pplications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartFactory.java
<ide>
<ide> /**
<ide> * SCIPIO: Cart factory to replace hardcoded ShoppingCart and WebShoppingCart constructors.
<add> * <p>
<add> * NOTE: The actual instance is represented by {@link ShoppingCartFactory.Factory}, due to the static
<add> * methods being the exact same as the instance methods which will lead to obscure-bug-making-errors
<add> * if try to put both in same class with slightly different names (this way the compiler will catch everything).
<ide> * <p>
<ide> * To use this class, create a file named <code>orderstoreconfig.properties</code> in your component's config folder
<ide> * and the following entry using your store's ID (the default factory class is given here):
<ide> private static final Map<String, Factory> storeIdCache = readInstances();
<ide> private static final Factory defaultFactory = readDefaultInstance(storeIdCache);
<ide>
<add> /** The instance is represented by {@link Factory} nested class. */
<add> private ShoppingCartFactory() {}
<add>
<ide> public static Factory get(Delegator delegator, String productStoreId) {
<ide> Factory factory = storeIdCache.get(productStoreId);
<ide> return (factory != null) ? factory : defaultFactory;
<ide> @Deprecated
<ide> public static Factory get(String productStoreId) {
<ide> return get(null, productStoreId);
<del> }
<del>
<del> // Static helper wrapper methods around the factory methods to help simplify code (the get() calls are unnecessary overhead almost every time)
<del>
<del> /**
<del> * Full web shopping cart constructor.
<del> * <p>
<del> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<del> * block, because it modifies session variables that must match the cart contents.
<del> */
<del> public static ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
<del> return get(request).createWebShoppingCart(request, locale, currencyUom);
<del> }
<del>
<del> /**
<del> * Common web shopping cart constructor.
<del> * <p>
<del> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<del> * block, because it modifies session variables that must match the cart contents.
<del> */
<del> public static ShoppingCart createWebShoppingCart(HttpServletRequest request) {
<del> return get(request).createWebShoppingCart(request);
<del> }
<del>
<del> /** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
<del> public static ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
<del> return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart);
<del> }
<del>
<del> /** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<del> public static ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
<del> return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart, exactCopy);
<del> }
<del>
<del> /** Performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
<del> public static ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
<del> return get(request).copyWebShoppingCart(request, locale, currencyUom);
<del> }
<del>
<del> /** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
<del> public static ShoppingCart copyShoppingCart(ShoppingCart cart) {
<del> return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart);
<del> }
<del>
<del> /** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<del> public static ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
<del> return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart, exactCopy);
<del> }
<del>
<del> /** Creates new empty ShoppingCart object. */
<del> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
<del> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
<del> }
<del>
<del> /** Creates new empty ShoppingCart object. */
<del> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
<del> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
<del> }
<del>
<del> /** Creates a new empty ShoppingCart object. */
<del> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
<del> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, locale, currencyUom);
<del> }
<del>
<del> /** Creates a new empty ShoppingCartHelper object. */
<del> public static ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
<del> return get(delegator, cart.getProductStoreId()).createShoppingCartHelper(delegator, dispatcher, cart);
<del> }
<del>
<del> /** The actual factory methods (mostly identical to the static methods) */
<del> public interface Factory extends Serializable {
<del>
<del> /**
<del> * Full web shopping cart constructor.
<del> * <p>
<del> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<del> * block, because it modifies session variables that must match the cart contents.
<del> */
<del> ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
<del>
<del> /**
<del> * Common web shopping cart constructor.
<del> * <p>
<del> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<del> * block, because it modifies session variables that must match the cart contents.
<del> */
<del> ShoppingCart createWebShoppingCart(HttpServletRequest request);
<del>
<del> /** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
<del> ShoppingCart copyWebShoppingCart(ShoppingCart cart);
<del>
<del> /** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<del> ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy);
<del>
<del> /** Performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
<del> ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
<del>
<del> /** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
<del> ShoppingCart copyShoppingCart(ShoppingCart cart);
<del>
<del> /** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<del> ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy);
<del>
<del> /** Creates new empty ShoppingCart object. */
<del> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId);
<del>
<del> /** Creates new empty ShoppingCart object. */
<del> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom);
<del>
<del> /** Creates a new empty ShoppingCart object. */
<del> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom);
<del>
<del> /** Creates a new empty ShoppingCartHelper object. */
<del> ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart);
<ide> }
<ide>
<ide> private static Map<String, Factory> readInstances() {
<ide> return factory;
<ide> }
<ide>
<add> // Static standard helper wrapper methods around the Factory methods, to help simplify code
<add> // (the get() calls are unnecessary to write manually in code in all known cases, because delegator and productStoreId are always already known to the factory methods)
<add>
<add> /** Creates new empty (non-web) ShoppingCart object. */
<add> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
<add> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
<add> }
<add>
<add> /** Creates new empty (non-web) ShoppingCart object. */
<add> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
<add> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
<add> }
<add>
<add> /** Creates a new empty (non-web) ShoppingCart object. */
<add> public static ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
<add> return get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, locale, currencyUom);
<add> }
<add>
<add> /** Creates a new cloned (non-web) ShoppingCart Object, using legacy (partial) cloning. */
<add> public static ShoppingCart copyShoppingCart(ShoppingCart cart) {
<add> return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart);
<add> }
<add>
<add> /** Creates a new cloned (non-web) ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<add> public static ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy) {
<add> return get(cart.getDelegator(), cart.getProductStoreId()).copyShoppingCart(cart, exactCopy);
<add> }
<add>
<add> /**
<add> * Creates a new web ShoppingCart Object - full web shopping cart constructor.
<add> * <p>
<add> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<add> * block, because it modifies session variables that must match the cart contents.
<add> */
<add> public static ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
<add> return get(request).createWebShoppingCart(request, locale, currencyUom);
<add> }
<add>
<add> /**
<add> * Creates a new web ShoppingCart Object - common web shopping cart constructor.
<add> * <p>
<add> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<add> * block, because it modifies session variables that must match the cart contents.
<add> */
<add> public static ShoppingCart createWebShoppingCart(HttpServletRequest request) {
<add> return get(request).createWebShoppingCart(request);
<add> }
<add>
<add> /** Creates a new cloned web ShoppingCart Object, using legacy (partial) cloning. */
<add> public static ShoppingCart copyWebShoppingCart(ShoppingCart cart) {
<add> return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart);
<add> }
<add>
<add> /** Creates a new cloned web ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<add> public static ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy) {
<add> return get(cart.getDelegator(), cart.getProductStoreId()).copyWebShoppingCart(cart, exactCopy);
<add> }
<add>
<add> /** Creates a new cloned web ShoppingCart Object - performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
<add> public static ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom) {
<add> return get(request).copyWebShoppingCart(request, locale, currencyUom);
<add> }
<add>
<add> /** Creates a new empty (web) ShoppingCartHelper object. */
<add> public static ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
<add> return get(delegator, cart.getProductStoreId()).createShoppingCartHelper(delegator, dispatcher, cart);
<add> }
<add>
<add> // Instance methods and interfaces
<add>
<add> /** Actual ShoppingCart factory and instance methods (mostly identical to the static methods) */
<add> public interface Factory extends Serializable {
<add>
<add> /** Creates new empty (non-web) ShoppingCart object. */
<add> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId);
<add>
<add> /** Creates new empty (non-web) ShoppingCart object. */
<add> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom);
<add>
<add> /** Creates a new empty (non-web) ShoppingCart object. */
<add> ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom);
<add>
<add> /** Creates a new cloned (non-web) ShoppingCart Object, using legacy (partial) cloning. */
<add> ShoppingCart copyShoppingCart(ShoppingCart cart);
<add>
<add> /** Creates a new cloned (non-web) ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<add> ShoppingCart copyShoppingCart(ShoppingCart cart, boolean exactCopy);
<add>
<add> /**
<add> * Creates a new web ShoppingCart Object - full web shopping cart constructor.
<add> * <p>
<add> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<add> * block, because it modifies session variables that must match the cart contents.
<add> */
<add> ShoppingCart createWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
<add>
<add> /**
<add> * Creates a new web ShoppingCart Object - common web shopping cart constructor.
<add> * <p>
<add> * SCIPIO: NOTE: 2018-11-30: This constructor should ONLY be inside a {@link CartSync#synchronizedSection(HttpServletRequest)}
<add> * block, because it modifies session variables that must match the cart contents.
<add> */
<add> ShoppingCart createWebShoppingCart(HttpServletRequest request);
<add>
<add> /** Creates a new cloned ShoppingCart Object, using legacy (partial) cloning. */
<add> ShoppingCart copyWebShoppingCart(ShoppingCart cart);
<add>
<add> /** Creates a new cloned ShoppingCart Object, with option between legacy (partial) and full/exact cloning the whole cart. */
<add> ShoppingCart copyWebShoppingCart(ShoppingCart cart, boolean exactCopy);
<add>
<add> /** Creates a new cloned web ShoppingCart Object - performs an exact, deep copy of the cart. Changes to this copy do not affect the main cart. */
<add> ShoppingCart copyWebShoppingCart(HttpServletRequest request, Locale locale, String currencyUom);
<add>
<add> /** Creates a new empty (web) ShoppingCartHelper object. */
<add> ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart);
<add> }
<add>
<ide> public static abstract class BasicFactory implements Factory {
<add> @Override
<add> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
<add> return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
<add> }
<add>
<add> @Override
<add> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
<add> return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
<add> }
<add>
<add> @Override
<add> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
<add> return new ShoppingCart(delegator, productStoreId, locale, currencyUom);
<add> }
<add>
<ide> @Override
<ide> public ShoppingCart copyShoppingCart(ShoppingCart cart) {
<ide> return new ShoppingCart(cart);
<ide> }
<ide>
<ide> @Override
<del> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom, String billToCustomerPartyId, String billFromVendorPartyId) {
<del> return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom, billToCustomerPartyId, billFromVendorPartyId);
<del> }
<del>
<del> @Override
<del> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, String webSiteId, Locale locale, String currencyUom) {
<del> return new ShoppingCart(delegator, productStoreId, webSiteId, locale, currencyUom);
<del> }
<del>
<del> @Override
<del> public ShoppingCart createShoppingCart(Delegator delegator, String productStoreId, Locale locale, String currencyUom) {
<del> return new ShoppingCart(delegator, productStoreId, locale, currencyUom);
<del> }
<del>
<del> @Override
<ide> public ShoppingCartHelper createShoppingCartHelper(Delegator delegator, LocalDispatcher dispatcher, ShoppingCart cart) {
<ide> return new ShoppingCartHelper(delegator, dispatcher, cart);
<ide> } |
|
JavaScript | bsd-3-clause | 78c1d36c98bf4b7bd7ea0bdbca73d23cba3975e9 | 0 | firebug/tracing-console,firebug/tracing-console | /* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false */
/*global FBTrace:true, Components:true, Proxy:true, define:true */
// A note on terminology: here a "closure"/"environment" is generally thought
// of as a container of "scopes".
define([
"firebug/lib/object",
"firebug/firebug",
"firebug/lib/wrapper"
],
function(Obj, Firebug, Wrapper) {
"use strict";
// ********************************************************************************************* //
// Constants
const Cu = Components.utils;
const ScopeProxy = function() {};
const OptimizedAway = Object.create(null);
Object.freeze(OptimizedAway);
// ********************************************************************************************* //
var ClosureInspector =
{
hasInit: false,
Debugger: null,
getInactiveDebuggerForContext: function(context)
{
if (context.inactiveDebugger)
return context.inactiveDebugger;
if (!this.hasInit)
{
this.hasInit = true;
try
{
Cu.import("resource://gre/modules/jsdebugger.jsm");
window.addDebuggerToGlobal(window);
this.Debugger = window.Debugger;
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; Debugger not found", exc);
}
}
if (!this.Debugger)
return;
var dbg = new this.Debugger();
dbg.enabled = false;
context.inactiveDebugger = dbg;
return dbg;
},
getVariableOrOptimizedAway: function(scope, name)
{
try
{
var ret = scope.getVariable(name);
if (ret !== undefined)
return ret;
// The variable is either optimized away or actually set to undefined.
// Optimized-away ones are apparantly not settable, so try to detect
// them by that (it seems rather safe).
scope.setVariable(name, 0);
if (scope.getVariable(name) === undefined)
return OptimizedAway;
scope.setVariable(name, undefined);
return undefined;
}
catch (exc)
{
// E.g. optimized-away "arguments" can throw "Debugger scope is not live".
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getVariableOrOptimizedAway caught an exception", exc);
return OptimizedAway;
}
},
isOptimizedAway: function(obj)
{
return obj === OptimizedAway;
},
isSimple: function(dobj)
{
return (typeof dobj !== "object" || dobj === OptimizedAway);
},
unwrap: function(global, dglobal, obj)
{
dglobal.defineProperty("_firebugUnwrappedDebuggerObject", {
value: obj,
writable: true,
configurable: true
});
return global._firebugUnwrappedDebuggerObject;
},
isScopeInteresting: function(scope)
{
return !!scope.parent;
},
getFunctionFromObject: function(obj)
{
var first = true;
while (obj)
{
var names = obj.getOwnPropertyNames(), pd;
// "constructor" is boring, use it last
var ind = names.indexOf("constructor");
if (ind !== -1)
{
names.splice(ind, 1);
names.push("constructor");
}
// XXX keep a Map of scopes, and take the highest container of the first one or the (first) deepest one or something
for (var i = 0; i < names.length; ++i)
{
// We assume that the first own property, or the first
// enumerable property of the prototype (or "constructor"),
// that is a function with some scope (i.e., it is interpreted,
// JSScript-backed, and without optimized-away scope) shares
// this scope with 'obj'.
var name = names[i];
try
{
pd = obj.getOwnPropertyDescriptor(name);
}
catch (e)
{
// getOwnPropertyDescriptor sometimes fails with
// "Illegal operation on WrappedNative prototype object",
// for instance on [window].proto.gopd("localStorage").
continue;
}
if (!pd || (!first && !pd.enumerable && name !== "constructor"))
continue;
var toTest = [pd.get, pd.set, pd.value];
for (var j = 0; j < toTest.length; ++j)
{
var f = toTest[j];
if (f && f.environment && this.isScopeInteresting(f.environment))
return f;
}
}
if (!first)
break;
first = false;
obj = obj.proto;
}
// None found. :(
return undefined;
},
// Within the security context of the (wrapped) window 'win', find a relevant
// closure for the content object 'obj' (may be from another frame).
// Throws exceptions on error.
getEnvironmentForObject: function(win, obj, context)
{
var dbg = this.getInactiveDebuggerForContext(context);
if (!dbg)
throw new Error("debugger not available");
if (!obj || !(typeof obj === "object" || typeof obj === "function"))
throw new TypeError("can't get scope of non-object");
var objGlobal = Cu.getGlobalForObject(obj);
if (win !== objGlobal && !(win.document && objGlobal.document &&
win.document.nodePrincipal.subsumes(objGlobal.document.nodePrincipal)))
{
throw new Error("permission denied to access cross origin scope");
}
var dglobal = dbg.addDebuggee(objGlobal);
var dobj = dglobal.makeDebuggeeValue(obj);
if (typeof obj === "object")
dobj = this.getFunctionFromObject(dobj);
if (!dobj || !dobj.environment || !this.isScopeInteresting(dobj.environment))
throw new Error("missing closure");
return dobj.environment;
},
getClosureVariablesList: function(obj, context)
{
var ret = [];
// Avoid 'window' and 'document' getting associated with closures.
var win = context.baseWindow || context.window;
if (obj === win || obj === win.document)
return ret;
try
{
var env = this.getEnvironmentForObject(win, obj, context);
for (var scope = env; scope; scope = scope.parent)
{
if (scope.type === "with" && scope.getVariable("profileEnd"))
{
// Almost certainly the with(_FirebugCommandLine) block,
// which is at the top of the scope chain on objects
// defined through the console. Hide it for a nicer display.
break;
}
if (!this.isScopeInteresting(scope))
break;
ret.push.apply(ret, scope.names());
}
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getClosureVariablesList failed", exc);
}
return ret;
},
getClosureWrapper: function(obj, win, context)
{
var env = this.getEnvironmentForObject(win, obj, context);
var dbg = this.getInactiveDebuggerForContext(context);
var dglobal = dbg.addDebuggee(win);
// Return a wrapper for its scoped variables.
var self = this;
var handler = {};
handler.getOwnPropertyDescriptor = function(name)
{
if (name === "__exposedProps__")
{
// Expose mostly everything, rw, through another proxy.
return {
value: Proxy.create({
getPropertyDescriptor: function(name)
{
if (name === "__exposedProps__" || name === "__proto__")
return;
return {value: "rw", enumerable: true};
}
})
};
}
return {
get: function()
{
try
{
var scope = env.find(name);
if (!scope)
return undefined;
var dval = self.getVariableOrOptimizedAway(scope, name);
if (self.isSimple(dval))
return dval;
var uwWin = Wrapper.getContentView(win);
return self.unwrap(uwWin, dglobal, dval);
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; failed to return value from getter", exc);
return undefined;
}
},
set: function(value)
{
var dvalue = dglobal.makeDebuggeeValue(value);
var scope = env.find(name);
if (!scope)
throw new Error("can't create new closure variables");
if (self.getVariableOrOptimizedAway(scope, name) === OptimizedAway)
throw new Error("can't set optimized-away closure variables");
scope.setVariable(name, dvalue);
}
};
};
handler.getPropertyDescriptor = handler.getOwnPropertyDescriptor;
return Proxy.create(handler);
},
getScopeWrapper: function(obj, win, context, isScope)
{
var scope;
try
{
if (isScope)
scope = Object.getPrototypeOf(obj).scope.parent;
else
scope = this.getEnvironmentForObject(win, obj, context);
if (!scope || !this.isScopeInteresting(scope))
return;
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getScopeWrapper failed", exc);
return;
}
var dbg = this.getInactiveDebuggerForContext(context);
var dwin = dbg.addDebuggee(win);
var scopeDataHolder = Object.create(ScopeProxy.prototype);
scopeDataHolder.scope = scope;
var names, namesSet;
var lazyCreateNames = function()
{
lazyCreateNames = function() {};
names = scope.names();
namesSet = new Set;
for (var i = 0; i < names.length; ++i)
namesSet.add(names[i]);
};
var self = this;
return Proxy.create({
desc: function(name)
{
if (!this.has(name))
return;
return {
get: function() {
var dval = self.getVariableOrOptimizedAway(scope, name);
if (self.isSimple(dval))
return dval;
var uwWin = Wrapper.getContentView(win);
return self.unwrap(uwWin, dwin, dval);
},
set: function(value) {
var dval = dwin.makeDebuggeeValue(value);
scope.setVariable(name, dval);
}
};
},
has: function(name)
{
lazyCreateNames();
return namesSet.has(name);
},
hasOwn: function(name) { return this.has(name); },
getOwnPropertyDescriptor: function(name) { return this.desc(name); },
getPropertyDescriptor: function(name) { return this.desc(name); },
keys: function()
{
lazyCreateNames();
return names;
},
enumerate: function() { return this.keys(); },
getOwnPropertyNames: function() { return this.keys(); },
getPropertyNames: function() { return this.keys(); }
}, scopeDataHolder);
},
isScopeWrapper: function(obj)
{
return obj instanceof ScopeProxy;
},
extendLanguageSyntax: function(expr, win, context)
{
// Temporary FireClosure compatibility.
if (Firebug.JSAutoCompleter.transformScopeExpr)
return expr;
var fname = "__fb_scopedVars";
var newExpr = Firebug.JSAutoCompleter.transformScopeOperator(expr, fname);
if (expr === newExpr)
return expr;
if (FBTrace.DBG_COMMANDLINE)
{
FBTrace.sysout("ClosureInspector; transforming expression: `" +
expr + "` -> `" + newExpr + "`");
}
// Stick the helper function for .%-expressions on the window object.
// This really belongs on the command line object, but that doesn't
// work when stopped in the debugger (issue 5321, which depends on
// integrating JSD2) and we really need this to work there.
// To avoid leaking capabilities into arbitrary web pages, this is
// only injected when needed.
try
{
var self = this;
Object.defineProperty(Wrapper.getContentView(win), fname, {
value: function(obj)
{
return self.getClosureWrapper(obj, win, context);
},
writable: true,
configurable: true
});
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; failed to inject " + fname, exc);
}
return newExpr;
}
};
Firebug.ClosureInspector = ClosureInspector;
return ClosureInspector;
// ********************************************************************************************* //
});
| extension/content/firebug/console/closureInspector.js | /* See license.txt for terms of usage */
/*jshint esnext:true, es5:true, curly:false */
/*global FBTrace:true, Components:true, Proxy:true, define:true */
// A note on terminology: here a "closure" is generally thought of as a container of "scopes".
define([
"firebug/lib/object",
"firebug/firebug",
"firebug/lib/wrapper"
],
function(Obj, Firebug, Wrapper) {
"use strict";
// ********************************************************************************************* //
// Constants
const Ci = Components.interfaces;
const Cu = Components.utils;
const ScopeProxy = function() {};
const OptimizedAway = Object.create(null);
Object.freeze(OptimizedAway);
// ********************************************************************************************* //
var ClosureInspector =
{
hasInit: false,
Debugger: null,
getInactiveDebuggerForContext: function(context)
{
if (context.inactiveDebugger)
return context.inactiveDebugger;
if (!this.hasInit)
{
this.hasInit = true;
try
{
Cu.import("resource://gre/modules/jsdebugger.jsm");
window.addDebuggerToGlobal(window);
this.Debugger = window.Debugger;
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; Debugger not found", exc);
}
}
if (!this.Debugger)
return;
var dbg = new this.Debugger();
dbg.enabled = false;
context.inactiveDebugger = dbg;
return dbg;
},
getVariableOrOptimizedAway: function(env, name)
{
try
{
var ret = env.getVariable(name);
if (ret !== undefined)
return ret;
// The variable is either optimized away or actually set to undefined.
// Optimized-away ones are apparantly not settable, so try to detect
// them by that (it seems rather safe).
env.setVariable(name, 0);
if (env.getVariable(name) === undefined)
return OptimizedAway;
env.setVariable(name, undefined);
return undefined;
}
catch (exc)
{
// E.g. optimized-away "arguments" can throw "Debugger scope is not live".
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getVariableOrOptimizedAway caught an exception", exc);
return OptimizedAway;
}
},
isOptimizedAway: function(obj)
{
return obj === OptimizedAway;
},
isSimple: function(dobj)
{
return (typeof dobj !== "object" || dobj === OptimizedAway);
},
unwrap: function(global, dglobal, obj)
{
dglobal.defineProperty("_firebugUnwrappedDebuggerObject", {
value: obj,
writable: true,
configurable: true
});
return global._firebugUnwrappedDebuggerObject;
},
scopeIsInteresting: function(env)
{
return !!env.parent;
},
getFunctionFromObject: function(obj)
{
var first = true;
while (obj)
{
var names = obj.getOwnPropertyNames(), pd;
// "constructor" is boring, use it last
var ind = names.indexOf("constructor");
if (ind !== -1)
{
names.splice(ind, 1);
names.push("constructor");
}
// XXX keep a Map of scopes, and take the highest container of the first one or the (first) deepest one or something
for (var i = 0; i < names.length; ++i)
{
// We assume that the first own property, or the first
// enumerable property of the prototype (or "constructor"),
// that is a function with some scope (i.e., it is interpreted,
// JSScript-backed, and without optimized-away scope) shares
// this scope with 'obj'.
var name = names[i];
try
{
pd = obj.getOwnPropertyDescriptor(name);
}
catch (e)
{
// getOwnPropertyDescriptor sometimes fails with
// "Illegal operation on WrappedNative prototype object",
// for instance on [window].proto.gopd("localStorage").
continue;
}
if (!pd || (!first && !pd.enumerable && name !== "constructor"))
continue;
var toTest = [pd.get, pd.set, pd.value];
for (var j = 0; j < toTest.length; ++j)
{
var f = toTest[j];
if (f && f.environment && this.scopeIsInteresting(f.environment))
return f;
}
}
if (!first)
break;
first = false;
obj = obj.proto;
}
// None found. :(
return undefined;
},
// Within the security context of the (wrapped) window 'win', find a relevant
// closure for the content object 'obj' (may be from another frame).
// Throws exceptions on error.
getEnvironmentForObject: function(win, obj, context)
{
var dbg = this.getInactiveDebuggerForContext(context);
if (!dbg)
throw new Error("debugger not available");
if (!obj || !(typeof obj === "object" || typeof obj === "function"))
throw new TypeError("can't get scope of non-object");
var objGlobal = Cu.getGlobalForObject(obj);
if (win !== objGlobal && !(win.document && objGlobal.document &&
win.document.nodePrincipal.subsumes(objGlobal.document.nodePrincipal)))
{
throw new Error("permission denied to access cross origin scope");
}
var dglobal = dbg.addDebuggee(objGlobal);
var dobj = dglobal.makeDebuggeeValue(obj);
if (typeof obj === "object")
dobj = this.getFunctionFromObject(dobj);
if (!dobj || !dobj.environment || !this.scopeIsInteresting(dobj.environment))
throw new Error("missing closure");
return dobj.environment;
},
getClosureVariablesList: function(obj, context)
{
var ret = [];
// Avoid 'window' and 'document' getting associated with closures.
var win = context.baseWindow || context.window;
if (obj === win || obj === win.document)
return ret;
try
{
var env = this.getEnvironmentForObject(win, obj, context);
for (var scope = env; scope; scope = scope.parent)
{
if (scope.type === "with" && scope.getVariable("profileEnd"))
{
// Almost certainly the with(_FirebugCommandLine) block,
// which is at the top of the scope chain on objects
// defined through the console. Hide it for a nicer display.
break;
}
if (!this.scopeIsInteresting(scope))
break;
ret.push.apply(ret, scope.names());
}
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getClosureVariablesList failed", exc);
}
return ret;
},
getClosureWrapper: function(obj, win, context)
{
var env = this.getEnvironmentForObject(win, obj, context);
var dbg = this.getInactiveDebuggerForContext(context);
var dglobal = dbg.addDebuggee(win);
// Return a wrapper for its scoped variables.
var self = this;
var handler = {};
handler.getOwnPropertyDescriptor = function(name)
{
if (name === "__exposedProps__")
{
// Expose mostly everything, rw, through another proxy.
return {
value: Proxy.create({
getPropertyDescriptor: function(name)
{
if (name === "__exposedProps__" || name === "__proto__")
return;
return {value: "rw", enumerable: true};
}
})
};
}
return {
get: function()
{
try
{
var scope = env.find(name);
if (!scope)
return undefined;
var dval = self.getVariableOrOptimizedAway(scope, name);
if (self.isSimple(dval))
return dval;
var uwWin = Wrapper.getContentView(win);
return self.unwrap(uwWin, dglobal, dval);
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; failed to return value from getter", exc);
return undefined;
}
},
set: function(value)
{
var dvalue = dglobal.makeDebuggeeValue(value);
var scope = env.find(name);
if (!scope)
throw new Error("can't create new closure variables");
if (self.getVariableOrOptimizedAway(scope, name) === OptimizedAway)
throw new Error("can't set optimized-away closure variables");
scope.setVariable(name, dvalue);
}
};
};
handler.getPropertyDescriptor = handler.getOwnPropertyDescriptor;
return Proxy.create(handler);
},
getScopeWrapper: function(obj, win, context, isScope)
{
var scope;
try
{
if (isScope)
scope = Object.getPrototypeOf(obj).scope.parent;
else
scope = this.getEnvironmentForObject(win, obj, context);
if (!scope || !this.scopeIsInteresting(scope))
return;
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; getScopeWrapper failed", exc);
return;
}
var dbg = this.getInactiveDebuggerForContext(context);
var dwin = dbg.addDebuggee(win);
var scopeDataHolder = Object.create(ScopeProxy.prototype);
scopeDataHolder.scope = scope;
var names, namesSet;
var lazyCreateNames = function()
{
lazyCreateNames = function() {};
names = scope.names();
namesSet = new Set;
for (var i = 0; i < names.length; ++i)
namesSet.add(names[i]);
};
var self = this;
return Proxy.create({
desc: function(name)
{
if (!this.has(name))
return;
return {
get: function() {
var dval = self.getVariableOrOptimizedAway(scope, name);
if (self.isSimple(dval))
return dval;
var uwWin = Wrapper.getContentView(win);
return self.unwrap(uwWin, dwin, dval);
},
set: function(value) {
var dval = dwin.makeDebuggeeValue(value);
scope.setVariable(name, dval);
}
};
},
has: function(name)
{
lazyCreateNames();
return namesSet.has(name);
},
hasOwn: function(name) { return this.has(name); },
getOwnPropertyDescriptor: function(name) { return this.desc(name); },
getPropertyDescriptor: function(name) { return this.desc(name); },
keys: function()
{
lazyCreateNames();
return names;
},
enumerate: function() { return this.keys(); },
getOwnPropertyNames: function() { return this.keys(); },
getPropertyNames: function() { return this.keys(); }
}, scopeDataHolder);
},
isScopeWrapper: function(obj)
{
return obj instanceof ScopeProxy;
},
extendLanguageSyntax: function(expr, win, context)
{
// Temporary FireClosure compatibility.
if (Firebug.JSAutoCompleter.transformScopeExpr)
return expr;
var fname = "__fb_scopedVars";
var newExpr = Firebug.JSAutoCompleter.transformScopeOperator(expr, fname);
if (expr === newExpr)
return expr;
if (FBTrace.DBG_COMMANDLINE)
{
FBTrace.sysout("ClosureInspector; transforming expression: `" +
expr + "` -> `" + newExpr + "`");
}
// Stick the helper function for .%-expressions on the window object.
// This really belongs on the command line object, but that doesn't
// work when stopped in the debugger (issue 5321, which depends on
// integrating JSD2) and we really need this to work there.
// To avoid leaking capabilities into arbitrary web pages, this is
// only injected when needed.
try
{
var self = this;
Object.defineProperty(Wrapper.getContentView(win), fname, {
value: function(obj)
{
return self.getClosureWrapper(obj, win, context);
},
writable: true,
configurable: true
});
}
catch (exc)
{
if (FBTrace.DBG_COMMANDLINE)
FBTrace.sysout("ClosureInspector; failed to inject " + fname, exc);
}
return newExpr;
}
};
Firebug.ClosureInspector = ClosureInspector;
return ClosureInspector;
// ********************************************************************************************* //
});
| Some naming changes
| extension/content/firebug/console/closureInspector.js | Some naming changes | <ide><path>xtension/content/firebug/console/closureInspector.js
<ide> /*jshint esnext:true, es5:true, curly:false */
<ide> /*global FBTrace:true, Components:true, Proxy:true, define:true */
<ide>
<del>// A note on terminology: here a "closure" is generally thought of as a container of "scopes".
<add>// A note on terminology: here a "closure"/"environment" is generally thought
<add>// of as a container of "scopes".
<ide>
<ide> define([
<ide> "firebug/lib/object",
<ide> // ********************************************************************************************* //
<ide> // Constants
<ide>
<del>const Ci = Components.interfaces;
<ide> const Cu = Components.utils;
<ide>
<ide> const ScopeProxy = function() {};
<ide> return dbg;
<ide> },
<ide>
<del> getVariableOrOptimizedAway: function(env, name)
<add> getVariableOrOptimizedAway: function(scope, name)
<ide> {
<ide> try
<ide> {
<del> var ret = env.getVariable(name);
<add> var ret = scope.getVariable(name);
<ide> if (ret !== undefined)
<ide> return ret;
<ide>
<ide> // The variable is either optimized away or actually set to undefined.
<ide> // Optimized-away ones are apparantly not settable, so try to detect
<ide> // them by that (it seems rather safe).
<del> env.setVariable(name, 0);
<del> if (env.getVariable(name) === undefined)
<add> scope.setVariable(name, 0);
<add> if (scope.getVariable(name) === undefined)
<ide> return OptimizedAway;
<del> env.setVariable(name, undefined);
<add> scope.setVariable(name, undefined);
<ide> return undefined;
<ide> }
<ide> catch (exc)
<ide> return global._firebugUnwrappedDebuggerObject;
<ide> },
<ide>
<del> scopeIsInteresting: function(env)
<del> {
<del> return !!env.parent;
<add> isScopeInteresting: function(scope)
<add> {
<add> return !!scope.parent;
<ide> },
<ide>
<ide> getFunctionFromObject: function(obj)
<ide> for (var j = 0; j < toTest.length; ++j)
<ide> {
<ide> var f = toTest[j];
<del> if (f && f.environment && this.scopeIsInteresting(f.environment))
<add> if (f && f.environment && this.isScopeInteresting(f.environment))
<ide> return f;
<ide> }
<ide> }
<ide> if (typeof obj === "object")
<ide> dobj = this.getFunctionFromObject(dobj);
<ide>
<del> if (!dobj || !dobj.environment || !this.scopeIsInteresting(dobj.environment))
<add> if (!dobj || !dobj.environment || !this.isScopeInteresting(dobj.environment))
<ide> throw new Error("missing closure");
<ide>
<ide> return dobj.environment;
<ide> // defined through the console. Hide it for a nicer display.
<ide> break;
<ide> }
<del> if (!this.scopeIsInteresting(scope))
<add> if (!this.isScopeInteresting(scope))
<ide> break;
<ide>
<ide> ret.push.apply(ret, scope.names());
<ide> scope = Object.getPrototypeOf(obj).scope.parent;
<ide> else
<ide> scope = this.getEnvironmentForObject(win, obj, context);
<del> if (!scope || !this.scopeIsInteresting(scope))
<add> if (!scope || !this.isScopeInteresting(scope))
<ide> return;
<ide> }
<ide> catch (exc) |
|
Java | apache-2.0 | 43151a3db2c7a208f9298e7ab6cdbce52f5a7b33 | 0 | NSIT/liquibase,klopfdreh/liquibase,dbmanul/dbmanul,adriens/liquibase,maberle/liquibase,lazaronixon/liquibase,mwaylabs/liquibase,evigeant/liquibase,OpenCST/liquibase,Willem1987/liquibase,liquibase/liquibase,tjardo83/liquibase,vfpfafrf/liquibase,Willem1987/liquibase,tjardo83/liquibase,mbreslow/liquibase,talklittle/liquibase,rkrzewski/liquibase,dprguard2000/liquibase,pellcorp/liquibase,syncron/liquibase,fbiville/liquibase,russ-p/liquibase,instantdelay/liquibase,instantdelay/liquibase,Vampire/liquibase,dyk/liquibase,fbiville/liquibase,hbogaards/liquibase,jimmycd/liquibase,klopfdreh/liquibase,gquintana/liquibase,iherasymenko/liquibase,OculusVR/shanghai-liquibase,syncron/liquibase,foxel/liquibase,vbekiaris/liquibase,vfpfafrf/liquibase,dyk/liquibase,hbogaards/liquibase,jimmycd/liquibase,liquibase/liquibase,OculusVR/shanghai-liquibase,EVODelavega/liquibase,cbotiza/liquibase,mortegac/liquibase,vast-engineering/liquibase,C0mmi3/liquibase,iherasymenko/liquibase,ZEPowerGroup/liquibase,instantdelay/liquibase,AlisonSouza/liquibase,Vampire/liquibase,cbotiza/liquibase,vfpfafrf/liquibase,mattbertolini/liquibase,dprguard2000/liquibase,evigeant/liquibase,maberle/liquibase,vbekiaris/liquibase,ArloL/liquibase,iherasymenko/liquibase,pellcorp/liquibase,mattbertolini/liquibase,fossamagna/liquibase,klopfdreh/liquibase,liquibase/liquibase,gquintana/liquibase,vast-engineering/liquibase,ZEPowerGroup/liquibase,Datical/liquibase,Datical/liquibase,adriens/liquibase,foxel/liquibase,AlisonSouza/liquibase,hbogaards/liquibase,danielkec/liquibase,ArloL/liquibase,mwaylabs/liquibase,mbreslow/liquibase,mortegac/liquibase,mortegac/liquibase,vast-engineering/liquibase,ZEPowerGroup/liquibase,FreshGrade/liquibase,gquintana/liquibase,lazaronixon/liquibase,AlisonSouza/liquibase,EVODelavega/liquibase,OculusVR/shanghai-liquibase,NSIT/liquibase,balazs-zsoldos/liquibase,jimmycd/liquibase,dyk/liquibase,dyk/liquibase,OpenCST/liquibase,OpenCST/liquibase,danielkec/liquibase,cleiter/liquibase,ivaylo5ev/liquibase,danielkec/liquibase,C0mmi3/liquibase,fossamagna/liquibase,OculusVR/shanghai-liquibase,maberle/liquibase,FreshGrade/liquibase,AlisonSouza/liquibase,vfpfafrf/liquibase,CoderPaulK/liquibase,C0mmi3/liquibase,cleiter/liquibase,mwaylabs/liquibase,cleiter/liquibase,instantdelay/liquibase,russ-p/liquibase,vbekiaris/liquibase,ivaylo5ev/liquibase,fbiville/liquibase,mortegac/liquibase,ArloL/liquibase,syncron/liquibase,dprguard2000/liquibase,CoderPaulK/liquibase,EVODelavega/liquibase,mbreslow/liquibase,CoderPaulK/liquibase,NSIT/liquibase,danielkec/liquibase,pellcorp/liquibase,cbotiza/liquibase,adriens/liquibase,EVODelavega/liquibase,hbogaards/liquibase,FreshGrade/liquibase,FreshGrade/liquibase,rkrzewski/liquibase,balazs-zsoldos/liquibase,balazs-zsoldos/liquibase,lazaronixon/liquibase,talklittle/liquibase,evigeant/liquibase,foxel/liquibase,Vampire/liquibase,Datical/liquibase,C0mmi3/liquibase,dbmanul/dbmanul,vbekiaris/liquibase,maberle/liquibase,cleiter/liquibase,dbmanul/dbmanul,russ-p/liquibase,CoderPaulK/liquibase,OpenCST/liquibase,cbotiza/liquibase,tjardo83/liquibase,NSIT/liquibase,fbiville/liquibase,gquintana/liquibase,lazaronixon/liquibase,rkrzewski/liquibase,vast-engineering/liquibase,pellcorp/liquibase,fossamagna/liquibase,syncron/liquibase,Willem1987/liquibase,balazs-zsoldos/liquibase,evigeant/liquibase,mattbertolini/liquibase,russ-p/liquibase,mattbertolini/liquibase,iherasymenko/liquibase,tjardo83/liquibase,Datical/liquibase,dbmanul/dbmanul,Willem1987/liquibase,dprguard2000/liquibase,talklittle/liquibase,mwaylabs/liquibase,klopfdreh/liquibase,talklittle/liquibase,mbreslow/liquibase,foxel/liquibase,jimmycd/liquibase | package liquibase.jvm.integration.commandline;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.exception.CommandLineParsingException;
import liquibase.exception.DatabaseException;
import liquibase.exception.ValidationFailedException;
import liquibase.lockservice.LockService;
import liquibase.logging.LogFactory;
import liquibase.logging.LogLevel;
import liquibase.logging.Logger;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.CompositeResourceAccessor;
import liquibase.resource.FileSystemResourceAccessor;
import liquibase.servicelocator.ServiceLocator;
import liquibase.util.LiquibaseUtil;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Class for executing Liquibase via the command line.
*/
public class Main {
protected ClassLoader classLoader;
protected String driver;
protected String username;
protected String password;
protected String url;
protected String databaseClass;
protected String defaultSchemaName;
protected String changeLogFile;
protected String classpath;
protected String contexts;
protected Boolean promptForNonLocalDatabase = null;
protected Boolean includeSystemClasspath;
protected String defaultsFile = "liquibase.properties";
protected String diffTypes;
protected String changeSetAuthor;
protected String changeSetContext;
protected String dataDir;
protected String currentDateTimeFunction;
protected String command;
protected Set<String> commandParams = new HashSet<String>();
protected String logLevel;
protected String logFile;
protected Map<String, Object> changeLogParameters = new HashMap<String, Object>();
public static void main(String args[]) throws CommandLineParsingException, IOException {
try {
String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY);
if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
System.out.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false");
return;
}
Main main = new Main();
if (args.length == 1 && "--help".equals(args[0])) {
main.printHelp(System.out);
return;
} else if (args.length == 1 && "--version".equals(args[0])) {
System.out.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator());
return;
}
try {
main.parseOptions(args);
} catch (CommandLineParsingException e) {
main.printHelp(Arrays.asList(e.getMessage()), System.out);
System.exit(-2);
}
File propertiesFile = new File(main.defaultsFile);
if (propertiesFile.exists()) {
main.parsePropertiesFile(new FileInputStream(propertiesFile));
}
List<String> setupMessages = main.checkSetup();
if (setupMessages.size() > 0) {
main.printHelp(setupMessages, System.out);
return;
}
try {
main.applyDefaults();
main.configureClassLoader();
main.doMigration();
} catch (Throwable e) {
String message = e.getMessage();
if (e.getCause() != null) {
message = e.getCause().getMessage();
}
if (message == null) {
message = "Unknown Reason";
}
if (e.getCause() instanceof ValidationFailedException) {
((ValidationFailedException) e.getCause()).printDescriptiveError(System.out);
} else {
System.out.println("Liquibase Update Failed: " + message + generateLogLevelWarningMessage());
LogFactory.getLogger().info(message, e);
}
System.exit(-1);
}
if ("update".equals(main.command)) {
System.out.println("Liquibase Update Successful");
} else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) {
System.out.println("Liquibase Rollback Successful");
}
} catch (Throwable e) {
String message = "Unexpected error running Liquibase: " + e.getMessage();
System.out.println(message);
LogFactory.getLogger().severe(message, e);
System.exit(-3);
}
System.exit(0);
}
private static String generateLogLevelWarningMessage() {
Logger logger = LogFactory.getLogger();
if (logger == null || logger.getLogLevel() == null || (logger.getLogLevel().equals(LogLevel.DEBUG))) {
return "";
} else {
return ". For more information, use the --logLevel flag)";
}
}
/**
* On windows machines, it splits args on '=' signs. Put it back like it was.
*/
protected String[] fixupArgs(String[] args) {
List<String> fixedArgs = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) {
String nextArg = null;
if (i + 1 < args.length) {
nextArg = args[i + 1];
}
if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) {
arg = arg + "=" + nextArg;
i++;
}
}
fixedArgs.add(arg);
}
return fixedArgs.toArray(new String[fixedArgs.size()]);
}
protected List<String> checkSetup() {
List<String> messages = new ArrayList<String>();
if (command == null) {
messages.add("Command not passed");
} else if (!isCommand(command)) {
messages.add("Unknown command: " + command);
} else {
if (url == null) {
messages.add("--url is required");
}
if (isChangeLogRequired(command) && changeLogFile == null) {
messages.add("--changeLog is required");
}
}
return messages;
}
private boolean isChangeLogRequired(String command) {
return command.toLowerCase().startsWith("update")
|| command.toLowerCase().startsWith("rollback")
|| "validate".equals(command);
}
private boolean isCommand(String arg) {
return "migrate".equals(arg)
|| "migrateSQL".equalsIgnoreCase(arg)
|| "update".equalsIgnoreCase(arg)
|| "updateSQL".equalsIgnoreCase(arg)
|| "updateCount".equalsIgnoreCase(arg)
|| "updateCountSQL".equalsIgnoreCase(arg)
|| "rollback".equalsIgnoreCase(arg)
|| "rollbackToDate".equalsIgnoreCase(arg)
|| "rollbackCount".equalsIgnoreCase(arg)
|| "rollbackSQL".equalsIgnoreCase(arg)
|| "rollbackToDateSQL".equalsIgnoreCase(arg)
|| "rollbackCountSQL".equalsIgnoreCase(arg)
|| "futureRollbackSQL".equalsIgnoreCase(arg)
|| "updateTestingRollback".equalsIgnoreCase(arg)
|| "tag".equalsIgnoreCase(arg)
|| "listLocks".equalsIgnoreCase(arg)
|| "dropAll".equalsIgnoreCase(arg)
|| "releaseLocks".equalsIgnoreCase(arg)
|| "status".equalsIgnoreCase(arg)
|| "validate".equalsIgnoreCase(arg)
|| "help".equalsIgnoreCase(arg)
|| "diff".equalsIgnoreCase(arg)
|| "diffChangeLog".equalsIgnoreCase(arg)
|| "generateChangeLog".equalsIgnoreCase(arg)
|| "clearCheckSums".equalsIgnoreCase(arg)
|| "dbDoc".equalsIgnoreCase(arg)
|| "changelogSync".equalsIgnoreCase(arg)
|| "changelogSyncSQL".equalsIgnoreCase(arg)
|| "markNextChangeSetRan".equalsIgnoreCase(arg)
|| "markNextChangeSetRanSQL".equalsIgnoreCase(arg);
}
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException {
Properties props = new Properties();
props.load(propertiesInputStream);
for (Map.Entry entry : props.entrySet()) {
try {
if (entry.getKey().equals("promptOnNonLocalDatabase")) {
continue;
}
if (((String) entry.getKey()).startsWith("parameter.")) {
changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue());
} else {
Field field = getClass().getDeclaredField((String) entry.getKey());
Object currentValue = field.get(this);
if (currentValue == null) {
String value = entry.getValue().toString().trim();
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
}
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'");
}
}
}
protected void printHelp(List<String> errorMessages, PrintStream stream) {
stream.println("Errors:");
for (String message : errorMessages) {
stream.println(" " + message);
}
stream.println();
printHelp(stream);
}
protected void printHelp(PrintStream stream) {
stream.println("Usage: java -jar liquibase.jar [options] [command]");
stream.println("");
stream.println("Standard Commands:");
stream.println(" update Updates database to current version");
stream.println(" updateSQL Writes SQL to update database to current");
stream.println(" version to STDOUT");
stream.println(" updateCount <num> Applies next NUM changes to the database");
stream.println(" updateSQL <num> Writes SQL to apply next NUM changes");
stream.println(" to the database");
stream.println(" rollback <tag> Rolls back the database to the the state is was");
stream.println(" when the tag was applied");
stream.println(" rollbackSQL <tag> Writes SQL to roll back the database to that");
stream.println(" state it was in when the tag was applied");
stream.println(" to STDOUT");
stream.println(" rollbackToDate <date/time> Rolls back the database to the the state is was");
stream.println(" at the given date/time.");
stream.println(" Date Format: yyyy-MM-dd HH:mm:ss");
stream.println(" rollbackToDateSQL <date/time> Writes SQL to roll back the database to that");
stream.println(" state it was in at the given date/time version");
stream.println(" to STDOUT");
stream.println(" rollbackCount <value> Rolls back the last <value> change sets");
stream.println(" applied to the database");
stream.println(" rollbackCountSQL <value> Writes SQL to roll back the last");
stream.println(" <value> change sets to STDOUT");
stream.println(" applied to the database");
stream.println(" futureRollbackSQL Writes SQL to roll back the database to the ");
stream.println(" current state after the changes in the ");
stream.println(" changeslog have been applied");
stream.println(" updateTestingRollback Updates database, then rolls back changes before");
stream.println(" updating again. Useful for testing");
stream.println(" rollback support");
stream.println(" generateChangeLog Writes Change Log XML to copy the current state");
stream.println(" of the database to standard out");
stream.println("");
stream.println("Diff Commands");
stream.println(" diff [diff parameters] Writes description of differences");
stream.println(" to standard out");
stream.println(" diffChangeLog [diff parameters] Writes Change Log XML to update");
stream.println(" the database");
stream.println(" to the reference database to standard out");
stream.println("");
stream.println("Documentation Commands");
stream.println(" dbDoc <outputDirectory> Generates Javadoc-like documentation");
stream.println(" based on current database and change log");
stream.println("");
stream.println("Maintenance Commands");
stream.println(" tag <tag string> 'Tags' the current database state for future rollback");
stream.println(" status [--verbose] Outputs count (list if --verbose) of unrun changesets");
stream.println(" validate Checks changelog for errors");
stream.println(" clearCheckSums Removes all saved checksums from database log.");
stream.println(" Useful for 'MD5Sum Check Failed' errors");
stream.println(" changelogSync Mark all changes as executed in the database");
stream.println(" changelogSyncSQL Writes SQL to mark all changes as executed ");
stream.println(" in the database to STDOUT");
stream.println(" markNextChangeSetRan Mark the next change changes as executed ");
stream.println(" in the database");
stream.println(" markNextChangeSetRanSQL Writes SQL to mark the next change ");
stream.println(" as executed in the database to STDOUT");
stream.println(" listLocks Lists who currently has locks on the");
stream.println(" database changelog");
stream.println(" releaseLocks Releases all locks on the database changelog");
stream.println(" dropAll Drop all database objects owned by user");
stream.println("");
stream.println("Required Parameters:");
stream.println(" --changeLogFile=<path and filename> Migration file");
stream.println(" --username=<value> Database username");
stream.println(" --password=<value> Database password");
stream.println(" --url=<value> Database URL");
stream.println("");
stream.println("Optional Parameters:");
stream.println(" --classpath=<value> Classpath containing");
stream.println(" migration files and JDBC Driver");
stream.println(" --driver=<jdbc.driver.ClassName> Database driver class name");
stream.println(" --databaseClass=<database.ClassName> custom liquibase.database.Database");
stream.println(" implementation to use");
stream.println(" --defaultSchemaName=<name> Default database schema to use");
stream.println(" --contexts=<value> ChangeSet contexts to execute");
stream.println(" --defaultsFile=</path/to/file.properties> File with default option values");
stream.println(" (default: ./liquibase.properties)");
stream.println(" --includeSystemClasspath=<true|false> Include the system classpath");
stream.println(" in the Liquibase classpath");
stream.println(" (default: true)");
stream.println(" --promptForNonLocalDatabase=<true|false> Prompt if non-localhost");
stream.println(" databases (default: false)");
stream.println(" --logLevel=<level> Execution log level");
stream.println(" --logFile=<file> Log file");
stream.println(" (finest, finer, debug, info,");
stream.println(" warning, severe)");
stream.println(" --currentDateTimeFunction=<value> Overrides current date time function");
stream.println(" used in SQL.");
stream.println(" Useful for unsupported databases");
stream.println(" --help Prints this message");
stream.println(" --version Prints this version information");
stream.println("");
stream.println("Required Diff Parameters:");
stream.println(" --referenceUsername=<value> Reference Database username");
stream.println(" --referencePassword=<value> Reference Database password");
stream.println(" --referenceUrl=<value> Reference Database URL");
stream.println("");
stream.println("Optional Diff Parameters:");
stream.println(" --referenceDriver=<jdbc.driver.ClassName> Reference Database driver class name");
stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given ");
stream.println(" directory");
stream.println("");
stream.println("Change Log Properties:");
stream.println(" -D<property.name>=<property.value> Pass a name/value pair for");
stream.println(" substitution in the change log(s)");
stream.println("");
stream.println("Default value for parameters can be stored in a file called");
stream.println("'liquibase.properties' that is read from the current working directory.");
stream.println("");
stream.println("Full documentation is available at");
stream.println("http://www.liquibase.org/manual/command_line");
stream.println("");
}
public Main() {
// options = createOptions();
}
protected void parseOptions(String[] args) throws CommandLineParsingException {
args = fixupArgs(args);
boolean seenCommand = false;
for (String arg : args) {
if (isCommand(arg)) {
this.command = arg;
if (this.command.equalsIgnoreCase("migrate")) {
this.command = "update";
} else if (this.command.equalsIgnoreCase("migrateSQL")) {
this.command = "updateSQL";
}
seenCommand = true;
} else if (seenCommand) {
if (arg.startsWith("-D")) {
String[] splitArg = splitArg(arg);
String attributeName = splitArg[0].replaceFirst("^-D", "");
String value = splitArg[1];
changeLogParameters.put(attributeName, value);
} else {
commandParams.add(arg);
}
} else if (arg.startsWith("--")) {
String[] splitArg = splitArg(arg);
String attributeName = splitArg[0];
String value = splitArg[1];
try {
Field field = getClass().getDeclaredField(attributeName);
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'");
}
} else {
throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'");
}
}
}
private String[] splitArg(String arg) throws CommandLineParsingException {
String[] splitArg = arg.split("=");
if (splitArg.length < 2) {
throw new CommandLineParsingException("Could not parse '" + arg + "'");
} else if (splitArg.length > 2) {
StringBuffer secondHalf = new StringBuffer();
for (int j = 1; j < splitArg.length; j++) {
secondHalf.append(splitArg[j]).append("=");
}
splitArg = new String[]{
splitArg[0],
secondHalf.toString().replaceFirst("=$", "")
};
}
splitArg[0] = splitArg[0].replaceFirst("--", "");
return splitArg;
}
protected void applyDefaults() {
if (this.promptForNonLocalDatabase == null) {
this.promptForNonLocalDatabase = Boolean.FALSE;
}
if (this.logLevel == null) {
this.logLevel = "info";
}
if (this.includeSystemClasspath == null) {
this.includeSystemClasspath = Boolean.TRUE;
}
}
protected void configureClassLoader() throws CommandLineParsingException {
final List<URL> urls = new ArrayList<URL>();
if (this.classpath != null) {
String[] classpath;
if (isWindows()) {
classpath = this.classpath.split(";");
} else {
classpath = this.classpath.split(":");
}
for (String classpathEntry : classpath) {
File classPathFile = new File(classpathEntry);
if (!classPathFile.exists()) {
throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist");
}
try {
if (classpathEntry.endsWith(".war")) {
addWarFileClasspathEntries(classPathFile, urls);
} else if (classpathEntry.endsWith(".ear")) {
JarFile earZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = earZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(earZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
} else if (entry.getName().toLowerCase().endsWith("war")) {
File warFile = extract(earZip, entry);
addWarFileClasspathEntries(warFile, urls);
}
}
} else {
urls.add(new File(classpathEntry).toURL());
}
} catch (Exception e) {
throw new CommandLineParsingException(e);
}
}
}
if (includeSystemClasspath) {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
}
});
} else {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]));
}
});
}
ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader));
Thread.currentThread().setContextClassLoader(classLoader);
}
private void addWarFileClasspathEntries(File classPathFile, List<URL> urls) throws IOException {
URL url = new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/");
urls.add(url);
JarFile warZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = warZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("WEB-INF/lib")
&& entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(warZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
}
}
}
private File extract(JarFile jar, JarEntry entry) throws IOException {
// expand to temp dir and add to list
File tempFile = File.createTempFile("liquibase.tmp", null);
// read from jar and write to the tempJar file
BufferedInputStream inStream = null;
BufferedOutputStream outStream = null;
try {
inStream = new BufferedInputStream(jar.getInputStream(entry));
outStream = new BufferedOutputStream(
new FileOutputStream(tempFile));
int status;
while ((status = inStream.read()) != -1) {
outStream.write(status);
}
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException ioe) {
;
}
}
if (inStream != null) {
try {
inStream.close();
} catch (IOException ioe) {
;
}
}
}
return tempFile;
}
protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.out);
return;
}
try {
if (null != logFile) {
LogFactory.getLogger().setLogLevel(logLevel, logFile);
} else {
LogFactory.getLogger().setLogLevel(logLevel);
}
} catch (IllegalArgumentException e) {
throw new CommandLineParsingException(e.getMessage(), e);
}
FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader);
Database database = CommandLineUtils.createDatabaseObject(classLoader, this.url, this.username, this.password, this.driver, this.defaultSchemaName, this.databaseClass);
try {
CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener);
if ("diff".equalsIgnoreCase(command)) {
CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams), database);
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams), database);
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
CommandLineUtils.doGenerateChangeLog(changeLogFile, database, defaultSchemaName, StringUtils.trimToNull(diffTypes), StringUtils.trimToNull(changeSetAuthor), StringUtils.trimToNull(changeSetContext), StringUtils.trimToNull(dataDir));
return;
}
Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database);
liquibase.setCurrentDateTimeFunction(currentDateTimeFunction);
for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) {
liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
}
if ("listLocks".equalsIgnoreCase(command)) {
liquibase.reportLocks(System.out);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
LockService.getInstance(database).forceReleaseLock();
System.out.println("Successfully released all database change log locks for " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
liquibase.tag(commandParams.iterator().next());
System.out.println("Successfully tagged " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("dropAll".equals(command)) {
liquibase.dropAll();
System.out.println("All objects dropped from " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
liquibase.reportStatus(runVerbose, contexts, getOutputWriter());
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
liquibase.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
return;
}
System.out.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
liquibase.clearCheckSums();
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
if (changeLogFile == null) {
throw new CommandLineParsingException("dbdoc requires a changeLog parameter");
}
liquibase.generateDocumentation(commandParams.iterator().next());
return;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if ("update".equalsIgnoreCase(command)) {
liquibase.update(contexts);
} else if ("changelogSync".equalsIgnoreCase(command)) {
liquibase.changeLogSync(contexts);
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
liquibase.changeLogSync(contexts, getOutputWriter());
} else if ("markNextChangeSetRan".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(contexts);
} else if ("markNextChangeSetRanSQL".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(contexts, getOutputWriter());
} else if ("updateCount".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), contexts);
} else if ("updateCountSQL".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("updateSQL".equalsIgnoreCase(command)) {
liquibase.update(contexts, getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
liquibase.rollback(commandParams.iterator().next(), contexts);
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
liquibase.rollback(dateFormat.parse(commandParams.iterator().next()), contexts);
} else if ("rollbackCount".equalsIgnoreCase(command)) {
liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), contexts);
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
liquibase.rollback(commandParams.iterator().next(), contexts, getOutputWriter());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
liquibase.rollback(dateFormat.parse(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackCountSQL requires a rollback tag");
}
liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
liquibase.futureRollbackSQL(contexts, getOutputWriter());
} else if ("updateTestingRollback".equalsIgnoreCase(command)) {
liquibase.updateTestingRollback(contexts);
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd HH:mm:ss'");
}
} finally {
try {
database.rollback();
database.close();
} catch (DatabaseException e) {
LogFactory.getLogger().warning("problem closing connection", e);
}
}
}
private String getCommandParam(String paramName) throws CommandLineParsingException {
for (String param : commandParams) {
String[] splitArg = splitArg(param);
String attributeName = splitArg[0];
String value = splitArg[1];
if (attributeName.equalsIgnoreCase(paramName)) {
return value;
}
}
return null;
}
private Database createReferenceDatabaseFromCommandParams(Set<String> commandParams) throws CommandLineParsingException, DatabaseException {
String driver = null;
String url = null;
String username = null;
String password = null;
String defaultSchemaName = this.defaultSchemaName;
for (String param : commandParams) {
String[] splitArg = splitArg(param);
String attributeName = splitArg[0];
String value = splitArg[1];
if ("referenceDriver".equalsIgnoreCase(attributeName)) {
driver = value;
} else if ("referenceUrl".equalsIgnoreCase(attributeName)) {
url = value;
} else if ("referenceUsername".equalsIgnoreCase(attributeName)) {
username = value;
} else if ("referencePassword".equalsIgnoreCase(attributeName)) {
password = value;
} else if ("referenceDefaultSchemaName".equalsIgnoreCase(attributeName)) {
defaultSchemaName = value;
} else if ("dataOutputDirectory".equalsIgnoreCase(attributeName)) {
dataDir = value;
}
}
// if (driver == null) {
// driver = DatabaseFactory.getWriteExecutor().findDefaultDriver(url);
// }
if (url == null) {
throw new CommandLineParsingException("referenceUrl parameter missing");
}
return CommandLineUtils.createDatabaseObject(classLoader, url, username, password, driver, defaultSchemaName, null);
// Driver driverObject;
// try {
// driverObject = (Driver) Class.forName(driver, true, classLoader).newInstance();
// } catch (Exception e) {
// throw new RuntimeException("Cannot find database driver: " + e.getMessage());
// }
//
// Properties info = new Properties();
// info.put("user", username);
// info.put("password", password);
//
// Connection connection;
// try {
// connection = driverObject.connect(url, info);
// } catch (SQLException e) {
// throw new DatabaseException("Connection could not be created to " + url + ": " + e.getMessage(), e);
// }
// if (connection == null) {
// throw new DatabaseException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
// }
//
// Database database = DatabaseFactory.getWriteExecutor().findCorrectDatabaseImplementation(connection);
// database.setDefaultSchemaName(defaultSchemaName);
//
// return database;
}
private Writer getOutputWriter() {
return new OutputStreamWriter(System.out);
}
public boolean isWindows() {
return System.getProperty("os.name").startsWith("Windows ");
}
}
| liquibase-core/src/main/java/liquibase/jvm/integration/commandline/Main.java | package liquibase.jvm.integration.commandline;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.exception.CommandLineParsingException;
import liquibase.exception.DatabaseException;
import liquibase.exception.ValidationFailedException;
import liquibase.lockservice.LockService;
import liquibase.logging.LogFactory;
import liquibase.logging.LogLevel;
import liquibase.logging.Logger;
import liquibase.resource.ClassLoaderResourceAccessor;
import liquibase.resource.CompositeResourceAccessor;
import liquibase.resource.FileSystemResourceAccessor;
import liquibase.servicelocator.ServiceLocator;
import liquibase.util.LiquibaseUtil;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Class for executing Liquibase via the command line.
*/
public class Main {
protected ClassLoader classLoader;
protected String driver;
protected String username;
protected String password;
protected String url;
protected String databaseClass;
protected String defaultSchemaName;
protected String changeLogFile;
protected String classpath;
protected String contexts;
protected Boolean promptForNonLocalDatabase = null;
protected Boolean includeSystemClasspath;
protected String defaultsFile = "liquibase.properties";
protected String diffTypes;
protected String changeSetAuthor;
protected String changeSetContext;
protected String dataDir;
protected String currentDateTimeFunction;
protected String command;
protected Set<String> commandParams = new HashSet<String>();
protected String logLevel;
protected String logFile;
protected Map<String, Object> changeLogParameters = new HashMap<String, Object>();
public static void main(String args[]) throws CommandLineParsingException, IOException {
try {
String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY);
if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
System.out.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false");
return;
}
Main main = new Main();
if (args.length == 1 && "--help".equals(args[0])) {
main.printHelp(System.out);
return;
} else if (args.length == 1 && "--version".equals(args[0])) {
System.out.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator());
return;
}
try {
main.parseOptions(args);
} catch (CommandLineParsingException e) {
main.printHelp(Arrays.asList(e.getMessage()), System.out);
System.exit(-2);
}
File propertiesFile = new File(main.defaultsFile);
if (propertiesFile.exists()) {
main.parsePropertiesFile(new FileInputStream(propertiesFile));
}
List<String> setupMessages = main.checkSetup();
if (setupMessages.size() > 0) {
main.printHelp(setupMessages, System.out);
return;
}
try {
main.applyDefaults();
main.configureClassLoader();
main.doMigration();
} catch (Throwable e) {
String message = e.getMessage();
if (e.getCause() != null) {
message = e.getCause().getMessage();
}
if (message == null) {
message = "Unknown Reason";
}
if (e.getCause() instanceof ValidationFailedException) {
((ValidationFailedException) e.getCause()).printDescriptiveError(System.out);
} else {
System.out.println("Liquibase Update Failed: " + message + generateLogLevelWarningMessage());
LogFactory.getLogger().info(message, e);
}
System.exit(-1);
}
if ("update".equals(main.command)) {
System.out.println("Liquibase Update Successful");
} else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) {
System.out.println("Liquibase Rollback Successful");
}
} catch (Throwable e) {
String message = "Unexpected error running Liquibase: " + e.getMessage();
System.out.println(message);
LogFactory.getLogger().severe(message, e);
System.exit(-3);
}
System.exit(0);
}
private static String generateLogLevelWarningMessage() {
Logger logger = LogFactory.getLogger();
if (logger == null || logger.getLogLevel() == null || (logger.getLogLevel().equals(LogLevel.DEBUG))) {
return "";
} else {
return ". For more information, use the --logLevel flag)";
}
}
/**
* On windows machines, it splits args on '=' signs. Put it back like it was.
*/
protected String[] fixupArgs(String[] args) {
List<String> fixedArgs = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) {
String nextArg = null;
if (i + 1 < args.length) {
nextArg = args[i + 1];
}
if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) {
arg = arg + "=" + nextArg;
i++;
}
}
fixedArgs.add(arg);
}
return fixedArgs.toArray(new String[fixedArgs.size()]);
}
protected List<String> checkSetup() {
List<String> messages = new ArrayList<String>();
if (command == null) {
messages.add("Command not passed");
} else if (!isCommand(command)) {
messages.add("Unknown command: " + command);
} else {
if (url == null) {
messages.add("--url is required");
}
if (isChangeLogRequired(command) && changeLogFile == null) {
messages.add("--changeLog is required");
}
}
return messages;
}
private boolean isChangeLogRequired(String command) {
return command.toLowerCase().startsWith("update")
|| command.toLowerCase().startsWith("rollback")
|| "validate".equals(command);
}
private boolean isCommand(String arg) {
return "migrate".equals(arg)
|| "migrateSQL".equalsIgnoreCase(arg)
|| "update".equalsIgnoreCase(arg)
|| "updateSQL".equalsIgnoreCase(arg)
|| "updateCount".equalsIgnoreCase(arg)
|| "updateCountSQL".equalsIgnoreCase(arg)
|| "rollback".equalsIgnoreCase(arg)
|| "rollbackToDate".equalsIgnoreCase(arg)
|| "rollbackCount".equalsIgnoreCase(arg)
|| "rollbackSQL".equalsIgnoreCase(arg)
|| "rollbackToDateSQL".equalsIgnoreCase(arg)
|| "rollbackCountSQL".equalsIgnoreCase(arg)
|| "futureRollbackSQL".equalsIgnoreCase(arg)
|| "updateTestingRollback".equalsIgnoreCase(arg)
|| "tag".equalsIgnoreCase(arg)
|| "listLocks".equalsIgnoreCase(arg)
|| "dropAll".equalsIgnoreCase(arg)
|| "releaseLocks".equalsIgnoreCase(arg)
|| "status".equalsIgnoreCase(arg)
|| "validate".equalsIgnoreCase(arg)
|| "help".equalsIgnoreCase(arg)
|| "diff".equalsIgnoreCase(arg)
|| "diffChangeLog".equalsIgnoreCase(arg)
|| "generateChangeLog".equalsIgnoreCase(arg)
|| "clearCheckSums".equalsIgnoreCase(arg)
|| "dbDoc".equalsIgnoreCase(arg)
|| "changelogSync".equalsIgnoreCase(arg)
|| "changelogSyncSQL".equalsIgnoreCase(arg)
|| "markNextChangeSetRan".equalsIgnoreCase(arg)
|| "markNextChangeSetRanSQL".equalsIgnoreCase(arg);
}
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException {
Properties props = new Properties();
props.load(propertiesInputStream);
for (Map.Entry entry : props.entrySet()) {
try {
if (entry.getKey().equals("promptOnNonLocalDatabase")) {
continue;
}
if (((String) entry.getKey()).startsWith("parameter.")) {
changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue());
} else {
Field field = getClass().getDeclaredField((String) entry.getKey());
Object currentValue = field.get(this);
if (currentValue == null) {
String value = entry.getValue().toString().trim();
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
}
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'");
}
}
}
protected void printHelp(List<String> errorMessages, PrintStream stream) {
stream.println("Errors:");
for (String message : errorMessages) {
stream.println(" " + message);
}
stream.println();
printHelp(stream);
}
protected void printHelp(PrintStream stream) {
stream.println("Usage: java -jar liquibase.jar [options] [command]");
stream.println("");
stream.println("Standard Commands:");
stream.println(" update Updates database to current version");
stream.println(" updateSQL Writes SQL to update database to current");
stream.println(" version to STDOUT");
stream.println(" updateCount <num> Applies next NUM changes to the database");
stream.println(" updateSQL <num> Writes SQL to apply next NUM changes");
stream.println(" to the database");
stream.println(" rollback <tag> Rolls back the database to the the state is was");
stream.println(" when the tag was applied");
stream.println(" rollbackSQL <tag> Writes SQL to roll back the database to that");
stream.println(" state it was in when the tag was applied");
stream.println(" to STDOUT");
stream.println(" rollbackToDate <date/time> Rolls back the database to the the state is was");
stream.println(" at the given date/time.");
stream.println(" Date Format: yyyy-MM-dd HH:mm:ss");
stream.println(" rollbackToDateSQL <date/time> Writes SQL to roll back the database to that");
stream.println(" state it was in at the given date/time version");
stream.println(" to STDOUT");
stream.println(" rollbackCount <value> Rolls back the last <value> change sets");
stream.println(" applied to the database");
stream.println(" rollbackCountSQL <value> Writes SQL to roll back the last");
stream.println(" <value> change sets to STDOUT");
stream.println(" applied to the database");
stream.println(" futureRollbackSQL Writes SQL to roll back the database to the ");
stream.println(" current state after the changes in the ");
stream.println(" changeslog have been applied");
stream.println(" updateTestingRollback Updates database, then rolls back changes before");
stream.println(" updating again. Useful for testing");
stream.println(" rollback support");
stream.println(" generateChangeLog Writes Change Log XML to copy the current state");
stream.println(" of the database to standard out");
stream.println("");
stream.println("Diff Commands");
stream.println(" diff [diff parameters] Writes description of differences");
stream.println(" to standard out");
stream.println(" diffChangeLog [diff parameters] Writes Change Log XML to update");
stream.println(" the database");
stream.println(" to the reference database to standard out");
stream.println("");
stream.println("Documentation Commands");
stream.println(" dbDoc <outputDirectory> Generates Javadoc-like documentation");
stream.println(" based on current database and change log");
stream.println("");
stream.println("Maintenance Commands");
stream.println(" tag <tag string> 'Tags' the current database state for future rollback");
stream.println(" status [--verbose] Outputs count (list if --verbose) of unrun changesets");
stream.println(" validate Checks changelog for errors");
stream.println(" clearCheckSums Removes all saved checksums from database log.");
stream.println(" Useful for 'MD5Sum Check Failed' errors");
stream.println(" changelogSync Mark all changes as executed in the database");
stream.println(" changelogSyncSQL Writes SQL to mark all changes as executed ");
stream.println(" in the database to STDOUT");
stream.println(" markNextChangeSetRan Mark the next change changes as executed ");
stream.println(" in the database");
stream.println(" markNextChangeSetRanSQL Writes SQL to mark the next change ");
stream.println(" as executed in the database to STDOUT");
stream.println(" listLocks Lists who currently has locks on the");
stream.println(" database changelog");
stream.println(" releaseLocks Releases all locks on the database changelog");
stream.println(" dropAll Drop all database objects owned by user");
stream.println("");
stream.println("Required Parameters:");
stream.println(" --changeLogFile=<path and filename> Migration file");
stream.println(" --username=<value> Database username");
stream.println(" --password=<value> Database password");
stream.println(" --url=<value> Database URL");
stream.println("");
stream.println("Optional Parameters:");
stream.println(" --classpath=<value> Classpath containing");
stream.println(" migration files and JDBC Driver");
stream.println(" --driver=<jdbc.driver.ClassName> Database driver class name");
stream.println(" --databaseClass=<database.ClassName> custom liquibase.database.Database");
stream.println(" implementation to use");
stream.println(" --defaultSchemaName=<name> Default database schema to use");
stream.println(" --contexts=<value> ChangeSet contexts to execute");
stream.println(" --defaultsFile=</path/to/file.properties> File with default option values");
stream.println(" (default: ./liquibase.properties)");
stream.println(" --includeSystemClasspath=<true|false> Include the system classpath");
stream.println(" in the Liquibase classpath");
stream.println(" (default: true)");
stream.println(" --promptForNonLocalDatabase=<true|false> Prompt if non-localhost");
stream.println(" databases (default: false)");
stream.println(" --logLevel=<level> Execution log level");
stream.println(" --logFile=<file> Log file");
stream.println(" (finest, finer, debug, info,");
stream.println(" warning, severe)");
stream.println(" --currentDateTimeFunction=<value> Overrides current date time function");
stream.println(" used in SQL.");
stream.println(" Useful for unsupported databases");
stream.println(" --help Prints this message");
stream.println(" --version Prints this version information");
stream.println("");
stream.println("Required Diff Parameters:");
stream.println(" --referenceUsername=<value> Reference Database username");
stream.println(" --referencePassword=<value> Reference Database password");
stream.println(" --referenceUrl=<value> Reference Database URL");
stream.println("");
stream.println("Optional Diff Parameters:");
stream.println(" --referenceDriver=<jdbc.driver.ClassName> Reference Database driver class name");
stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given directory");
stream.println("");
stream.println("Change Log Properties:");
stream.println(" -D<property.name>=<property.value> Pass a name/value pair for");
stream.println(" substitution in the change log(s)");
stream.println("");
stream.println("Default value for parameters can be stored in a file called");
stream.println("'liquibase.properties' that is read from the current working directory.");
stream.println("");
stream.println("Full documentation is available at");
stream.println("http://www.liquibase.org/manual/command_line");
stream.println("");
}
public Main() {
// options = createOptions();
}
protected void parseOptions(String[] args) throws CommandLineParsingException {
args = fixupArgs(args);
boolean seenCommand = false;
for (String arg : args) {
if (isCommand(arg)) {
this.command = arg;
if (this.command.equalsIgnoreCase("migrate")) {
this.command = "update";
} else if (this.command.equalsIgnoreCase("migrateSQL")) {
this.command = "updateSQL";
}
seenCommand = true;
} else if (seenCommand) {
if (arg.startsWith("-D")) {
String[] splitArg = splitArg(arg);
String attributeName = splitArg[0].replaceFirst("^-D", "");
String value = splitArg[1];
changeLogParameters.put(attributeName, value);
} else {
commandParams.add(arg);
}
} else if (arg.startsWith("--")) {
String[] splitArg = splitArg(arg);
String attributeName = splitArg[0];
String value = splitArg[1];
try {
Field field = getClass().getDeclaredField(attributeName);
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'");
}
} else {
throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'");
}
}
}
private String[] splitArg(String arg) throws CommandLineParsingException {
String[] splitArg = arg.split("=");
if (splitArg.length < 2) {
throw new CommandLineParsingException("Could not parse '" + arg + "'");
} else if (splitArg.length > 2) {
StringBuffer secondHalf = new StringBuffer();
for (int j = 1; j < splitArg.length; j++) {
secondHalf.append(splitArg[j]).append("=");
}
splitArg = new String[]{
splitArg[0],
secondHalf.toString().replaceFirst("=$", "")
};
}
splitArg[0] = splitArg[0].replaceFirst("--", "");
return splitArg;
}
protected void applyDefaults() {
if (this.promptForNonLocalDatabase == null) {
this.promptForNonLocalDatabase = Boolean.FALSE;
}
if (this.logLevel == null) {
this.logLevel = "info";
}
if (this.includeSystemClasspath == null) {
this.includeSystemClasspath = Boolean.TRUE;
}
}
protected void configureClassLoader() throws CommandLineParsingException {
final List<URL> urls = new ArrayList<URL>();
if (this.classpath != null) {
String[] classpath;
if (isWindows()) {
classpath = this.classpath.split(";");
} else {
classpath = this.classpath.split(":");
}
for (String classpathEntry : classpath) {
File classPathFile = new File(classpathEntry);
if (!classPathFile.exists()) {
throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist");
}
try {
if (classpathEntry.endsWith(".war")) {
addWarFileClasspathEntries(classPathFile, urls);
} else if (classpathEntry.endsWith(".ear")) {
JarFile earZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = earZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(earZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
} else if (entry.getName().toLowerCase().endsWith("war")) {
File warFile = extract(earZip, entry);
addWarFileClasspathEntries(warFile, urls);
}
}
} else {
urls.add(new File(classpathEntry).toURL());
}
} catch (Exception e) {
throw new CommandLineParsingException(e);
}
}
}
if (includeSystemClasspath) {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
}
});
} else {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]));
}
});
}
ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader));
Thread.currentThread().setContextClassLoader(classLoader);
}
private void addWarFileClasspathEntries(File classPathFile, List<URL> urls) throws IOException {
URL url = new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/");
urls.add(url);
JarFile warZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = warZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("WEB-INF/lib")
&& entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(warZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
}
}
}
private File extract(JarFile jar, JarEntry entry) throws IOException {
// expand to temp dir and add to list
File tempFile = File.createTempFile("liquibase.tmp", null);
// read from jar and write to the tempJar file
BufferedInputStream inStream = null;
BufferedOutputStream outStream = null;
try {
inStream = new BufferedInputStream(jar.getInputStream(entry));
outStream = new BufferedOutputStream(
new FileOutputStream(tempFile));
int status;
while ((status = inStream.read()) != -1) {
outStream.write(status);
}
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException ioe) {
;
}
}
if (inStream != null) {
try {
inStream.close();
} catch (IOException ioe) {
;
}
}
}
return tempFile;
}
protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.out);
return;
}
try {
if (null != logFile) {
LogFactory.getLogger().setLogLevel(logLevel, logFile);
} else {
LogFactory.getLogger().setLogLevel(logLevel);
}
} catch (IllegalArgumentException e) {
throw new CommandLineParsingException(e.getMessage(), e);
}
FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader);
Database database = CommandLineUtils.createDatabaseObject(classLoader, this.url, this.username, this.password, this.driver, this.defaultSchemaName, this.databaseClass);
try {
CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener);
if ("diff".equalsIgnoreCase(command)) {
CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams), database);
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams), database);
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
CommandLineUtils.doGenerateChangeLog(changeLogFile, database, defaultSchemaName, StringUtils.trimToNull(diffTypes), StringUtils.trimToNull(changeSetAuthor), StringUtils.trimToNull(changeSetContext), StringUtils.trimToNull(dataDir));
return;
}
Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database);
liquibase.setCurrentDateTimeFunction(currentDateTimeFunction);
for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) {
liquibase.setChangeLogParameter(entry.getKey(), entry.getValue());
}
if ("listLocks".equalsIgnoreCase(command)) {
liquibase.reportLocks(System.out);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
LockService.getInstance(database).forceReleaseLock();
System.out.println("Successfully released all database change log locks for " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
liquibase.tag(commandParams.iterator().next());
System.out.println("Successfully tagged " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("dropAll".equals(command)) {
liquibase.dropAll();
System.out.println("All objects dropped from " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
liquibase.reportStatus(runVerbose, contexts, getOutputWriter());
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
liquibase.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
return;
}
System.out.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
liquibase.clearCheckSums();
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
if (changeLogFile == null) {
throw new CommandLineParsingException("dbdoc requires a changeLog parameter");
}
liquibase.generateDocumentation(commandParams.iterator().next());
return;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if ("update".equalsIgnoreCase(command)) {
liquibase.update(contexts);
} else if ("changelogSync".equalsIgnoreCase(command)) {
liquibase.changeLogSync(contexts);
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
liquibase.changeLogSync(contexts, getOutputWriter());
} else if ("markNextChangeSetRan".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(contexts);
} else if ("markNextChangeSetRanSQL".equalsIgnoreCase(command)) {
liquibase.markNextChangeSetRan(contexts, getOutputWriter());
} else if ("updateCount".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), contexts);
} else if ("updateCountSQL".equalsIgnoreCase(command)) {
liquibase.update(Integer.parseInt(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("updateSQL".equalsIgnoreCase(command)) {
liquibase.update(contexts, getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
liquibase.rollback(commandParams.iterator().next(), contexts);
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
liquibase.rollback(dateFormat.parse(commandParams.iterator().next()), contexts);
} else if ("rollbackCount".equalsIgnoreCase(command)) {
liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), contexts);
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
liquibase.rollback(commandParams.iterator().next(), contexts, getOutputWriter());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
liquibase.rollback(dateFormat.parse(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
if (commandParams == null || commandParams.size() == 0) {
throw new CommandLineParsingException("rollbackCountSQL requires a rollback tag");
}
liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), contexts, getOutputWriter());
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
liquibase.futureRollbackSQL(contexts, getOutputWriter());
} else if ("updateTestingRollback".equalsIgnoreCase(command)) {
liquibase.updateTestingRollback(contexts);
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd HH:mm:ss'");
}
} finally {
try {
database.rollback();
database.close();
} catch (DatabaseException e) {
LogFactory.getLogger().warning("problem closing connection", e);
}
}
}
private String getCommandParam(String paramName) throws CommandLineParsingException {
for (String param : commandParams) {
String[] splitArg = splitArg(param);
String attributeName = splitArg[0];
String value = splitArg[1];
if (attributeName.equalsIgnoreCase(paramName)) {
return value;
}
}
return null;
}
private Database createReferenceDatabaseFromCommandParams(Set<String> commandParams) throws CommandLineParsingException, DatabaseException {
String driver = null;
String url = null;
String username = null;
String password = null;
String defaultSchemaName = this.defaultSchemaName;
for (String param : commandParams) {
String[] splitArg = splitArg(param);
String attributeName = splitArg[0];
String value = splitArg[1];
if ("referenceDriver".equalsIgnoreCase(attributeName)) {
driver = value;
} else if ("referenceUrl".equalsIgnoreCase(attributeName)) {
url = value;
} else if ("referenceUsername".equalsIgnoreCase(attributeName)) {
username = value;
} else if ("referencePassword".equalsIgnoreCase(attributeName)) {
password = value;
} else if ("referenceDefaultSchemaName".equalsIgnoreCase(attributeName)) {
defaultSchemaName = value;
} else if ("dataOutputDirectory".equalsIgnoreCase(attributeName)) {
dataDir = value;
}
}
// if (driver == null) {
// driver = DatabaseFactory.getWriteExecutor().findDefaultDriver(url);
// }
if (url == null) {
throw new CommandLineParsingException("referenceUrl parameter missing");
}
return CommandLineUtils.createDatabaseObject(classLoader, url, username, password, driver, defaultSchemaName, null);
// Driver driverObject;
// try {
// driverObject = (Driver) Class.forName(driver, true, classLoader).newInstance();
// } catch (Exception e) {
// throw new RuntimeException("Cannot find database driver: " + e.getMessage());
// }
//
// Properties info = new Properties();
// info.put("user", username);
// info.put("password", password);
//
// Connection connection;
// try {
// connection = driverObject.connect(url, info);
// } catch (SQLException e) {
// throw new DatabaseException("Connection could not be created to " + url + ": " + e.getMessage(), e);
// }
// if (connection == null) {
// throw new DatabaseException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
// }
//
// Database database = DatabaseFactory.getWriteExecutor().findCorrectDatabaseImplementation(connection);
// database.setDefaultSchemaName(defaultSchemaName);
//
// return database;
}
private Writer getOutputWriter() {
return new OutputStreamWriter(System.out);
}
public boolean isWindows() {
return System.getProperty("os.name").startsWith("Windows ");
}
}
| Fixed failing test case where part of Main's printHelp method was
longer than 80 characters.
git-svn-id: a91d99a4c51940524e539abe295d6ea473345dd2@1501 e6edf6fb-f266-4316-afb4-e53d95876a76
| liquibase-core/src/main/java/liquibase/jvm/integration/commandline/Main.java | Fixed failing test case where part of Main's printHelp method was longer than 80 characters. | <ide><path>iquibase-core/src/main/java/liquibase/jvm/integration/commandline/Main.java
<ide> stream.println("");
<ide> stream.println("Optional Diff Parameters:");
<ide> stream.println(" --referenceDriver=<jdbc.driver.ClassName> Reference Database driver class name");
<del> stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given directory");
<add> stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given ");
<add> stream.println(" directory");
<ide> stream.println("");
<ide> stream.println("Change Log Properties:");
<ide> stream.println(" -D<property.name>=<property.value> Pass a name/value pair for"); |
|
Java | apache-2.0 | 8fa18209b949b6aaeade24874a9995d57f629208 | 0 | SylvesterAbreu/jackrabbit,bartosz-grabski/jackrabbit,tripodsan/jackrabbit,SylvesterAbreu/jackrabbit,Kast0rTr0y/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit,sdmcraft/jackrabbit,Kast0rTr0y/jackrabbit,kigsmtua/jackrabbit,Kast0rTr0y/jackrabbit,SylvesterAbreu/jackrabbit,Overseas-Student-Living/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,bartosz-grabski/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,Overseas-Student-Living/jackrabbit,tripodsan/jackrabbit,afilimonov/jackrabbit | /*
* 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.jackrabbit.jcr2spi.version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.jackrabbit.jcr2spi.NodeImpl;
import org.apache.jackrabbit.jcr2spi.SessionImpl;
import org.apache.jackrabbit.jcr2spi.ItemLifeCycleListener;
import org.apache.jackrabbit.jcr2spi.state.NodeState;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.Node;
import javax.jcr.Item;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.nodetype.ConstraintViolationException;
import java.util.Calendar;
/**
* <code>VersionImpl</code>...
*/
public class VersionImpl extends NodeImpl implements Version {
private static Logger log = LoggerFactory.getLogger(VersionImpl.class);
public VersionImpl(SessionImpl session, NodeState state,
ItemLifeCycleListener[] listeners) {
super(session, state, listeners);
}
//------------------------------------------------------------< Version >---
/**
*
* @return
* @throws RepositoryException
* @see Version#getContainingHistory()
*/
public VersionHistory getContainingHistory() throws RepositoryException {
return (VersionHistory) getParent();
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getCreated()
*/
public Calendar getCreated() throws RepositoryException {
return getProperty(NameConstants.JCR_CREATED).getDate();
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getSuccessors()
*/
public Version[] getSuccessors() throws RepositoryException {
return getVersions(NameConstants.JCR_SUCCESSORS);
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getPredecessors()
*/
public Version[] getPredecessors() throws RepositoryException {
return getVersions(NameConstants.JCR_PREDECESSORS);
}
//---------------------------------------------------------------< Item >---
/**
*
* @param otherItem
* @return
* @see Item#isSame(Item)
*/
public boolean isSame(Item otherItem) throws RepositoryException {
checkStatus();
if (otherItem instanceof VersionImpl) {
// since all versions are referenceable, protected and live
// in the same workspace, a simple comparision of the UUIDs is sufficient
VersionImpl other = ((VersionImpl) otherItem);
try {
return getUUID().equals(other.getUUID());
} catch (RepositoryException e) {
// should never occur
log.error("Internal error while retrieving UUID of version.", e);
}
}
return false;
}
//-----------------------------------------------------------< ItemImpl >---
/**
* Always throws ConstraintViolationException since the version storage is
* protected.
*
* @throws UnsupportedRepositoryOperationException
* @throws ConstraintViolationException
* @throws RepositoryException
*/
protected void checkIsWritable() throws UnsupportedRepositoryOperationException, ConstraintViolationException, RepositoryException {
super.checkIsWritable();
throw new ConstraintViolationException("Version is protected");
}
/**
* Always returns false
*
* @throws RepositoryException
* @see NodeImpl#isWritable()
*/
protected boolean isWritable() throws RepositoryException {
super.isWritable();
return false;
}
//------------------------------------------------------------< private >---
/**
*
* @param propertyName
* @return
*/
private Version[] getVersions(Name propertyName) throws RepositoryException {
Version[] versions;
Value[] values = getProperty(propertyName).getValues();
if (values != null) {
versions = new Version[values.length];
for (int i = 0; i < values.length; i++) {
Node n = session.getNodeByUUID(values[i].getString());
if (n instanceof Version) {
versions[i] = (Version) n;
} else {
throw new RepositoryException("Version property contains invalid value not pointing to a 'Version'");
}
}
} else {
versions = new Version[0];
}
return versions;
}
public Node getFrozenNode() throws RepositoryException {
throw new UnsupportedRepositoryOperationException("JCR-1104");
}
public Version getLinearPredecessor() throws RepositoryException {
throw new UnsupportedRepositoryOperationException("JCR-1104");
}
public Version getLinearSuccessor() throws RepositoryException {
throw new UnsupportedRepositoryOperationException("JCR-1104");
}
} | jackrabbit-jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/version/VersionImpl.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.jackrabbit.jcr2spi.version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.jackrabbit.jcr2spi.NodeImpl;
import org.apache.jackrabbit.jcr2spi.SessionImpl;
import org.apache.jackrabbit.jcr2spi.ItemLifeCycleListener;
import org.apache.jackrabbit.jcr2spi.state.NodeState;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.Node;
import javax.jcr.Item;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.nodetype.ConstraintViolationException;
import java.util.Calendar;
/**
* <code>VersionImpl</code>...
*/
public class VersionImpl extends NodeImpl implements Version {
private static Logger log = LoggerFactory.getLogger(VersionImpl.class);
public VersionImpl(SessionImpl session, NodeState state,
ItemLifeCycleListener[] listeners) {
super(session, state, listeners);
}
//------------------------------------------------------------< Version >---
/**
*
* @return
* @throws RepositoryException
* @see Version#getContainingHistory()
*/
public VersionHistory getContainingHistory() throws RepositoryException {
return (VersionHistory) getParent();
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getCreated()
*/
public Calendar getCreated() throws RepositoryException {
return getProperty(NameConstants.JCR_CREATED).getDate();
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getSuccessors()
*/
public Version[] getSuccessors() throws RepositoryException {
return getVersions(NameConstants.JCR_SUCCESSORS);
}
/**
*
* @return
* @throws RepositoryException
* @see Version#getPredecessors()
*/
public Version[] getPredecessors() throws RepositoryException {
return getVersions(NameConstants.JCR_PREDECESSORS);
}
//---------------------------------------------------------------< Item >---
/**
*
* @param otherItem
* @return
* @see Item#isSame(Item)
*/
public boolean isSame(Item otherItem) throws RepositoryException {
checkStatus();
if (otherItem instanceof VersionImpl) {
// since all versions are referenceable, protected and live
// in the same workspace, a simple comparision of the UUIDs is sufficient
VersionImpl other = ((VersionImpl) otherItem);
try {
return getUUID().equals(other.getUUID());
} catch (RepositoryException e) {
// should never occur
log.error("Internal error while retrieving UUID of version.", e);
}
}
return false;
}
//-----------------------------------------------------------< ItemImpl >---
/**
* Always throws ConstraintViolationException since the version storage is
* protected.
*
* @throws UnsupportedRepositoryOperationException
* @throws ConstraintViolationException
* @throws RepositoryException
*/
protected void checkIsWritable() throws UnsupportedRepositoryOperationException, ConstraintViolationException, RepositoryException {
super.checkIsWritable();
throw new ConstraintViolationException("Version is protected");
}
/**
* Always returns false
*
* @throws RepositoryException
* @see NodeImpl#isWritable()
*/
protected boolean isWritable() throws RepositoryException {
super.isWritable();
return false;
}
//------------------------------------------------------------< private >---
/**
*
* @param propertyName
* @return
*/
private Version[] getVersions(Name propertyName) throws RepositoryException {
Version[] versions;
Value[] values = getProperty(propertyName).getValues();
if (values != null) {
versions = new Version[values.length];
for (int i = 0; i < values.length; i++) {
Node n = session.getNodeByUUID(values[i].getString());
if (n instanceof Version) {
versions[i] = (Version) n;
} else {
throw new RepositoryException("Version property contains invalid value not pointing to a 'Version'");
}
}
} else {
versions = new Version[0];
}
return versions;
}
} | JCR-1104: JSR 283 support
Add dummy Version methods in jcr2spi
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@770614 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/version/VersionImpl.java | JCR-1104: JSR 283 support | <ide><path>ackrabbit-jcr2spi/src/main/java/org/apache/jackrabbit/jcr2spi/version/VersionImpl.java
<ide> }
<ide> return versions;
<ide> }
<add>
<add> public Node getFrozenNode() throws RepositoryException {
<add> throw new UnsupportedRepositoryOperationException("JCR-1104");
<add> }
<add>
<add> public Version getLinearPredecessor() throws RepositoryException {
<add> throw new UnsupportedRepositoryOperationException("JCR-1104");
<add> }
<add>
<add> public Version getLinearSuccessor() throws RepositoryException {
<add> throw new UnsupportedRepositoryOperationException("JCR-1104");
<add> }
<add>
<ide> } |
|
JavaScript | mpl-2.0 | c6559c8db73bf5be7583517a3c45f5fbf181cd7d | 0 | platfarm-com/teuthis,platfarm-com/teuthis | /*! Teuthis XHR proxy/cache
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
// At the moment, responseText / responseXML facading are not supported
var _ = require('lodash/core');
_.isNil = require('lodash/isNil');
var RequestCache = require('./request-cache');
// Save a reference to the native XMLHttpRequest
var nativeXMLHttpRequest = XMLHttpRequest;
var options = {
debugMethods: false,
debugCache: false,
debugEvents: false,
debugErrorEvents: true,
debugCachePuts: false,
debugCacheHits: false,
debugCacheMiss: false,
debugCacheBoot: false,
};
// Global function to determine if a request should be cached or not
var cacheSelector = function() { return false; }
var onerrorhook = function(e, isOnSend, xhr, realXhr, alternativeResponse) { }
var onloadhook = function(isOnSend, xhr, realXhr) { }
var onmisshook = function(xhr, realXhr, res) { return false; }
var cachekeymangler = function(urlkey) { return urlkey; }
var requestCache = null;
function XMLHttpRequestProxy() {
// console.log('[Teuthis] XMLHttpRequestProxy constructor');
var xhr = new nativeXMLHttpRequest();
if (_.isNil(requestCache)) {
requestCache = new RequestCache({instanceName: 'Teuthis'});
}
var store = requestCache;
var method_ = null;
var url_ = null;
var shouldAddToCache_ = false;
var self = this;
// Facade the status, statusText and response properties to spec XMLHttpRequest
this.status = 0; // This is the status if error due to browser offline, etc.
this.statusText = "";
this.response = "";
// Facade the onload, onreadystatechange to spec XMLHttpRequest
this.onreadystatechange = null;
this.onload = null;
Object.defineProperty(self, 'proxymethod', { get: function() {return method_;} });
Object.defineProperty(self, 'proxyurl', { get: function() {return url_;} });
function shouldCache(method, url) {
if (_.isFunction(cacheSelector)) { return cacheSelector.call(self, method, url); }
return false;
}
// monkey-patch onreadystatechange to copy the status from the original.
// then call the users onreadystatechange
// This does happen each time an instance is constructed, perhaps this is redundant
xhr.onreadystatechange = function onreadystatechange () {
self.status = xhr.status;
self.statusText = xhr.statusText;
self.readyState = xhr.readyState;
if (_.isFunction(self.onreadystatechange)) { return self.onreadystatechange(); }
};
// monkey-patch onload to save the value into cache, if we had a miss in send()
// Call the users on-load once the value is saved into the cache, or immediately if not caching
xhr.onload = function onload () {
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload ' + xhr.status + ' ' + xhr.statusText);
self.status = xhr.status;
self.statusText = xhr.statusText;
self.response = xhr.response;
if (xhr.status >= 200 && xhr.status < 300 && xhr.response) {
if (shouldAddToCache_ === true) {
var mangled = cachekeymangler(url_);
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload do-put ' + method_ + ' ' + mangled);
// console.log('proxy-cache-type ' + xhr.responseType); // + ', ' + xhr.responseText.substring(0,64));
// if (xhr.responseType === 'arraybuffer')
// Assuming the response is string or arraybuffer then clone it first, otherwise things seem to not work properly
var savedResponse = xhr.response.slice(0);
var cachedResponse = { v: savedResponse, ts: Date.now() };
store.put(method_, mangled, cachedResponse, function() {
if (_.isFunction(onloadhook)) { onloadhook(shouldAddToCache_, self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
});
shouldAddToCache_ = false;
return;
}
}
if (_.isFunction(onloadhook)) { onloadhook(shouldAddToCache_, self, xhr); } // Allow proxy success to be hooked as well
if (_.isFunction(self.onload)) { self.onload(); } // Call original
};
xhr.onerror = function onerror (event) {
// Note when using a file: URL in an Android webview, if the file is missing we get an error but status code is 0
// and event.error is not defined
if (options.debugErrorEvents) console.log('[Teuthis] proxy-xhr-onerror event=' + event.type + ' ' + method_ + ' ' + url_);
if (options.debugErrorEvents) console.log('[Teuthis] proxy-xhr-onerror error.name=' + (event.error && event.error.name) + ' error.message=' + (event.error && event.error.message));
if (_.isFunction(onerrorhook)) {
var alternativeResponse = {};
if (onerrorhook(event, shouldAddToCache_, self, xhr, alternativeResponse)) {
// If user returns true then dont call onerror, instead call onload with fake data, such as a crossed tile PNG
self.status = +200;
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
if (alternativeResponse.response) {
self.response = alternativeResponse.response;
}
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-error', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
if (_.isFunction(self.onerror)) { self.onerror(event); }
}
// Facade XMLHttpRequest.open() with a version that saves the arguments for later use, then calls the original
this.open = function() {
if (options.debugMethods) console.log('[Teuthis] proxy-xhr-open ' + arguments[0] + ' ' + arguments[1]);
method_ = arguments[0];
url_ = arguments[1];
shouldAddToCache_ = false;
xhr.open.apply(xhr, arguments);
};
// Facade XMLHttpRequest.send() with a version that queries our offline cache,
// calls the original if the response is not found in the cache, then adds the response to the cache,
// or calls to onload() with the cached response if found
this.send = function() {
if (options.debugMethods) console.log('[Teuthis] proxy-xhr-send ' + method_ + ' ' + url_);
if (shouldCache(method_, url_)) {
var mangled = cachekeymangler(url_);
if (options.debugCache) console.log('[Teuthis] proxy-try-cache ' + method_ + ' ' + mangled);
store.match(method_, mangled, function(key, cachedValue) {
if (!cachedValue.v || !cachedValue.ts) {
// something is badly wrong... we need to treat as a miss
console.warn('invalid cache data');
// This is a hack copy/paste - we really need to refactor this code
if (options.debugCache) console.log('[Teuthis] proxy-try-cache miss ' + method_ + ' ' + mangled);
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
shouldAddToCache_ = true;
xhr.send.apply(xhr, arguments);
}
if (options.debugCache) console.log('[Teuthis] proxy-try-cache hit ' + method_ + ' ' + mangled);
// hit
self.status = +200;
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = cachedValue.v;
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
// Now, how do we update the LRU time?
var o = {v: cachedValue.v, ts: Date.now()};
store.put(method_, mangled, o, function() { });
}, function(key) {
if (options.debugCache) console.log('[Teuthis] proxy-try-cache miss ' + method_ + ' ' + mangled);
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
shouldAddToCache_ = true;
xhr.send.apply(xhr, arguments);
});
} else {
xhr.send.apply(xhr, arguments);
}
};
// facade all other XMLHttpRequest getters, except 'status'
["responseURL", "responseText", "responseXML", "upload"].forEach(function(item) {
Object.defineProperty(self, item, {
get: function() {return xhr[item];},
});
});
// facade all other XMLHttpRequest properties getters and setters'
["ontimeout", "timeout", "responseType", "withCredentials", "onprogress", "onloadstart", "onloadend", "onabort"].forEach(function(item) {
Object.defineProperty(self, item, {
get: function() {return xhr[item];},
set: function(val) {xhr[item] = val;},
});
});
// facade all pure XMLHttpRequest methods and EVentTarget ancestor methods
["addEventListener", "removeEventListener", "dispatchEvent",
"abort", "getAllResponseHeaders", "getResponseHeader", "overrideMimeType", "setRequestHeader"].forEach(function(item) {
Object.defineProperty(self, item, {
value: function() {return xhr[item].apply(xhr, arguments);},
});
});
};
// Set a function that returns true if method + url shold be cached
// Example:
// XMLHttpRequestProxy.setCacheSelector(function (method, url) {
// if (method === 'GET' && url.startsWith('https://') ) {
// return true;
// }
// return false;
// });
XMLHttpRequestProxy.setCacheSelector = function (cacheSelector_) {
cacheSelector = cacheSelector_;
}
XMLHttpRequestProxy.setErrorHook = function (onerrorhook_) {
onerrorhook = onerrorhook_;
}
XMLHttpRequestProxy.setLoadHook = function (onloadhook_) {
onloadhook = onloadhook_;
}
XMLHttpRequestProxy.setMissHook = function (onmisshook_) {
onmisshook = onmisshook_;
}
XMLHttpRequestProxy.setCacheKeyMangler = function (cachekeymangler_) {
cachekeymangler = cachekeymangler_;
}
// Get the underlying RequestCache store so the user can monitor usage statistics, etc.
XMLHttpRequestProxy.getStore = function () { return requestCache; }
// Set the underlying RequestCache store to a custom instance.
XMLHttpRequestProxy.setStore = function (store) { requestCache = store; }
// Create an instance of the request cache, shared among all XHR.
// If not called, and setStore not called, then happens on first XHR
XMLHttpRequestProxy.init = function(options_) {
options = Object.assign({}, options, options_);
console.log('Teuthis: Options=' + JSON.stringify(options));
if (_.isNil(requestCache)) {
var cacheOptions = {instanceName: 'Teuthis'};
// FIXME: there must be a Object or _ method to do this mapping
if (_.has(options_, 'debugCachePuts')) { cacheOptions.debugCachePuts = options_.debugCachePuts; }
if (_.has(options_, 'debugCacheHits')) { cacheOptions.debugCacheHits = options_.debugCacheHits; }
if (_.has(options_, 'debugCacheMiss')) { cacheOptions.debugCacheMiss = options_.debugCacheMiss; }
if (_.has(options_, 'debugCacheBoot')) { cacheOptions.debugCacheBoot = options_.debugCacheBoot; }
requestCache = new RequestCache(cacheOptions);
} else {
requestCache.setDebugOptions(options_);
}
return requestCache;
}
// For each value present in options_, update debugging options
XMLHttpRequestProxy.setOptions = function(options_) {
// TODO: at some point I should update all this code to ES2015, given it is being babelled anyway
_.each(options, function (v, k) {
if (_.has(options_, k)) {
options[k] = options_[k];
}
});
requestCache.setDebugOptions(options_);
}
module.exports = XMLHttpRequestProxy;
| lib/xhr-proxy.js | /*! Teuthis XHR proxy/cache
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
// At the moment, responseText / responseXML facading are not supported
var _ = require('lodash/core');
_.isNil = require('lodash/isNil');
var RequestCache = require('./request-cache');
// Save a reference to the native XMLHttpRequest
var nativeXMLHttpRequest = XMLHttpRequest;
var options = {
debugMethods: false,
debugCache: false,
debugEvents: false,
debugErrorEvents: true,
debugCachePuts: false,
debugCacheHits: false,
debugCacheMiss: false,
debugCacheBoot: false,
};
// Global function to determine if a request should be cached or not
var cacheSelector = function() { return false; }
var onerrorhook = function(e, isOnSend, xhr, realXhr, alternativeResponse) { }
var onloadhook = function(isOnSend, xhr, realXhr) { }
var onmisshook = function(xhr, realXhr, res) { return false; }
var cachekeymangler = function(urlkey) { return urlkey; }
var requestCache = null;
function XMLHttpRequestProxy() {
// console.log('[Teuthis] XMLHttpRequestProxy constructor');
var xhr = new nativeXMLHttpRequest();
if (_.isNil(requestCache)) {
requestCache = new RequestCache({instanceName: 'Teuthis'});
}
var store = requestCache;
var method_ = null;
var url_ = null;
var shouldAddToCache_ = false;
var self = this;
// Facade the status, statusText and response properties to spec XMLHttpRequest
this.status = 0; // This is the status if error due to browser offline, etc.
this.statusText = "";
this.response = "";
// Facade the onload, onreadystatechange to spec XMLHttpRequest
this.onreadystatechange = null;
this.onload = null;
Object.defineProperty(self, 'proxymethod', { get: function() {return method_;} });
Object.defineProperty(self, 'proxyurl', { get: function() {return url_;} });
function shouldCache(method, url) {
if (_.isFunction(cacheSelector)) { return cacheSelector.call(self, method, url); }
return false;
}
// monkey-patch onreadystatechange to copy the status from the original.
// then call the users onreadystatechange
// This does happen each time an instance is constructed, perhaps this is redundant
xhr.onreadystatechange = function onreadystatechange () {
self.status = xhr.status;
self.statusText = xhr.statusText;
self.readyState = xhr.readyState;
if (_.isFunction(self.onreadystatechange)) { return self.onreadystatechange(); }
};
// monkey-patch onload to save the value into cache, if we had a miss in send()
// Call the users on-load once the value is saved into the cache, or immediately if not caching
xhr.onload = function onload () {
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload ' + xhr.status + ' ' + xhr.statusText);
self.status = xhr.status;
self.statusText = xhr.statusText;
self.response = xhr.response;
if (xhr.status >= 200 && xhr.status < 300 && xhr.response) {
if (shouldAddToCache_ === true) {
var mangled = cachekeymangler(url_);
if (options.debugEvents) console.log('[Teuthis] proxy-xhr-onload do-put ' + method_ + ' ' + mangled);
// console.log('proxy-cache-type ' + xhr.responseType); // + ', ' + xhr.responseText.substring(0,64));
// if (xhr.responseType === 'arraybuffer')
// Assuming the response is string or arraybuffer then clone it first, otherwise things seem to not work properly
var savedResponse = xhr.response.slice(0);
var cachedResponse = { v: savedResponse, ts: Date.now() };
store.put(method_, mangled, cachedResponse, function() {
if (_.isFunction(onloadhook)) { onloadhook(shouldAddToCache_, self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
});
shouldAddToCache_ = false;
return;
}
}
if (_.isFunction(onloadhook)) { onloadhook(shouldAddToCache_, self, xhr); } // Allow proxy success to be hooked as well
if (_.isFunction(self.onload)) { self.onload(); } // Call original
};
xhr.onerror = function onerror (event) {
// Note when using a file: URL in an Android webview, if the file is missing we get an error but status code is 0
// and event.error is not defined
if (options.debugErrorEvents) console.log('[Teuthis] proxy-xhr-onerror event=' + event.type + ' ' + method_ + ' ' + url_);
if (options.debugErrorEvents) console.log('[Teuthis] proxy-xhr-onerror error.name=' + (event.error && event.error.name) + ' error.message=' + (event.error && event.error.message));
if (_.isFunction(onerrorhook)) {
var alternativeResponse = {};
if (onerrorhook(event, shouldAddToCache_, self, xhr, alternativeResponse)) {
// If user returns true then dont call onerror, instead call onload with fake data, such as a crossed tile PNG
self.status = +200;
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
if (alternativeResponse.response) {
self.response = alternativeResponse.response;
}
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-error', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
if (_.isFunction(self.onerror)) { self.onerror(event); }
}
// Facade XMLHttpRequest.open() with a version that saves the arguments for later use, then calls the original
this.open = function() {
if (options.debugMethods) console.log('[Teuthis] proxy-xhr-open ' + arguments[0] + ' ' + arguments[1]);
method_ = arguments[0];
url_ = arguments[1];
shouldAddToCache_ = false;
xhr.open.apply(xhr, arguments);
};
// Facade XMLHttpRequest.send() with a version that queries our offline cache,
// calls the original if the response is not found in the cache, then adds the response to the cache,
// or calls to onload() with the cached response if found
this.send = function() {
if (options.debugMethods) console.log('[Teuthis] proxy-xhr-send ' + method_ + ' ' + url_);
if (shouldCache(method_, url_)) {
var mangled = cachekeymangler(url_);
if (options.debugCache) console.log('[Teuthis] proxy-try-cache ' + method_ + ' ' + mangled);
store.match(method_, mangled, function(key, cachedValue) {
if (!cachedValue.v || !cachedValue.ts) {
// something is badly wrong... we need to treat as a miss
console.warn('invalid cache data');
// This is a hack copy/paste - we really need to refactor this code
if (options.debugCache) console.log('[Teuthis] proxy-try-cache miss ' + method_ + ' ' + mangled);
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
shouldAddToCache_ = true;
xhr.send.apply(xhr, arguments);
}
if (options.debugCache) console.log('[Teuthis] proxy-try-cache hit ' + method_ + ' ' + mangled);
// hit
self.status = +200;
self.statusText = '200 OK';
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = cachedValue;
self.readyState = 4; // Done
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
// Now, how do we update the LRU time?
var o = {v: cachedValue.v.slice(0), ts: Date.now()};
store.put(method_, mangled, o, function() { });
}, function(key) {
if (options.debugCache) console.log('[Teuthis] proxy-try-cache miss ' + method_ + ' ' + mangled);
// miss - not in our cache. So try and fetch from the real Internet
//console.log('onMiss called'); console.log(arguments);
if (_.isFunction(onmisshook)) {
var res = {url: url_, status: +200, statusText: '200 OK', response: undefined, readyState: 4};
var patch = onmisshook(self, xhr, res);
if (patch) {
// Miss hook returns undefined, or otherwise, a replacement response,
// and it should fix self status, statusText, response, and readyState
self.status = res.status;
self.statusText = res.statusText;
if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
self.response = res.response;
self.readyState = res.readyState;
if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
if (_.isFunction(self.onload)) { self.onload(); }
return;
}
}
shouldAddToCache_ = true;
xhr.send.apply(xhr, arguments);
});
} else {
xhr.send.apply(xhr, arguments);
}
};
// facade all other XMLHttpRequest getters, except 'status'
["responseURL", "responseText", "responseXML", "upload"].forEach(function(item) {
Object.defineProperty(self, item, {
get: function() {return xhr[item];},
});
});
// facade all other XMLHttpRequest properties getters and setters'
["ontimeout", "timeout", "responseType", "withCredentials", "onprogress", "onloadstart", "onloadend", "onabort"].forEach(function(item) {
Object.defineProperty(self, item, {
get: function() {return xhr[item];},
set: function(val) {xhr[item] = val;},
});
});
// facade all pure XMLHttpRequest methods and EVentTarget ancestor methods
["addEventListener", "removeEventListener", "dispatchEvent",
"abort", "getAllResponseHeaders", "getResponseHeader", "overrideMimeType", "setRequestHeader"].forEach(function(item) {
Object.defineProperty(self, item, {
value: function() {return xhr[item].apply(xhr, arguments);},
});
});
};
// Set a function that returns true if method + url shold be cached
// Example:
// XMLHttpRequestProxy.setCacheSelector(function (method, url) {
// if (method === 'GET' && url.startsWith('https://') ) {
// return true;
// }
// return false;
// });
XMLHttpRequestProxy.setCacheSelector = function (cacheSelector_) {
cacheSelector = cacheSelector_;
}
XMLHttpRequestProxy.setErrorHook = function (onerrorhook_) {
onerrorhook = onerrorhook_;
}
XMLHttpRequestProxy.setLoadHook = function (onloadhook_) {
onloadhook = onloadhook_;
}
XMLHttpRequestProxy.setMissHook = function (onmisshook_) {
onmisshook = onmisshook_;
}
XMLHttpRequestProxy.setCacheKeyMangler = function (cachekeymangler_) {
cachekeymangler = cachekeymangler_;
}
// Get the underlying RequestCache store so the user can monitor usage statistics, etc.
XMLHttpRequestProxy.getStore = function () { return requestCache; }
// Set the underlying RequestCache store to a custom instance.
XMLHttpRequestProxy.setStore = function (store) { requestCache = store; }
// Create an instance of the request cache, shared among all XHR.
// If not called, and setStore not called, then happens on first XHR
XMLHttpRequestProxy.init = function(options_) {
options = Object.assign({}, options, options_);
console.log('Teuthis: Options=' + JSON.stringify(options));
if (_.isNil(requestCache)) {
var cacheOptions = {instanceName: 'Teuthis'};
// FIXME: there must be a Object or _ method to do this mapping
if (_.has(options_, 'debugCachePuts')) { cacheOptions.debugCachePuts = options_.debugCachePuts; }
if (_.has(options_, 'debugCacheHits')) { cacheOptions.debugCacheHits = options_.debugCacheHits; }
if (_.has(options_, 'debugCacheMiss')) { cacheOptions.debugCacheMiss = options_.debugCacheMiss; }
if (_.has(options_, 'debugCacheBoot')) { cacheOptions.debugCacheBoot = options_.debugCacheBoot; }
requestCache = new RequestCache(cacheOptions);
} else {
requestCache.setDebugOptions(options_);
}
return requestCache;
}
// For each value present in options_, update debugging options
XMLHttpRequestProxy.setOptions = function(options_) {
// TODO: at some point I should update all this code to ES2015, given it is being babelled anyway
_.each(options, function (v, k) {
if (_.has(options_, k)) {
options[k] = options_[k];
}
});
requestCache.setDebugOptions(options_);
}
module.exports = XMLHttpRequestProxy;
| Fix cache error with LRU update
| lib/xhr-proxy.js | Fix cache error with LRU update | <ide><path>ib/xhr-proxy.js
<ide> self.status = +200;
<ide> self.statusText = '200 OK';
<ide> if (_.isFunction(self.onreadystatechange)) { self.onreadystatechange(); }
<del> self.response = cachedValue;
<add> self.response = cachedValue.v;
<ide> self.readyState = 4; // Done
<ide> if (_.isFunction(onloadhook)) { onloadhook('on-match', self, xhr); }
<ide> if (_.isFunction(self.onload)) { self.onload(); }
<ide>
<ide> // Now, how do we update the LRU time?
<del> var o = {v: cachedValue.v.slice(0), ts: Date.now()};
<add> var o = {v: cachedValue.v, ts: Date.now()};
<ide> store.put(method_, mangled, o, function() { });
<ide> }, function(key) {
<ide> if (options.debugCache) console.log('[Teuthis] proxy-try-cache miss ' + method_ + ' ' + mangled); |
|
Java | mit | a54ffe917e12f6626b8ae473d1b9a5c3a88e3d5d | 0 | mitritim/JavaPhone | /*
* 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 javaphone;
/**
*
* @author LimeDV
*/
public class CustomerListGUI extends javax.swing.JFrame {
/**
* Creates new form StartPageGUI
*/
public CustomerListGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
menu = new javax.swing.JPanel();
main = new javax.swing.JPanel();
customerList = new javax.swing.JLabel();
viewPhone = new javax.swing.JCheckBox();
viewBradband = new javax.swing.JCheckBox();
filterWorker = new javax.swing.JLabel();
workerDropdown = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
buttonStartpage = new javax.swing.JButton();
buttonAddNewCustomer = new javax.swing.JButton();
buttonCustomer = new javax.swing.JButton();
buttonWorker = new javax.swing.JButton();
buttonServices = new javax.swing.JButton();
buttonLoggOut = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Kunder | lpPhone");
setPreferredSize(new java.awt.Dimension(1080, 720));
menu.setAlignmentX(0.0F);
menu.setAlignmentY(0.0F);
main.setAlignmentY(0.0F);
customerList.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
customerList.setText("Kundlista");
viewPhone.setText("Telefoni");
viewBradband.setText("Bredband");
filterWorker.setText("Filtrera för handläggare:");
workerDropdown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
workerDropdown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
workerDropdownActionPerformed(evt);
}
});
jTable1.setBackground(new java.awt.Color(240, 240, 240));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Kund ID", "Namn", "Telefon", "Bredband"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setGridColor(new java.awt.Color(240, 240, 240));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout mainLayout = new javax.swing.GroupLayout(main);
main.setLayout(mainLayout);
mainLayout.setHorizontalGroup(
mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainLayout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 718, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(mainLayout.createSequentialGroup()
.addComponent(customerList)
.addGap(57, 57, 57)
.addComponent(viewPhone)
.addGap(61, 61, 61)
.addComponent(viewBradband)
.addGap(65, 65, 65)
.addComponent(filterWorker)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(workerDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainLayout.setVerticalGroup(
mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(viewPhone)
.addComponent(viewBradband)
.addComponent(filterWorker)
.addComponent(workerDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(customerList))
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(286, Short.MAX_VALUE))
);
buttonStartpage.setText("Startsida");
buttonStartpage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStartpageActionPerformed(evt);
}
});
buttonAddNewCustomer.setText("Lägg till ny kund");
buttonAddNewCustomer.setMaximumSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.setMinimumSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.setPreferredSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddNewCustomerActionPerformed(evt);
}
});
buttonCustomer.setText("Kunder");
buttonCustomer.setMaximumSize(new java.awt.Dimension(83, 25));
buttonCustomer.setMinimumSize(new java.awt.Dimension(83, 25));
buttonCustomer.setPreferredSize(new java.awt.Dimension(83, 25));
buttonWorker.setText("Handläggare");
buttonWorker.setMaximumSize(new java.awt.Dimension(83, 25));
buttonWorker.setMinimumSize(new java.awt.Dimension(83, 25));
buttonWorker.setPreferredSize(new java.awt.Dimension(83, 25));
buttonWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonWorkerActionPerformed(evt);
}
});
buttonServices.setText("Abonemang");
buttonServices.setMaximumSize(new java.awt.Dimension(83, 25));
buttonServices.setMinimumSize(new java.awt.Dimension(83, 25));
buttonServices.setPreferredSize(new java.awt.Dimension(83, 25));
buttonServices.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonServicesActionPerformed(evt);
}
});
buttonLoggOut.setText("Logga ut");
buttonLoggOut.setMaximumSize(new java.awt.Dimension(83, 25));
buttonLoggOut.setMinimumSize(new java.awt.Dimension(83, 25));
buttonLoggOut.setPreferredSize(new java.awt.Dimension(83, 25));
buttonLoggOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoggOutActionPerformed(evt);
}
});
javax.swing.GroupLayout menuLayout = new javax.swing.GroupLayout(menu);
menu.setLayout(menuLayout);
menuLayout.setHorizontalGroup(
menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(menuLayout.createSequentialGroup()
.addComponent(buttonStartpage, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(main, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(menuLayout.createSequentialGroup()
.addGroup(menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonWorker, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonServices, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonLoggOut, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonAddNewCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(892, 899, Short.MAX_VALUE))
);
menuLayout.setVerticalGroup(
menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(menuLayout.createSequentialGroup()
.addGroup(menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(main, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(menuLayout.createSequentialGroup()
.addComponent(buttonStartpage, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonAddNewCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonWorker, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonServices, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonLoggOut, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, 0))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(menu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(menu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(1102, 765));
setLocationRelativeTo(null);
}// </editor-fold>
private void buttonLoggOutActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void buttonAddNewCustomerActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
NewCustomerGUI a = new NewCustomerGUI();
a.setVisible(true);
}
private void workerDropdownActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void buttonStartpageActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
StartPageGUI s = new StartPageGUI();
s.setVisible(true);
}
private void buttonWorkerActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
WorkerListGUI wl = new WorkerListGUI();
wl.setVisible(true);
}
private void buttonServicesActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
ServicesGUI se = new ServicesGUI();
se.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartPageGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonAddNewCustomer;
private javax.swing.JButton buttonCustomer;
private javax.swing.JButton buttonLoggOut;
private javax.swing.JButton buttonServices;
private javax.swing.JButton buttonStartpage;
private javax.swing.JButton buttonWorker;
private javax.swing.JLabel customerList;
private javax.swing.JLabel filterWorker;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JPanel main;
private javax.swing.JPanel menu;
private javax.swing.JCheckBox viewBradband;
private javax.swing.JCheckBox viewPhone;
private javax.swing.JComboBox workerDropdown;
// End of variables declaration
}
| src/javaphone/CustomerListGUI.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 javaphone;
/**
*
* @author LimeDV
*/
public class CustomerListGUI extends javax.swing.JFrame {
/**
* Creates new form StartPageGUI
*/
public CustomerListGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
menu = new javax.swing.JPanel();
main = new javax.swing.JPanel();
customerList = new javax.swing.JLabel();
viewPhone = new javax.swing.JCheckBox();
viewBradband = new javax.swing.JCheckBox();
filterWorker = new javax.swing.JLabel();
workerDropdown = new javax.swing.JComboBox();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
buttonStartpage = new javax.swing.JButton();
buttonAddNewCustomer = new javax.swing.JButton();
buttonCustomer = new javax.swing.JButton();
buttonWorker = new javax.swing.JButton();
buttonServices = new javax.swing.JButton();
buttonLoggOut = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Kunder | lpPhone");
setPreferredSize(new java.awt.Dimension(1080, 720));
menu.setAlignmentX(0.0F);
menu.setAlignmentY(0.0F);
main.setAlignmentY(0.0F);
customerList.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
customerList.setText("Kundlista");
viewPhone.setText("Telefoni");
viewBradband.setText("Bredband");
filterWorker.setText("Filtrera för handläggare:");
workerDropdown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
workerDropdown.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
workerDropdownActionPerformed(evt);
}
});
jTable1.setBackground(new java.awt.Color(240, 240, 240));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Kund ID", "Namn", "Telefon", "Bredband"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setGridColor(new java.awt.Color(240, 240, 240));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout mainLayout = new javax.swing.GroupLayout(main);
main.setLayout(mainLayout);
mainLayout.setHorizontalGroup(
mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainLayout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 718, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(mainLayout.createSequentialGroup()
.addComponent(customerList)
.addGap(57, 57, 57)
.addComponent(viewPhone)
.addGap(61, 61, 61)
.addComponent(viewBradband)
.addGap(65, 65, 65)
.addComponent(filterWorker)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(workerDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
mainLayout.setVerticalGroup(
mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainLayout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(mainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(viewPhone)
.addComponent(viewBradband)
.addComponent(filterWorker)
.addComponent(workerDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(customerList))
.addGap(31, 31, 31)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(260, Short.MAX_VALUE))
);
buttonStartpage.setText("Startsida");
buttonStartpage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonStartpageActionPerformed(evt);
}
});
buttonAddNewCustomer.setText("Lägg till ny kund");
buttonAddNewCustomer.setMaximumSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.setMinimumSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.setPreferredSize(new java.awt.Dimension(83, 25));
buttonAddNewCustomer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddNewCustomerActionPerformed(evt);
}
});
buttonCustomer.setText("Kunder");
buttonCustomer.setMaximumSize(new java.awt.Dimension(83, 25));
buttonCustomer.setMinimumSize(new java.awt.Dimension(83, 25));
buttonCustomer.setPreferredSize(new java.awt.Dimension(83, 25));
buttonWorker.setText("Handläggare");
buttonWorker.setMaximumSize(new java.awt.Dimension(83, 25));
buttonWorker.setMinimumSize(new java.awt.Dimension(83, 25));
buttonWorker.setPreferredSize(new java.awt.Dimension(83, 25));
buttonWorker.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonWorkerActionPerformed(evt);
}
});
buttonServices.setText("Abonemang");
buttonServices.setMaximumSize(new java.awt.Dimension(83, 25));
buttonServices.setMinimumSize(new java.awt.Dimension(83, 25));
buttonServices.setPreferredSize(new java.awt.Dimension(83, 25));
buttonServices.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonServicesActionPerformed(evt);
}
});
buttonLoggOut.setText("Logga ut");
buttonLoggOut.setMaximumSize(new java.awt.Dimension(83, 25));
buttonLoggOut.setMinimumSize(new java.awt.Dimension(83, 25));
buttonLoggOut.setPreferredSize(new java.awt.Dimension(83, 25));
buttonLoggOut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoggOutActionPerformed(evt);
}
});
javax.swing.GroupLayout menuLayout = new javax.swing.GroupLayout(menu);
menu.setLayout(menuLayout);
menuLayout.setHorizontalGroup(
menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(menuLayout.createSequentialGroup()
.addComponent(buttonStartpage, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(main, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(menuLayout.createSequentialGroup()
.addGroup(menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(buttonCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonWorker, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonServices, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonLoggOut, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(buttonAddNewCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(892, 899, Short.MAX_VALUE))
);
menuLayout.setVerticalGroup(
menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(menuLayout.createSequentialGroup()
.addGroup(menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(main, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(menuLayout.createSequentialGroup()
.addComponent(buttonStartpage, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonAddNewCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonCustomer, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonWorker, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonServices, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(buttonLoggOut, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, 0))
);
jMenu1.setText("Edit");
jMenuBar1.add(jMenu1);
jMenu2.setText("Hjälp");
jMenuItem1.setText("jMenuItem1");
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(menu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(menu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(1102, 765));
setLocationRelativeTo(null);
}// </editor-fold>
private void buttonLoggOutActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void buttonAddNewCustomerActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
NewCustomerGUI a = new NewCustomerGUI();
a.setVisible(true);
}
private void workerDropdownActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void buttonStartpageActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
StartPageGUI s = new StartPageGUI();
s.setVisible(true);
}
private void buttonWorkerActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
WorkerListGUI wl = new WorkerListGUI();
wl.setVisible(true);
}
private void buttonServicesActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
ServicesGUI se = new ServicesGUI();
se.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartPageGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartPageGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonAddNewCustomer;
private javax.swing.JButton buttonCustomer;
private javax.swing.JButton buttonLoggOut;
private javax.swing.JButton buttonServices;
private javax.swing.JButton buttonStartpage;
private javax.swing.JButton buttonWorker;
private javax.swing.JLabel customerList;
private javax.swing.JLabel filterWorker;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JPanel main;
private javax.swing.JPanel menu;
private javax.swing.JCheckBox viewBradband;
private javax.swing.JCheckBox viewPhone;
private javax.swing.JComboBox workerDropdown;
// End of variables declaration
}
| Update CustomerListGUI.java | src/javaphone/CustomerListGUI.java | Update CustomerListGUI.java | <ide><path>rc/javaphone/CustomerListGUI.java
<ide> buttonWorker = new javax.swing.JButton();
<ide> buttonServices = new javax.swing.JButton();
<ide> buttonLoggOut = new javax.swing.JButton();
<del> jMenuBar1 = new javax.swing.JMenuBar();
<del> jMenu1 = new javax.swing.JMenu();
<del> jMenu2 = new javax.swing.JMenu();
<del> jMenuItem1 = new javax.swing.JMenuItem();
<ide>
<ide> setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
<ide> setTitle("Kunder | lpPhone");
<ide> .addComponent(customerList))
<ide> .addGap(31, 31, 31)
<ide> .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
<del> .addContainerGap(260, Short.MAX_VALUE))
<add> .addContainerGap(286, Short.MAX_VALUE))
<ide> );
<ide>
<ide> buttonStartpage.setText("Startsida");
<ide> .addGap(0, 0, 0))
<ide> );
<ide>
<del> jMenu1.setText("Edit");
<del> jMenuBar1.add(jMenu1);
<del>
<del> jMenu2.setText("Hjälp");
<del>
<del> jMenuItem1.setText("jMenuItem1");
<del> jMenu2.add(jMenuItem1);
<del>
<del> jMenuBar1.add(jMenu2);
<del>
<del> setJMenuBar(jMenuBar1);
<del>
<ide> javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
<ide> getContentPane().setLayout(layout);
<ide> layout.setHorizontalGroup(
<ide> private javax.swing.JButton buttonWorker;
<ide> private javax.swing.JLabel customerList;
<ide> private javax.swing.JLabel filterWorker;
<del> private javax.swing.JMenu jMenu1;
<del> private javax.swing.JMenu jMenu2;
<del> private javax.swing.JMenuBar jMenuBar1;
<del> private javax.swing.JMenuItem jMenuItem1;
<ide> private javax.swing.JScrollPane jScrollPane1;
<ide> private javax.swing.JTable jTable1;
<ide> private javax.swing.JPanel main; |
|
JavaScript | mit | 51b0158dc3d57b569aa8ea7ef02c5f9f1ab09a3f | 0 | gbuesing/mustache.couch.js | /*
* jquery.couch.listchanges.js
* A helper for using the CouchDB changes feed to update HTML views rendered from list funs
*
* Plays well with mustache.couch.js for server-side list fun HTML rendering:
* http://github.com/gbuesing/mustache.couch.js
*
* Copyright 2011, Geoff Buesing
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
* Example:
*
* <ul data-update-type="newRows" data-update-seq="12345">
* <li data-key="key">Foo</li>
* </ul>
*
* <script>
* $('ul').listChanges();
* </script>
*
* When data-update-type="allRows", inner html of container element will be replaced with returned rows.
*
* When data-update-type="newRows", startkey/endkey will be adjusted to return only updated rows.
* New rows will be prepended or appended to the container as appropriate with the value of the
* descending querystring var. "newRows" requires embedding the row key in each row in a
* data-key attribute.
*
* The update_seq can optionally be specified in the data-update-seq attribute; this will save a call to
* retrieve the update_seq via Ajax after the page has loaded.
*
* The list fun needs to return the entire page for a standard request, and just the templated rows
* for XHR requests (rows_only=true is appended to the XHR querystring as a convenience.)
*
* See https://github.com/gbuesing/mustache.couch.js/tree/master/example
*/
(function( $ ){
$.fn.listChanges = function(opts) {
return this.each(function() {
listChanges($(this), opts || {});
});
}
function listChanges(container, opts) {
var updateSeq = opts.updateSeq || container.attr('data-update-seq');
var updateType = opts.updateType || container.attr('data-update-type') || 'allRows';
var explicitUrl = opts.url || container.attr('data-url');
var preload = !!explicitUrl;
var url = explicitUrl || window.location.pathname + window.location.search;
var urlParts = url.split('?');
var urlPath = urlParts[0];
var params = getParams(urlParts[1]);
var db = opts.db || urlPath.split('/')[1];
params.rows_only = true;
var descending = opts.descending || (params.descending === 'true') || container.attr('data-descending');
var xhr, inFlight = false, queued = false;
var queryForUpdates = function() {
if (inFlight) {
queued = true;
return;
};
inFlight = true;
var highkeyElem, containerUpdateMethod = 'html';
if (updateType === 'newRows') {
containerUpdateMethod = descending ? 'prepend' : 'append';
highkeyElem = descending ? container.children('[data-key]:first') : container.children('[data-key]:last');
if (highkeyElem) { updateParamsForNewRowsQuery(params, highkeyElem, descending) };
}
xhr = $.ajax({
type: 'GET',
url: urlPath,
data: params,
dataType: 'html',
cache: false,
success: function(data) {
if (data && data.match(/\S/)) {
container[containerUpdateMethod](data);
if (opts.success) {
var newRows;
if (highkeyElem) { newRows = descending ? highkeyElem.prevAll() : highkeyElem.nextAll() };
opts.success(newRows);
}
}
inFlight = false;
if (queued) {
queued = false;
container.trigger('update');
};
},
error: function() {
inFlight = false;
}
});
}
container.bind('update.listChanges', queryForUpdates);
if (preload) { container.trigger('update') };
var changes = $.couch.db(db).changes(updateSeq, opts.changesOpts);
changes.onChange(function() {
container.trigger('update');
});
container.data('changes', changes);
container.bind('stop.listChanges', function() {
changes.stop();
if (xhr) { xhr.abort() };
container.removeData('changes');
container.unbind('.listChanges');
});
}
// helper funs
function getParams(querystring) {
var params = {};
if (querystring.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = querystring.split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
params[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : null;
}
}
return params;
}
function updateParamsForNewRowsQuery(params, highkeyElem, descending) {
var highkey = highkeyElem.attr('data-key');
var highkey_docid = highkeyElem.attr('data-docid');
if (!highkey) { return };
delete params.limit;
if (descending) {
params.endkey = highkey;
params.inclusive_end = false;
if (highkey_docid) { params.endkey_docid = highkey_docid };
delete params.startkey;
} else {
params.startkey = highkey;
params.skip = 1;
if (highkey_docid) { params.startkey_docid = highkey_docid };
delete params.endkey;
}
}
})( jQuery );
| jquery.couch.listchanges.js | /*
* jquery.couch.listchanges.js
* A helper for using the CouchDB changes feed to update HTML views rendered from list funs
*
* Plays well with mustache.couch.js for server-side list fun HTML rendering:
* http://github.com/gbuesing/mustache.couch.js
*
* Copyright 2011, Geoff Buesing
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
* Example:
*
* <ul data-update-type="newRows" data-update-seq="12345">
* <li data-key="key">Foo</li>
* </ul>
*
* <script>
* $('ul').listChanges();
* </script>
*
* When data-update-type="allRows", inner html of container element will be replaced with returned rows.
*
* When data-update-type="newRows", startkey/endkey will be adjusted to return only updated rows.
* New rows will be prepended or appended to the container as appropriate with the value of the
* descending querystring var. "newRows" requires embedding the row key in each row in a
* data-key attribute.
*
* The update_seq can optionally be specified in the data-update-seq attribute; this will save a call to
* retrieve the update_seq via Ajax after the page has loaded.
*
* The list fun needs to return the entire page for a standard request, and just the templated rows
* for XHR requests (rows_only=true is appended to the XHR querystring as a convenience.)
*
* See https://github.com/gbuesing/mustache.couch.js/tree/master/example
*/
(function( $ ){
$.fn.listChanges = function(opts) {
listChanges(this.eq(0), opts || {});
return this;
}
function listChanges(container, opts) {
var updateSeq = opts.updateSeq || container.attr('data-update-seq');
var updateType = opts.updateType || container.attr('data-update-type') || 'allRows';
var url = opts.url || window.location.pathname + window.location.search;
var urlParts = url.split('?');
var urlPath = urlParts[0];
var params = getParams(urlParts[1]);
var db = opts.db || urlPath.split('/')[1];
params.rows_only = true;
var descending = opts.descending || (params.descending === 'true');
var preload = !!opts.url;
var xhr, inFlight = false, queued = false;
var queryForUpdates = function() {
if (inFlight) {
queued = true;
return;
};
inFlight = true;
var highkeyElem, containerUpdateMethod = 'html';
if (updateType === 'newRows') {
containerUpdateMethod = descending ? 'prepend' : 'append';
highkeyElem = descending ? container.children('[data-key]:first') : container.children('[data-key]:last');
if (highkeyElem) { updateParamsForNewRowsQuery(params, highkeyElem, descending) };
}
xhr = $.ajax({
type: 'GET',
url: urlPath,
data: params,
dataType: 'html',
cache: false,
success: function(data) {
if (data && data.match(/\S/)) {
container[containerUpdateMethod](data);
if (opts.success) {
var newRows;
if (highkeyElem) { newRows = descending ? highkeyElem.prevAll() : highkeyElem.nextAll() };
opts.success(newRows);
}
}
inFlight = false;
if (queued) {
queued = false;
container.trigger('update');
};
},
error: function() {
inFlight = false;
}
});
}
container.bind('update.listChanges', queryForUpdates);
if (preload) { container.trigger('update') };
var changes = $.couch.db(db).changes(updateSeq, opts.changesOpts);
changes.onChange(function() {
container.trigger('update');
});
container.data('changes', changes);
container.bind('stop.listChanges', function() {
changes.stop();
if (xhr) { xhr.abort() };
container.removeData('changes');
container.unbind('.listChanges');
});
}
// helper funs
function getParams(querystring) {
var params = {};
if (querystring.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = querystring.split("&"); nKeyId < aCouples.length; nKeyId++) {
aItKey = aCouples[nKeyId].split("=");
params[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : null;
}
}
return params;
}
function updateParamsForNewRowsQuery(params, highkeyElem, descending) {
var highkey = highkeyElem.attr('data-key');
var highkey_docid = highkeyElem.attr('data-docid');
if (!highkey) { return };
delete params.limit;
if (descending) {
params.endkey = highkey;
params.inclusive_end = false;
if (highkey_docid) { params.endkey_docid = highkey_docid };
delete params.startkey;
} else {
params.startkey = highkey;
params.skip = 1;
if (highkey_docid) { params.startkey_docid = highkey_docid };
delete params.endkey;
}
}
})( jQuery );
| Allow url and descending opts to be specified as data- attributes. Iterate over each element when setting up plugin so that multiple containers can be specified
| jquery.couch.listchanges.js | Allow url and descending opts to be specified as data- attributes. Iterate over each element when setting up plugin so that multiple containers can be specified | <ide><path>query.couch.listchanges.js
<ide> (function( $ ){
<ide>
<ide> $.fn.listChanges = function(opts) {
<del> listChanges(this.eq(0), opts || {});
<del> return this;
<add> return this.each(function() {
<add> listChanges($(this), opts || {});
<add> });
<ide> }
<ide>
<ide> function listChanges(container, opts) {
<ide> var updateSeq = opts.updateSeq || container.attr('data-update-seq');
<ide> var updateType = opts.updateType || container.attr('data-update-type') || 'allRows';
<del> var url = opts.url || window.location.pathname + window.location.search;
<add> var explicitUrl = opts.url || container.attr('data-url');
<add> var preload = !!explicitUrl;
<add> var url = explicitUrl || window.location.pathname + window.location.search;
<ide> var urlParts = url.split('?');
<ide> var urlPath = urlParts[0];
<ide> var params = getParams(urlParts[1]);
<ide> var db = opts.db || urlPath.split('/')[1];
<ide> params.rows_only = true;
<del> var descending = opts.descending || (params.descending === 'true');
<del> var preload = !!opts.url;
<add> var descending = opts.descending || (params.descending === 'true') || container.attr('data-descending');
<ide> var xhr, inFlight = false, queued = false;
<ide>
<ide> var queryForUpdates = function() { |
|
Java | apache-2.0 | error: pathspec 'src/test/java/com/emc/ecs/cloudfoundry/broker/service/BucketInstanceWorkflowTest.java' did not match any file(s) known to git
| 2746ff638b58fb75b262495abec9d192cd0df6f1 | 1 | emccode/ecs-cf-service-broker,spiegela/ecs-cf-service-broker,codedellemc/ecs-cf-service-broker | package com.emc.ecs.cloudfoundry.broker.service;
import com.emc.ecs.cloudfoundry.broker.model.PlanProxy;
import com.emc.ecs.cloudfoundry.broker.model.ServiceDefinitionProxy;
import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstance;
import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceRepository;
import com.github.paulcwarren.ginkgo4j.Ginkgo4jRunner;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import java.util.*;
import static com.emc.ecs.common.Fixtures.*;
import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(Ginkgo4jRunner.class)
public class BucketInstanceWorkflowTest {
private EcsService ecs;
private ServiceInstanceRepository instanceRepo;
private Map<String, Object> parameters = new HashMap<>();
private InstanceWorkflow workflow;
private ServiceDefinitionProxy serviceProxy = new ServiceDefinitionProxy();
private PlanProxy planProxy = new PlanProxy();
private ServiceInstance bucketInstance = serviceInstanceFixture();
private ArgumentCaptor<ServiceInstance> instCaptor = ArgumentCaptor.forClass(ServiceInstance.class);
{
Describe("BucketInstanceWorkflow", () -> {
BeforeEach(() -> {
ecs = mock(EcsService.class);
instanceRepo = mock(ServiceInstanceRepository.class);
workflow = new BucketInstanceWorkflow(instanceRepo, ecs);
});
Context("#changePlan", () -> {
BeforeEach(() -> {
doNothing().when(ecs)
.changeBucketPlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
});
It("should change the plan", () -> {
workflow.changePlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
verify(ecs, times(1))
.changeBucketPlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
});
});
Context("#delete", () -> {
BeforeEach(() -> {
doNothing().when(instanceRepo)
.save(any(ServiceInstance.class));
});
Context("with multiple references", () -> {
BeforeEach(() -> {
Set<String> refs = new HashSet<>(Arrays.asList(
BUCKET_NAME,
BUCKET_NAME + "2"
));
bucketInstance.setReferences(refs);
when(instanceRepo.find(BUCKET_NAME))
.thenReturn(bucketInstance);
when(instanceRepo.find(BUCKET_NAME + "2"))
.thenReturn(bucketInstance);
});
It("should not delete the bucket" ,() -> {
workflow.delete(BUCKET_NAME);
verify(ecs, times(0))
.deleteBucket(BUCKET_NAME);
});
It("should update each references", () -> {
workflow.delete(BUCKET_NAME);
verify(instanceRepo, times(1))
.save(instCaptor.capture());
ServiceInstance savedInst = instCaptor.getValue();
assertEquals(1, savedInst.getReferenceCount());
assert(savedInst.getReferences().contains(BUCKET_NAME + "2"));
});
});
Context("with a single reference", () -> {
BeforeEach(() -> {
Set<String> refs = new HashSet<>(Collections.singletonList(BUCKET_NAME));
bucketInstance.setReferences(refs);
when(instanceRepo.find(BUCKET_NAME))
.thenReturn(bucketInstance);
doNothing().when(ecs).deleteBucket(BUCKET_NAME);
});
It("should delete the bucket", () -> {
workflow.delete(BUCKET_NAME);
verify(ecs, times(1))
.deleteBucket(BUCKET_NAME);
});
});
});
Context("#create", () -> {
BeforeEach(() -> {
doNothing().when(ecs)
.createBucket(BUCKET_NAME, serviceProxy, planProxy, parameters);
workflow.withCreateRequest(bucketCreateRequestFixture(parameters));
});
It("should create the bucket", () -> {
workflow.create(BUCKET_NAME, serviceProxy, planProxy, parameters);
verify(ecs, times(1))
.createBucket(BUCKET_NAME, serviceProxy, planProxy, parameters);
});
});
});
}
}
| src/test/java/com/emc/ecs/cloudfoundry/broker/service/BucketInstanceWorkflowTest.java | Add test for bucket instance workflow
| src/test/java/com/emc/ecs/cloudfoundry/broker/service/BucketInstanceWorkflowTest.java | Add test for bucket instance workflow | <ide><path>rc/test/java/com/emc/ecs/cloudfoundry/broker/service/BucketInstanceWorkflowTest.java
<add>package com.emc.ecs.cloudfoundry.broker.service;
<add>
<add>import com.emc.ecs.cloudfoundry.broker.model.PlanProxy;
<add>import com.emc.ecs.cloudfoundry.broker.model.ServiceDefinitionProxy;
<add>import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstance;
<add>import com.emc.ecs.cloudfoundry.broker.repository.ServiceInstanceRepository;
<add>import com.github.paulcwarren.ginkgo4j.Ginkgo4jRunner;
<add>import org.junit.runner.RunWith;
<add>import org.mockito.ArgumentCaptor;
<add>
<add>import java.util.*;
<add>
<add>import static com.emc.ecs.common.Fixtures.*;
<add>import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.*;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.mockito.Mockito.*;
<add>
<add>@RunWith(Ginkgo4jRunner.class)
<add>public class BucketInstanceWorkflowTest {
<add>
<add> private EcsService ecs;
<add> private ServiceInstanceRepository instanceRepo;
<add> private Map<String, Object> parameters = new HashMap<>();
<add> private InstanceWorkflow workflow;
<add> private ServiceDefinitionProxy serviceProxy = new ServiceDefinitionProxy();
<add> private PlanProxy planProxy = new PlanProxy();
<add> private ServiceInstance bucketInstance = serviceInstanceFixture();
<add> private ArgumentCaptor<ServiceInstance> instCaptor = ArgumentCaptor.forClass(ServiceInstance.class);
<add>
<add> {
<add> Describe("BucketInstanceWorkflow", () -> {
<add> BeforeEach(() -> {
<add> ecs = mock(EcsService.class);
<add> instanceRepo = mock(ServiceInstanceRepository.class);
<add> workflow = new BucketInstanceWorkflow(instanceRepo, ecs);
<add> });
<add>
<add> Context("#changePlan", () -> {
<add> BeforeEach(() -> {
<add> doNothing().when(ecs)
<add> .changeBucketPlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> });
<add>
<add> It("should change the plan", () -> {
<add> workflow.changePlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> verify(ecs, times(1))
<add> .changeBucketPlan(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> });
<add> });
<add>
<add> Context("#delete", () -> {
<add>
<add> BeforeEach(() -> {
<add> doNothing().when(instanceRepo)
<add> .save(any(ServiceInstance.class));
<add> });
<add>
<add> Context("with multiple references", () -> {
<add> BeforeEach(() -> {
<add> Set<String> refs = new HashSet<>(Arrays.asList(
<add> BUCKET_NAME,
<add> BUCKET_NAME + "2"
<add> ));
<add> bucketInstance.setReferences(refs);
<add> when(instanceRepo.find(BUCKET_NAME))
<add> .thenReturn(bucketInstance);
<add> when(instanceRepo.find(BUCKET_NAME + "2"))
<add> .thenReturn(bucketInstance);
<add> });
<add>
<add> It("should not delete the bucket" ,() -> {
<add> workflow.delete(BUCKET_NAME);
<add> verify(ecs, times(0))
<add> .deleteBucket(BUCKET_NAME);
<add> });
<add>
<add> It("should update each references", () -> {
<add> workflow.delete(BUCKET_NAME);
<add> verify(instanceRepo, times(1))
<add> .save(instCaptor.capture());
<add> ServiceInstance savedInst = instCaptor.getValue();
<add> assertEquals(1, savedInst.getReferenceCount());
<add> assert(savedInst.getReferences().contains(BUCKET_NAME + "2"));
<add> });
<add>
<add> });
<add>
<add> Context("with a single reference", () -> {
<add> BeforeEach(() -> {
<add> Set<String> refs = new HashSet<>(Collections.singletonList(BUCKET_NAME));
<add> bucketInstance.setReferences(refs);
<add> when(instanceRepo.find(BUCKET_NAME))
<add> .thenReturn(bucketInstance);
<add> doNothing().when(ecs).deleteBucket(BUCKET_NAME);
<add> });
<add>
<add> It("should delete the bucket", () -> {
<add> workflow.delete(BUCKET_NAME);
<add> verify(ecs, times(1))
<add> .deleteBucket(BUCKET_NAME);
<add> });
<add> });
<add> });
<add>
<add> Context("#create", () -> {
<add> BeforeEach(() -> {
<add> doNothing().when(ecs)
<add> .createBucket(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> workflow.withCreateRequest(bucketCreateRequestFixture(parameters));
<add> });
<add>
<add> It("should create the bucket", () -> {
<add> workflow.create(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> verify(ecs, times(1))
<add> .createBucket(BUCKET_NAME, serviceProxy, planProxy, parameters);
<add> });
<add> });
<add> });
<add> }
<add>} |
|
Java | mit | a20aca9319fdb125c6660bc8eada902b63d5bc42 | 0 | molenzwiebel/Commons,dentmaged/Commons,dentmaged/Commons,vemacs/Commons,skipperguy12/Commons,vemacs/Commons,skipperguy12/Commons | package tc.oc.commons.bukkit.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.common.base.Strings;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.ChatPaginator;
import org.bukkit.util.Vector;
import com.google.common.collect.ImmutableMap;
public class BukkitUtils {
private static final ItemFactory factory = Bukkit.getServer().getItemFactory();
/** Makes strings have pretty colors */
public static String colorize(String s) {
return s.replace('&', '\u00A7').replace('`', '\u00A7');
}
public static List<String> colorizeList(List<String> list) {
List<String> result = new ArrayList<String>();
for (String line : list) {
result.add(colorize(line));
}
return result;
}
public static String woolMessage(DyeColor color) {
return dyeColorToChatColor(color) + color.toString().replace("_", " ") + " WOOL";
}
public static String dashedChatMessage(String message, String c, ChatColor color) {
message = " " + message + " ";
String dashes = Strings.repeat(c, (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2) / 2);
return color + dashes + message + color + dashes;
}
public static String dashedChatMessage(String message, String c, ChatColor dashColor, ChatColor messageColor) {
message = " " + message + " ";
String dashes = Strings.repeat(c, (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2) / (c.length() * 2));
return dashColor + dashes + ChatColor.RESET + messageColor + message + ChatColor.RESET + dashColor + dashes;
}
public static Vector blockToVector(Block block) {
return block.getLocation().toVector();
}
public static ItemStack generateBook(String title, String author, List<String> pages) {
ItemStack stack = new ItemStack(Material.WRITTEN_BOOK);
BookMeta meta = (BookMeta) factory.getItemMeta(Material.WRITTEN_BOOK);
meta.setTitle(title);
meta.setAuthor(author);
meta.setPages(pages);
stack.setItemMeta(meta);
return stack;
}
public static ChatColor dyeColorToChatColor(DyeColor dyeColor) {
ChatColor chatColor = DYE_CHAT_MAP.get(dyeColor);
if (chatColor != null) {
return chatColor;
} else {
return ChatColor.WHITE;
}
}
public static DyeColor chatColorToDyeColor(ChatColor chatColor) {
DyeColor dyeColor = CHAT_DYE_MAP.get(chatColor);
if (dyeColor != null) {
return dyeColor;
} else {
return DyeColor.WHITE;
}
}
private static final Map<DyeColor, ChatColor> DYE_CHAT_MAP = ImmutableMap.<DyeColor, ChatColor>builder()
.put(DyeColor.BLACK, ChatColor.BLACK)
.put(DyeColor.BLUE, ChatColor.DARK_BLUE)
.put(DyeColor.GREEN, ChatColor.DARK_GREEN)
.put(DyeColor.CYAN, ChatColor.DARK_AQUA)
.put(DyeColor.RED, ChatColor.RED)
.put(DyeColor.PURPLE, ChatColor.DARK_PURPLE)
.put(DyeColor.ORANGE, ChatColor.GOLD)
.put(DyeColor.SILVER, ChatColor.GRAY)
.put(DyeColor.GRAY, ChatColor.DARK_GRAY)
.put(DyeColor.LIGHT_BLUE, ChatColor.BLUE)
.put(DyeColor.LIME, ChatColor.GREEN)
.put(DyeColor.BROWN, ChatColor.DARK_RED)
.put(DyeColor.MAGENTA, ChatColor.LIGHT_PURPLE)
.put(DyeColor.YELLOW, ChatColor.YELLOW)
.put(DyeColor.WHITE, ChatColor.WHITE)
.put(DyeColor.PINK, ChatColor.LIGHT_PURPLE).build();
private static final Map<ChatColor, DyeColor> CHAT_DYE_MAP = ImmutableMap.<ChatColor, DyeColor>builder()
.put(ChatColor.AQUA, DyeColor.LIGHT_BLUE)
.put(ChatColor.BLACK, DyeColor.BLACK)
.put(ChatColor.BLUE, DyeColor.LIGHT_BLUE)
.put(ChatColor.DARK_AQUA, DyeColor.CYAN)
.put(ChatColor.DARK_BLUE, DyeColor.BLUE)
.put(ChatColor.DARK_GRAY, DyeColor.GRAY)
.put(ChatColor.DARK_GREEN, DyeColor.GREEN)
.put(ChatColor.DARK_PURPLE, DyeColor.PURPLE)
.put(ChatColor.DARK_RED, DyeColor.RED)
.put(ChatColor.GOLD, DyeColor.ORANGE)
.put(ChatColor.GRAY, DyeColor.SILVER)
.put(ChatColor.GREEN, DyeColor.LIME)
.put(ChatColor.LIGHT_PURPLE, DyeColor.MAGENTA)
.put(ChatColor.RED, DyeColor.RED)
.put(ChatColor.WHITE, DyeColor.WHITE)
.put(ChatColor.YELLOW, DyeColor.YELLOW).build();
public static Color colorOf(ChatColor chatColor) {
Color color = CHAT_COLOR_MAP.get(chatColor);
if (color != null) {
return color;
} else {
return Color.WHITE;
}
}
private static final Map<ChatColor, Color> CHAT_COLOR_MAP = ImmutableMap.<ChatColor, Color>builder()
.put(ChatColor.BLACK, Color.fromRGB(0, 0, 0))
.put(ChatColor.DARK_BLUE, Color.fromRGB(0, 0, 170))
.put(ChatColor.DARK_GREEN, Color.fromRGB(0, 170, 0))
.put(ChatColor.DARK_AQUA, Color.fromRGB(0, 170, 170))
.put(ChatColor.DARK_RED, Color.fromRGB(170, 0, 0))
.put(ChatColor.DARK_PURPLE, Color.fromRGB(170, 0, 170))
.put(ChatColor.GOLD, Color.fromRGB(255, 170, 0))
.put(ChatColor.GRAY, Color.fromRGB(170, 170, 170))
.put(ChatColor.DARK_GRAY, Color.fromRGB(85, 85, 85))
.put(ChatColor.BLUE, Color.fromRGB(85, 85, 255))
.put(ChatColor.GREEN, Color.fromRGB(85, 255, 85))
.put(ChatColor.AQUA, Color.fromRGB(85, 255, 255))
.put(ChatColor.RED, Color.fromRGB(255, 85, 85))
.put(ChatColor.LIGHT_PURPLE, Color.fromRGB(255, 85, 255))
.put(ChatColor.YELLOW, Color.fromRGB(255, 255, 85))
.put(ChatColor.WHITE, Color.fromRGB(255, 255, 255)).build();
public static String potionEffectTypeName(final PotionEffectType type) {
String name = POTION_EFFECT_MAP.get(type);
if (name != null) {
return name;
} else {
return "Unknown";
}
}
public static final Map<PotionEffectType, String> POTION_EFFECT_MAP = ImmutableMap.<PotionEffectType, String>builder()
.put(PotionEffectType.BLINDNESS, "Blindness")
.put(PotionEffectType.CONFUSION, "Nausea")
.put(PotionEffectType.DAMAGE_RESISTANCE, "Resistance")
.put(PotionEffectType.FAST_DIGGING, "Haste")
.put(PotionEffectType.FIRE_RESISTANCE, "Fire Resistance")
.put(PotionEffectType.HARM, "Instant Damage")
.put(PotionEffectType.HEAL, "Instant Health")
.put(PotionEffectType.HUNGER, "Hunger")
.put(PotionEffectType.INCREASE_DAMAGE, "Strength")
.put(PotionEffectType.INVISIBILITY, "Invisibility")
.put(PotionEffectType.JUMP, "Jump Boost")
.put(PotionEffectType.NIGHT_VISION, "Night Vision")
.put(PotionEffectType.POISON, "Poison")
.put(PotionEffectType.REGENERATION, "Regeneration")
.put(PotionEffectType.SLOW, "Slowness")
.put(PotionEffectType.SLOW_DIGGING, "Mining Fatigue")
.put(PotionEffectType.SPEED, "Speed")
.put(PotionEffectType.WATER_BREATHING, "Water Breating")
.put(PotionEffectType.WEAKNESS, "Weakness")
.put(PotionEffectType.WITHER, "Wither")
.put(PotionEffectType.HEALTH_BOOST, "Health Boost")
.put(PotionEffectType.ABSORPTION, "Absorption")
.put(PotionEffectType.SATURATION, "Saturation")
.build();
}
| bukkit/src/main/java/tc/oc/commons/bukkit/util/BukkitUtils.java | package tc.oc.commons.bukkit.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.common.base.Strings;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemFactory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.util.ChatPaginator;
import org.bukkit.util.Vector;
import com.google.common.collect.ImmutableMap;
public class BukkitUtils {
private static final ItemFactory factory = Bukkit.getServer().getItemFactory();
/** Makes strings have pretty colors */
public static String colorize(String s) {
return s.replace('&', '\u00A7').replace('`', '\u00A7');
}
public static List<String> colorizeList(List<String> list) {
List<String> result = new ArrayList<String>();
for (String line : list) {
result.add(colorize(line));
}
return result;
}
public static String woolMessage(DyeColor color) {
return dyeColorToChatColor(color) + color.toString().replace("_", " ") + " WOOL";
}
public static String dashedChatMessage(String message, String c, ChatColor color) {
message = " " + message + " ";
String dashes = Strings.repeat(c, (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2) / 2);
return color + dashes + message + color + dashes;
}
public static Vector blockToVector(Block block) {
return block.getLocation().toVector();
}
public static ItemStack generateBook(String title, String author, List<String> pages) {
ItemStack stack = new ItemStack(Material.WRITTEN_BOOK);
BookMeta meta = (BookMeta) factory.getItemMeta(Material.WRITTEN_BOOK);
meta.setTitle(title);
meta.setAuthor(author);
meta.setPages(pages);
stack.setItemMeta(meta);
return stack;
}
public static ChatColor dyeColorToChatColor(DyeColor dyeColor) {
ChatColor chatColor = DYE_CHAT_MAP.get(dyeColor);
if (chatColor != null) {
return chatColor;
} else {
return ChatColor.WHITE;
}
}
public static DyeColor chatColorToDyeColor(ChatColor chatColor) {
DyeColor dyeColor = CHAT_DYE_MAP.get(chatColor);
if (dyeColor != null) {
return dyeColor;
} else {
return DyeColor.WHITE;
}
}
private static final Map<DyeColor, ChatColor> DYE_CHAT_MAP = ImmutableMap.<DyeColor, ChatColor>builder()
.put(DyeColor.BLACK, ChatColor.BLACK)
.put(DyeColor.BLUE, ChatColor.DARK_BLUE)
.put(DyeColor.GREEN, ChatColor.DARK_GREEN)
.put(DyeColor.CYAN, ChatColor.DARK_AQUA)
.put(DyeColor.RED, ChatColor.RED)
.put(DyeColor.PURPLE, ChatColor.DARK_PURPLE)
.put(DyeColor.ORANGE, ChatColor.GOLD)
.put(DyeColor.SILVER, ChatColor.GRAY)
.put(DyeColor.GRAY, ChatColor.DARK_GRAY)
.put(DyeColor.LIGHT_BLUE, ChatColor.BLUE)
.put(DyeColor.LIME, ChatColor.GREEN)
.put(DyeColor.BROWN, ChatColor.DARK_RED)
.put(DyeColor.MAGENTA, ChatColor.LIGHT_PURPLE)
.put(DyeColor.YELLOW, ChatColor.YELLOW)
.put(DyeColor.WHITE, ChatColor.WHITE)
.put(DyeColor.PINK, ChatColor.LIGHT_PURPLE).build();
private static final Map<ChatColor, DyeColor> CHAT_DYE_MAP = ImmutableMap.<ChatColor, DyeColor>builder()
.put(ChatColor.AQUA, DyeColor.LIGHT_BLUE)
.put(ChatColor.BLACK, DyeColor.BLACK)
.put(ChatColor.BLUE, DyeColor.LIGHT_BLUE)
.put(ChatColor.DARK_AQUA, DyeColor.CYAN)
.put(ChatColor.DARK_BLUE, DyeColor.BLUE)
.put(ChatColor.DARK_GRAY, DyeColor.GRAY)
.put(ChatColor.DARK_GREEN, DyeColor.GREEN)
.put(ChatColor.DARK_PURPLE, DyeColor.PURPLE)
.put(ChatColor.DARK_RED, DyeColor.RED)
.put(ChatColor.GOLD, DyeColor.ORANGE)
.put(ChatColor.GRAY, DyeColor.SILVER)
.put(ChatColor.GREEN, DyeColor.LIME)
.put(ChatColor.LIGHT_PURPLE, DyeColor.MAGENTA)
.put(ChatColor.RED, DyeColor.RED)
.put(ChatColor.WHITE, DyeColor.WHITE)
.put(ChatColor.YELLOW, DyeColor.YELLOW).build();
public static Color colorOf(ChatColor chatColor) {
Color color = CHAT_COLOR_MAP.get(chatColor);
if (color != null) {
return color;
} else {
return Color.WHITE;
}
}
private static final Map<ChatColor, Color> CHAT_COLOR_MAP = ImmutableMap.<ChatColor, Color>builder()
.put(ChatColor.BLACK, Color.fromRGB(0, 0, 0))
.put(ChatColor.DARK_BLUE, Color.fromRGB(0, 0, 170))
.put(ChatColor.DARK_GREEN, Color.fromRGB(0, 170, 0))
.put(ChatColor.DARK_AQUA, Color.fromRGB(0, 170, 170))
.put(ChatColor.DARK_RED, Color.fromRGB(170, 0, 0))
.put(ChatColor.DARK_PURPLE, Color.fromRGB(170, 0, 170))
.put(ChatColor.GOLD, Color.fromRGB(255, 170, 0))
.put(ChatColor.GRAY, Color.fromRGB(170, 170, 170))
.put(ChatColor.DARK_GRAY, Color.fromRGB(85, 85, 85))
.put(ChatColor.BLUE, Color.fromRGB(85, 85, 255))
.put(ChatColor.GREEN, Color.fromRGB(85, 255, 85))
.put(ChatColor.AQUA, Color.fromRGB(85, 255, 255))
.put(ChatColor.RED, Color.fromRGB(255, 85, 85))
.put(ChatColor.LIGHT_PURPLE, Color.fromRGB(255, 85, 255))
.put(ChatColor.YELLOW, Color.fromRGB(255, 255, 85))
.put(ChatColor.WHITE, Color.fromRGB(255, 255, 255)).build();
public static String potionEffectTypeName(final PotionEffectType type) {
String name = POTION_EFFECT_MAP.get(type);
if (name != null) {
return name;
} else {
return "Unknown";
}
}
public static final Map<PotionEffectType, String> POTION_EFFECT_MAP = ImmutableMap.<PotionEffectType, String>builder()
.put(PotionEffectType.BLINDNESS, "Blindness")
.put(PotionEffectType.CONFUSION, "Nausea")
.put(PotionEffectType.DAMAGE_RESISTANCE, "Resistance")
.put(PotionEffectType.FAST_DIGGING, "Haste")
.put(PotionEffectType.FIRE_RESISTANCE, "Fire Resistance")
.put(PotionEffectType.HARM, "Instant Damage")
.put(PotionEffectType.HEAL, "Instant Health")
.put(PotionEffectType.HUNGER, "Hunger")
.put(PotionEffectType.INCREASE_DAMAGE, "Strength")
.put(PotionEffectType.INVISIBILITY, "Invisibility")
.put(PotionEffectType.JUMP, "Jump Boost")
.put(PotionEffectType.NIGHT_VISION, "Night Vision")
.put(PotionEffectType.POISON, "Poison")
.put(PotionEffectType.REGENERATION, "Regeneration")
.put(PotionEffectType.SLOW, "Slowness")
.put(PotionEffectType.SLOW_DIGGING, "Mining Fatigue")
.put(PotionEffectType.SPEED, "Speed")
.put(PotionEffectType.WATER_BREATHING, "Water Breating")
.put(PotionEffectType.WEAKNESS, "Weakness")
.put(PotionEffectType.WITHER, "Wither")
.put(PotionEffectType.HEALTH_BOOST, "Health Boost")
.put(PotionEffectType.ABSORPTION, "Absorption")
.put(PotionEffectType.SATURATION, "Saturation")
.build();
}
| Add additional dashedChatMessage method
| bukkit/src/main/java/tc/oc/commons/bukkit/util/BukkitUtils.java | Add additional dashedChatMessage method | <ide><path>ukkit/src/main/java/tc/oc/commons/bukkit/util/BukkitUtils.java
<ide> message = " " + message + " ";
<ide> String dashes = Strings.repeat(c, (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2) / 2);
<ide> return color + dashes + message + color + dashes;
<add> }
<add>
<add> public static String dashedChatMessage(String message, String c, ChatColor dashColor, ChatColor messageColor) {
<add> message = " " + message + " ";
<add> String dashes = Strings.repeat(c, (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2) / (c.length() * 2));
<add> return dashColor + dashes + ChatColor.RESET + messageColor + message + ChatColor.RESET + dashColor + dashes;
<ide> }
<ide>
<ide> public static Vector blockToVector(Block block) { |
|
JavaScript | mit | 0299bc17cb9578b815add3a06bfb0cb54f351be8 | 0 | boykotdogan/boykotdogan,boykotdogan/boykotdogan | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
//console.log(info.url);
// location.replace('http://www.google.com');
//return {cancel: true};
return {redirectUrl: "https://www.google.com.tr/search?q=do%C4%9Fan+medya+grubunu+boykot+ediyoruz"};
// return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
},
{
urls: ["*://*.hurriyet.com.tr/*",
"*://*.cnnturk.com/*",
"*://*.slowturk.com.tr/*",
"*://*.posta.com.tr/*",
"*://*.fanatik.com.tr/*",
"*://*.dr.com.tr/*",
"*://*.hepsiburada.com/*",
"*://*.hurriyetdailynews.com/*",
"*://*.tmeast.com/*",
"*://*.doganburda.com/*",
"*://*.doganegmont.com.tr/*",
"*://*.dpp.com.tr/*",
"*://*.yaysat.com.tr/*",
"*://*.dpc.com.tr/*",
"*://*.ddt.com.tr/*",
"*://*.dha.com.tr/*",
"*://*.kanald.com.tr*",
"*://*.cnnturk.com/*",
"*://*.teve2.com.tr/*",
"*://*.dreamtv.com.tr/*",
"*://*.radyod.com.tr/*",
"*://*.radyonom.com/*",
"*://*.dproductions.com.tr/*",
"*://*.dmc.com.tr/*",
"*://*.dsmart.com.tr/*",
"*://*.hurriyetemlak.com/*",
"*://*.hurriyetoto.com/*",
"*://*.yenibiris.com/*",
"*://*.ekolay.net/*",
"*://*.hurriyetaile.com/*",
"*://*.mahmure.com/*",
"*://*.yakala.co/*",
"*://*.bigpara.com/*",
"*://*.medyanet.net/*",
"*://*.ekolay.net/*",
"*://*.radyonom.com/*",
"*://*.dproductions.com.tr/*",
"*://*.dsmart.com.tr/*",
"*://*.dsmartgo.com.tr/*",
"*://*.tmeast.com/*",
"*://*.dogankitap.com.tr/*",
"*://*.designprintpost.com/*",
"*://*.dogandisticaret.com.tr/*",
"*://*.designprintpost.com/*",
"*://*.dpc.com.tr/*",
"*://*.yaysat.com.tr/*",
"*://*.ditas.com.tr/*",
"*://*.celikhalat.com.tr/*",
"*://*.doganorganik.com.tr/*",
"*://*.milpa.com.tr/*",
"*://*.suzuki.com.tr/*",
"*://*.ddm.com.tr/*",
"*://*.isiltur.com/*",
"*://*.isilclub.com/*",
"*://*.miltabodrummarina.com/*",
"*://*.milta.com.tr/*",
"*://*.doganfaktoring.com.tr/*",
"*://*.oncugsyo.com.tr/*"]
},
["blocking"]
);
| background.js | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
chrome.webRequest.onBeforeRequest.addListener(
function(info) {
//console.log(info.url);
// location.replace('http://www.google.com');
//return {cancel: true};
return {redirectUrl: "https://www.google.com.tr/search?q=do%C4%9Fan+medya+grubunu+boykot+ediyoruz"};
// return {redirectUrl: host + details.url.match(/^https?:\/\/[^\/]+([\S\s]*)/)[1]};
},
{
urls: ["*://*.hurriyet.com.tr/*",
"*://*.cnnturk.com/*",
"*://*.slowturk.com.tr/*",
"*://*.posta.com.tr/*",
"*://*.fanatik.com.tr/*",
"*://*.dr.com.tr/*",
"*://*.hepsiburada.com/*",
"*://*.hurriyetdailynews.com/*",
"*://*.tmeast.com/*",
"*://*.doganburda.com/*",
"*://*.doganegmont.com.tr/*",
"*://*.dpp.com.tr/*",
"*://*.yaysat.com.tr/*",
"*://*.dpc.com.tr/*",
"*://*.ddt.com.tr/*",
"*://*.dha.com.tr/*",
"*://*.kanald.com.tr*",
"*://*.cnnturk.com/*",
"*://*.teve2.com.tr/*",
"*://*.dreamtv.com.tr/*",
"*://*.radyod.com.tr/*",
"*://*.slowturk.com.tr/*",
"*://*radyonom.com/*",
"*://*.dproductions.com.tr/*",
"*://*.dmc.com.tr/*",
"*://*.dsmart.com.tr/*"
]
},
["blocking"]
);
| Update background.js
38. satir sonrasi yeni boykot sirketleri eklendi. bugfixler yapildi. | background.js | Update background.js | <ide><path>ackground.js
<ide> "*://*.teve2.com.tr/*",
<ide> "*://*.dreamtv.com.tr/*",
<ide> "*://*.radyod.com.tr/*",
<del> "*://*.slowturk.com.tr/*",
<del> "*://*radyonom.com/*",
<add> "*://*.radyonom.com/*",
<ide> "*://*.dproductions.com.tr/*",
<ide> "*://*.dmc.com.tr/*",
<del> "*://*.dsmart.com.tr/*"
<del> ]
<add> "*://*.dsmart.com.tr/*",
<add> "*://*.hurriyetemlak.com/*",
<add> "*://*.hurriyetoto.com/*",
<add> "*://*.yenibiris.com/*",
<add> "*://*.ekolay.net/*",
<add> "*://*.hurriyetaile.com/*",
<add> "*://*.mahmure.com/*",
<add> "*://*.yakala.co/*",
<add> "*://*.bigpara.com/*",
<add> "*://*.medyanet.net/*",
<add> "*://*.ekolay.net/*",
<add> "*://*.radyonom.com/*",
<add> "*://*.dproductions.com.tr/*",
<add> "*://*.dsmart.com.tr/*",
<add> "*://*.dsmartgo.com.tr/*",
<add> "*://*.tmeast.com/*",
<add> "*://*.dogankitap.com.tr/*",
<add> "*://*.designprintpost.com/*",
<add> "*://*.dogandisticaret.com.tr/*",
<add> "*://*.designprintpost.com/*",
<add> "*://*.dpc.com.tr/*",
<add> "*://*.yaysat.com.tr/*",
<add> "*://*.ditas.com.tr/*",
<add> "*://*.celikhalat.com.tr/*",
<add> "*://*.doganorganik.com.tr/*",
<add> "*://*.milpa.com.tr/*",
<add> "*://*.suzuki.com.tr/*",
<add> "*://*.ddm.com.tr/*",
<add> "*://*.isiltur.com/*",
<add> "*://*.isilclub.com/*",
<add> "*://*.miltabodrummarina.com/*",
<add> "*://*.milta.com.tr/*",
<add> "*://*.doganfaktoring.com.tr/*",
<add> "*://*.oncugsyo.com.tr/*"]
<ide> },
<ide> ["blocking"]
<ide> ); |
|
Java | apache-2.0 | 97f7ad35a525cd82d1f4916e5b6b68a870c6f5b8 | 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.util.indexing.impl.perFileVersion;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import com.intellij.testFramework.fixtures.TempDirTestFixture;
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl;
import com.intellij.util.indexing.*;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class PersistentSubIndexerVersionEnumeratorTest extends LightJavaCodeInsightFixtureTestCase {
private TempDirTestFixture myDirTestFixture;
private File myRoot;
private PersistentSubIndexerRetriever<MyIndexFileAttribute, String> myMap;
@Override
protected void setUp() throws Exception {
super.setUp();
myRoot = FileUtil.createTempDirectory("persistent", "map");
myDirTestFixture = new TempDirTestFixtureImpl();
myDirTestFixture.setUp();
}
@Override
protected void tearDown() throws Exception {
try {
if (myMap != null) {
myMap.close();
}
myDirTestFixture.tearDown();
}
catch (Exception e) {
addSuppressedException(e);
} finally {
super.tearDown();
}
}
public void testAddRetrieve() throws IOException {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
persistIndexedState(boo1);
assertTrue(isIndexedState(foo1));
assertTrue(isIndexedState(boo1));
assertFalse(isIndexedState(foo2));
assertFalse(isIndexedState(baz1));
}
public void testInvalidation() throws IOException {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
assertTrue(isIndexedState(foo1));
myMap.close();
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
assertFalse(isIndexedState(foo2));
persistIndexedState(foo2);
assertTrue(isIndexedState(foo2));
assertFalse(isIndexedState(foo1));
}
public void testStaleKeysRemoval() {
int baseThreshold = PersistentSubIndexerVersionEnumerator.getStorageSizeLimit();
PersistentSubIndexerVersionEnumerator.setStorageSizeLimit(2);
try {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
persistIndexedState(boo1);
persistIndexedState(bar1);
persistIndexedState(baz1);
assertTrue(isIndexedState(foo1));
assertTrue(isIndexedState(boo1));
assertTrue(isIndexedState(bar1));
assertTrue(isIndexedState(baz1));
myMap.close();
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
fail();
} catch (IOException ignored) {
// it's ok
} finally {
PersistentSubIndexerVersionEnumerator.setStorageSizeLimit(baseThreshold);
}
}
private static final Key<MyIndexFileAttribute> ATTRIBUTE_KEY = Key.create("my.index.attr.key");
private static class MyPerFileIndexExtension implements CompositeDataIndexer<String, String, MyIndexFileAttribute, String> {
@Nullable
@Override
public MyIndexFileAttribute calculateSubIndexer(@NotNull IndexedFile file) {
return file.getFile().getUserData(ATTRIBUTE_KEY);
}
@NotNull
@Override
public String getSubIndexerVersion(@NotNull MyIndexFileAttribute attribute) {
return attribute.name + ":" + attribute.version;
}
@NotNull
@Override
public KeyDescriptor<String> getSubIndexerVersionDescriptor() {
return EnumeratorStringDescriptor.INSTANCE;
}
@NotNull
@Override
public Map<String, String> map(@NotNull FileContent inputData, @NotNull MyIndexFileAttribute attribute) {
return null;
}
}
private final MyIndexFileAttribute foo1 = new MyIndexFileAttribute(1, "foo");
private final MyIndexFileAttribute foo2 = new MyIndexFileAttribute(2, "foo");
private final MyIndexFileAttribute foo3 = new MyIndexFileAttribute(3, "foo");
private final MyIndexFileAttribute bar1 = new MyIndexFileAttribute(1, "bar");
private final MyIndexFileAttribute bar2 = new MyIndexFileAttribute(2, "bar");
private final MyIndexFileAttribute baz1 = new MyIndexFileAttribute(1, "baz");
private final MyIndexFileAttribute boo1 = new MyIndexFileAttribute(1, "boo");
private static final class MyIndexFileAttribute {
final int version;
final String name;
private MyIndexFileAttribute(int version, String name) {
this.version = version;
this.name = name;
}
}
@NotNull
VirtualFile file(@NotNull MyIndexFileAttribute attribute) {
return myDirTestFixture.createFile(attribute.name + ".java");
}
void persistIndexedState(@NotNull MyIndexFileAttribute attribute) {
VirtualFile file = file(attribute);
file.putUserData(ATTRIBUTE_KEY, attribute);
try {
myMap.setIndexedState(((VirtualFileWithId) file).getId(), new IndexedFileImpl(file, getProject()));
}
catch (IOException e) {
LOG.error(e);
fail(e.getMessage());
} finally {
file.putUserData(ATTRIBUTE_KEY, null);
}
}
boolean isIndexedState(@NotNull MyIndexFileAttribute attribute) {
VirtualFile file = file(attribute);
file.putUserData(ATTRIBUTE_KEY, attribute);
try {
return myMap.getSubIndexerState(((VirtualFileWithId)file).getId(), new IndexedFileImpl(file, getProject())) == FileIndexingState.UP_TO_DATE;
}
catch (IOException e) {
LOG.error(e);
fail(e.getMessage());
return false;
} finally {
file.putUserData(ATTRIBUTE_KEY, null);
}
}
}
| java/java-tests/testSrc/com/intellij/util/indexing/impl/perFileVersion/PersistentSubIndexerVersionEnumeratorTest.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.util.indexing.impl.perFileVersion;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase;
import com.intellij.testFramework.fixtures.TempDirTestFixture;
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl;
import com.intellij.util.indexing.*;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Map;
public class PersistentSubIndexerVersionEnumeratorTest extends LightJavaCodeInsightFixtureTestCase {
private TempDirTestFixture myDirTestFixture;
private File myRoot;
private PersistentSubIndexerRetriever<MyIndexFileAttribute, String> myMap;
@Override
protected void setUp() throws Exception {
super.setUp();
myRoot = FileUtil.createTempDirectory("persistent", "map");
myDirTestFixture = new TempDirTestFixtureImpl();
myDirTestFixture.setUp();
}
@Override
protected void tearDown() throws Exception {
try {
myMap.close();
myDirTestFixture.tearDown();
}
catch (Exception e) {
addSuppressedException(e);
} finally {
super.tearDown();
}
}
public void testAddRetrieve() throws IOException {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
persistIndexedState(boo1);
assertTrue(isIndexedState(foo1));
assertTrue(isIndexedState(boo1));
assertFalse(isIndexedState(foo2));
assertFalse(isIndexedState(baz1));
}
public void testInvalidation() throws IOException {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
assertTrue(isIndexedState(foo1));
myMap.close();
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
assertFalse(isIndexedState(foo2));
persistIndexedState(foo2);
assertTrue(isIndexedState(foo2));
assertFalse(isIndexedState(foo1));
}
public void testStaleKeysRemoval() {
int baseThreshold = PersistentSubIndexerVersionEnumerator.getStorageSizeLimit();
PersistentSubIndexerVersionEnumerator.setStorageSizeLimit(2);
try {
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
persistIndexedState(foo1);
persistIndexedState(boo1);
persistIndexedState(bar1);
persistIndexedState(baz1);
assertTrue(isIndexedState(foo1));
assertTrue(isIndexedState(boo1));
assertTrue(isIndexedState(bar1));
assertTrue(isIndexedState(baz1));
myMap.close();
myMap = new PersistentSubIndexerRetriever<>(myRoot, "index_name", 0, new MyPerFileIndexExtension());
fail();
} catch (IOException ignored) {
// it's ok
} finally {
PersistentSubIndexerVersionEnumerator.setStorageSizeLimit(baseThreshold);
}
}
private static final Key<MyIndexFileAttribute> ATTRIBUTE_KEY = Key.create("my.index.attr.key");
private static class MyPerFileIndexExtension implements CompositeDataIndexer<String, String, MyIndexFileAttribute, String> {
@Nullable
@Override
public MyIndexFileAttribute calculateSubIndexer(@NotNull IndexedFile file) {
return file.getFile().getUserData(ATTRIBUTE_KEY);
}
@NotNull
@Override
public String getSubIndexerVersion(@NotNull MyIndexFileAttribute attribute) {
return attribute.name + ":" + attribute.version;
}
@NotNull
@Override
public KeyDescriptor<String> getSubIndexerVersionDescriptor() {
return EnumeratorStringDescriptor.INSTANCE;
}
@NotNull
@Override
public Map<String, String> map(@NotNull FileContent inputData, @NotNull MyIndexFileAttribute attribute) {
return null;
}
}
private final MyIndexFileAttribute foo1 = new MyIndexFileAttribute(1, "foo");
private final MyIndexFileAttribute foo2 = new MyIndexFileAttribute(2, "foo");
private final MyIndexFileAttribute foo3 = new MyIndexFileAttribute(3, "foo");
private final MyIndexFileAttribute bar1 = new MyIndexFileAttribute(1, "bar");
private final MyIndexFileAttribute bar2 = new MyIndexFileAttribute(2, "bar");
private final MyIndexFileAttribute baz1 = new MyIndexFileAttribute(1, "baz");
private final MyIndexFileAttribute boo1 = new MyIndexFileAttribute(1, "boo");
private static final class MyIndexFileAttribute {
final int version;
final String name;
private MyIndexFileAttribute(int version, String name) {
this.version = version;
this.name = name;
}
}
@NotNull
VirtualFile file(@NotNull MyIndexFileAttribute attribute) {
return myDirTestFixture.createFile(attribute.name + ".java");
}
void persistIndexedState(@NotNull MyIndexFileAttribute attribute) {
VirtualFile file = file(attribute);
file.putUserData(ATTRIBUTE_KEY, attribute);
try {
myMap.setIndexedState(((VirtualFileWithId) file).getId(), new IndexedFileImpl(file, getProject()));
}
catch (IOException e) {
LOG.error(e);
fail(e.getMessage());
} finally {
file.putUserData(ATTRIBUTE_KEY, null);
}
}
boolean isIndexedState(@NotNull MyIndexFileAttribute attribute) {
VirtualFile file = file(attribute);
file.putUserData(ATTRIBUTE_KEY, attribute);
try {
return myMap.getSubIndexerState(((VirtualFileWithId)file).getId(), new IndexedFileImpl(file, getProject())) == FileIndexingState.UP_TO_DATE;
}
catch (IOException e) {
LOG.error(e);
fail(e.getMessage());
return false;
} finally {
file.putUserData(ATTRIBUTE_KEY, null);
}
}
}
| Fix NPE in PersistentSubIndexerVersionEnumeratorTest.
GitOrigin-RevId: 8dee0640744f1076d6788204f08bfeb35d8e58dd | java/java-tests/testSrc/com/intellij/util/indexing/impl/perFileVersion/PersistentSubIndexerVersionEnumeratorTest.java | Fix NPE in PersistentSubIndexerVersionEnumeratorTest. | <ide><path>ava/java-tests/testSrc/com/intellij/util/indexing/impl/perFileVersion/PersistentSubIndexerVersionEnumeratorTest.java
<ide> @Override
<ide> protected void tearDown() throws Exception {
<ide> try {
<del> myMap.close();
<add> if (myMap != null) {
<add> myMap.close();
<add> }
<ide> myDirTestFixture.tearDown();
<ide> }
<ide> catch (Exception e) { |
|
Java | bsd-3-clause | d2651a08e0fbb0436cf126c01c6edd5f83387d96 | 0 | mohsenuss91/Orchid,subgraph/Orchid | package org.torproject.jtor.circuits.impl;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.torproject.jtor.Logger;
import org.torproject.jtor.TorException;
import org.torproject.jtor.directory.Router;
public class ConnectionManagerImpl {
private static final String[] MANDATORY_CIPHERS = {
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
"SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
"SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"};
private static final TrustManager[] NULL_TRUST = {
new X509TrustManager() {
private final X509Certificate[] empty = {};
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return empty;
}
}
};
private final Map<Router, ConnectionImpl> activeConnections;
X509V3CertificateGenerator b;
private final SSLContext sslContext;
private final Logger logger;
private SSLSocketFactory socketFactory;
public ConnectionManagerImpl(Logger logger) {
try {
sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(null, NULL_TRUST, null);
} catch (NoSuchAlgorithmException e) {
throw new TorException(e);
} catch (KeyManagementException e) {
throw new TorException(e);
}
socketFactory = sslContext.getSocketFactory();
activeConnections = new HashMap<Router, ConnectionImpl>();
this.logger = logger;
}
public ConnectionImpl createConnection(Router router) {
final SSLSocket socket = createSocket();
socket.setEnabledCipherSuites(MANDATORY_CIPHERS);
socket.setUseClientMode(true);
return new ConnectionImpl(this, logger, socket, router);
}
SSLSocket createSocket() {
try {
return (SSLSocket) socketFactory.createSocket();
} catch (IOException e) {
throw new TorException(e);
}
}
void addActiveConnection(ConnectionImpl connection) {
synchronized(activeConnections) {
activeConnections.put(connection.getRouter(), connection);
}
}
void removeActiveConnection(ConnectionImpl connection) {
synchronized(activeConnections) {
activeConnections.remove(connection);
}
}
public ConnectionImpl findActiveLinkForRouter(Router router) {
synchronized(activeConnections) {
return activeConnections.get(router);
}
}
}
| src/org/torproject/jtor/circuits/impl/ConnectionManagerImpl.java | package org.torproject.jtor.circuits.impl;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.x509.X509V3CertificateGenerator;
import org.torproject.jtor.TorException;
import org.torproject.jtor.directory.Router;
public class ConnectionManagerImpl {
private static final String[] MANDATORY_CIPHERS = {
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
"SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
"SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"};
private static final TrustManager[] NULL_TRUST = {
new X509TrustManager() {
private final X509Certificate[] empty = {};
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return empty;
}
}
};
private final Map<Router, ConnectionImpl> activeConnections;
X509V3CertificateGenerator b;
private final SSLContext sslContext;
private SSLSocketFactory socketFactory;
public ConnectionManagerImpl() {
try {
sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(null, NULL_TRUST, null);
} catch (NoSuchAlgorithmException e) {
throw new TorException(e);
} catch (KeyManagementException e) {
throw new TorException(e);
}
socketFactory = sslContext.getSocketFactory();
activeConnections = new HashMap<Router, ConnectionImpl>();
}
public ConnectionImpl createConnection(Router router) {
final SSLSocket socket = createSocket();
socket.setEnabledCipherSuites(MANDATORY_CIPHERS);
socket.setUseClientMode(true);
return new ConnectionImpl(this, socket, router);
}
SSLSocket createSocket() {
try {
return (SSLSocket) socketFactory.createSocket();
} catch (IOException e) {
throw new TorException(e);
}
}
void addActiveConnection(ConnectionImpl connection) {
synchronized(activeConnections) {
activeConnections.put(connection.getRouter(), connection);
}
}
void removeActiveConnection(ConnectionImpl connection) {
synchronized(activeConnections) {
activeConnections.remove(connection);
}
}
public ConnectionImpl findActiveLinkForRouter(Router router) {
synchronized(activeConnections) {
return activeConnections.get(router);
}
}
}
| Pass Logger to connections | src/org/torproject/jtor/circuits/impl/ConnectionManagerImpl.java | Pass Logger to connections | <ide><path>rc/org/torproject/jtor/circuits/impl/ConnectionManagerImpl.java
<ide> import javax.net.ssl.X509TrustManager;
<ide>
<ide> import org.bouncycastle.x509.X509V3CertificateGenerator;
<add>import org.torproject.jtor.Logger;
<ide> import org.torproject.jtor.TorException;
<ide> import org.torproject.jtor.directory.Router;
<ide>
<ide> new X509TrustManager() {
<ide> private final X509Certificate[] empty = {};
<ide> public void checkClientTrusted(X509Certificate[] chain, String authType)
<del> throws CertificateException {
<add> throws CertificateException {
<ide> }
<ide>
<ide> public void checkServerTrusted(X509Certificate[] chain, String authType)
<ide> }
<ide> }
<ide> };
<del>
<add>
<ide> private final Map<Router, ConnectionImpl> activeConnections;
<ide> X509V3CertificateGenerator b;
<ide>
<ide> private final SSLContext sslContext;
<add> private final Logger logger;
<ide> private SSLSocketFactory socketFactory;
<del>
<del> public ConnectionManagerImpl() {
<add>
<add> public ConnectionManagerImpl(Logger logger) {
<ide> try {
<ide> sslContext = SSLContext.getInstance("SSLv3");
<ide> sslContext.init(null, NULL_TRUST, null);
<ide> }
<ide> socketFactory = sslContext.getSocketFactory();
<ide> activeConnections = new HashMap<Router, ConnectionImpl>();
<add> this.logger = logger;
<ide> }
<del>
<add>
<ide> public ConnectionImpl createConnection(Router router) {
<ide> final SSLSocket socket = createSocket();
<ide> socket.setEnabledCipherSuites(MANDATORY_CIPHERS);
<ide> socket.setUseClientMode(true);
<del> return new ConnectionImpl(this, socket, router);
<add> return new ConnectionImpl(this, logger, socket, router);
<ide> }
<del>
<add>
<ide> SSLSocket createSocket() {
<ide> try {
<ide> return (SSLSocket) socketFactory.createSocket();
<ide> throw new TorException(e);
<ide> }
<ide> }
<del>
<add>
<ide> void addActiveConnection(ConnectionImpl connection) {
<ide> synchronized(activeConnections) {
<ide> activeConnections.put(connection.getRouter(), connection);
<ide> }
<ide> }
<del>
<add>
<ide> void removeActiveConnection(ConnectionImpl connection) {
<ide> synchronized(activeConnections) {
<ide> activeConnections.remove(connection);
<ide> }
<ide> }
<del>
<add>
<ide> public ConnectionImpl findActiveLinkForRouter(Router router) {
<ide> synchronized(activeConnections) {
<ide> return activeConnections.get(router);
<ide> }
<del>
<ide> }
<ide>
<ide> } |
|
Java | lgpl-2.1 | d3f36d856186f51602ee4a056bbbf78484def6b3 | 0 | svartika/ccnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,cawka/ndnx,ebollens/ccnmp,svartika/ccnx,cawka/ndnx,svartika/ccnx,svartika/ccnx,ebollens/ccnmp,svartika/ccnx,svartika/ccnx,cawka/ndnx,cawka/ndnx,ebollens/ccnmp | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* 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 USA.
*/
package org.ccnx.ccn.profiles.security.access.group;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.support.ByteArrayCompare;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.io.content.ContentGoneException;
import org.ccnx.ccn.io.content.ContentNotReadyException;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.io.content.LinkAuthenticator;
import org.ccnx.ccn.io.content.PublicKeyObject;
import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject;
import org.ccnx.ccn.profiles.VersionMissingException;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.namespace.NamespaceProfile;
import org.ccnx.ccn.profiles.namespace.ParameterizedName;
import org.ccnx.ccn.profiles.search.LatestVersionPathfinder;
import org.ccnx.ccn.profiles.search.Pathfinder;
import org.ccnx.ccn.profiles.search.Pathfinder.SearchResults;
import org.ccnx.ccn.profiles.security.access.AccessControlManager;
import org.ccnx.ccn.profiles.security.access.AccessControlPolicyMarker;
import org.ccnx.ccn.profiles.security.access.AccessControlProfile;
import org.ccnx.ccn.profiles.security.access.AccessDeniedException;
import org.ccnx.ccn.profiles.security.access.AccessControlPolicyMarker.AccessControlPolicyMarkerObject;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLObject;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLOperation;
import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlProfile.PrincipalInfo;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* This class is used in updating node keys and by #getEffectiveNodeKey(ContentName).
* To achieve this, we walk up the tree for this node. At each point, we check to
* see if a node key exists. If one exists, we decrypt it if we know an appropriate
* key. Otherwise we return null.
*
* We are going for a low-enumeration approach. We could enumerate node keys and
* see if we have rights on the latest version; but then we need to enumerate keys
* and figure out whether we have a copy of a key or one of its previous keys.
* If we don't know our group memberships, even if we enumerate the node key
* access, we don't know what groups we're a member of.
*
* Node keys and ACLs evolve in the following fashion:
* - if ACL adds rights, by adding a group, we merely add encrypted node key blocks for
* the same node key version (ACL version increases, node key version does not)
* - if an ACL removes rights, by removing a group, we version the ACL and the node key
* (both versions increase)
* - if a group adds rights by adding a member, we merely add key blocks to the group key
* (no change to node key or ACL)
* - if a group removes rights by removing a member, we need to evolve all the node keys
* that point to that node key, at the time of next write using that node key (so we don't
* have to enumerate them). (node key version increases, but ACL version does not).
*
* One could have the node key (NK) point to its ACL version, or vice versa, but they really
* do most efficiently evolve in parallel. One could have the ACL point to group versions,
* and update the ACL and NK together in the last case as well.
* In this last case, we want to update the NK only on next write; if we never write again,
* we never need to generate a new NK (unless we can delete). And we want to wait as long
* as possible, to skip NK updates with no corresponding writes.
* But, a writer needs to determine first what the most recent node key is for a given
* node, and then must determine whether or not that node key must be updated -- whether or
* not the most recent versions of groups are what that node key is encrypted under.
* Ideally we don't want to have it update the ACL, as that allows management access separation --
* we can let writers write the node key without allowing them to write the ACL.
*
* So, we can't store the group version information in the ACL. We don't necessarily
* want a writer to have to pull all the node key blocks to see what version of each
* group the node key is encrypted under.
*
* We could name the node key blocks <prefix>/<access marker>/NK/\#version/<group name>:<group key id>,
* if we could match on partial components, but we can't.
*
* We can name the node key blocks <prefix>/<access marker>/NK/\#version/<group key id> with
* a link pointing to that from NK/\#version/<group name>.
*
* For both read and write, we don't actually care what the ACL says. We only care what
* the node key is. Most efficient option, if we have a full key cache, is to list the
* node key blocks by key id used to encrypt them, and then pull one for a key in our cache.
* On the read side, we're looking at a specific version NK, and we might have rights by going
* through its later siblings. On the write side, we're looking at the latest version NK, and
* we should have rights to one of the key blocks, or we don't have rights.
* If we don't have a full key cache, we have to walk the access hierarchy. In that case,
* the most efficient thing to do is to pull the latest version of the ACL for that node
* (if we have a NK, we have an ACL, and vice versa, so we can enumerate NK and then pull
* ACLs). We then walk that ACL. If we know we are in one of the groups in that ACL, walk
* back to find the group key encrypting that node key. If we don't, walk the groups in that
* ACL to find out if we're in any of them. If we are, pull the current group key, see if
* it works, and start working backwards through group keys, populating the cache in the process,
* to find the relevant group key.
*
* Right answer might be intentional containment. Besides the overall group key structures,
* we make a master list that points to the current versions of all the groups. That would
* have to be writable by anyone who is on the manage list for any group. That would let you
* get, easily, a single list indicating what groups are available and what their versions are.
* Unless NE lets you do that in a single pass, which would be better. (Enumerate name/latestversion,
* not just given name, enumerate versions.)
*
*
* Operational Process:
*
* read:
* - look at content, find data key
* - data key refers to specific node key and version used to encrypt it
* - attempt to retrieve that node key from cache, if get it, done
* - go to specific node key key directory, attempt to find a block we can decrypt using keys in cache;
* if so, done
* - (maybe) for groups that node key is encrypted under which we believe we are a member of,
* attempt to retrieve the group key version we need to decrypt the node key
* - if that node key has been superseded, find the latest version of the node key (if we're not
* allowed access to that, we're not allowed access to the data) and walk first the cache,
* then the groups we believe we're a member of, then the groups we don't know about,
* trying to find a key to read it (== retrieve latest version of node key process)
* - if still can't read node key, attempt to find a new ACL interposed between the data node
* and the old node key node, and see if we have access to its latest node key (== retrieve
* latest version of node key process), and then crawl through previous key blocks till we
* get the one we want
*
* write:
* - find closest node key (non-gone)
* - decrypt its latest version, if can't, have no read access, which means have no write access
* - determine whether it's "dirty" -- needs to be superseded. ACL-changes update node key versions,
* what we need to do is determine whether any groups have updated their keys
* - if so, replace it
* - use it to protect data key
// We don't have a key cached. Either we don't have access, we aren't in one of the
// relevant groups, or we are, but we haven't pulled the appropriate version of the group
// key (because it's old, or because we don't know we're in that group).
// We can get this node key because either we're in one of the groups it was made
// available to, or because it's old, and we have access to one of the groups that
// has current access.
// Want to get the latest version of this node key, then do the walk to figure
// out how to read it. Need to split this code up:
// Given specific version (potentially old):
// - enumerate key blocks and group names
// - if we have one cached, use key
// - for groups we believe we're a member of, pull the link and see what key it points to
// - if it's older than the group key we know, walk back from the group key we know, caching
// all the way (this will err on the side of reading; starting from the current group will
// err on the side of making access control coverage look more extensive)
// - if we know nothing else, pull the latest version and walk that if it's newer than this one
// - if that results in a key, chain backwards to this key
// Given latest version:
// - enumerate key blocks, and group names
// - if we have one cached, just use it
// - walk the groups, starting with the groups we believe we're a member of
// - for groups we believe we're in, check if we're still in, then check for a given key
// - walk the groups we don't know if we're in, see if we're in, and can pull the necessary key
// - given that, unwrap the key and return it
// basic flow -- flag that says whether we believe we have the latest or not, if set, walk
// groups we don't know about, if not set, pull latest and if we get something later, make
// recursive call saying we believe it's the latest (2-depth recursion max)
// As we look at more stuff, we cache more keys, and fall more and more into the cache-only
// path.
*
*/
public class GroupAccessControlManager extends AccessControlManager {
/**
* Marker in a Root object that this is the profile we want.
*/
public static final String PROFILE_NAME_STRING = "/ccnx.org/ccn/profiles/security/access/group/GroupAccessControlProfile";
/**
* This algorithm must be capable of key wrap (RSA, ElGamal, etc).
*/
public static final String DEFAULT_GROUP_KEY_ALGORITHM = "RSA";
public static final int DEFAULT_GROUP_KEY_LENGTH = 1024;
public static final String NODE_KEY_LABEL = "Node Key";
private ArrayList<ParameterizedName> _userStorage = new ArrayList<ParameterizedName>();
private ArrayList<GroupManager> _groupManager = new ArrayList<GroupManager>();
static Comparator<byte[]> byteArrayComparator = new ByteArrayCompare();
private TreeMap<byte[], GroupManager> hashToGroupManagerMap = new TreeMap<byte[], GroupManager>(byteArrayComparator);
private HashMap<ContentName, GroupManager> prefixToGroupManagerMap = new HashMap<ContentName, GroupManager>();
private HashSet<ContentName> _myIdentities = new HashSet<ContentName>();
public GroupAccessControlManager() {
// must call initialize
}
public GroupAccessControlManager(ContentName namespace) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, null);
}
public GroupAccessControlManager(ContentName namespace, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, GroupAccessControlProfile.groupNamespaceName(namespace),
GroupAccessControlProfile.userNamespaceName(namespace), handle);
}
public GroupAccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, groupStorage, userStorage, null);
}
public GroupAccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, new ContentName[]{groupStorage}, new ContentName[]{userStorage}, handle);
}
public GroupAccessControlManager(ContentName namespace, ContentName[] groupStorage, ContentName[] userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
initialize(namespace, groupStorage, userStorage, handle);
}
private void initialize(ContentName namespace, ContentName[] groupStorage, ContentName[] userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
ArrayList<ParameterizedName> parameterizedNames = new ArrayList<ParameterizedName>();
for (ContentName uStorage: userStorage) {
if (null == uStorage)
continue;
ParameterizedName pName = new ParameterizedName("User", uStorage, null);
parameterizedNames.add(pName);
}
for (ContentName gStorage: groupStorage) {
if (null == gStorage)
continue;
ParameterizedName pName = new ParameterizedName("Group", gStorage, null);
parameterizedNames.add(pName);
}
if (null == handle) handle = CCNHandle.open();
AccessControlPolicyMarker r = new AccessControlPolicyMarker(ContentName.fromNative(GroupAccessControlManager.PROFILE_NAME_STRING), parameterizedNames, null);
ContentName policyPrefix = NamespaceProfile.policyNamespace(namespace);
ContentName policyMarkerName = AccessControlProfile.getAccessControlPolicyName(policyPrefix);
AccessControlPolicyMarkerObject policyInformation = new AccessControlPolicyMarkerObject(policyMarkerName, r, SaveType.REPOSITORY, handle);
initialize(policyInformation, handle);
}
@Override
public boolean initialize(AccessControlPolicyMarkerObject policyInformation, CCNHandle handle) throws ConfigurationException, IOException {
if (null == handle) {
_handle = CCNHandle.open();
} else {
_handle = handle;
}
// set up information based on contents of policy
// also need a static method/command line program to create a Root with the right types of information
// for this access control manager type
int componentCount = policyInformation.getBaseName().count();
componentCount -= NamespaceProfile.policyPostfix().count();
componentCount -= AccessControlProfile.AccessControlPolicyContentName().count();
_namespace = policyInformation.getBaseName().cut(componentCount);
ArrayList<ParameterizedName> parameterizedNames = policyInformation.policy().parameterizedNames();
for (ParameterizedName pName: parameterizedNames) {
String label = pName.label();
if (label.equals("Group")) {
GroupManager gm = new GroupManager(this, pName, _handle);
_groupManager.add(gm);
byte[] distinguishingHash = GroupAccessControlProfile.PrincipalInfo.contentPrefixToDistinguishingHash(pName.prefix());
hashToGroupManagerMap.put(distinguishingHash, gm);
prefixToGroupManagerMap.put(pName.prefix(), gm);
}
else if (label.equals("User")) _userStorage.add(pName);
}
return true;
}
public GroupManager groupManager() throws Exception {
if (_groupManager.size() > 1) throw new Exception("A group manager can only be retrieved by name when there are more than one.");
return _groupManager.get(0);
}
public void registerGroupStorage(ContentName groupStorage) throws IOException {
ParameterizedName pName = new ParameterizedName("Group", groupStorage, null);
GroupManager gm = new GroupManager(this, pName, _handle);
_groupManager.add(gm);
byte[] distinguishingHash = GroupAccessControlProfile.PrincipalInfo.contentPrefixToDistinguishingHash(pName.prefix());
hashToGroupManagerMap.put(distinguishingHash, gm);
prefixToGroupManagerMap.put(pName.prefix(), gm);
}
public void registerUserStorage(ContentName userStorage) {
ParameterizedName pName = new ParameterizedName("User", userStorage, null);
_userStorage.add(pName);
}
public GroupManager groupManager(byte[] distinguishingHash) {
GroupManager gm = hashToGroupManagerMap.get(distinguishingHash);
if (gm == null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Failed to retrieve a group manager with distinguishing hash " + DataUtils.printHexBytes(distinguishingHash));
}
}
return gm;
}
public GroupManager groupManager(ContentName prefixName) {
GroupManager gm = prefixToGroupManagerMap.get(prefixName);
if (gm == null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "GroupAccessControlManager: failed to retrieve a group manager with prefix " + prefixName);
}
}
return gm;
}
public boolean isGroupName(ContentName principalPublicKeyName) {
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principalPublicKeyName)) return true;
}
return false;
}
public Tuple<ContentName, String> parsePrefixAndFriendlyNameFromPublicKeyName(ContentName principalPublicKeyName) {
// for each group manager/user namespace, there is a prefix, then a "friendly" name component,
// then optionally a postfix that gets tacked on to go from the prefix to the public key
// e.g. Alice's key in the user namespace might be:
// /parc.com/Users/Alice/Keys/EncryptionKey
// where the distinguising prefix would be computed from /parc.com/Users, Alice is the friendly
// name, and the rest is stored in the group manager for /parc.com/Users, generated out of the
// relevant entry in the Roots spec, and just used in a function to go from (distinguishing hash, friendly name)
// to key name
// loop through the group managers, see if the prefix matches, if so, pull that prefix, and take
// the component after that prefix as the friendly name
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principalPublicKeyName)) {
ContentName prefix = gm.getGroupStorage().prefix();
String friendlyName = principalPublicKeyName.postfix(prefix).stringComponent(0);
return new Tuple<ContentName, String>(prefix, friendlyName);
}
}
// NOTE: as there are multiple user prefixes, each with a distinguishing hash and an optional
// suffix, you have to have a list of those and iterate over them as well.
for (ParameterizedName userStorage: _userStorage) {
if (userStorage.prefix().isPrefixOf(principalPublicKeyName)) {
String friendlyName = principalPublicKeyName.postfix(userStorage.prefix()).stringComponent(0);
return new Tuple<ContentName, String>(userStorage.prefix(), friendlyName);
}
}
return null;
}
// TODO
public ContentName getPrincipalPublicKeyName(byte [] distinguishingHash, String friendlyName) {
// look up the distinguishing hash in the user and group maps
// pull the name prefix and postfix from the tables
// make the key name as <prefix>/friendlyName/<postfix>
return null;
}
/**
* Publish my identity (i.e. my public key) under a specified CCN name
* @param identity the name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws IOException
* @throws ConfigurationException
*/
public void publishMyIdentity(ContentName identity, PublicKey myPublicKey)
throws InvalidKeyException, ContentEncodingException, IOException, ConfigurationException {
KeyManager km = _handle.keyManager();
if (null == myPublicKey) {
myPublicKey = km.getDefaultPublicKey();
}
PublicKeyObject pko = new PublicKeyObject(identity, myPublicKey, SaveType.REPOSITORY, handle());
pko.save();
_myIdentities.add(identity);
}
/**
* Add an identity to my set. Assume the key is already published.
*/
public void addMyIdentity(ContentName identity) {
_myIdentities.add(identity);
}
/**
* Publish the specified identity (i.e. the public key) of a specified user
* @param userName the name of the user
* @param userPublicKey the public key of the user
* @throws ConfigurationException
* @throws IOException
* @throws MalformedContentNameStringException
*/
public void publishUserIdentity(String userName, PublicKey userPublicKey)
throws ConfigurationException, IOException, MalformedContentNameStringException {
PublicKeyObject pko = new PublicKeyObject(ContentName.fromNative(userName), userPublicKey, SaveType.REPOSITORY, handle());
System.out.println("saving user pubkey to repo:" + userName);
pko.save();
}
public boolean haveIdentity(ContentName userName) {
return _myIdentities.contains(userName);
}
public String nodeKeyLabel() {
return NODE_KEY_LABEL;
}
/**
* Get the latest key for a specified principal
* TODO shortcut slightly -- the principal we have cached might not meet the
* constraints of the link.
* @param principal the principal
* @return the public key object
* @throws IOException
* @throws ContentDecodingException
*/
public PublicKeyObject getLatestKeyForPrincipal(Link principal) throws ContentDecodingException, IOException {
if (null == principal) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Cannot retrieve key for empty principal.");
}
return null;
}
PublicKeyObject pko = null;
boolean isGroup = false;
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principal)) {
pko = gm.getLatestPublicKeyForGroup(principal);
isGroup = true;
break;
}
}
if (!isGroup) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Retrieving latest key for user: " + principal.targetName());
}
LinkAuthenticator targetAuth = principal.targetAuthenticator();
if (null != targetAuth) {
pko = new PublicKeyObject(principal.targetName(), targetAuth.publisher(), handle());
}
else pko = new PublicKeyObject(principal.targetName(), handle());
}
return pko;
}
/**
* Creates the root ACL for _namespace.
* This initialization must be done before any other ACL or node key can be read or written.
* @param rootACL the root ACL
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
public void initializeNamespace(ACL rootACL)
throws InvalidKeyException, ContentEncodingException, ContentNotReadyException,
ContentGoneException, IOException {
// generates the new node key
generateNewNodeKey(_namespace, null, rootACL);
// write the root ACL
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(_namespace), rootACL, handle());
aclo.save();
}
/**
* Retrieves the latest version of an ACL effective at this node, either stored
* here or at one of its ancestors.
* @param nodeName the name of the node
* @return the ACL object
* @throws IOException
* @throws ContentDecodingException
*/
public ACLObject getEffectiveACLObject(ContentName nodeName) throws ContentDecodingException, IOException {
// Find the closest node that has a non-gone ACL
ACLObject aclo = findAncestorWithACL(nodeName, null);
if (null != aclo) {
// parallel find doesn't get us the latest version. Serial does,
// but it's kind of an artifact.
aclo.update();
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found between node {0} and namespace root {1}. Returning root ACL.",
nodeName, getNamespaceRoot());
}
return getACLObjectForNode(getNamespaceRoot());
}
return aclo;
}
private ACLObject findAncestorWithACL(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// selector method, remove when pick faster one.
return findAncestorWithACLInParallel(dataNodeName, stopPoint);
}
/**
* Look for an ACL that is on dataNodeName or above, but below stopPoint. If stopPoint is
* null, then take it to be the root for this AccessControlManager (which we assume to have
* an ACL). This is the old serial search, which has been replaced tyb the parallel search
* below. Keep it here temporarily.
* @param dataNodeName
* @param stopPoint
* @return
* @throws ContentDecodingException
* @throws IOException
*/
@SuppressWarnings("unused")
private ACLObject findAncestorWithACLSerial(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// If dataNodeName is the root of this AccessControlManager, there can be no ACL between
// dataNodeName (inclusive) and the root (exclusive), so return null.
if (getNamespaceRoot().equals(dataNodeName)) return null;
if (null == stopPoint) {
stopPoint = getNamespaceRoot();
} else if (!getNamespaceRoot().isPrefixOf(stopPoint)) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: Stopping point {0} must be an ancestor of the starting point {1}!",
stopPoint, dataNodeName);
}
throw new IOException("findAncestorWithACL: invalid search space: stopping point " + stopPoint + " must be an ancestor of the starting point " +
dataNodeName + "!");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: start point {0}, stop before {1}", dataNodeName, stopPoint);
}
int stopCount = stopPoint.count();
ACLObject ancestorACLObject = null;
ContentName parentName = dataNodeName;
ContentName nextParentName = null;
while (null == ancestorACLObject) {
ancestorACLObject = getACLObjectForNodeIfExists(parentName);
if (null != ancestorACLObject) {
if (ancestorACLObject.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found an ACL object at {0} but its GONE.", ancestorACLObject.getVersionedName());
}
ancestorACLObject = null;
} else {
// got one
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found an ACL object at {0}", ancestorACLObject.getVersionedName());
}
break;
}
}
nextParentName = parentName.parent();
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: no ACL object at node {0}, looking next at {1}", parentName, nextParentName);
}
// stop looking once we're above our namespace, or if we've already checked the top level
if (parentName.count() == stopCount) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: giving up, next search point would be {0}, stop point is {1}, no ACL found",
parentName, stopPoint);
}
break;
}
parentName = nextParentName;
}
if (null == ancestorACLObject) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL,
"No ACL available in ancestor tree between {0} and {1} (not-inclusive) out of namespace rooted at {2}.",
dataNodeName, stopPoint, getNamespaceRoot());
}
return null;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found ACL for {0} at ancestor {1}: ", dataNodeName, ancestorACLObject.getVersionedName());
}
return ancestorACLObject;
}
/**
* Implement a parallel findAncestorWithACL; drop it in separately so we can
* switch back and forth in testing.
*/
private ACLObject findAncestorWithACLInParallel(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// If dataNodeName is the root of this AccessControlManager, there can be no ACL between
// dataNodeName (inclusive) and the root (exclusive), so return null.
if (getNamespaceRoot().equals(dataNodeName)) return null;
if (null == stopPoint) {
stopPoint = getNamespaceRoot();
} else if (!getNamespaceRoot().isPrefixOf(stopPoint)) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: Stopping point {0} must be an ancestor of the starting point {1}!",
stopPoint, dataNodeName);
}
throw new IOException("findAncestorWithACLInParallel: invalid search space: stopping point " + stopPoint + " must be an ancestor of the starting point " +
dataNodeName + "!");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: start point {0}, stop before {1}", dataNodeName, stopPoint);
}
int stopCount = stopPoint.count();
// Pathfinder searches from start point to stop point inclusive, want exclusive, so hand
// it one level down from stop point.
Pathfinder pathfinder = new LatestVersionPathfinder(dataNodeName, dataNodeName.cut(stopCount+1),
GroupAccessControlProfile.aclPostfix(), true, false, SystemConfiguration.EXTRA_LONG_TIMEOUT,
null, handle());
SearchResults searchResults = pathfinder.waitForResults();
if (null != searchResults.getResult()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: found {0}", searchResults.getResult().name());
}
ACLObject aclo = new ACLObject(searchResults.getResult(), handle());
return aclo;
}
return null;
}
/**
* Try to pull an ACL for a particular node. If it doesn't exist, will time
* out. Use enumeration to decide whether to call this to avoid the timeout.
* @param aclNodeName the node name
* @return the ACL object
* @throws ContentDecodingException
* @throws IOException
*/
public ACLObject getACLObjectForNode(ContentName aclNodeName)
throws ContentDecodingException, IOException {
// Get the latest version of the acl. We don't care so much about knowing what version it was.
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(aclNodeName), handle());
aclo.update();
// if there is no update, this will probably throw an exception -- IO or XMLStream
if (aclo.isGone()) {
// treat as if no acl on node
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getACLObjectForNode: Asked to get an ACL object for specific node {0}, but ACL there is GONE! Returning null.",
aclNodeName);
}
return null;
}
return aclo;
}
/**
* Try to pull an ACL for a specified node if it exists.
* @param aclNodeName the name of the node
* @return the ACL object
* @throws IOException
* @throws ContentDecodingException
*/
public ACLObject getACLObjectForNodeIfExists(ContentName aclNodeName) throws ContentDecodingException, IOException {
// TODO really want to check simple existence here, but need to integrate with verifier
// use. GLV too slow for negative results. Given that we need latest version, at least
// use the segment we get, and don't pull it twice.
ContentName aclName = new ContentName(GroupAccessControlProfile.aclName(aclNodeName));
ContentObject aclNameList = VersioningProfile.getLatestVersion(aclName,
null, SystemConfiguration.MAX_TIMEOUT, handle().defaultVerifier(), handle());
if (null != aclNameList) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found latest version of acl for {0} at {1} type: {2}",
aclNodeName, aclName, aclNameList.signedInfo().getTypeName());
}
ACLObject aclo = new ACLObject(aclNameList, handle());
if (aclo.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "ACL object is GONE, returning anyway {0}", aclo.getVersionedName());
}
}
return aclo;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found on node: " + aclNodeName);
}
return null;
}
/**
* Get the effective ACL for a node specified by its name
* @param nodeName the name of the node
* @return the effective ACL
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentDecodingException
* @throws IOException
*/
public ACL getEffectiveACL(ContentName nodeName)
throws ContentNotReadyException, ContentGoneException, ContentDecodingException, IOException {
ACLObject aclo = getEffectiveACLObject(nodeName);
if (null != aclo) {
return aclo.acl();
}
return null;
}
/**
* Adds an ACL to a node that doesn't have one, or replaces one that exists.
* Just writes, doesn't bother to look at any current ACL. Does need to pull
* the effective node key at this node, though, to wrap the old ENK in a new
* node key.
*
* @param nodeName the name of the node
* @param newACL the new ACL
* @return
* @throws InvalidKeyException
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws NoSuchAlgorithmException
*/
public ACL setACL(ContentName nodeName, ACL newACL)
throws AccessDeniedException, InvalidKeyException, ContentNotReadyException, ContentGoneException, IOException, NoSuchAlgorithmException {
// Throws access denied exception if we can't read the old node key.
NodeKey effectiveNodeKey = getEffectiveNodeKey(nodeName);
// generates the new node key, wraps it under the new acl, and wraps the old node key
generateNewNodeKey(nodeName, effectiveNodeKey, newACL);
// write the acl
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(nodeName), newACL, handle());
aclo.save();
return aclo.acl();
}
/**
* Delete the ACL at this node if one exists, returning control to the
* next ACL upstream.
* We simply add a supserseded by block at this node, wrapping this key in the key of the upstream
* node. If we don't have read access at that node, throw AccessDeniedException.
* Then we write a GONE block here for the ACL, and a new node key version with a superseded by block.
* The superseded by block should probably be encrypted not with the ACL in force, but with the effective
* node key of the parent -- that will be derivable from the appropriate ACL, and will have the right semantics
* if a new ACL is interposed later. In the meantime, all the people with the newly in-force ancestor
* ACL should be able to read this content.
* @param nodeName
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public void deleteACL(ContentName nodeName)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
// First, find ACL at this node if one exists.
ACLObject thisNodeACL = getACLObjectForNodeIfExists(nodeName);
if (null == thisNodeACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Asked to delete ACL for node {0} that doesn't have one. Doing nothing.", nodeName);
}
return;
} else if (thisNodeACL.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Asked to delete ACL for node {0} that has already been deleted. Doing nothing.", nodeName);
}
return;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Deleting ACL for node {0} latest version: {1}", nodeName, thisNodeACL.getVersionedName());
}
// We know we have an ACL at this node. So we know we have a node key at this
// node. Get the latest version of this node key.
NodeKey nk = getLatestNodeKeyForNode(nodeName);
// Next, find the node key that would be in force here after this deletion.
// Do that by getting the effective node key at the parent
ContentName parentName = nodeName.parent();
NodeKey effectiveParentNodeKey = getEffectiveNodeKey(parentName);
// And then deriving what the effective node key would be here, if
// we inherited from the parent
NodeKey ourEffectiveNodeKeyFromParent =
effectiveParentNodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
// Generate a superseded block for this node, wrapping its key in the parent.
// TODO want to wrap key in parent's effective key, but can't point to that -- no way to name an
// effective node key... need one.
// need to mangl stored key name into superseded block name, need to wrap
// in ourEffNodeKeyFromParent, make sure stored key id points up to our ENKFP.storedKeyName()
KeyDirectory.addSupersededByBlock(nk.storedNodeKeyName(), nk.nodeKey(),
ourEffectiveNodeKeyFromParent.storedNodeKeyName(),
ourEffectiveNodeKeyFromParent.storedNodeKeyID(),
effectiveParentNodeKey.nodeKey(), handle());
// Then mark the ACL as gone.
thisNodeACL.saveAsGone();
}
/**
* Pulls the ACL for this node, if one exists, and modifies it to include
* the following changes, then stores the result using setACL, updating
* the node key if necessary in the process.
*
* @param nodeName the name of the node
* @param ACLUpdates the updates to the ACL
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL updateACL(ContentName nodeName, ArrayList<ACL.ACLOperation> ACLUpdates)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
ACLObject currentACL = getACLObjectForNodeIfExists(nodeName);
ACL newACL = null;
if (null != currentACL) {
newACL = currentACL.acl();
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Adding brand new ACL to node {0}", nodeName);
}
//TODO: if no operations is specified, then a new empty ACL is created...
newACL = new ACL();
}
LinkedList<Link> newReaders = newACL.update(ACLUpdates);
if ((null == newReaders) || (null == currentACL)) {
// null newReaders means we revoked someone.
// null currentACL means we're starting from scratch
// Set the ACL and update the node key.
return setACL(nodeName, newACL);
}
// If we get back a list of new readers, it means all we have to do
// is add key blocks for them, not update the node key. (And it means
// we have a node key for this node.)
// Wait to save the new ACL till we are sure we're allowed to do this.
KeyDirectory keyDirectory = null;
try {
// If we can't read the node key, we can't update. Get the effective node key.
// Better be a node key here... and we'd better be allowed to read it.
NodeKey latestNodeKey = getLatestNodeKeyForNode(nodeName);
if (null == latestNodeKey) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Cannot read the latest node key for {0}", nodeName);
}
throw new AccessDeniedException("Cannot read the latest node key for " + nodeName);
}
keyDirectory = new KeyDirectory(this, latestNodeKey.storedNodeKeyName(), handle());
for (Link principal : newReaders) {
PublicKeyObject latestKey = getLatestKeyForPrincipal(principal);
if (!latestKey.available()) {
latestKey.waitForData(SystemConfiguration.getDefaultTimeout());
}
if (latestKey.available()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "updateACL: Adding wrapped key block for reader: " + latestKey.getVersionedName());
}
try {
keyDirectory.addWrappedKeyBlock(latestNodeKey.nodeKey(), latestKey.getVersionedName(), latestKey.publicKey());
} catch (VersionMissingException e) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "UNEXPECTED: latest key for principal: " + latestKey.getVersionedName() + " has no version? Skipping.");
}
}
} else {
// Do we use an old key or give up?
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "updateACL: No key for {0} found. Skipping.", principal);
}
}
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
// If we got here, we got the node key we were updating, so we are allowed
// to at least read this stuff (though maybe not write it). Save the acl.
currentACL.save(newACL);
return newACL;
}
/**
* Add readers to a specified node
* @param nodeName the name of the node
* @param newReaders the list of new readers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addReaders(ContentName nodeName, ArrayList<Link> newReaders)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : newReaders){
ops.add(ACLOperation.addReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Remove readers from a specified node
* @param nodeName the name of the node
* @param removedReaders the list of removed readers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeReaders(ContentName nodeName, ArrayList<Link> removedReaders)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : removedReaders){
ops.add(ACLOperation.removeReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Add writers to a specified node.
* @param nodeName the name of the node
* @param newWriters the list of new writers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addWriters(ContentName nodeName, ArrayList<Link> newWriters)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : newWriters){
ops.add(ACLOperation.addWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Remove writers from a specified node.
* @param nodeName the name of the node
* @param removedWriters the list of removed writers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeWriters(ContentName nodeName, ArrayList<Link> removedWriters)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : removedWriters){
ops.add(ACLOperation.removeWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Add managers to a specified node
* @param nodeName the name of the node
* @param newManagers the list of new managers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addManagers(ContentName nodeName, ArrayList<Link> newManagers)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: newManagers){
ops.add(ACLOperation.addManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Remove managers from a specified node
* @param nodeName the name of the node
* @param removedManagers the list of removed managers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeManagers(ContentName nodeName, ArrayList<Link> removedManagers)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: removedManagers){
ops.add(ACLOperation.removeManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Get the ancestor node key in force at this node (if we can decrypt it),
* including a key at this node itself. We use the fact that ACLs and
* node keys are co-located; if you have one, you have the other.
* @param nodeName the name of the node
* @return null means while node keys exist, we can't decrypt any of them --
* we have no read access to this node (which implies no write access)
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws IOException if something is wrong (e.g. no node keys at all)
* @throws NoSuchAlgorithmException
*/
protected NodeKey findAncestorWithNodeKey(ContentName nodeName)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// climb up looking for node keys, then make sure that one isn't GONE
// if it isn't, call read-side routine to figure out how to decrypt it
ACLObject effectiveACL = findAncestorWithACL(nodeName, null);
if (null != effectiveACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Got ACL named: {0} attempting to retrieve node key from {1}",
effectiveACL.getVersionedName(), AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
}
} else {
// We're not searching at the namespace root; because we assume we have
// already made sure we have an ACL there. So if we get back NULL, we
// go stratight to our namespace root.
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found between node {0} and namespace root {1}, assume ACL is at namespace root.",
nodeName, getNamespaceRoot());
}
}
return getLatestNodeKeyForNode(
(null != effectiveACL) ? AccessControlProfile.accessRoot(effectiveACL.getBaseName()) : getNamespaceRoot());
}
/**
* Write path: get the latest node key for a node.
* @param nodeName the name of the node
* @return the corresponding node key
* @throws IOException
* @throws ContentDecodingException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getLatestNodeKeyForNode(ContentName nodeName)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
ContentName nodeKeyPrefix = GroupAccessControlProfile.nodeKeyName(nodeName);
ContentObject co = VersioningProfile.getLatestVersion(nodeKeyPrefix,
null, SystemConfiguration.MAX_TIMEOUT, handle().defaultVerifier(), handle());
ContentName nodeKeyVersionedName = null;
if (co != null) {
nodeKeyVersionedName = co.name().subname(0, nodeKeyPrefix.count() + 1);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "getLatestNodeKeyForNode: {0} is the latest version found for {1}.", nodeKeyVersionedName, nodeName);
}
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "getLatestNodeKeyForNode: no latest version found for {0}.", nodeName);
}
return null;
}
// DKS TODO this may not handle ACL deletion correctly -- we need to make sure that this
// key wasn't superseded by something that isn't a later version of itself.
// then, pull the node key we can decrypt
return getNodeKeyByVersionedName(nodeKeyVersionedName, null);
}
/**
* Read path:
* Retrieve a specific node key from a given location, as specified by a
* key it was used to wrap, and, if possible, find a key we can use to
* unwrap the node key.
*
* Throw an exception if there is no node key block at the appropriate name.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return the node key
* @throws IOException
* @throws ContentDecodingException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getSpecificNodeKey(ContentName nodeKeyName, byte [] nodeKeyIdentifier)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
if ((null == nodeKeyName) && (null == nodeKeyIdentifier)) {
throw new IllegalArgumentException("Node key name and identifier cannot both be null!");
}
// We should know what node key to use (down to the version), but we have to find the specific
// wrapped key copy we can decrypt.
NodeKey nk = getNodeKeyByVersionedName(nodeKeyName, nodeKeyIdentifier);
if (null == nk) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "No decryptable node key available at {0}, access denied.", nodeKeyName);
}
return null;
}
return nk;
}
/**
* We have the name of a specific version of a node key. Now we just need to figure
* out which of our keys can be used to decrypt it.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return
* @throws IOException
* @throws AccessDeniedException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
NodeKey getNodeKeyByVersionedName(ContentName nodeKeyName, byte [] nodeKeyIdentifier)
throws AccessDeniedException, InvalidKeyException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
NodeKey nk = null;
KeyDirectory keyDirectory = null;
try {
keyDirectory = new KeyDirectory(this, nodeKeyName, handle());
keyDirectory.waitForNoUpdatesOrResult(SystemConfiguration.LONG_TIMEOUT);
// this will handle the caching.
Key unwrappedKey = keyDirectory.getUnwrappedKey(nodeKeyIdentifier);
if (null != unwrappedKey) {
nk = new NodeKey(nodeKeyName, unwrappedKey);
} else {
throw new AccessDeniedException("Access denied: cannot retrieve key " + DataUtils.printBytes(nodeKeyIdentifier) + " at name " + nodeKeyName);
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
return nk;
}
/**
* Write path:
* Get the effective node key in force at this node, used to derive keys to
* encrypt content. Vertical chaining. Works if you ask for node which has
* a node key.
* TODO -- when called by writers, check to see if node key is dirty & update.
* @param nodeName
* @return
* @throws AccessDeniedException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws IOException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getEffectiveNodeKey(ContentName nodeName)
throws AccessDeniedException, InvalidKeyException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// Get the ancestor node key in force at this node.
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found node key at {0}", nodeKey.storedNodeKeyName());
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Computing effective node key for {0} using stored node key {1}", nodeName, effectiveNodeKey.storedNodeKeyName());
}
return effectiveNodeKey;
}
/**
* Like #getEffectiveNodeKey(ContentName), except checks to see if node
* key is dirty and updates it if necessary.
* @param nodeName
* @return
* @throws AccessDeniedException
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws AccessDeniedException, InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getFreshEffectiveNodeKey(ContentName nodeName)
throws AccessDeniedException, InvalidKeyException, ContentDecodingException,
ContentEncodingException, ContentNotReadyException, ContentGoneException, IOException, NoSuchAlgorithmException {
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
// This should be the latest node key; i.e. not superseded.
if (nodeKeyIsDirty(nodeKey.storedNodeKeyName())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: Found node key at {0}, updating.", nodeKey.storedNodeKeyName());
}
ContentName nodeKeyNodeName = GroupAccessControlProfile.accessRoot(nodeKey.storedNodeKeyName());
ACLObject acl = getACLObjectForNode(nodeKeyNodeName);
nodeKey = generateNewNodeKey(nodeKeyNodeName, nodeKey, acl.acl());
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: Found node key at {0}", nodeKey.storedNodeKeyName());
}
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: retrieved stored node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), nodeKey);
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: computed effective node key for node {0} label {1}: {2} using stored node key {3}"
, nodeName, nodeKeyLabel(), effectiveNodeKey, effectiveNodeKey.storedNodeKeyName());
}
return effectiveNodeKey;
}
/**
* Do we need to update this node key?
* First, we look to see whether or not we know the key is dirty -- i.e.
* does it have a superseded block (if it's gone, it will also have a
* superseded block). If not, we have to really check...
* Basically, we look at all the entities this node key is encrypted for,
* and determine whether any of them have a new version of their public
* key. If so, the node key is dirty.
*
* The initial implementation of this will be simple and slow -- iterating through
* groups and assuming the active object system will keep updating itself whenever
* a new key appears. Eventually, we might want an index directory of all the
* versions of keys, so that one name enumeration request might give us information
* about whether keys have been updated. (Or some kind of aggregate versioning,
* that tell us a) whether any groups have changed their versions, or b) just the
* ones we care about have.)
*
* This can be called by anyone -- the data about whether a node key is dirty
* is visible to anyone. Fixing a dirty node key requires access, though.
* @param theNodeKeyName this might be the name of the node where the NK is stored,
* or the NK name itself.
* We assume this exists -- that there at some point has been a node key here.
* TODO ephemeral node key naming
* @return
* @throws IOException
* @throws ContentDecodingException
*/
public boolean nodeKeyIsDirty(ContentName theNodeKeyName) throws ContentDecodingException, IOException {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty called.");
}
// first, is this a node key name?
if (!GroupAccessControlProfile.isNodeKeyName(theNodeKeyName)) {
// assume it's a data node name.
theNodeKeyName = GroupAccessControlProfile.nodeKeyName(theNodeKeyName);
}
// get the requested version of this node key; or if unversioned, get the latest.
KeyDirectory nodeKeyDirectory = null;
try {
nodeKeyDirectory = new KeyDirectory(this, theNodeKeyName, handle());
nodeKeyDirectory.waitForChildren();
if (null == nodeKeyDirectory) {
throw new IOException("Cannot get node key directory for : " + theNodeKeyName);
}
if (nodeKeyDirectory.hasSupersededBlock()) {
return true;
}
for (PrincipalInfo principal : nodeKeyDirectory.getCopyOfPrincipals().values()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: found principal called {0}", principal.friendlyName());
}
if (principal.isGroup()) {
Group theGroup = groupManager(principal.distinguishingHash()).getGroup(principal.friendlyName());
if (theGroup.publicKeyVersion().after(principal.versionTimestamp())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: the key of principal {0} is out of date", principal.friendlyName());
}
return true;
}
else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: the key of principal {0} is up to date", principal.friendlyName());
}
}
} else {
// DKS TODO -- for now, don't handle versioning of non-group keys
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "User key for {0}, not checking version.", principal.friendlyName());
}
// Technically, we're not handling versioning for user keys, but be nice. Start
// by seeing if we have a link to the key in our user space.
// If the principal isn't available in our enumerated list, have to go get its key
// from the wrapped key object.
}
}
return false;
} finally {
if (null != nodeKeyDirectory)
nodeKeyDirectory.stopEnumerating();
}
}
/**
* Would we update this data key if we were doing reencryption?
* This one is simpler -- what node key is the data key encrypted under, and is
* that node key dirty?
*
* This can be called by anyone -- the data about whether a data key is dirty
* is visible to anyone. Fixing a dirty key requires access, though.
*
* @param dataName
* @return
* @throws IOException
* @throws ContentNotReadyException
* @throws ContentDecodingException
*/
public boolean dataKeyIsDirty(ContentName dataName) throws ContentNotReadyException, IOException {
// TODO -- do we need to check whether there *is* a key?
// The trick: we need the header information in the wrapped key; we don't need to unwrap it.
// ephemeral key naming
WrappedKeyObject wrappedDataKey = new WrappedKeyObject(GroupAccessControlProfile.dataKeyName(dataName), handle());
return nodeKeyIsDirty(wrappedDataKey.wrappedKey().wrappingKeyName());
}
/**
* Find the key to use to wrap a data key at this node for encryption. This requires
* the current effective node key, and wrapping this data key in it. If the
* current node key is dirty, this causes a new one to be generated.
* If data at the current node is public, this returns null. Does not check
* to see whether content is excluded from encryption (e.g. by being access
* control data).
* @param dataNodeName the node for which to find a data key wrapping key
* @param publisher in case output key retrieval needs to be specialized by publisher
* @return if null, the data is to be unencrypted.
* @param newRandomDataKey
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
@Override
public NodeKey getDataKeyWrappingKey(ContentName dataNodeName, PublisherPublicKeyDigest publisher)
throws AccessDeniedException, InvalidKeyException,
ContentEncodingException, IOException, NoSuchAlgorithmException {
NodeKey effectiveNodeKey = getFreshEffectiveNodeKey(dataNodeName);
if (null == effectiveNodeKey) {
throw new AccessDeniedException("Cannot retrieve effective node key for node: " + dataNodeName + ".");
}
return effectiveNodeKey;
}
/**
* Retrieve the node key wrapping this data key for decryption.
* @throws IOException
* @throws ContentDecodingException
* @throws ContentEncodingException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
@Override
public Key getDataKeyWrappingKey(ContentName dataNodeName, WrappedKeyObject wrappedDataKeyObject)
throws InvalidKeyException, ContentNotReadyException, ContentGoneException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
NodeKey enk = getNodeKeyForObject(dataNodeName, wrappedDataKeyObject);
if (null != enk) {
return enk.nodeKey();
}
return null;
}
/**
* Get the data key wrapping key if we happened to have cached a copy of the decryption key.
* @param dataNodeName
* @param wrappedDataKeyObject
* @param cachedWrappingKey
* @return
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
@Override
public Key getDataKeyWrappingKey(ContentName dataNodeName, ContentName wrappingKeyName, Key cachedWrappingKey) throws InvalidKeyException, ContentEncodingException {
NodeKey cachedWrappingKeyNK = new NodeKey(wrappingKeyName, cachedWrappingKey);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: retrieved stored node key for node {0} label {1}: {2}", dataNodeName, nodeKeyLabel(), cachedWrappingKeyNK);
}
NodeKey enk = cachedWrappingKeyNK.computeDescendantNodeKey(dataNodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: computed effective node key for node {0} label {1}: {2}", dataNodeName, nodeKeyLabel(), enk);
}
if (null != enk) {
return enk.nodeKey();
}
return null;
}
/**
* We've looked for a node key we can decrypt at the expected node key location,
* but no dice. See if a new ACL has been interposed granting us rights at a lower
* portion of the tree.
* @param dataNodeName
* @param wrappingKeyName
* @param wrappingKeyIdentifier
* @return
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
protected NodeKey getNodeKeyUsingInterposedACL(ContentName dataNodeName,
ContentName wrappingKeyName, byte[] wrappingKeyIdentifier)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
ContentName stopPoint = AccessControlProfile.accessRoot(wrappingKeyName);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: looking for an ACL above {0} but below {1}",
dataNodeName, stopPoint);
}
ACLObject nearestACL = findAncestorWithACL(dataNodeName, stopPoint);
// TODO update to make sure non-gone....
if (null == nearestACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Node key {0} is the nearest ACL to {1}", wrappingKeyName , dataNodeName);
}
return null;
}
NodeKey currentNodeKey = getLatestNodeKeyForNode(GroupAccessControlProfile.accessRoot(nearestACL.getVersionedName()));
// We have retrieved the current node key at the node where the ACL was interposed.
// But the data key is wrapped in the previous node key that was at this node prior to the ACL interposition.
// So we need to retrieve the previous node key, which was wrapped with KeyDirectory.addPreviousKeyBlock
// at the time the ACL was interposed.
ContentName previousKeyName = ContentName.fromNative(currentNodeKey.storedNodeKeyName(), GroupAccessControlProfile.PREVIOUS_KEY_NAME);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: retrieving previous key at {0}", previousKeyName);
}
WrappedKeyObject wrappedPreviousNodeKey = new WrappedKeyObject(previousKeyName, _handle);
wrappedPreviousNodeKey.update();
Key pnk = wrappedPreviousNodeKey.wrappedKey().unwrapKey(currentNodeKey.nodeKey());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: returning previous node key for node {0}", currentNodeKey.storedNodeKeyName());
}
NodeKey previousNodeKey = new NodeKey(currentNodeKey.storedNodeKeyName(), pnk);
return previousNodeKey;
}
/**
* Make a new node key and encrypt it under the given ACL.
* If there is a previous node key (oldEffectiveNodeKey not null), it is wrapped in the new node key.
* Put all the blocks into the aggregating writer, but don't flush.
*
* @param nodeName
* @param oldEffectiveNodeKey
* @param effectiveACL
* @return
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
protected NodeKey generateNewNodeKey(ContentName nodeName, NodeKey oldEffectiveNodeKey, ACL effectiveACL)
throws InvalidKeyException, ContentEncodingException, ContentNotReadyException,
ContentGoneException, IOException {
// Get the name of the key directory; this is unversioned. Make a new version of it.
ContentName nodeKeyDirectoryName = VersioningProfile.addVersion(GroupAccessControlProfile.nodeKeyName(nodeName));
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: generating new node key {0}", nodeKeyDirectoryName);
Log.info(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: for node {0} with old effective node key {1}", nodeName, oldEffectiveNodeKey);
}
// Now, generate the node key.
if (effectiveACL.publiclyReadable()) {
// TODO Put something here that will represent public; need to then make it so that key-reading code will do
// the right thing when it encounters it.
throw new UnsupportedOperationException("Need to implement public node key representation!");
}
byte [] nodeKeyBytes = new byte[NodeKey.DEFAULT_NODE_KEY_LENGTH];
_random.nextBytes(nodeKeyBytes);
Key nodeKey = new SecretKeySpec(nodeKeyBytes, NodeKey.DEFAULT_NODE_KEY_ALGORITHM);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: for node {0} the new node key is {1}", nodeName, DataUtils.printHexBytes(nodeKey.getEncoded()));
}
// Now, wrap it under the keys listed in its ACL.
// Make a key directory. If we give it a versioned name. Don't start enumerating; we don't need to.
KeyDirectory nodeKeyDirectory = new KeyDirectory(this, nodeKeyDirectoryName, false, handle());
NodeKey theNodeKey = new NodeKey(nodeKeyDirectoryName, nodeKey);
// Add a key block for every reader on the ACL. As managers and writers can read, they are all readers.
// TODO -- pulling public keys here; could be slow; might want to manage concurrency over acl.
for (Link aclEntry : effectiveACL.contents()) {
PublicKeyObject entryPublicKey = null;
boolean isInGroupManager = false;
for (GroupManager gm: _groupManager) {
if (gm.isGroup(aclEntry)) {
entryPublicKey = gm.getLatestPublicKeyForGroup(aclEntry);
isInGroupManager = true;
break;
}
}
if (! isInGroupManager) {
// Calls update. Will get latest version if name unversioned.
if (aclEntry.targetAuthenticator() != null) {
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), aclEntry.targetAuthenticator().publisher(), handle());
} else {
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), handle());
}
}
entryPublicKey.waitForData(SystemConfiguration.getDefaultTimeout());
try {
nodeKeyDirectory.addWrappedKeyBlock(nodeKey, entryPublicKey.getVersionedName(), entryPublicKey.publicKey());
} catch (VersionMissingException ve) {
Log.logException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName(), ve);
throw new IOException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName() + ": " + ve);
}
}
// Add a superseded by block to the previous key. Two cases: old effective node key is at the same level
// as us (we are superseding it entirely), or we are interposing a key (old key is above or below us).
// OK, here are the options:
// Replaced node key is a derived node key -- we are interposing an ACL
// Replaced node key is a stored node key
// -- we are updating that node key to a new version
// NK/vn replaced by NK/vn+k -- new node key will be later version of previous node key
// -- we don't get called if we are deleting an ACL here -- no new node key is added.
if (oldEffectiveNodeKey != null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is not null.");
}
if (oldEffectiveNodeKey.isDerivedNodeKey()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is derived node key.");
}
// Interposing an ACL.
// Add a previous key block wrapping the previous key. There is nothing to link to.
nodeKeyDirectory.addPreviousKeyBlock(oldEffectiveNodeKey.nodeKey(), nodeKeyDirectoryName, nodeKey);
} else {
// We're replacing a previous version of this key. New version should have a previous key
// entry
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is not a derived node key.");
}
try {
if (!VersioningProfile.isLaterVersionOf(nodeKeyDirectoryName, oldEffectiveNodeKey.storedNodeKeyName())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: Unexpected: replacing node key stored at {0} with new node key {1}" +
" but latter is not later version of the former.", oldEffectiveNodeKey.storedNodeKeyName(), nodeKeyDirectoryName);
}
}
} catch (VersionMissingException vex) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "Very unexpected version missing exception when replacing node key : {0}", vex);
}
// Add a previous key link to the old version of the key.
// TODO do we need to add publisher?
nodeKeyDirectory.waitForChildren();
nodeKeyDirectory.addPreviousKeyLink(oldEffectiveNodeKey.storedNodeKeyName(), null);
// OK, just add superseded-by block to the old directory.
KeyDirectory.addSupersededByBlock(
oldEffectiveNodeKey.storedNodeKeyName(), oldEffectiveNodeKey.nodeKey(),
theNodeKey.storedNodeKeyName(), theNodeKey.storedNodeKeyID(), theNodeKey.nodeKey(), handle());
}
}
}
// Return the key for use, along with its name.
return theNodeKey;
}
/**
*
* @param nodeName
* @param wko
* @return
* @throws ContentNotReadyException
* @throws ContentGoneException
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public NodeKey getNodeKeyForObject(ContentName nodeName, WrappedKeyObject wko)
throws ContentNotReadyException, ContentGoneException, InvalidKeyException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// First, we go and look for the node key where the data key suggests
// it should be, and attempt to decrypt it from there.
NodeKey nk = null;
try {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: trying to get specific node key at {0}", wko.wrappedKey().wrappingKeyName());
}
nk = getSpecificNodeKey(wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: got specific node key {0} at {1}", nk, wko.wrappedKey().wrappingKeyName());
}
} catch (AccessDeniedException ex) {
// ignore
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: ignoring access denied exception as we're gong to try harder: {0}", ex.getMessage());
}
}
if (null == nk) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: trying to get node key using interposed ACL for {0}", wko.wrappedKey().wrappingKeyName());
}
// OK, we will have gotten an exception if the node key simply didn't exist
// there, so this means that we don't have rights to read it there.
// The only way we might have rights not visible from this link is if an
// ACL has been interposed between where we are and the node key, and that
// ACL does give us rights.
nk = getNodeKeyUsingInterposedACL(nodeName, wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (null == nk) {
// Still can't find one we can read. Give up. Return null, and allow caller to throw the
// access exception.
return null;
}
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: retrieved stored node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), nk);
}
NodeKey enk = nk.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: computed effective node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), enk);
}
return enk;
}
/**
* Overrides the method of the same name in AccessControlManager.
* GroupAccessControlManager specifies additional content that is not to be protected,
* such as group metadata.
*/
public boolean isProtectedContent(ContentName name, PublisherPublicKeyDigest publisher, ContentType contentType, CCNHandle handle) {
if (isGroupName(name)) {
// Don't encrypt the group metadata
return false;
}
return super.isProtectedContent(name, publisher, contentType, handle);
}
public boolean haveKnownGroupMemberships() {
for (GroupManager gm: _groupManager) {
if (gm.haveKnownGroupMemberships()) return true;
}
return false;
}
}
| javasrc/src/org/ccnx/ccn/profiles/security/access/group/GroupAccessControlManager.java | /**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* 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 USA.
*/
package org.ccnx.ccn.profiles.security.access.group;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.logging.Level;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.CCNFlowControl.SaveType;
import org.ccnx.ccn.impl.support.ByteArrayCompare;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.impl.support.Tuple;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.io.content.ContentGoneException;
import org.ccnx.ccn.io.content.ContentNotReadyException;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.io.content.LinkAuthenticator;
import org.ccnx.ccn.io.content.PublicKeyObject;
import org.ccnx.ccn.io.content.WrappedKey.WrappedKeyObject;
import org.ccnx.ccn.profiles.VersionMissingException;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.namespace.NamespaceProfile;
import org.ccnx.ccn.profiles.namespace.ParameterizedName;
import org.ccnx.ccn.profiles.search.LatestVersionPathfinder;
import org.ccnx.ccn.profiles.search.Pathfinder;
import org.ccnx.ccn.profiles.search.Pathfinder.SearchResults;
import org.ccnx.ccn.profiles.security.access.AccessControlManager;
import org.ccnx.ccn.profiles.security.access.AccessControlPolicyMarker;
import org.ccnx.ccn.profiles.security.access.AccessControlProfile;
import org.ccnx.ccn.profiles.security.access.AccessDeniedException;
import org.ccnx.ccn.profiles.security.access.AccessControlPolicyMarker.AccessControlPolicyMarkerObject;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLObject;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLOperation;
import org.ccnx.ccn.profiles.security.access.group.GroupAccessControlProfile.PrincipalInfo;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
import org.ccnx.ccn.protocol.PublisherPublicKeyDigest;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* This class is used in updating node keys and by #getEffectiveNodeKey(ContentName).
* To achieve this, we walk up the tree for this node. At each point, we check to
* see if a node key exists. If one exists, we decrypt it if we know an appropriate
* key. Otherwise we return null.
*
* We are going for a low-enumeration approach. We could enumerate node keys and
* see if we have rights on the latest version; but then we need to enumerate keys
* and figure out whether we have a copy of a key or one of its previous keys.
* If we don't know our group memberships, even if we enumerate the node key
* access, we don't know what groups we're a member of.
*
* Node keys and ACLs evolve in the following fashion:
* - if ACL adds rights, by adding a group, we merely add encrypted node key blocks for
* the same node key version (ACL version increases, node key version does not)
* - if an ACL removes rights, by removing a group, we version the ACL and the node key
* (both versions increase)
* - if a group adds rights by adding a member, we merely add key blocks to the group key
* (no change to node key or ACL)
* - if a group removes rights by removing a member, we need to evolve all the node keys
* that point to that node key, at the time of next write using that node key (so we don't
* have to enumerate them). (node key version increases, but ACL version does not).
*
* One could have the node key (NK) point to its ACL version, or vice versa, but they really
* do most efficiently evolve in parallel. One could have the ACL point to group versions,
* and update the ACL and NK together in the last case as well.
* In this last case, we want to update the NK only on next write; if we never write again,
* we never need to generate a new NK (unless we can delete). And we want to wait as long
* as possible, to skip NK updates with no corresponding writes.
* But, a writer needs to determine first what the most recent node key is for a given
* node, and then must determine whether or not that node key must be updated -- whether or
* not the most recent versions of groups are what that node key is encrypted under.
* Ideally we don't want to have it update the ACL, as that allows management access separation --
* we can let writers write the node key without allowing them to write the ACL.
*
* So, we can't store the group version information in the ACL. We don't necessarily
* want a writer to have to pull all the node key blocks to see what version of each
* group the node key is encrypted under.
*
* We could name the node key blocks <prefix>/<access marker>/NK/\#version/<group name>:<group key id>,
* if we could match on partial components, but we can't.
*
* We can name the node key blocks <prefix>/<access marker>/NK/\#version/<group key id> with
* a link pointing to that from NK/\#version/<group name>.
*
* For both read and write, we don't actually care what the ACL says. We only care what
* the node key is. Most efficient option, if we have a full key cache, is to list the
* node key blocks by key id used to encrypt them, and then pull one for a key in our cache.
* On the read side, we're looking at a specific version NK, and we might have rights by going
* through its later siblings. On the write side, we're looking at the latest version NK, and
* we should have rights to one of the key blocks, or we don't have rights.
* If we don't have a full key cache, we have to walk the access hierarchy. In that case,
* the most efficient thing to do is to pull the latest version of the ACL for that node
* (if we have a NK, we have an ACL, and vice versa, so we can enumerate NK and then pull
* ACLs). We then walk that ACL. If we know we are in one of the groups in that ACL, walk
* back to find the group key encrypting that node key. If we don't, walk the groups in that
* ACL to find out if we're in any of them. If we are, pull the current group key, see if
* it works, and start working backwards through group keys, populating the cache in the process,
* to find the relevant group key.
*
* Right answer might be intentional containment. Besides the overall group key structures,
* we make a master list that points to the current versions of all the groups. That would
* have to be writable by anyone who is on the manage list for any group. That would let you
* get, easily, a single list indicating what groups are available and what their versions are.
* Unless NE lets you do that in a single pass, which would be better. (Enumerate name/latestversion,
* not just given name, enumerate versions.)
*
*
* Operational Process:
*
* read:
* - look at content, find data key
* - data key refers to specific node key and version used to encrypt it
* - attempt to retrieve that node key from cache, if get it, done
* - go to specific node key key directory, attempt to find a block we can decrypt using keys in cache;
* if so, done
* - (maybe) for groups that node key is encrypted under which we believe we are a member of,
* attempt to retrieve the group key version we need to decrypt the node key
* - if that node key has been superseded, find the latest version of the node key (if we're not
* allowed access to that, we're not allowed access to the data) and walk first the cache,
* then the groups we believe we're a member of, then the groups we don't know about,
* trying to find a key to read it (== retrieve latest version of node key process)
* - if still can't read node key, attempt to find a new ACL interposed between the data node
* and the old node key node, and see if we have access to its latest node key (== retrieve
* latest version of node key process), and then crawl through previous key blocks till we
* get the one we want
*
* write:
* - find closest node key (non-gone)
* - decrypt its latest version, if can't, have no read access, which means have no write access
* - determine whether it's "dirty" -- needs to be superseded. ACL-changes update node key versions,
* what we need to do is determine whether any groups have updated their keys
* - if so, replace it
* - use it to protect data key
// We don't have a key cached. Either we don't have access, we aren't in one of the
// relevant groups, or we are, but we haven't pulled the appropriate version of the group
// key (because it's old, or because we don't know we're in that group).
// We can get this node key because either we're in one of the groups it was made
// available to, or because it's old, and we have access to one of the groups that
// has current access.
// Want to get the latest version of this node key, then do the walk to figure
// out how to read it. Need to split this code up:
// Given specific version (potentially old):
// - enumerate key blocks and group names
// - if we have one cached, use key
// - for groups we believe we're a member of, pull the link and see what key it points to
// - if it's older than the group key we know, walk back from the group key we know, caching
// all the way (this will err on the side of reading; starting from the current group will
// err on the side of making access control coverage look more extensive)
// - if we know nothing else, pull the latest version and walk that if it's newer than this one
// - if that results in a key, chain backwards to this key
// Given latest version:
// - enumerate key blocks, and group names
// - if we have one cached, just use it
// - walk the groups, starting with the groups we believe we're a member of
// - for groups we believe we're in, check if we're still in, then check for a given key
// - walk the groups we don't know if we're in, see if we're in, and can pull the necessary key
// - given that, unwrap the key and return it
// basic flow -- flag that says whether we believe we have the latest or not, if set, walk
// groups we don't know about, if not set, pull latest and if we get something later, make
// recursive call saying we believe it's the latest (2-depth recursion max)
// As we look at more stuff, we cache more keys, and fall more and more into the cache-only
// path.
*
*/
public class GroupAccessControlManager extends AccessControlManager {
/**
* Marker in a Root object that this is the profile we want.
*/
public static final String PROFILE_NAME_STRING = "/ccnx.org/ccn/profiles/security/access/group/GroupAccessControlProfile";
/**
* This algorithm must be capable of key wrap (RSA, ElGamal, etc).
*/
public static final String DEFAULT_GROUP_KEY_ALGORITHM = "RSA";
public static final int DEFAULT_GROUP_KEY_LENGTH = 1024;
public static final String NODE_KEY_LABEL = "Node Key";
private ArrayList<ParameterizedName> _userStorage = new ArrayList<ParameterizedName>();
private ArrayList<GroupManager> _groupManager = new ArrayList<GroupManager>();
static Comparator<byte[]> byteArrayComparator = new ByteArrayCompare();
private TreeMap<byte[], GroupManager> hashToGroupManagerMap = new TreeMap<byte[], GroupManager>(byteArrayComparator);
private HashMap<ContentName, GroupManager> prefixToGroupManagerMap = new HashMap<ContentName, GroupManager>();
private HashSet<ContentName> _myIdentities = new HashSet<ContentName>();
public GroupAccessControlManager() {
// must call initialize
}
public GroupAccessControlManager(ContentName namespace) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, null);
}
public GroupAccessControlManager(ContentName namespace, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, GroupAccessControlProfile.groupNamespaceName(namespace),
GroupAccessControlProfile.userNamespaceName(namespace), handle);
}
public GroupAccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, groupStorage, userStorage, null);
}
public GroupAccessControlManager(ContentName namespace, ContentName groupStorage, ContentName userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
this(namespace, new ContentName[]{groupStorage}, new ContentName[]{userStorage}, handle);
}
public GroupAccessControlManager(ContentName namespace, ContentName[] groupStorage, ContentName[] userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
initialize(namespace, groupStorage, userStorage, handle);
}
private void initialize(ContentName namespace, ContentName[] groupStorage, ContentName[] userStorage, CCNHandle handle) throws ConfigurationException, IOException, MalformedContentNameStringException {
ArrayList<ParameterizedName> parameterizedNames = new ArrayList<ParameterizedName>();
for (ContentName uStorage: userStorage) {
if (null == uStorage)
continue;
ParameterizedName pName = new ParameterizedName("User", uStorage, null);
parameterizedNames.add(pName);
}
for (ContentName gStorage: groupStorage) {
if (null == gStorage)
continue;
ParameterizedName pName = new ParameterizedName("Group", gStorage, null);
parameterizedNames.add(pName);
}
if (null == handle) handle = CCNHandle.open();
AccessControlPolicyMarker r = new AccessControlPolicyMarker(ContentName.fromNative(GroupAccessControlManager.PROFILE_NAME_STRING), parameterizedNames, null);
ContentName policyPrefix = NamespaceProfile.policyNamespace(namespace);
ContentName policyMarkerName = AccessControlProfile.getAccessControlPolicyName(policyPrefix);
AccessControlPolicyMarkerObject policyInformation = new AccessControlPolicyMarkerObject(policyMarkerName, r, SaveType.REPOSITORY, handle);
initialize(policyInformation, handle);
}
@Override
public boolean initialize(AccessControlPolicyMarkerObject policyInformation, CCNHandle handle) throws ConfigurationException, IOException {
if (null == handle) {
_handle = CCNHandle.open();
} else {
_handle = handle;
}
// set up information based on contents of policy
// also need a static method/command line program to create a Root with the right types of information
// for this access control manager type
int componentCount = policyInformation.getBaseName().count();
componentCount -= NamespaceProfile.policyPostfix().count();
componentCount -= AccessControlProfile.AccessControlPolicyContentName().count();
_namespace = policyInformation.getBaseName().cut(componentCount);
ArrayList<ParameterizedName> parameterizedNames = policyInformation.policy().parameterizedNames();
for (ParameterizedName pName: parameterizedNames) {
String label = pName.label();
if (label.equals("Group")) {
GroupManager gm = new GroupManager(this, pName, _handle);
_groupManager.add(gm);
byte[] distinguishingHash = GroupAccessControlProfile.PrincipalInfo.contentPrefixToDistinguishingHash(pName.prefix());
hashToGroupManagerMap.put(distinguishingHash, gm);
prefixToGroupManagerMap.put(pName.prefix(), gm);
}
else if (label.equals("User")) _userStorage.add(pName);
}
return true;
}
public GroupManager groupManager() throws Exception {
if (_groupManager.size() > 1) throw new Exception("A group manager can only be retrieved by name when there are more than one.");
return _groupManager.get(0);
}
public void registerGroupStorage(ContentName groupStorage) throws IOException {
ParameterizedName pName = new ParameterizedName("Group", groupStorage, null);
GroupManager gm = new GroupManager(this, pName, _handle);
_groupManager.add(gm);
byte[] distinguishingHash = GroupAccessControlProfile.PrincipalInfo.contentPrefixToDistinguishingHash(pName.prefix());
hashToGroupManagerMap.put(distinguishingHash, gm);
prefixToGroupManagerMap.put(pName.prefix(), gm);
}
public GroupManager groupManager(byte[] distinguishingHash) {
GroupManager gm = hashToGroupManagerMap.get(distinguishingHash);
if (gm == null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Failed to retrieve a group manager with distinguishing hash " + DataUtils.printHexBytes(distinguishingHash));
}
}
return gm;
}
public GroupManager groupManager(ContentName prefixName) {
GroupManager gm = prefixToGroupManagerMap.get(prefixName);
if (gm == null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "GroupAccessControlManager: failed to retrieve a group manager with prefix " + prefixName);
}
}
return gm;
}
public boolean isGroupName(ContentName principalPublicKeyName) {
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principalPublicKeyName)) return true;
}
return false;
}
public Tuple<ContentName, String> parsePrefixAndFriendlyNameFromPublicKeyName(ContentName principalPublicKeyName) {
// for each group manager/user namespace, there is a prefix, then a "friendly" name component,
// then optionally a postfix that gets tacked on to go from the prefix to the public key
// e.g. Alice's key in the user namespace might be:
// /parc.com/Users/Alice/Keys/EncryptionKey
// where the distinguising prefix would be computed from /parc.com/Users, Alice is the friendly
// name, and the rest is stored in the group manager for /parc.com/Users, generated out of the
// relevant entry in the Roots spec, and just used in a function to go from (distinguishing hash, friendly name)
// to key name
// loop through the group managers, see if the prefix matches, if so, pull that prefix, and take
// the component after that prefix as the friendly name
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principalPublicKeyName)) {
ContentName prefix = gm.getGroupStorage().prefix();
String friendlyName = principalPublicKeyName.postfix(prefix).stringComponent(0);
return new Tuple<ContentName, String>(prefix, friendlyName);
}
}
// NOTE: as there are multiple user prefixes, each with a distinguishing hash and an optional
// suffix, you have to have a list of those and iterate over them as well.
for (ParameterizedName userStorage: _userStorage) {
if (userStorage.prefix().isPrefixOf(principalPublicKeyName)) {
String friendlyName = principalPublicKeyName.postfix(userStorage.prefix()).stringComponent(0);
return new Tuple<ContentName, String>(userStorage.prefix(), friendlyName);
}
}
return null;
}
// TODO
public ContentName getPrincipalPublicKeyName(byte [] distinguishingHash, String friendlyName) {
// look up the distinguishing hash in the user and group maps
// pull the name prefix and postfix from the tables
// make the key name as <prefix>/friendlyName/<postfix>
return null;
}
/**
* Publish my identity (i.e. my public key) under a specified CCN name
* @param identity the name
* @param myPublicKey my public key
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws IOException
* @throws ConfigurationException
*/
public void publishMyIdentity(ContentName identity, PublicKey myPublicKey)
throws InvalidKeyException, ContentEncodingException, IOException, ConfigurationException {
KeyManager km = _handle.keyManager();
if (null == myPublicKey) {
myPublicKey = km.getDefaultPublicKey();
}
PublicKeyObject pko = new PublicKeyObject(identity, myPublicKey, SaveType.REPOSITORY, handle());
pko.save();
_myIdentities.add(identity);
}
/**
* Add an identity to my set. Assume the key is already published.
*/
public void addMyIdentity(ContentName identity) {
_myIdentities.add(identity);
}
/**
* Publish the specified identity (i.e. the public key) of a specified user
* @param userName the name of the user
* @param userPublicKey the public key of the user
* @throws ConfigurationException
* @throws IOException
* @throws MalformedContentNameStringException
*/
public void publishUserIdentity(String userName, PublicKey userPublicKey)
throws ConfigurationException, IOException, MalformedContentNameStringException {
PublicKeyObject pko = new PublicKeyObject(ContentName.fromNative(userName), userPublicKey, SaveType.REPOSITORY, handle());
System.out.println("saving user pubkey to repo:" + userName);
pko.save();
}
public boolean haveIdentity(ContentName userName) {
return _myIdentities.contains(userName);
}
public String nodeKeyLabel() {
return NODE_KEY_LABEL;
}
/**
* Get the latest key for a specified principal
* TODO shortcut slightly -- the principal we have cached might not meet the
* constraints of the link.
* @param principal the principal
* @return the public key object
* @throws IOException
* @throws ContentDecodingException
*/
public PublicKeyObject getLatestKeyForPrincipal(Link principal) throws ContentDecodingException, IOException {
if (null == principal) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Cannot retrieve key for empty principal.");
}
return null;
}
PublicKeyObject pko = null;
boolean isGroup = false;
for (GroupManager gm: _groupManager) {
if (gm.isGroup(principal)) {
pko = gm.getLatestPublicKeyForGroup(principal);
isGroup = true;
break;
}
}
if (!isGroup) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Retrieving latest key for user: " + principal.targetName());
}
LinkAuthenticator targetAuth = principal.targetAuthenticator();
if (null != targetAuth) {
pko = new PublicKeyObject(principal.targetName(), targetAuth.publisher(), handle());
}
else pko = new PublicKeyObject(principal.targetName(), handle());
}
return pko;
}
/**
* Creates the root ACL for _namespace.
* This initialization must be done before any other ACL or node key can be read or written.
* @param rootACL the root ACL
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
public void initializeNamespace(ACL rootACL)
throws InvalidKeyException, ContentEncodingException, ContentNotReadyException,
ContentGoneException, IOException {
// generates the new node key
generateNewNodeKey(_namespace, null, rootACL);
// write the root ACL
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(_namespace), rootACL, handle());
aclo.save();
}
/**
* Retrieves the latest version of an ACL effective at this node, either stored
* here or at one of its ancestors.
* @param nodeName the name of the node
* @return the ACL object
* @throws IOException
* @throws ContentDecodingException
*/
public ACLObject getEffectiveACLObject(ContentName nodeName) throws ContentDecodingException, IOException {
// Find the closest node that has a non-gone ACL
ACLObject aclo = findAncestorWithACL(nodeName, null);
if (null != aclo) {
// parallel find doesn't get us the latest version. Serial does,
// but it's kind of an artifact.
aclo.update();
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found between node {0} and namespace root {1}. Returning root ACL.",
nodeName, getNamespaceRoot());
}
return getACLObjectForNode(getNamespaceRoot());
}
return aclo;
}
private ACLObject findAncestorWithACL(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// selector method, remove when pick faster one.
return findAncestorWithACLInParallel(dataNodeName, stopPoint);
}
/**
* Look for an ACL that is on dataNodeName or above, but below stopPoint. If stopPoint is
* null, then take it to be the root for this AccessControlManager (which we assume to have
* an ACL). This is the old serial search, which has been replaced tyb the parallel search
* below. Keep it here temporarily.
* @param dataNodeName
* @param stopPoint
* @return
* @throws ContentDecodingException
* @throws IOException
*/
@SuppressWarnings("unused")
private ACLObject findAncestorWithACLSerial(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// If dataNodeName is the root of this AccessControlManager, there can be no ACL between
// dataNodeName (inclusive) and the root (exclusive), so return null.
if (getNamespaceRoot().equals(dataNodeName)) return null;
if (null == stopPoint) {
stopPoint = getNamespaceRoot();
} else if (!getNamespaceRoot().isPrefixOf(stopPoint)) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: Stopping point {0} must be an ancestor of the starting point {1}!",
stopPoint, dataNodeName);
}
throw new IOException("findAncestorWithACL: invalid search space: stopping point " + stopPoint + " must be an ancestor of the starting point " +
dataNodeName + "!");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: start point {0}, stop before {1}", dataNodeName, stopPoint);
}
int stopCount = stopPoint.count();
ACLObject ancestorACLObject = null;
ContentName parentName = dataNodeName;
ContentName nextParentName = null;
while (null == ancestorACLObject) {
ancestorACLObject = getACLObjectForNodeIfExists(parentName);
if (null != ancestorACLObject) {
if (ancestorACLObject.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found an ACL object at {0} but its GONE.", ancestorACLObject.getVersionedName());
}
ancestorACLObject = null;
} else {
// got one
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found an ACL object at {0}", ancestorACLObject.getVersionedName());
}
break;
}
}
nextParentName = parentName.parent();
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: no ACL object at node {0}, looking next at {1}", parentName, nextParentName);
}
// stop looking once we're above our namespace, or if we've already checked the top level
if (parentName.count() == stopCount) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACL: giving up, next search point would be {0}, stop point is {1}, no ACL found",
parentName, stopPoint);
}
break;
}
parentName = nextParentName;
}
if (null == ancestorACLObject) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL,
"No ACL available in ancestor tree between {0} and {1} (not-inclusive) out of namespace rooted at {2}.",
dataNodeName, stopPoint, getNamespaceRoot());
}
return null;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found ACL for {0} at ancestor {1}: ", dataNodeName, ancestorACLObject.getVersionedName());
}
return ancestorACLObject;
}
/**
* Implement a parallel findAncestorWithACL; drop it in separately so we can
* switch back and forth in testing.
*/
private ACLObject findAncestorWithACLInParallel(ContentName dataNodeName, ContentName stopPoint) throws ContentDecodingException, IOException {
// If dataNodeName is the root of this AccessControlManager, there can be no ACL between
// dataNodeName (inclusive) and the root (exclusive), so return null.
if (getNamespaceRoot().equals(dataNodeName)) return null;
if (null == stopPoint) {
stopPoint = getNamespaceRoot();
} else if (!getNamespaceRoot().isPrefixOf(stopPoint)) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: Stopping point {0} must be an ancestor of the starting point {1}!",
stopPoint, dataNodeName);
}
throw new IOException("findAncestorWithACLInParallel: invalid search space: stopping point " + stopPoint + " must be an ancestor of the starting point " +
dataNodeName + "!");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: start point {0}, stop before {1}", dataNodeName, stopPoint);
}
int stopCount = stopPoint.count();
// Pathfinder searches from start point to stop point inclusive, want exclusive, so hand
// it one level down from stop point.
Pathfinder pathfinder = new LatestVersionPathfinder(dataNodeName, dataNodeName.cut(stopCount+1),
GroupAccessControlProfile.aclPostfix(), true, false, SystemConfiguration.EXTRA_LONG_TIMEOUT,
null, handle());
SearchResults searchResults = pathfinder.waitForResults();
if (null != searchResults.getResult()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "findAncestorWithACLInParallel: found {0}", searchResults.getResult().name());
}
ACLObject aclo = new ACLObject(searchResults.getResult(), handle());
return aclo;
}
return null;
}
/**
* Try to pull an ACL for a particular node. If it doesn't exist, will time
* out. Use enumeration to decide whether to call this to avoid the timeout.
* @param aclNodeName the node name
* @return the ACL object
* @throws ContentDecodingException
* @throws IOException
*/
public ACLObject getACLObjectForNode(ContentName aclNodeName)
throws ContentDecodingException, IOException {
// Get the latest version of the acl. We don't care so much about knowing what version it was.
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(aclNodeName), handle());
aclo.update();
// if there is no update, this will probably throw an exception -- IO or XMLStream
if (aclo.isGone()) {
// treat as if no acl on node
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getACLObjectForNode: Asked to get an ACL object for specific node {0}, but ACL there is GONE! Returning null.",
aclNodeName);
}
return null;
}
return aclo;
}
/**
* Try to pull an ACL for a specified node if it exists.
* @param aclNodeName the name of the node
* @return the ACL object
* @throws IOException
* @throws ContentDecodingException
*/
public ACLObject getACLObjectForNodeIfExists(ContentName aclNodeName) throws ContentDecodingException, IOException {
// TODO really want to check simple existence here, but need to integrate with verifier
// use. GLV too slow for negative results. Given that we need latest version, at least
// use the segment we get, and don't pull it twice.
ContentName aclName = new ContentName(GroupAccessControlProfile.aclName(aclNodeName));
ContentObject aclNameList = VersioningProfile.getLatestVersion(aclName,
null, SystemConfiguration.MAX_TIMEOUT, handle().defaultVerifier(), handle());
if (null != aclNameList) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found latest version of acl for {0} at {1} type: {2}",
aclNodeName, aclName, aclNameList.signedInfo().getTypeName());
}
ACLObject aclo = new ACLObject(aclNameList, handle());
if (aclo.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "ACL object is GONE, returning anyway {0}", aclo.getVersionedName());
}
}
return aclo;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found on node: " + aclNodeName);
}
return null;
}
/**
* Get the effective ACL for a node specified by its name
* @param nodeName the name of the node
* @return the effective ACL
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentDecodingException
* @throws IOException
*/
public ACL getEffectiveACL(ContentName nodeName)
throws ContentNotReadyException, ContentGoneException, ContentDecodingException, IOException {
ACLObject aclo = getEffectiveACLObject(nodeName);
if (null != aclo) {
return aclo.acl();
}
return null;
}
/**
* Adds an ACL to a node that doesn't have one, or replaces one that exists.
* Just writes, doesn't bother to look at any current ACL. Does need to pull
* the effective node key at this node, though, to wrap the old ENK in a new
* node key.
*
* @param nodeName the name of the node
* @param newACL the new ACL
* @return
* @throws InvalidKeyException
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws NoSuchAlgorithmException
*/
public ACL setACL(ContentName nodeName, ACL newACL)
throws AccessDeniedException, InvalidKeyException, ContentNotReadyException, ContentGoneException, IOException, NoSuchAlgorithmException {
// Throws access denied exception if we can't read the old node key.
NodeKey effectiveNodeKey = getEffectiveNodeKey(nodeName);
// generates the new node key, wraps it under the new acl, and wraps the old node key
generateNewNodeKey(nodeName, effectiveNodeKey, newACL);
// write the acl
ACLObject aclo = new ACLObject(GroupAccessControlProfile.aclName(nodeName), newACL, handle());
aclo.save();
return aclo.acl();
}
/**
* Delete the ACL at this node if one exists, returning control to the
* next ACL upstream.
* We simply add a supserseded by block at this node, wrapping this key in the key of the upstream
* node. If we don't have read access at that node, throw AccessDeniedException.
* Then we write a GONE block here for the ACL, and a new node key version with a superseded by block.
* The superseded by block should probably be encrypted not with the ACL in force, but with the effective
* node key of the parent -- that will be derivable from the appropriate ACL, and will have the right semantics
* if a new ACL is interposed later. In the meantime, all the people with the newly in-force ancestor
* ACL should be able to read this content.
* @param nodeName
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public void deleteACL(ContentName nodeName)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
// First, find ACL at this node if one exists.
ACLObject thisNodeACL = getACLObjectForNodeIfExists(nodeName);
if (null == thisNodeACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Asked to delete ACL for node {0} that doesn't have one. Doing nothing.", nodeName);
}
return;
} else if (thisNodeACL.isGone()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Asked to delete ACL for node {0} that has already been deleted. Doing nothing.", nodeName);
}
return;
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Deleting ACL for node {0} latest version: {1}", nodeName, thisNodeACL.getVersionedName());
}
// We know we have an ACL at this node. So we know we have a node key at this
// node. Get the latest version of this node key.
NodeKey nk = getLatestNodeKeyForNode(nodeName);
// Next, find the node key that would be in force here after this deletion.
// Do that by getting the effective node key at the parent
ContentName parentName = nodeName.parent();
NodeKey effectiveParentNodeKey = getEffectiveNodeKey(parentName);
// And then deriving what the effective node key would be here, if
// we inherited from the parent
NodeKey ourEffectiveNodeKeyFromParent =
effectiveParentNodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
// Generate a superseded block for this node, wrapping its key in the parent.
// TODO want to wrap key in parent's effective key, but can't point to that -- no way to name an
// effective node key... need one.
// need to mangl stored key name into superseded block name, need to wrap
// in ourEffNodeKeyFromParent, make sure stored key id points up to our ENKFP.storedKeyName()
KeyDirectory.addSupersededByBlock(nk.storedNodeKeyName(), nk.nodeKey(),
ourEffectiveNodeKeyFromParent.storedNodeKeyName(),
ourEffectiveNodeKeyFromParent.storedNodeKeyID(),
effectiveParentNodeKey.nodeKey(), handle());
// Then mark the ACL as gone.
thisNodeACL.saveAsGone();
}
/**
* Pulls the ACL for this node, if one exists, and modifies it to include
* the following changes, then stores the result using setACL, updating
* the node key if necessary in the process.
*
* @param nodeName the name of the node
* @param ACLUpdates the updates to the ACL
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL updateACL(ContentName nodeName, ArrayList<ACL.ACLOperation> ACLUpdates)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
ACLObject currentACL = getACLObjectForNodeIfExists(nodeName);
ACL newACL = null;
if (null != currentACL) {
newACL = currentACL.acl();
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Adding brand new ACL to node {0}", nodeName);
}
//TODO: if no operations is specified, then a new empty ACL is created...
newACL = new ACL();
}
LinkedList<Link> newReaders = newACL.update(ACLUpdates);
if ((null == newReaders) || (null == currentACL)) {
// null newReaders means we revoked someone.
// null currentACL means we're starting from scratch
// Set the ACL and update the node key.
return setACL(nodeName, newACL);
}
// If we get back a list of new readers, it means all we have to do
// is add key blocks for them, not update the node key. (And it means
// we have a node key for this node.)
// Wait to save the new ACL till we are sure we're allowed to do this.
KeyDirectory keyDirectory = null;
try {
// If we can't read the node key, we can't update. Get the effective node key.
// Better be a node key here... and we'd better be allowed to read it.
NodeKey latestNodeKey = getLatestNodeKeyForNode(nodeName);
if (null == latestNodeKey) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Cannot read the latest node key for {0}", nodeName);
}
throw new AccessDeniedException("Cannot read the latest node key for " + nodeName);
}
keyDirectory = new KeyDirectory(this, latestNodeKey.storedNodeKeyName(), handle());
for (Link principal : newReaders) {
PublicKeyObject latestKey = getLatestKeyForPrincipal(principal);
if (!latestKey.available()) {
latestKey.waitForData(SystemConfiguration.getDefaultTimeout());
}
if (latestKey.available()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "updateACL: Adding wrapped key block for reader: " + latestKey.getVersionedName());
}
try {
keyDirectory.addWrappedKeyBlock(latestNodeKey.nodeKey(), latestKey.getVersionedName(), latestKey.publicKey());
} catch (VersionMissingException e) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "UNEXPECTED: latest key for principal: " + latestKey.getVersionedName() + " has no version? Skipping.");
}
}
} else {
// Do we use an old key or give up?
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "updateACL: No key for {0} found. Skipping.", principal);
}
}
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
// If we got here, we got the node key we were updating, so we are allowed
// to at least read this stuff (though maybe not write it). Save the acl.
currentACL.save(newACL);
return newACL;
}
/**
* Add readers to a specified node
* @param nodeName the name of the node
* @param newReaders the list of new readers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addReaders(ContentName nodeName, ArrayList<Link> newReaders)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : newReaders){
ops.add(ACLOperation.addReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Remove readers from a specified node
* @param nodeName the name of the node
* @param removedReaders the list of removed readers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeReaders(ContentName nodeName, ArrayList<Link> removedReaders)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link reader : removedReaders){
ops.add(ACLOperation.removeReaderOperation(reader));
}
return updateACL(nodeName, ops);
}
/**
* Add writers to a specified node.
* @param nodeName the name of the node
* @param newWriters the list of new writers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addWriters(ContentName nodeName, ArrayList<Link> newWriters)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : newWriters){
ops.add(ACLOperation.addWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Remove writers from a specified node.
* @param nodeName the name of the node
* @param removedWriters the list of removed writers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeWriters(ContentName nodeName, ArrayList<Link> removedWriters)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link writer : removedWriters){
ops.add(ACLOperation.removeWriterOperation(writer));
}
return updateACL(nodeName, ops);
}
/**
* Add managers to a specified node
* @param nodeName the name of the node
* @param newManagers the list of new managers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL addManagers(ContentName nodeName, ArrayList<Link> newManagers)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: newManagers){
ops.add(ACLOperation.addManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Remove managers from a specified node
* @param nodeName the name of the node
* @param removedManagers the list of removed managers
* @return the updated ACL
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public ACL removeManagers(ContentName nodeName, ArrayList<Link> removedManagers)
throws InvalidKeyException, ContentDecodingException, IOException, NoSuchAlgorithmException {
ArrayList<ACLOperation> ops = new ArrayList<ACLOperation>();
for(Link manager: removedManagers){
ops.add(ACLOperation.removeManagerOperation(manager));
}
return updateACL(nodeName, ops);
}
/**
* Get the ancestor node key in force at this node (if we can decrypt it),
* including a key at this node itself. We use the fact that ACLs and
* node keys are co-located; if you have one, you have the other.
* @param nodeName the name of the node
* @return null means while node keys exist, we can't decrypt any of them --
* we have no read access to this node (which implies no write access)
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidCipherTextException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws IOException if something is wrong (e.g. no node keys at all)
* @throws NoSuchAlgorithmException
*/
protected NodeKey findAncestorWithNodeKey(ContentName nodeName)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// climb up looking for node keys, then make sure that one isn't GONE
// if it isn't, call read-side routine to figure out how to decrypt it
ACLObject effectiveACL = findAncestorWithACL(nodeName, null);
if (null != effectiveACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Got ACL named: {0} attempting to retrieve node key from {1}",
effectiveACL.getVersionedName(), AccessControlProfile.accessRoot(effectiveACL.getVersionedName()));
}
} else {
// We're not searching at the namespace root; because we assume we have
// already made sure we have an ACL there. So if we get back NULL, we
// go stratight to our namespace root.
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "No ACL found between node {0} and namespace root {1}, assume ACL is at namespace root.",
nodeName, getNamespaceRoot());
}
}
return getLatestNodeKeyForNode(
(null != effectiveACL) ? AccessControlProfile.accessRoot(effectiveACL.getBaseName()) : getNamespaceRoot());
}
/**
* Write path: get the latest node key for a node.
* @param nodeName the name of the node
* @return the corresponding node key
* @throws IOException
* @throws ContentDecodingException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getLatestNodeKeyForNode(ContentName nodeName)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
ContentName nodeKeyPrefix = GroupAccessControlProfile.nodeKeyName(nodeName);
ContentObject co = VersioningProfile.getLatestVersion(nodeKeyPrefix,
null, SystemConfiguration.MAX_TIMEOUT, handle().defaultVerifier(), handle());
ContentName nodeKeyVersionedName = null;
if (co != null) {
nodeKeyVersionedName = co.name().subname(0, nodeKeyPrefix.count() + 1);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "getLatestNodeKeyForNode: {0} is the latest version found for {1}.", nodeKeyVersionedName, nodeName);
}
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "getLatestNodeKeyForNode: no latest version found for {0}.", nodeName);
}
return null;
}
// DKS TODO this may not handle ACL deletion correctly -- we need to make sure that this
// key wasn't superseded by something that isn't a later version of itself.
// then, pull the node key we can decrypt
return getNodeKeyByVersionedName(nodeKeyVersionedName, null);
}
/**
* Read path:
* Retrieve a specific node key from a given location, as specified by a
* key it was used to wrap, and, if possible, find a key we can use to
* unwrap the node key.
*
* Throw an exception if there is no node key block at the appropriate name.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return the node key
* @throws IOException
* @throws ContentDecodingException
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getSpecificNodeKey(ContentName nodeKeyName, byte [] nodeKeyIdentifier)
throws InvalidKeyException, AccessDeniedException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
if ((null == nodeKeyName) && (null == nodeKeyIdentifier)) {
throw new IllegalArgumentException("Node key name and identifier cannot both be null!");
}
// We should know what node key to use (down to the version), but we have to find the specific
// wrapped key copy we can decrypt.
NodeKey nk = getNodeKeyByVersionedName(nodeKeyName, nodeKeyIdentifier);
if (null == nk) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "No decryptable node key available at {0}, access denied.", nodeKeyName);
}
return null;
}
return nk;
}
/**
* We have the name of a specific version of a node key. Now we just need to figure
* out which of our keys can be used to decrypt it.
* @param nodeKeyName
* @param nodeKeyIdentifier
* @return
* @throws IOException
* @throws AccessDeniedException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
NodeKey getNodeKeyByVersionedName(ContentName nodeKeyName, byte [] nodeKeyIdentifier)
throws AccessDeniedException, InvalidKeyException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
NodeKey nk = null;
KeyDirectory keyDirectory = null;
try {
keyDirectory = new KeyDirectory(this, nodeKeyName, handle());
keyDirectory.waitForNoUpdatesOrResult(SystemConfiguration.LONG_TIMEOUT);
// this will handle the caching.
Key unwrappedKey = keyDirectory.getUnwrappedKey(nodeKeyIdentifier);
if (null != unwrappedKey) {
nk = new NodeKey(nodeKeyName, unwrappedKey);
} else {
throw new AccessDeniedException("Access denied: cannot retrieve key " + DataUtils.printBytes(nodeKeyIdentifier) + " at name " + nodeKeyName);
}
} finally {
if (null != keyDirectory) {
keyDirectory.stopEnumerating();
}
}
return nk;
}
/**
* Write path:
* Get the effective node key in force at this node, used to derive keys to
* encrypt content. Vertical chaining. Works if you ask for node which has
* a node key.
* TODO -- when called by writers, check to see if node key is dirty & update.
* @param nodeName
* @return
* @throws AccessDeniedException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws IOException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getEffectiveNodeKey(ContentName nodeName)
throws AccessDeniedException, InvalidKeyException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// Get the ancestor node key in force at this node.
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Found node key at {0}", nodeKey.storedNodeKeyName());
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Computing effective node key for {0} using stored node key {1}", nodeName, effectiveNodeKey.storedNodeKeyName());
}
return effectiveNodeKey;
}
/**
* Like #getEffectiveNodeKey(ContentName), except checks to see if node
* key is dirty and updates it if necessary.
* @param nodeName
* @return
* @throws AccessDeniedException
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws AccessDeniedException, InvalidKeyException
* @throws NoSuchAlgorithmException
*/
public NodeKey getFreshEffectiveNodeKey(ContentName nodeName)
throws AccessDeniedException, InvalidKeyException, ContentDecodingException,
ContentEncodingException, ContentNotReadyException, ContentGoneException, IOException, NoSuchAlgorithmException {
NodeKey nodeKey = findAncestorWithNodeKey(nodeName);
if (null == nodeKey) {
throw new AccessDeniedException("Cannot retrieve node key for node: " + nodeName + ".");
}
// This should be the latest node key; i.e. not superseded.
if (nodeKeyIsDirty(nodeKey.storedNodeKeyName())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: Found node key at {0}, updating.", nodeKey.storedNodeKeyName());
}
ContentName nodeKeyNodeName = GroupAccessControlProfile.accessRoot(nodeKey.storedNodeKeyName());
ACLObject acl = getACLObjectForNode(nodeKeyNodeName);
nodeKey = generateNewNodeKey(nodeKeyNodeName, nodeKey, acl.acl());
} else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: Found node key at {0}", nodeKey.storedNodeKeyName());
}
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: retrieved stored node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), nodeKey);
}
NodeKey effectiveNodeKey = nodeKey.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getFreshEffectiveNodeKey: computed effective node key for node {0} label {1}: {2} using stored node key {3}"
, nodeName, nodeKeyLabel(), effectiveNodeKey, effectiveNodeKey.storedNodeKeyName());
}
return effectiveNodeKey;
}
/**
* Do we need to update this node key?
* First, we look to see whether or not we know the key is dirty -- i.e.
* does it have a superseded block (if it's gone, it will also have a
* superseded block). If not, we have to really check...
* Basically, we look at all the entities this node key is encrypted for,
* and determine whether any of them have a new version of their public
* key. If so, the node key is dirty.
*
* The initial implementation of this will be simple and slow -- iterating through
* groups and assuming the active object system will keep updating itself whenever
* a new key appears. Eventually, we might want an index directory of all the
* versions of keys, so that one name enumeration request might give us information
* about whether keys have been updated. (Or some kind of aggregate versioning,
* that tell us a) whether any groups have changed their versions, or b) just the
* ones we care about have.)
*
* This can be called by anyone -- the data about whether a node key is dirty
* is visible to anyone. Fixing a dirty node key requires access, though.
* @param theNodeKeyName this might be the name of the node where the NK is stored,
* or the NK name itself.
* We assume this exists -- that there at some point has been a node key here.
* TODO ephemeral node key naming
* @return
* @throws IOException
* @throws ContentDecodingException
*/
public boolean nodeKeyIsDirty(ContentName theNodeKeyName) throws ContentDecodingException, IOException {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty called.");
}
// first, is this a node key name?
if (!GroupAccessControlProfile.isNodeKeyName(theNodeKeyName)) {
// assume it's a data node name.
theNodeKeyName = GroupAccessControlProfile.nodeKeyName(theNodeKeyName);
}
// get the requested version of this node key; or if unversioned, get the latest.
KeyDirectory nodeKeyDirectory = null;
try {
nodeKeyDirectory = new KeyDirectory(this, theNodeKeyName, handle());
nodeKeyDirectory.waitForChildren();
if (null == nodeKeyDirectory) {
throw new IOException("Cannot get node key directory for : " + theNodeKeyName);
}
if (nodeKeyDirectory.hasSupersededBlock()) {
return true;
}
for (PrincipalInfo principal : nodeKeyDirectory.getCopyOfPrincipals().values()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: found principal called {0}", principal.friendlyName());
}
if (principal.isGroup()) {
Group theGroup = groupManager(principal.distinguishingHash()).getGroup(principal.friendlyName());
if (theGroup.publicKeyVersion().after(principal.versionTimestamp())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: the key of principal {0} is out of date", principal.friendlyName());
}
return true;
}
else {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINE)) {
Log.fine(Log.FAC_ACCESSCONTROL, "NodeKeyIsDirty: the key of principal {0} is up to date", principal.friendlyName());
}
}
} else {
// DKS TODO -- for now, don't handle versioning of non-group keys
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "User key for {0}, not checking version.", principal.friendlyName());
}
// Technically, we're not handling versioning for user keys, but be nice. Start
// by seeing if we have a link to the key in our user space.
// If the principal isn't available in our enumerated list, have to go get its key
// from the wrapped key object.
}
}
return false;
} finally {
if (null != nodeKeyDirectory)
nodeKeyDirectory.stopEnumerating();
}
}
/**
* Would we update this data key if we were doing reencryption?
* This one is simpler -- what node key is the data key encrypted under, and is
* that node key dirty?
*
* This can be called by anyone -- the data about whether a data key is dirty
* is visible to anyone. Fixing a dirty key requires access, though.
*
* @param dataName
* @return
* @throws IOException
* @throws ContentNotReadyException
* @throws ContentDecodingException
*/
public boolean dataKeyIsDirty(ContentName dataName) throws ContentNotReadyException, IOException {
// TODO -- do we need to check whether there *is* a key?
// The trick: we need the header information in the wrapped key; we don't need to unwrap it.
// ephemeral key naming
WrappedKeyObject wrappedDataKey = new WrappedKeyObject(GroupAccessControlProfile.dataKeyName(dataName), handle());
return nodeKeyIsDirty(wrappedDataKey.wrappedKey().wrappingKeyName());
}
/**
* Find the key to use to wrap a data key at this node for encryption. This requires
* the current effective node key, and wrapping this data key in it. If the
* current node key is dirty, this causes a new one to be generated.
* If data at the current node is public, this returns null. Does not check
* to see whether content is excluded from encryption (e.g. by being access
* control data).
* @param dataNodeName the node for which to find a data key wrapping key
* @param publisher in case output key retrieval needs to be specialized by publisher
* @return if null, the data is to be unencrypted.
* @param newRandomDataKey
* @throws AccessDeniedException
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
@Override
public NodeKey getDataKeyWrappingKey(ContentName dataNodeName, PublisherPublicKeyDigest publisher)
throws AccessDeniedException, InvalidKeyException,
ContentEncodingException, IOException, NoSuchAlgorithmException {
NodeKey effectiveNodeKey = getFreshEffectiveNodeKey(dataNodeName);
if (null == effectiveNodeKey) {
throw new AccessDeniedException("Cannot retrieve effective node key for node: " + dataNodeName + ".");
}
return effectiveNodeKey;
}
/**
* Retrieve the node key wrapping this data key for decryption.
* @throws IOException
* @throws ContentDecodingException
* @throws ContentEncodingException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
@Override
public Key getDataKeyWrappingKey(ContentName dataNodeName, WrappedKeyObject wrappedDataKeyObject)
throws InvalidKeyException, ContentNotReadyException, ContentGoneException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
NodeKey enk = getNodeKeyForObject(dataNodeName, wrappedDataKeyObject);
if (null != enk) {
return enk.nodeKey();
}
return null;
}
/**
* Get the data key wrapping key if we happened to have cached a copy of the decryption key.
* @param dataNodeName
* @param wrappedDataKeyObject
* @param cachedWrappingKey
* @return
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
@Override
public Key getDataKeyWrappingKey(ContentName dataNodeName, ContentName wrappingKeyName, Key cachedWrappingKey) throws InvalidKeyException, ContentEncodingException {
NodeKey cachedWrappingKeyNK = new NodeKey(wrappingKeyName, cachedWrappingKey);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: retrieved stored node key for node {0} label {1}: {2}", dataNodeName, nodeKeyLabel(), cachedWrappingKeyNK);
}
NodeKey enk = cachedWrappingKeyNK.computeDescendantNodeKey(dataNodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: computed effective node key for node {0} label {1}: {2}", dataNodeName, nodeKeyLabel(), enk);
}
if (null != enk) {
return enk.nodeKey();
}
return null;
}
/**
* We've looked for a node key we can decrypt at the expected node key location,
* but no dice. See if a new ACL has been interposed granting us rights at a lower
* portion of the tree.
* @param dataNodeName
* @param wrappingKeyName
* @param wrappingKeyIdentifier
* @return
* @throws IOException
* @throws ContentDecodingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
*/
protected NodeKey getNodeKeyUsingInterposedACL(ContentName dataNodeName,
ContentName wrappingKeyName, byte[] wrappingKeyIdentifier)
throws ContentDecodingException, IOException, InvalidKeyException, NoSuchAlgorithmException {
ContentName stopPoint = AccessControlProfile.accessRoot(wrappingKeyName);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: looking for an ACL above {0} but below {1}",
dataNodeName, stopPoint);
}
ACLObject nearestACL = findAncestorWithACL(dataNodeName, stopPoint);
// TODO update to make sure non-gone....
if (null == nearestACL) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "Node key {0} is the nearest ACL to {1}", wrappingKeyName , dataNodeName);
}
return null;
}
NodeKey currentNodeKey = getLatestNodeKeyForNode(GroupAccessControlProfile.accessRoot(nearestACL.getVersionedName()));
// We have retrieved the current node key at the node where the ACL was interposed.
// But the data key is wrapped in the previous node key that was at this node prior to the ACL interposition.
// So we need to retrieve the previous node key, which was wrapped with KeyDirectory.addPreviousKeyBlock
// at the time the ACL was interposed.
ContentName previousKeyName = ContentName.fromNative(currentNodeKey.storedNodeKeyName(), GroupAccessControlProfile.PREVIOUS_KEY_NAME);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: retrieving previous key at {0}", previousKeyName);
}
WrappedKeyObject wrappedPreviousNodeKey = new WrappedKeyObject(previousKeyName, _handle);
wrappedPreviousNodeKey.update();
Key pnk = wrappedPreviousNodeKey.wrappedKey().unwrapKey(currentNodeKey.nodeKey());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "getNodeKeyUsingInterposedACL: returning previous node key for node {0}", currentNodeKey.storedNodeKeyName());
}
NodeKey previousNodeKey = new NodeKey(currentNodeKey.storedNodeKeyName(), pnk);
return previousNodeKey;
}
/**
* Make a new node key and encrypt it under the given ACL.
* If there is a previous node key (oldEffectiveNodeKey not null), it is wrapped in the new node key.
* Put all the blocks into the aggregating writer, but don't flush.
*
* @param nodeName
* @param oldEffectiveNodeKey
* @param effectiveACL
* @return
* @throws IOException
* @throws ContentGoneException
* @throws ContentNotReadyException
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
protected NodeKey generateNewNodeKey(ContentName nodeName, NodeKey oldEffectiveNodeKey, ACL effectiveACL)
throws InvalidKeyException, ContentEncodingException, ContentNotReadyException,
ContentGoneException, IOException {
// Get the name of the key directory; this is unversioned. Make a new version of it.
ContentName nodeKeyDirectoryName = VersioningProfile.addVersion(GroupAccessControlProfile.nodeKeyName(nodeName));
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: generating new node key {0}", nodeKeyDirectoryName);
Log.info(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: for node {0} with old effective node key {1}", nodeName, oldEffectiveNodeKey);
}
// Now, generate the node key.
if (effectiveACL.publiclyReadable()) {
// TODO Put something here that will represent public; need to then make it so that key-reading code will do
// the right thing when it encounters it.
throw new UnsupportedOperationException("Need to implement public node key representation!");
}
byte [] nodeKeyBytes = new byte[NodeKey.DEFAULT_NODE_KEY_LENGTH];
_random.nextBytes(nodeKeyBytes);
Key nodeKey = new SecretKeySpec(nodeKeyBytes, NodeKey.DEFAULT_NODE_KEY_ALGORITHM);
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: for node {0} the new node key is {1}", nodeName, DataUtils.printHexBytes(nodeKey.getEncoded()));
}
// Now, wrap it under the keys listed in its ACL.
// Make a key directory. If we give it a versioned name. Don't start enumerating; we don't need to.
KeyDirectory nodeKeyDirectory = new KeyDirectory(this, nodeKeyDirectoryName, false, handle());
NodeKey theNodeKey = new NodeKey(nodeKeyDirectoryName, nodeKey);
// Add a key block for every reader on the ACL. As managers and writers can read, they are all readers.
// TODO -- pulling public keys here; could be slow; might want to manage concurrency over acl.
for (Link aclEntry : effectiveACL.contents()) {
PublicKeyObject entryPublicKey = null;
boolean isInGroupManager = false;
for (GroupManager gm: _groupManager) {
if (gm.isGroup(aclEntry)) {
entryPublicKey = gm.getLatestPublicKeyForGroup(aclEntry);
isInGroupManager = true;
break;
}
}
if (! isInGroupManager) {
// Calls update. Will get latest version if name unversioned.
if (aclEntry.targetAuthenticator() != null) {
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), aclEntry.targetAuthenticator().publisher(), handle());
} else {
entryPublicKey = new PublicKeyObject(aclEntry.targetName(), handle());
}
}
entryPublicKey.waitForData(SystemConfiguration.getDefaultTimeout());
try {
nodeKeyDirectory.addWrappedKeyBlock(nodeKey, entryPublicKey.getVersionedName(), entryPublicKey.publicKey());
} catch (VersionMissingException ve) {
Log.logException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName(), ve);
throw new IOException("Unexpected version missing exception for public key " + entryPublicKey.getVersionedName() + ": " + ve);
}
}
// Add a superseded by block to the previous key. Two cases: old effective node key is at the same level
// as us (we are superseding it entirely), or we are interposing a key (old key is above or below us).
// OK, here are the options:
// Replaced node key is a derived node key -- we are interposing an ACL
// Replaced node key is a stored node key
// -- we are updating that node key to a new version
// NK/vn replaced by NK/vn+k -- new node key will be later version of previous node key
// -- we don't get called if we are deleting an ACL here -- no new node key is added.
if (oldEffectiveNodeKey != null) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is not null.");
}
if (oldEffectiveNodeKey.isDerivedNodeKey()) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is derived node key.");
}
// Interposing an ACL.
// Add a previous key block wrapping the previous key. There is nothing to link to.
nodeKeyDirectory.addPreviousKeyBlock(oldEffectiveNodeKey.nodeKey(), nodeKeyDirectoryName, nodeKey);
} else {
// We're replacing a previous version of this key. New version should have a previous key
// entry
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.FINER)) {
Log.finer(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: old effective node key is not a derived node key.");
}
try {
if (!VersioningProfile.isLaterVersionOf(nodeKeyDirectoryName, oldEffectiveNodeKey.storedNodeKeyName())) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "GenerateNewNodeKey: Unexpected: replacing node key stored at {0} with new node key {1}" +
" but latter is not later version of the former.", oldEffectiveNodeKey.storedNodeKeyName(), nodeKeyDirectoryName);
}
}
} catch (VersionMissingException vex) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.WARNING)) {
Log.warning(Log.FAC_ACCESSCONTROL, "Very unexpected version missing exception when replacing node key : {0}", vex);
}
// Add a previous key link to the old version of the key.
// TODO do we need to add publisher?
nodeKeyDirectory.waitForChildren();
nodeKeyDirectory.addPreviousKeyLink(oldEffectiveNodeKey.storedNodeKeyName(), null);
// OK, just add superseded-by block to the old directory.
KeyDirectory.addSupersededByBlock(
oldEffectiveNodeKey.storedNodeKeyName(), oldEffectiveNodeKey.nodeKey(),
theNodeKey.storedNodeKeyName(), theNodeKey.storedNodeKeyID(), theNodeKey.nodeKey(), handle());
}
}
}
// Return the key for use, along with its name.
return theNodeKey;
}
/**
*
* @param nodeName
* @param wko
* @return
* @throws ContentNotReadyException
* @throws ContentGoneException
* @throws InvalidKeyException
* @throws ContentEncodingException
* @throws ContentDecodingException
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public NodeKey getNodeKeyForObject(ContentName nodeName, WrappedKeyObject wko)
throws ContentNotReadyException, ContentGoneException, InvalidKeyException, ContentEncodingException,
ContentDecodingException, IOException, NoSuchAlgorithmException {
// First, we go and look for the node key where the data key suggests
// it should be, and attempt to decrypt it from there.
NodeKey nk = null;
try {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: trying to get specific node key at {0}", wko.wrappedKey().wrappingKeyName());
}
nk = getSpecificNodeKey(wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: got specific node key {0} at {1}", nk, wko.wrappedKey().wrappingKeyName());
}
} catch (AccessDeniedException ex) {
// ignore
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: ignoring access denied exception as we're gong to try harder: {0}", ex.getMessage());
}
}
if (null == nk) {
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: trying to get node key using interposed ACL for {0}", wko.wrappedKey().wrappingKeyName());
}
// OK, we will have gotten an exception if the node key simply didn't exist
// there, so this means that we don't have rights to read it there.
// The only way we might have rights not visible from this link is if an
// ACL has been interposed between where we are and the node key, and that
// ACL does give us rights.
nk = getNodeKeyUsingInterposedACL(nodeName, wko.wrappedKey().wrappingKeyName(),
wko.wrappedKey().wrappingKeyIdentifier());
if (null == nk) {
// Still can't find one we can read. Give up. Return null, and allow caller to throw the
// access exception.
return null;
}
}
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: retrieved stored node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), nk);
}
NodeKey enk = nk.computeDescendantNodeKey(nodeName, nodeKeyLabel());
if (Log.isLoggable(Log.FAC_ACCESSCONTROL, Level.INFO)) {
Log.info(Log.FAC_ACCESSCONTROL, "getNodeKeyForObject: computed effective node key for node {0} label {1}: {2}", nodeName, nodeKeyLabel(), enk);
}
return enk;
}
/**
* Overrides the method of the same name in AccessControlManager.
* GroupAccessControlManager specifies additional content that is not to be protected,
* such as group metadata.
*/
public boolean isProtectedContent(ContentName name, PublisherPublicKeyDigest publisher, ContentType contentType, CCNHandle handle) {
if (isGroupName(name)) {
// Don't encrypt the group metadata
return false;
}
return super.isProtectedContent(name, publisher, contentType, handle);
}
public boolean haveKnownGroupMemberships() {
for (GroupManager gm: _groupManager) {
if (gm.haveKnownGroupMemberships()) return true;
}
return false;
}
}
| Method to register additional user locations in GroupAccessControl
| javasrc/src/org/ccnx/ccn/profiles/security/access/group/GroupAccessControlManager.java | Method to register additional user locations in GroupAccessControl | <ide><path>avasrc/src/org/ccnx/ccn/profiles/security/access/group/GroupAccessControlManager.java
<ide> prefixToGroupManagerMap.put(pName.prefix(), gm);
<ide> }
<ide>
<add> public void registerUserStorage(ContentName userStorage) {
<add> ParameterizedName pName = new ParameterizedName("User", userStorage, null);
<add> _userStorage.add(pName);
<add> }
<add>
<ide> public GroupManager groupManager(byte[] distinguishingHash) {
<ide> GroupManager gm = hashToGroupManagerMap.get(distinguishingHash);
<ide> if (gm == null) { |
|
Java | apache-2.0 | 0583e23316016ba5d94e100407db404f19d84797 | 0 | gurbuzali/hazelcast-jet,gurbuzali/hazelcast-jet | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.pipeline;
import com.hazelcast.jet.JetException;
import com.hazelcast.jet.config.JobConfig;
import com.hazelcast.jet.config.ProcessingGuarantee;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.core.Processor.Context;
import com.hazelcast.jet.function.BiConsumerEx;
import com.hazelcast.jet.function.ConsumerEx;
import com.hazelcast.jet.function.FunctionEx;
import com.hazelcast.jet.impl.pipeline.transform.BatchSourceTransform;
import com.hazelcast.jet.impl.pipeline.transform.StreamSourceTransform;
import com.hazelcast.util.Preconditions;
import javax.annotation.Nonnull;
import java.util.List;
import static com.hazelcast.jet.core.processor.SourceProcessors.convenientSourceP;
import static com.hazelcast.jet.core.processor.SourceProcessors.convenientTimestampedSourceP;
import static com.hazelcast.jet.impl.util.Util.checkSerializable;
import static com.hazelcast.util.Preconditions.checkPositive;
/**
* Top-level class for Jet custom source builders. It is associated
* with a <em>context object</em> that holds any necessary state and
* resources you need to make your source work.
* <p>
* For further details refer to the factory methods:
* <ul>
* <li>{@link #batch(String, FunctionEx)}
* <li>{@link #timestampedStream(String, FunctionEx)}
* <li>{@link #stream(String, FunctionEx)}
* </ul>
*
* @param <C> type of the context object
*
* @since 3.0
*/
public final class SourceBuilder<C> {
private final String name;
private final FunctionEx<? super Context, ? extends C> createFn;
private FunctionEx<? super C, Object> createSnapshotFn = ctx -> null;
private BiConsumerEx<? super C, ? super List<Object>> restoreSnapshotFn = (ctx, states) -> { };
private ConsumerEx<? super C> destroyFn = ConsumerEx.noop();
private int preferredLocalParallelism;
/**
* The buffer object that the {@code fillBufferFn} gets on each call. Used
* in sources that emit items without a timestamp.
*
* @param <T> type of the emitted item
*/
public interface SourceBuffer<T> {
/**
* Returns the number of items the buffer holds.
*/
int size();
/**
* Closes the buffer, signaling that all items have been emitted. Only
* {@linkplain #batch} sources are allowed to call this method.
*
* @throws JetException if the source is a streaming source
*/
void close() throws JetException;
/**
* Adds an item to the buffer.
*/
void add(@Nonnull T item);
}
/**
* The buffer object that the {@code fillBufferFn} gets on each call. Used
* in sources that emit timestamped items.
*
* @param <T> type of the emitted item
*/
public interface TimestampedSourceBuffer<T> extends SourceBuffer<T> {
/**
* Adds an item to the buffer, assigning a timestamp to it. The timestamp
* is in milliseconds.
*/
void add(@Nonnull T item, long timestamp);
/**
* Adds an item to the buffer, assigning {@code System.currentTimeMillis()}
* to it as the timestamp.
*/
@Override
default void add(@Nonnull T item) {
add(item, System.currentTimeMillis());
}
}
private SourceBuilder(
@Nonnull String name,
@Nonnull FunctionEx<? super Context, ? extends C> createFn
) {
checkSerializable(createFn, "createFn");
this.name = name;
this.createFn = createFn;
}
/**
* Returns a fluent-API builder with which you can create a {@linkplain
* BatchSource batch source} for a Jet pipeline. The source will use
* {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it got from your {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the context object and a buffer object.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Once it has emitted all the data, {@code fillBufferFn} must call {@link
* SourceBuffer#close() buffer.close()}. This signals Jet to not call {@code
* fillBufferFn} again and at some later point it will call the {@code
* destroyFn} with the context object.
* <p>
* Unless you call {@link SourceBuilder.Batch#distributed builder.distributed()},
* Jet will create just a single processor that should emit all the data.
* If you do call it, make sure your distributed source takes care of
* splitting the data between processors. Your {@code createFn} should
* consult {@link Context#totalParallelism() processorContext.totalParallelism()}
* and {@link Context#globalProcessorIndex() processorContext.globalProcessorIndex()}.
* Jet calls it exactly once with each {@code globalProcessorIndex} from 0
* to {@code totalParallelism - 1} and each of the resulting context
* objects must emit its distinct slice of the total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* reads the lines from a single text file. Since you can't control on
* which member of the Jet cluster the source's processor will run, the
* file should be available on all members. The source emits one line per
* {@code fillBufferFn} call.
* <pre>{@code
* BatchSource<String> fileSource = SourceBuilder
* .batch("file-source", processorContext ->
* new BufferedReader(new FileReader("input.txt")))
* .<String>fillBufferFn((in, buf) -> {
* String line = in.readLine();
* if (line != null) {
* buf.add(line);
* } else {
* buf.close();
* }
* })
* .destroyFn(BufferedReader::close)
* .build();
* Pipeline p = Pipeline.create();
* BatchStage<String> srcStage = p.drawFrom(fileSource);
* }</pre>
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.Batch<Void> batch(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new Batch<Void>();
}
/**
* Returns a fluent-API builder with which you can create an {@linkplain
* StreamSource unbounded stream source} for a Jet pipeline. The source will
* use {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it got from your {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the state object and a buffer object.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Unless you call {@link SourceBuilder.Stream#distributed builder.distributed()},
* Jet will create just a single processor that should emit all the data.
* If you do call it, make sure your distributed source takes care of
* splitting the data between processors. Your {@code createFn} should
* consult {@link Context#totalParallelism() processorContext.totalParallelism()}
* and {@link Context#globalProcessorIndex() processorContext.globalProcessorIndex()}.
* Jet calls it exactly once with each {@code globalProcessorIndex} from 0
* to {@code totalParallelism - 1} and each of the resulting context objects
* must emit its distinct slice of the total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* polls a URL and emits all the lines it gets in the response:
* <pre>{@code
* StreamSource<String> socketSource = SourceBuilder
* .stream("http-source", processorContext -> HttpClients.createDefault())
* .<String>fillBufferFn((httpc, buf) -> {
* new BufferedReader(new InputStreamReader(
* httpc.execute(new HttpGet("localhost:8008"))
* .getEntity().getContent()))
* .lines()
* .forEach(buf::add);
* })
* .destroyFn(Closeable::close)
* .build();
* Pipeline p = Pipeline.create();
* StreamStage<String> srcStage = p.drawFrom(socketSource);
* }</pre>
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.Stream<Void> stream(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new Stream<Void>();
}
/**
* Returns a fluent-API builder with which you can create an {@linkplain
* StreamSource unbounded stream source} for a Jet pipeline. It will use
* {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* When emitting an item, the source can explicitly assign a timestamp to
* it. You can tell a Jet pipeline to use those timestamps by calling
* {@link StreamSourceStage#withNativeTimestamps sourceStage.withNativeTimestamps()}.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it gets from the given {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the context object and a buffer object. The
* buffer's {@link SourceBuilder.TimestampedSourceBuffer#add add()} method
* takes two arguments: the item and the timestamp in milliseconds.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Unless you call {@link SourceBuilder.TimestampedStream#distributed(int)
* builder.distributed()}, Jet will create just a single processor that
* should emit all the data. If you do call it, make sure your distributed
* source takes care of splitting the data between processors. Your {@code
* createFn} should consult {@link Context#totalParallelism()
* procContext.totalParallelism()} and {@link Context#globalProcessorIndex()
* procContext.globalProcessorIndex()}. Jet calls it exactly once with each
* {@code globalProcessorIndex} from 0 to {@code totalParallelism - 1} and
* each of the resulting context objects must emit its distinct slice of the
* total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* polls a URL and emits all the lines it gets in the response,
* interpreting the first 9 characters as the timestamp.
* <pre>{@code
* StreamSource<String> socketSource = SourceBuilder
* .timestampedStream("http-source",
* processorContext -> HttpClients.createDefault())
* .<String>fillBufferFn((httpc, buf) -> {
* new BufferedReader(new InputStreamReader(
* httpc.execute(new HttpGet("localhost:8008"))
* .getEntity().getContent()))
* .lines()
* .forEach(line -> {
* long timestamp = Long.valueOf(line.substring(0, 9));
* buf.add(line.substring(9), timestamp);
* });
* })
* .destroyFn(Closeable::close)
* .build();
* Pipeline p = Pipeline.create();
* StreamStage<String> srcStage = p.drawFrom(socketSource)
* .withNativeTimestamps(SECONDS.toMillis(5));
* }</pre>
* <p>
* <strong>NOTE:</strong> if the data source you're adapting to Jet is
* partitioned, you may run into issues with event skew between partitions
* assigned to a given parallel processor. The timestamp you get from one
* partition may be significantly behind the timestamp you already got from
* another one. If the skew is more than the allowed lag and you have
* {@linkplain StreamSourceStage#withNativeTimestamps(long) configured
* native timestamps}, you risk that the events will be late. Use a
* {@linkplain Sources#streamFromProcessorWithWatermarks custom processor}
* if you need to coalesce watermarks from multiple partitions.
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.TimestampedStream<Void> timestampedStream(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new TimestampedStream<Void>();
}
private abstract class Base<T> {
private Base() {
}
/**
* Sets the function that Jet will call when it is done cleaning up after
* an execution. It gives you the opportunity to release any resources that
* your context object may be holding. Jet also calls this function when
* the user cancels or restarts the job.
*/
@Nonnull
public Base<T> destroyFn(@Nonnull ConsumerEx<? super C> destroyFn) {
checkSerializable(destroyFn, "destroyFn");
SourceBuilder.this.destroyFn = destroyFn;
return this;
}
/**
* Declares that you're creating a distributed source. On each member of
* the cluster Jet will create as many processors as you specify with the
* {@code preferredLocalParallelism} parameter. If you call this, you must
* ensure that all the source processors are coordinated and not emitting
* duplicated data. The {@code createFn} can consult {@link
* Processor.Context#totalParallelism processorContext.totalParallelism()}
* and {@link Processor.Context#globalProcessorIndex
* processorContext.globalProcessorIndex()}. Jet calls {@code createFn}
* exactly once with each {@code globalProcessorIndex} from 0 to {@code
* totalParallelism - 1} and you can use this to make all the instances
* agree on which part of the data to emit.
* <p>
* If you don't call this method, there will be only one processor instance
* running on an arbitrary member.
*
* @param preferredLocalParallelism the requested number of processors on each cluster member
*/
@Nonnull
public Base<T> distributed(int preferredLocalParallelism) {
checkPositive(preferredLocalParallelism, "Preferred local parallelism must >= 1");
SourceBuilder.this.preferredLocalParallelism = preferredLocalParallelism;
return this;
}
/**
* Sets the function Jet calls when it's creating a snapshot of the
* current job state. This happens in all Jet jobs that have a {@linkplain
* JobConfig#setProcessingGuarantee(ProcessingGuarantee) processing
* guarantee} configured.
* <p>
* When Jet restarts a job, it first initializes your source as if starting
* a new job, and then passes the snapshot object you returned here to
* {@link FaultTolerant#restoreSnapshotFn restoreSnapshotFn}. After that it
* starts calling {@code fillBufferFn}, which must resume emitting the
* stream from the same item it was about to emit when the snapshot was
* taken.
* <p>
* The object you return must be serializable. Each source processor will
* call the function once per snapshot.
* <p>
* Here's an example of a fault-tolerant generator of an infinite sequence of
* integers:
* <pre>{@code
* StreamSource<Integer> source = SourceBuilder
* .stream("name", processorContext -> new AtomicInteger())
* .<Integer>fillBufferFn((numToEmit, buffer) -> {
* for (int i = 0; i < 100; i++) {
* buffer.add(numToEmit.getAndIncrement());
* }
* })
* .createSnapshotFn(numToEmit -> numToEmit.get())
* .restoreSnapshotFn((numToEmit, states) -> numToEmit.set(states.get(0)))
* .build();
* }</pre>
*
* @param <S> type of the snapshot object
*
* @since 3.1
*/
@Nonnull
abstract <S> FaultTolerant<? extends Base<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
);
}
private abstract class BaseNoTimestamps<T> extends Base<T> {
BiConsumerEx<? super C, ? super SourceBuffer<T>> fillBufferFn;
private BaseNoTimestamps() {
}
/**
* Sets the function that Jet will call whenever it needs more data from
* your source. The function receives the context object obtained from
* {@code createFn} and Jet's buffer object. It should add some items
* to the buffer, ideally those it can produce without making any blocking
* calls. On any given invocation the function may also choose not to add
* any items. Jet will automatically employ an exponential backoff strategy
* to avoid calling your function in a tight loop, if the previous call didn't
* add any items to the buffer.
*
* @param fillBufferFn function that fills the buffer with source data
* @param <T_NEW> type of the emitted items
* @return this builder with the item type reset to the one inferred from
* {@code fillBufferFn}
*/
@Nonnull
@SuppressWarnings("unchecked")
public <T_NEW> BaseNoTimestamps<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
checkSerializable(fillBufferFn, "fillBufferFn");
BaseNoTimestamps<T_NEW> newThis = (BaseNoTimestamps<T_NEW>) this;
newThis.fillBufferFn = fillBufferFn;
return newThis;
}
}
/**
* See {@link SourceBuilder#batch(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class Batch<T> extends BaseNoTimestamps<T> {
private Batch() {
}
/**
* {@inheritDoc}
* <p>
* Once it has emitted all the data, the function must call {@link
* SourceBuffer#close}.
*/
@Override @Nonnull
public <T_NEW> SourceBuilder<C>.Batch<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
return (Batch<T_NEW>) super.fillBufferFn(fillBufferFn);
}
@Override @Nonnull
public Batch<T> destroyFn(@Nonnull ConsumerEx<? super C> destroyFn) {
return (Batch<T>) super.destroyFn(destroyFn);
}
@Override @Nonnull
public Batch<T> distributed(int preferredLocalParallelism) {
return (Batch<T>) super.distributed(preferredLocalParallelism);
}
/**
* Builds and returns the batch source.
*/
@Nonnull
public BatchSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn must be non-null");
return new BatchSourceTransform<>(name, convenientSourceP(createFn, fillBufferFn, createSnapshotFn,
restoreSnapshotFn, destroyFn, preferredLocalParallelism, true));
}
/**
* A private method. Do not call.
*/
@Nonnull @Override
@SuppressWarnings("unchecked")
FaultTolerant createSnapshotFn(@Nonnull FunctionEx createSnapshotFn) {
throw new UnsupportedOperationException();
}
}
/**
* See {@link SourceBuilder#stream(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class Stream<T> extends BaseNoTimestamps<T> {
private Stream() {
}
@Override @Nonnull
public <T_NEW> Stream<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
return (Stream<T_NEW>) super.fillBufferFn(fillBufferFn);
}
@Override @Nonnull
public Stream<T> destroyFn(@Nonnull ConsumerEx<? super C> pDestroyFn) {
return (Stream<T>) super.destroyFn(pDestroyFn);
}
@Override @Nonnull
public Stream<T> distributed(int preferredLocalParallelism) {
return (Stream<T>) super.distributed(preferredLocalParallelism);
}
@Override @Nonnull
public <S> FaultTolerant<Stream<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
) {
return new FaultTolerant<>(this, createSnapshotFn);
}
/**
* Builds and returns the unbounded stream source.
*/
@Nonnull
public StreamSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn() wasn't called");
return new StreamSourceTransform<>(
name,
eventTimePolicy -> convenientSourceP(
createFn, fillBufferFn, createSnapshotFn, restoreSnapshotFn,
destroyFn, preferredLocalParallelism, false),
false, false);
}
}
/**
* See {@link SourceBuilder#timestampedStream(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class TimestampedStream<T> extends Base<T> {
private BiConsumerEx<? super C, ? super TimestampedSourceBuffer<T>> fillBufferFn;
private TimestampedStream() {
}
/**
* Sets the function that Jet will call whenever it needs more data from
* your source. The function receives the context object obtained from
* {@code createFn} and Jet's buffer object. It should add some items
* to the buffer, ideally those it can produce without making any blocking
* calls. The buffer's {@link SourceBuilder.TimestampedSourceBuffer#add add()}
* method takes two arguments: the item and the timestamp in milliseconds.
* <p>
* On any given invocation the function may also choose not to add
* any items. Jet will automatically employ an exponential backoff strategy
* to avoid calling your function in a tight loop, if the previous call didn't
* add any items to the buffer.
*
* @param fillBufferFn function that fills the buffer with source data
* @param <T_NEW> type of the emitted items
* @return this builder with the item type reset to the one inferred from
* {@code fillBufferFn}
*/
@Nonnull
@SuppressWarnings("unchecked")
public <T_NEW> TimestampedStream<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super TimestampedSourceBuffer<T_NEW>> fillBufferFn
) {
TimestampedStream<T_NEW> newThis = (TimestampedStream<T_NEW>) this;
newThis.fillBufferFn = fillBufferFn;
return newThis;
}
@Override @Nonnull
public TimestampedStream<T> destroyFn(@Nonnull ConsumerEx<? super C> pDestroyFn) {
return (TimestampedStream<T>) super.destroyFn(pDestroyFn);
}
@Override @Nonnull
public TimestampedStream<T> distributed(int preferredLocalParallelism) {
return (TimestampedStream<T>) super.distributed(preferredLocalParallelism);
}
@Override @Nonnull
public <S> FaultTolerant<TimestampedStream<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
) {
return new FaultTolerant<>(this, createSnapshotFn);
}
/**
* Builds and returns the timestamped stream source.
*/
@Nonnull
public StreamSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn must be set");
return new StreamSourceTransform<>(
name,
eventTimePolicy -> convenientTimestampedSourceP(createFn, fillBufferFn, eventTimePolicy,
createSnapshotFn, restoreSnapshotFn, destroyFn, preferredLocalParallelism),
true, true);
}
}
/**
* Represents a step in building a custom source where you add a {@link
* #restoreSnapshotFn} after adding a {@link Base#createSnapshotFn
* createSnapshotFn}.
*
* @param <B> type of the builder this sub-builder was created from
* @param <S> type of the object saved to the state snapshot
*
* @since 3.1
*/
public final class FaultTolerant<B, S> {
private final B parentBuilder;
@SuppressWarnings("unchecked")
private FaultTolerant(B parentBuilder, FunctionEx<? super C, ? extends S> createSnapshotFn) {
checkSerializable(createSnapshotFn, "createSnapshotFn");
this.parentBuilder = parentBuilder;
SourceBuilder.this.createSnapshotFn = (FunctionEx<? super C, Object>) createSnapshotFn;
}
/**
* Sets the function that restores the source's state from a snapshot.
* <p>
* When Jet is restarting a job after it was interrupted (failure or other
* reasons), it first initializes your source as if starting a new job and
* then passes the snapshot object (the one it got from your {@link
* Base#createSnapshotFn createSnapshotFn}) to this function. Then it
* starts calling {@code fillBufferFn}, which must resume emitting the
* stream from the same item it was about to emit when the snapshot was
* taken.
* <p>
* If your source is <em>not {@linkplain Base#distributed(int)
* distributed}</em>, the `List` in the second argument contains
* exactly 1 element; it is safe to use `get(0)` on it. If your source
* is distributed, the list will contain objects returned by {@code
* createSnapshotFn} in all parallel instances. This is why {@code
* restoreSnapshotFn} accepts a list of snapshot objects. It should
* figure out which part of the snapshot data pertains to it and it can
* do so as explained {@link Base#distributed here}.
*
* @since 3.1
*/
@SuppressWarnings("unchecked")
@Nonnull
public B restoreSnapshotFn(@Nonnull BiConsumerEx<? super C, ? super List<S>> restoreSnapshotFn) {
checkSerializable(restoreSnapshotFn, "restoreSnapshotFn");
SourceBuilder.this.restoreSnapshotFn = (BiConsumerEx<? super C, ? super List<Object>>) restoreSnapshotFn;
return parentBuilder;
}
}
}
| hazelcast-jet-core/src/main/java/com/hazelcast/jet/pipeline/SourceBuilder.java | /*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.pipeline;
import com.hazelcast.jet.JetException;
import com.hazelcast.jet.config.JobConfig;
import com.hazelcast.jet.config.ProcessingGuarantee;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.core.Processor.Context;
import com.hazelcast.jet.function.BiConsumerEx;
import com.hazelcast.jet.function.ConsumerEx;
import com.hazelcast.jet.function.FunctionEx;
import com.hazelcast.jet.impl.pipeline.transform.BatchSourceTransform;
import com.hazelcast.jet.impl.pipeline.transform.StreamSourceTransform;
import com.hazelcast.util.Preconditions;
import javax.annotation.Nonnull;
import java.util.List;
import static com.hazelcast.jet.core.processor.SourceProcessors.convenientSourceP;
import static com.hazelcast.jet.core.processor.SourceProcessors.convenientTimestampedSourceP;
import static com.hazelcast.jet.impl.util.Util.checkSerializable;
import static com.hazelcast.util.Preconditions.checkPositive;
/**
* Top-level class for Jet custom source builders. It is associated
* with a <em>context object</em> that holds any necessary state and
* resources you need to make your source work.
* <p>
* For further details refer to the factory methods:
* <ul>
* <li>{@link #batch(String, FunctionEx)}
* <li>{@link #timestampedStream(String, FunctionEx)}
* <li>{@link #stream(String, FunctionEx)}
* </ul>
*
* @param <C> type of the context object
*
* @since 3.0
*/
public final class SourceBuilder<C> {
private final String name;
private final FunctionEx<? super Context, ? extends C> createFn;
private FunctionEx<? super C, Object> createSnapshotFn = ctx -> null;
private BiConsumerEx<? super C, ? super List<Object>> restoreSnapshotFn = (ctx, states) -> { };
private ConsumerEx<? super C> destroyFn = ConsumerEx.noop();
private int preferredLocalParallelism;
/**
* The buffer object that the {@code fillBufferFn} gets on each call. Used
* in sources that emit items without a timestamp.
*
* @param <T> type of the emitted item
*/
public interface SourceBuffer<T> {
/**
* Returns the number of items the buffer holds.
*/
int size();
/**
* Closes the buffer, signaling that all items have been emitted. Only
* {@linkplain #batch} sources are allowed to call this method.
*
* @throws JetException if the source is a streaming source
*/
void close() throws JetException;
/**
* Adds an item to the buffer.
*/
void add(@Nonnull T item);
}
/**
* The buffer object that the {@code fillBufferFn} gets on each call. Used
* in sources that emit timestamped items.
*
* @param <T> type of the emitted item
*/
public interface TimestampedSourceBuffer<T> extends SourceBuffer<T> {
/**
* Adds an item to the buffer, assigning a timestamp to it. The timestamp
* is in milliseconds.
*/
void add(@Nonnull T item, long timestamp);
/**
* Adds an item to the buffer, assigning {@code System.currentTimeMillis()}
* to it as the timestamp.
*/
@Override
default void add(@Nonnull T item) {
add(item, System.currentTimeMillis());
}
}
private SourceBuilder(
@Nonnull String name,
@Nonnull FunctionEx<? super Context, ? extends C> createFn
) {
checkSerializable(createFn, "createFn");
this.name = name;
this.createFn = createFn;
}
/**
* Returns a fluent-API builder with which you can create a {@linkplain
* BatchSource batch source} for a Jet pipeline. The source will use
* {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it got from your {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the context object and a buffer object.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Once it has emitted all the data, {@code fillBufferFn} must call {@link
* SourceBuffer#close() buffer.close()}. This signals Jet to not call {@code
* fillBufferFn} again and at some later point it will call the {@code
* destroyFn} with the context object.
* <p>
* Unless you call {@link SourceBuilder.Batch#distributed builder.distributed()},
* Jet will create just a single processor that should emit all the data.
* If you do call it, make sure your distributed source takes care of
* splitting the data between processors. Your {@code createFn} should
* consult {@link Context#totalParallelism() processorContext.totalParallelism()}
* and {@link Context#globalProcessorIndex() processorContext.globalProcessorIndex()}.
* Jet calls it exactly once with each {@code globalProcessorIndex} from 0
* to {@code totalParallelism - 1} and each of the resulting context
* objects must emit its distinct slice of the total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* reads the lines from a single text file. Since you can't control on
* which member of the Jet cluster the source's processor will run, the
* file should be available on all members. The source emits one line per
* {@code fillBufferFn} call.
* <pre>{@code
* BatchSource<String> fileSource = SourceBuilder
* .batch("file-source", processorContext ->
* new BufferedReader(new FileReader("input.txt")))
* .<String>fillBufferFn((in, buf) -> {
* String line = in.readLine();
* if (line != null) {
* buf.add(line);
* } else {
* buf.close();
* }
* })
* .destroyFn(BufferedReader::close)
* .build();
* Pipeline p = Pipeline.create();
* BatchStage<String> srcStage = p.drawFrom(fileSource);
* }</pre>
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.Batch<Void> batch(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new Batch<Void>();
}
/**
* Returns a fluent-API builder with which you can create an {@linkplain
* StreamSource unbounded stream source} for a Jet pipeline. The source will
* use {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it got from your {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the state object and a buffer object.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Unless you call {@link SourceBuilder.Stream#distributed builder.distributed()},
* Jet will create just a single processor that should emit all the data.
* If you do call it, make sure your distributed source takes care of
* splitting the data between processors. Your {@code createFn} should
* consult {@link Context#totalParallelism() processorContext.totalParallelism()}
* and {@link Context#globalProcessorIndex() processorContext.globalProcessorIndex()}.
* Jet calls it exactly once with each {@code globalProcessorIndex} from 0
* to {@code totalParallelism - 1} and each of the resulting context objects
* must emit its distinct slice of the total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* polls a URL and emits all the lines it gets in the response:
* <pre>{@code
* StreamSource<String> socketSource = SourceBuilder
* .stream("http-source", processorContext -> HttpClients.createDefault())
* .<String>fillBufferFn((httpc, buf) -> {
* new BufferedReader(new InputStreamReader(
* httpc.execute(new HttpGet("localhost:8008"))
* .getEntity().getContent()))
* .lines()
* .forEach(buf::add);
* })
* .destroyFn(Closeable::close)
* .build();
* Pipeline p = Pipeline.create();
* StreamStage<String> srcStage = p.drawFrom(socketSource);
* }</pre>
* <p>
* <strong>NOTE:</strong> the source you build with this builder is not
* fault-tolerant. You shouldn't use it in jobs that require a processing
* guarantee.
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.Stream<Void> stream(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new Stream<Void>();
}
/**
* Returns a fluent-API builder with which you can create an {@linkplain
* StreamSource unbounded stream source} for a Jet pipeline. It will use
* {@linkplain Processor#isCooperative() non-cooperative} processors.
* <p>
* When emitting an item, the source can explicitly assign a timestamp to
* it. You can tell a Jet pipeline to use those timestamps by calling
* {@link StreamSourceStage#withNativeTimestamps sourceStage.withNativeTimestamps()}.
* <p>
* Each parallel processor that drives your source has its private instance
* of a <i>context object</i> it gets from the given {@code createFn}. To get
* the data items to emit to the pipeline, the processor repeatedly calls
* your {@code fillBufferFn} with the context object and a buffer object. The
* buffer's {@link SourceBuilder.TimestampedSourceBuffer#add add()} method
* takes two arguments: the item and the timestamp in milliseconds.
* <p>
* Your function should add some items to the buffer, ideally those it has
* ready without having to block. A hundred items at a time is enough to
* eliminate any per-call overheads within Jet. If it doesn't have any
* items ready, it may also return without adding anything. In any case the
* function should not take more than a second or so to complete, otherwise
* you risk interfering with Jet's coordination mechanisms and getting bad
* performance.
* <p>
* Unless you call {@link SourceBuilder.TimestampedStream#distributed(int)
* builder.distributed()}, Jet will create just a single processor that
* should emit all the data. If you do call it, make sure your distributed
* source takes care of splitting the data between processors. Your {@code
* createFn} should consult {@link Context#totalParallelism()
* procContext.totalParallelism()} and {@link Context#globalProcessorIndex()
* procContext.globalProcessorIndex()}. Jet calls it exactly once with each
* {@code globalProcessorIndex} from 0 to {@code totalParallelism - 1} and
* each of the resulting context objects must emit its distinct slice of the
* total source data.
* <p>
* Here's an example that builds a simple, non-distributed source that
* polls a URL and emits all the lines it gets in the response,
* interpreting the first 9 characters as the timestamp.
* <pre>{@code
* StreamSource<String> socketSource = SourceBuilder
* .timestampedStream("http-source",
* processorContext -> HttpClients.createDefault())
* .<String>fillBufferFn((httpc, buf) -> {
* new BufferedReader(new InputStreamReader(
* httpc.execute(new HttpGet("localhost:8008"))
* .getEntity().getContent()))
* .lines()
* .forEach(line -> {
* long timestamp = Long.valueOf(line.substring(0, 9));
* buf.add(line.substring(9), timestamp);
* });
* })
* .destroyFn(Closeable::close)
* .build();
* Pipeline p = Pipeline.create();
* StreamStage<String> srcStage = p.drawFrom(socketSource)
* .withNativeTimestamps(SECONDS.toMillis(5));
* }</pre>
* <p>
* <strong>NOTE:</strong> if the data source you're adapting to Jet is
* partitioned, you may run into issues with event skew between partitions
* assigned to a given parallel processor. The timestamp you get from one
* partition may be significantly behind the timestamp you already got from
* another one. If the skew is more than the allowed lag you have
* {@linkplain StreamSourceStage#withNativeTimestamps(long) configured},
* you risk that the events will be late. Use a {@linkplain
* Sources#streamFromProcessorWithWatermarks custom processor} if you need
* to coalesce watermarks from multiple partitions.
*
* @param name a descriptive name for the source (for diagnostic purposes)
* @param createFn a function that creates the source's context object
* @param <C> type of the context object
*
* @since 3.0
*/
@Nonnull
public static <C> SourceBuilder<C>.TimestampedStream<Void> timestampedStream(
@Nonnull String name,
@Nonnull FunctionEx<? super Processor.Context, ? extends C> createFn
) {
return new SourceBuilder<C>(name, createFn).new TimestampedStream<Void>();
}
private abstract class Base<T> {
private Base() {
}
/**
* Sets the function that Jet will call when it is done cleaning up after
* an execution. It gives you the opportunity to release any resources that
* your context object may be holding. Jet also calls this function when
* the user cancels or restarts the job.
*/
@Nonnull
public Base<T> destroyFn(@Nonnull ConsumerEx<? super C> destroyFn) {
checkSerializable(destroyFn, "destroyFn");
SourceBuilder.this.destroyFn = destroyFn;
return this;
}
/**
* Declares that you're creating a distributed source. On each member of
* the cluster Jet will create as many processors as you specify with the
* {@code preferredLocalParallelism} parameter. If you call this, you must
* ensure that all the source processors are coordinated and not emitting
* duplicated data. The {@code createFn} can consult {@link
* Processor.Context#totalParallelism processorContext.totalParallelism()}
* and {@link Processor.Context#globalProcessorIndex
* processorContext.globalProcessorIndex()}. Jet calls {@code createFn}
* exactly once with each {@code globalProcessorIndex} from 0 to {@code
* totalParallelism - 1} and you can use this to make all the instances
* agree on which part of the data to emit.
* <p>
* If you don't call this method, there will be only one processor instance
* running on an arbitrary member.
*
* @param preferredLocalParallelism the requested number of processors on each cluster member
*/
@Nonnull
public Base<T> distributed(int preferredLocalParallelism) {
checkPositive(preferredLocalParallelism, "Preferred local parallelism must >= 1");
SourceBuilder.this.preferredLocalParallelism = preferredLocalParallelism;
return this;
}
/**
* Sets the function Jet calls when it's creating a snapshot of the
* current job state. This happens in all Jet jobs that have a {@linkplain
* JobConfig#setProcessingGuarantee(ProcessingGuarantee) processing
* guarantee} configured.
* <p>
* When Jet restarts a job, it first initializes your source as if starting
* a new job, and then passes the snapshot object you returned here to
* {@link FaultTolerant#restoreSnapshotFn restoreSnapshotFn}. After that it
* starts calling {@code fillBufferFn}, which must resume emitting the
* stream from the same item it was about to emit when the snapshot was
* taken.
* <p>
* The object you return must be serializable. Each source processor will
* call the function once per snapshot.
* <p>
* Here's an example of a fault-tolerant generator of an infinite sequence of
* integers:
* <pre>{@code
* StreamSource<Integer> source = SourceBuilder
* .stream("name", processorContext -> new AtomicInteger())
* .<Integer>fillBufferFn((numToEmit, buffer) -> {
* for (int i = 0; i < 100; i++) {
* buffer.add(numToEmit.getAndIncrement());
* }
* })
* .createSnapshotFn(numToEmit -> numToEmit.get())
* .restoreSnapshotFn((numToEmit, states) -> numToEmit.set(states.get(0)))
* .build();
* }</pre>
*
* @param <S> type of the snapshot object
*
* @since 3.1
*/
@Nonnull
abstract <S> FaultTolerant<? extends Base<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
);
}
private abstract class BaseNoTimestamps<T> extends Base<T> {
BiConsumerEx<? super C, ? super SourceBuffer<T>> fillBufferFn;
private BaseNoTimestamps() {
}
/**
* Sets the function that Jet will call whenever it needs more data from
* your source. The function receives the context object obtained from
* {@code createFn} and Jet's buffer object. It should add some items
* to the buffer, ideally those it can produce without making any blocking
* calls. On any given invocation the function may also choose not to add
* any items. Jet will automatically employ an exponential backoff strategy
* to avoid calling your function in a tight loop, if the previous call didn't
* add any items to the buffer.
*
* @param fillBufferFn function that fills the buffer with source data
* @param <T_NEW> type of the emitted items
* @return this builder with the item type reset to the one inferred from
* {@code fillBufferFn}
*/
@Nonnull
@SuppressWarnings("unchecked")
public <T_NEW> BaseNoTimestamps<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
checkSerializable(fillBufferFn, "fillBufferFn");
BaseNoTimestamps<T_NEW> newThis = (BaseNoTimestamps<T_NEW>) this;
newThis.fillBufferFn = fillBufferFn;
return newThis;
}
}
/**
* See {@link SourceBuilder#batch(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class Batch<T> extends BaseNoTimestamps<T> {
private Batch() {
}
/**
* {@inheritDoc}
* <p>
* Once it has emitted all the data, the function must call {@link
* SourceBuffer#close}.
*/
@Override @Nonnull
public <T_NEW> SourceBuilder<C>.Batch<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
return (Batch<T_NEW>) super.fillBufferFn(fillBufferFn);
}
@Override @Nonnull
public Batch<T> destroyFn(@Nonnull ConsumerEx<? super C> destroyFn) {
return (Batch<T>) super.destroyFn(destroyFn);
}
@Override @Nonnull
public Batch<T> distributed(int preferredLocalParallelism) {
return (Batch<T>) super.distributed(preferredLocalParallelism);
}
/**
* Builds and returns the batch source.
*/
@Nonnull
public BatchSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn must be non-null");
return new BatchSourceTransform<>(name, convenientSourceP(createFn, fillBufferFn, createSnapshotFn,
restoreSnapshotFn, destroyFn, preferredLocalParallelism, true));
}
/**
* A private method. Do not call.
*/
@Nonnull @Override
@SuppressWarnings("unchecked")
FaultTolerant createSnapshotFn(@Nonnull FunctionEx createSnapshotFn) {
throw new UnsupportedOperationException();
}
}
/**
* See {@link SourceBuilder#stream(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class Stream<T> extends BaseNoTimestamps<T> {
private Stream() {
}
@Override @Nonnull
public <T_NEW> Stream<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super SourceBuffer<T_NEW>> fillBufferFn
) {
return (Stream<T_NEW>) super.fillBufferFn(fillBufferFn);
}
@Override @Nonnull
public Stream<T> destroyFn(@Nonnull ConsumerEx<? super C> pDestroyFn) {
return (Stream<T>) super.destroyFn(pDestroyFn);
}
@Override @Nonnull
public Stream<T> distributed(int preferredLocalParallelism) {
return (Stream<T>) super.distributed(preferredLocalParallelism);
}
@Override @Nonnull
public <S> FaultTolerant<Stream<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
) {
return new FaultTolerant<>(this, createSnapshotFn);
}
/**
* Builds and returns the unbounded stream source.
*/
@Nonnull
public StreamSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn() wasn't called");
return new StreamSourceTransform<>(
name,
eventTimePolicy -> convenientSourceP(
createFn, fillBufferFn, createSnapshotFn, restoreSnapshotFn,
destroyFn, preferredLocalParallelism, false),
false, false);
}
}
/**
* See {@link SourceBuilder#timestampedStream(String, FunctionEx)}.
*
* @param <T> type of emitted objects
*
* @since 3.0
*/
public final class TimestampedStream<T> extends Base<T> {
private BiConsumerEx<? super C, ? super TimestampedSourceBuffer<T>> fillBufferFn;
private TimestampedStream() {
}
/**
* Sets the function that Jet will call whenever it needs more data from
* your source. The function receives the context object obtained from
* {@code createFn} and Jet's buffer object. It should add some items
* to the buffer, ideally those it can produce without making any blocking
* calls. The buffer's {@link SourceBuilder.TimestampedSourceBuffer#add add()}
* method takes two arguments: the item and the timestamp in milliseconds.
* <p>
* On any given invocation the function may also choose not to add
* any items. Jet will automatically employ an exponential backoff strategy
* to avoid calling your function in a tight loop, if the previous call didn't
* add any items to the buffer.
*
* @param fillBufferFn function that fills the buffer with source data
* @param <T_NEW> type of the emitted items
* @return this builder with the item type reset to the one inferred from
* {@code fillBufferFn}
*/
@Nonnull
@SuppressWarnings("unchecked")
public <T_NEW> TimestampedStream<T_NEW> fillBufferFn(
@Nonnull BiConsumerEx<? super C, ? super TimestampedSourceBuffer<T_NEW>> fillBufferFn
) {
TimestampedStream<T_NEW> newThis = (TimestampedStream<T_NEW>) this;
newThis.fillBufferFn = fillBufferFn;
return newThis;
}
@Override @Nonnull
public TimestampedStream<T> destroyFn(@Nonnull ConsumerEx<? super C> pDestroyFn) {
return (TimestampedStream<T>) super.destroyFn(pDestroyFn);
}
@Override @Nonnull
public TimestampedStream<T> distributed(int preferredLocalParallelism) {
return (TimestampedStream<T>) super.distributed(preferredLocalParallelism);
}
@Override @Nonnull
public <S> FaultTolerant<TimestampedStream<T>, S> createSnapshotFn(
@Nonnull FunctionEx<? super C, ? extends S> createSnapshotFn
) {
return new FaultTolerant<>(this, createSnapshotFn);
}
/**
* Builds and returns the timestamped stream source.
*/
@Nonnull
public StreamSource<T> build() {
Preconditions.checkNotNull(fillBufferFn, "fillBufferFn must be set");
return new StreamSourceTransform<>(
name,
eventTimePolicy -> convenientTimestampedSourceP(createFn, fillBufferFn, eventTimePolicy,
createSnapshotFn, restoreSnapshotFn, destroyFn, preferredLocalParallelism),
true, true);
}
}
/**
* Represents a step in building a custom source where you add a {@link
* #restoreSnapshotFn} after adding a {@link Base#createSnapshotFn
* createSnapshotFn}.
*
* @param <B> type of the builder this sub-builder was created from
* @param <S> type of the object saved to the state snapshot
*
* @since 3.1
*/
public final class FaultTolerant<B, S> {
private final B parentBuilder;
@SuppressWarnings("unchecked")
private FaultTolerant(B parentBuilder, FunctionEx<? super C, ? extends S> createSnapshotFn) {
checkSerializable(createSnapshotFn, "createSnapshotFn");
this.parentBuilder = parentBuilder;
SourceBuilder.this.createSnapshotFn = (FunctionEx<? super C, Object>) createSnapshotFn;
}
/**
* Sets the function that restores the source's state from a snapshot.
* <p>
* When Jet is restarting a job after it was interrupted (failure or other
* reasons), it first initializes your source as if starting a new job and
* then passes the snapshot object (the one it got from your {@link
* Base#createSnapshotFn createSnapshotFn}) to this function. Then it
* starts calling {@code fillBufferFn}, which must resume emitting the
* stream from the same item it was about to emit when the snapshot was
* taken.
* <p>
* If your source is <em>not {@linkplain Base#distributed(int)
* distributed}</em>, the `List` in the second argument contains
* exactly 1 element; it is safe to use `get(0)` on it. If your source
* is distributed, the list will contain objects returned by {@code
* createSnapshotFn} in all parallel instances. This is why {@code
* restoreSnapshotFn} accepts a list of snapshot objects. It should
* figure out which part of the snapshot data pertains to it and it can
* do so as explained {@link Base#distributed here}.
*
* @since 3.1
*/
@SuppressWarnings("unchecked")
@Nonnull
public B restoreSnapshotFn(@Nonnull BiConsumerEx<? super C, ? super List<S>> restoreSnapshotFn) {
checkSerializable(restoreSnapshotFn, "restoreSnapshotFn");
SourceBuilder.this.restoreSnapshotFn = (BiConsumerEx<? super C, ? super List<Object>>) restoreSnapshotFn;
return parentBuilder;
}
}
}
| Fix SourceBuilder's javadoc (#1553)
Fixes #1550 | hazelcast-jet-core/src/main/java/com/hazelcast/jet/pipeline/SourceBuilder.java | Fix SourceBuilder's javadoc (#1553) | <ide><path>azelcast-jet-core/src/main/java/com/hazelcast/jet/pipeline/SourceBuilder.java
<ide> * Pipeline p = Pipeline.create();
<ide> * StreamStage<String> srcStage = p.drawFrom(socketSource);
<ide> * }</pre>
<del> * <p>
<del> * <strong>NOTE:</strong> the source you build with this builder is not
<del> * fault-tolerant. You shouldn't use it in jobs that require a processing
<del> * guarantee.
<ide> *
<ide> * @param name a descriptive name for the source (for diagnostic purposes)
<ide> * @param createFn a function that creates the source's context object
<ide> * partitioned, you may run into issues with event skew between partitions
<ide> * assigned to a given parallel processor. The timestamp you get from one
<ide> * partition may be significantly behind the timestamp you already got from
<del> * another one. If the skew is more than the allowed lag you have
<del> * {@linkplain StreamSourceStage#withNativeTimestamps(long) configured},
<del> * you risk that the events will be late. Use a {@linkplain
<del> * Sources#streamFromProcessorWithWatermarks custom processor} if you need
<del> * to coalesce watermarks from multiple partitions.
<add> * another one. If the skew is more than the allowed lag and you have
<add> * {@linkplain StreamSourceStage#withNativeTimestamps(long) configured
<add> * native timestamps}, you risk that the events will be late. Use a
<add> * {@linkplain Sources#streamFromProcessorWithWatermarks custom processor}
<add> * if you need to coalesce watermarks from multiple partitions.
<ide> *
<ide> * @param name a descriptive name for the source (for diagnostic purposes)
<ide> * @param createFn a function that creates the source's context object |
|
Java | mit | 496a86916773dd7b4eafd9d5e86f8412185a27e6 | 0 | ampotty/uip-pc2,ampotty/uip-pc2,ampotty/uip-pc2 | import java.io.BufferedReader;
import java.io.InputStreamReader;
class Carro {
private String marca;
private String modelo;
private int tanque_gasolina;
public void arrancar() {
System.out.println("Arranco el carro");
}
public double avanzar(double t, double v) {
if ( this.tanque_gasolina > 0 ) {
this.tanque_gasolina -= t*v/10;
return t*v;
} else {
// Se detiene y se apago
return 0.0;
}
}
} | Ejemplos/ejemplo53/Carro.java | import java.io.BufferedReader;
import java.io.InputStreamReader;
class Carro {
private String marca;
private String modelo;
private int tanque_gasolina;
public void arrancar() {
System.out.println("Arranco el carro");
}
public int avanzar() {
if ( this.tanque_gasolina > 0 ) {
System.out.println("Avanzo el carro");
double tiempo, velocidad, distancia;
BufferedReader x = new BufferedReader(
new InputStreamReader(System.in));
tiempo = Double.parseDouble(x.readLine());
velocidad = Double.parseDouble(x.readLine());
distancia = tiempo * velocidad;
}
return 0;
}
} | Una frase por ahí
| Ejemplos/ejemplo53/Carro.java | Una frase por ahí | <ide><path>jemplos/ejemplo53/Carro.java
<ide> System.out.println("Arranco el carro");
<ide> }
<ide>
<del> public int avanzar() {
<add> public double avanzar(double t, double v) {
<ide> if ( this.tanque_gasolina > 0 ) {
<del> System.out.println("Avanzo el carro");
<del> double tiempo, velocidad, distancia;
<del> BufferedReader x = new BufferedReader(
<del> new InputStreamReader(System.in));
<del> tiempo = Double.parseDouble(x.readLine());
<del> velocidad = Double.parseDouble(x.readLine());
<del> distancia = tiempo * velocidad;
<add> this.tanque_gasolina -= t*v/10;
<add> return t*v;
<add> } else {
<add> // Se detiene y se apago
<add> return 0.0;
<ide> }
<del> return 0;
<ide> }
<ide>
<ide> } |
|
JavaScript | isc | ff7627f275c4d77c169319afe0487c5b92c0fb98 | 0 | vyuh/sud | //'use strict';
(function () {
var pk = {};
function scope_gen(n) {
// for normal sudoku latin square, n is 3
// a latin square has n^4 cells
var i, j, r, c, gr, gc, l, p;
var out = [];
l = n * n * n * n;
/* malloc from stdlib.h */
for (i = 0; i < l; i++) {
var scope = new Array(l);
r = Math.floor(i / (n * n));
c = i % (n * n);
gr = Math.floor(r / n) * n;
gc = Math.floor(c / n) * n;
for (j = 0; j < n * n; j++) {
scope[r * n * n + j] = true;
scope[j * n * n + c] = true;
scope[(gr + Math.floor(j / n)) * n * n + gc + j %
n] = true;
}
scope[i] = false;
var eye = [];
for (j = 0; j < l; j++)
if (scope[j]) {
eye.push(j);
}
out.push(eye);
}
return out;
}
//the cell class
pk.cell = function (i) {
//cell object constructor
if (i) {
if (typeof i === "object") {
this.v = i.v;
} else {
var idea = i - 1;
if ((idea < 9) && (idea >= 0)) {
this.putIdea(idea);
} else {
this.v = 0x7fe7;
}
}
} else {
this.v = 0x7fe7;
}
};
pk.cell.prototype.putIdea = function (idea) {
this.v = (idea | pk.open | pk.may_b[idea]);
};
pk.cell.prototype.copyIn = function (i) {
this.v = i.v;
};
pk.cell.prototype.txt = function () {
return this.v.toString();
};
pk.cell.prototype.yo = function (mask) {
return ((this.v & mask) !== 0);
};
pk.cell.prototype.reset = function (mask) {
//reset the mask
this.v &= ~mask;
};
pk.cell.prototype.value = function () {
//value of an open or filled cell
return (this.v & pk.data);
};
pk.cell.prototype.rm = function (i) {
// returns success or failure (false or true respectively)
if (this.yo(pk.may_b[i])) {
//has it in probable
if (!this.yo(pk.wait)) {
return true;
// it is the only probable!!
}
this.reset(pk.may_b[i]);
this.v -= 1;
if (this.yo(pk.open)) {
// only one probable left now
for (i = 0; i < 9; i += 1) {
if (this.yo(pk.may_b[i])) {
break;
}
}
this.putIdea(i);
}
}
return false;
//removed ok
};
pk.cell.prototype.trial = function (i) {
// returns trial value or >=9 if no trial available
for (; i < 9; i += 1) {
if (this.yo(pk.may_b[i])) {
break;
}
}
return i;
};
//the package globals
pk.wait = 0x20;
pk.open = 0x10;
pk.data = 0xf;
pk.may_b = [
0x4000, 0x2000, 0x1000,
0x0800, 0x0400, 0x0200,
0x0100, 0x0080, 0x0040
];
pk.clr = scope_gen(3);
//the sud class. models a sudoku
pk.sud = function (inp) {
if (inp) {
if (typeof inp === "object") {
this.left = inp.left;
this.i_v = [];
for (var i = 0; i < 81; i += 1) {
this.i_v[i] = new pk.cell(inp.i_v[i]);
}
return;
} else inp = inp.toString()
} else inp = '123456789'
var len = inp.length
this.left = 81
this.i_v = []
var i = 0
for (; i < len && i < 81; i += 1) {
this.i_v[i] = new pk.cell(inp.charAt(i))
}
for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
arguments.callee.__out__ = []
}
pk.sud.prototype.copyIn = function (t) {
this.left = t.left;
for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
i]);
}
pk.sud.prototype.first = function () {
// first waiting cell or >=81; for ordered listing of solutions
var i = 0
for (; i < 81; i += 1) {
if (this.i_v[i].yo(pk.wait)) {
break;
}
}
return i
}
pk.sud.prototype.idea = function () {
//first open cell or >=81
var i = 0
for (; i < 81; i += 1) {
if (this.i_v[i].yo(pk.open)) {
break
}
}
return i
}
pk.sud.prototype.toString = function () {
var buf = ''
for (var i = 0; i < 81; i += 1) {
if (this.i_v[i].yo(pk.cell.open)) {
buf += '?';
} else {
buf += (1 + this.i_v[i].value());
}
}
return buf;
}
pk.sud.prototype.hook = function () {
// returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
var x, pos, val
while ((pos = this.idea()) < 81) {
val = this.i_v[pos].value()
for (x = 0; x < 20; x += 1) {
if (this.i_v[pk.clr[pos][x]].rm(val)) {
return -1;
}
}
this.i_v[pos].reset(pk.open)
if ((this.left -= 1) === 0) {
this.constructor.__out__.push(this.toString())
return this.constructor.__out__.length === this.constructor
.__n__ ? 2 : 1;
}
}
return 0
}
pk.sud.prototype.crook = function () {
var mc, cc, pos, val = 0
var copy = new pk.sud(this)
if ((pos = this.first()) < 81) {
mc = this.i_v[pos]
cc = copy.i_v[pos]
} else return 1
while ((val = mc.trial(val)) < 9) {
copy.copyIn(this)
cc.putIdea(val)
switch (copy.squash()) {
case 1:
val += 1
break
case 2:
return 2
case -1:
mc.rm(val) // should i check?
if (
((pos = this.idea()) < 81)
&&
(this.i_v[pos].value() > val)
) {
copy = null
return 0
}
}
}
copy = null
return 1
}
pk.sud.prototype.squash = function () {
var ret
do
if ((ret = this.hook()) !== 0) return ret;
while (0 === (ret = this.crook())) return ret
}
//the list class. subclass of sud.
//solution lister engine
//an iterator
pk.list = function (inp) {
// calling superclass constructor
pk.sud.call(this, inp)
this.status = function (ls, pos, val) {
this.l = new pk.list(ls)
this.p = pos
this.v = val
}
if (typeof inp === 'object') return
pk.nxt = []
switch (this.squash()) {
case -1:
break
case 2:
}
}
// subclass extends superclass
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
pk.list.prototype = Object.create(pk.sud.prototype)
pk.list.prototype.constructor = pk.list
pk.list.prototype.hook = function () {
// returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
var x, pos, val
if (pk.stata) {
if (pk.stata.length === 0) {
delete pk.stata
return 1
} else return 0
}
while ((pos = this.idea()) < 81) {
val = this.i_v[pos].value()
for (x = 0; x < 20; x += 1) {
if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
} // try removing braces
this.i_v[pos].reset(pk.open)
if ((this.left -= 1) === 0) {
pk.nxt.push(this.toString())
if (pk.nxt.length === pk.n) {
pk.stata = []
// i hope empty array is true in js
return 2
} else return 1
}
}
return 0
}
pk.list.prototype.crook = function () {
var mc, cc, pos, val = 0,
copy
if (pk.stata) {
copy = pk.stata.pop();
mc = this.i_v[copy.p];
cc = copy.l.i_v[copy.p];
} else {
if ((pos = this.first()) >= 81) return 1
else {
copy = new this.status(this, pos, 0)
mc = this.i_v[copy.p]
cc = copy.l.i_v[copy.p]
}
}
while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
if (!pk.stata) {
copy.l.copyIn(this);
cc.putIdea(copy.v);
}
switch (copy.l.squash()) {
case 1:
copy.v += 1;
break;
case 2:
pk.stata.push(copy);
return 2;
case -1:
mc.rm(copy.v); /* should i check? */
if (
((pos = this.idea()) < 81) && (this.i_v[pos].value() >
copy.v)) return 0
}
}
return 1
}
pk.list.prototype.next = function () {
if (pk.nxt.length === 0) return undefined
pk.out = pk.nxt
pk.nxt = []
this.squash()
return pk.out
}
pk.list.prototype.hasNext = function () {
return pk.nxt.length !== 0;
}
//exports
module.exports.iter = function (constraints, n) {
pk.n = n || 2
return new pk.list(constraints)
}
module.exports.list = function (constraints, n) {
var master = new pk.sud(constraints)
master.constructor.__n__ = n || 2;
switch (master.squash()) {
case -1:
console.log("no solution")
break
case 2:
}
return master.constructor.__out__
}
})();
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
| sud.js | //'use strict';
(function () {
var pk = {};
//to not clutter global namespace. pk picks the rags ;)
function scope_gen(n) {
// for normal sudoku latin square, n is 3
// a latin square has n^4 cells
var i, j, r, c, gr, gc, l, p;
var out = [];
l = n * n * n * n;
/* malloc from stdlib.h */
for (i = 0; i < l; i++) {
var scope = new Array(l);
r = Math.floor(i / (n * n));
c = i % (n * n);
gr = Math.floor(r / n) * n;
gc = Math.floor(c / n) * n;
for (j = 0; j < n * n; j++) {
scope[r * n * n + j] = true;
scope[j * n * n + c] = true;
scope[(gr + Math.floor(j / n)) * n * n + gc + j %
n] = true;
}
scope[i] = false;
var eye = [];
for (j = 0; j < l; j++)
if (scope[j]) {
eye.push(j);
}
out.push(eye);
}
return out;
}
//the cell class
pk.cell = function (i) {
//cell object constructor
if (i) {
if (typeof i === "object") {
this.v = i.v;
} else {
var idea = i - 1;
if ((idea < 9) && (idea >= 0)) {
this.putIdea(idea);
} else {
this.v = 0x7fe7;
}
}
} else {
this.v = 0x7fe7;
}
};
pk.cell.prototype.putIdea = function (idea) {
this.v = (idea | pk.open | pk.may_b[idea]);
};
pk.cell.prototype.copyIn = function (i) {
this.v = i.v;
};
pk.cell.prototype.txt = function () {
return this.v.toString();
};
pk.cell.prototype.yo = function (mask) {
return ((this.v & mask) !== 0);
};
pk.cell.prototype.reset = function (mask) { //reset the mask
this.v &= ~mask;
};
pk.cell.prototype.value = function () { //value of an open or filled cell
return (this.v & pk.data);
};
pk.cell.prototype.rm = function (i) { // returns success or failure (false or true respectively)
if (this.yo(pk.may_b[i])) { //has it in probable
if (!this.yo(pk.wait)) {
return true; // it is the only probable!!
}
this.reset(pk.may_b[i]);
this.v -= 1;
if (this.yo(pk.open)) { // only one probable left now
for (i = 0; i < 9; i += 1) {
if (this.yo(pk.may_b[i])) {
break;
}
}
this.putIdea(i);
}
}
return false; //removed ok
};
pk.cell.prototype.trial = function (i) { // returns trial value or >=9 if no trial available
for (; i < 9; i += 1) {
if (this.yo(pk.may_b[i])) {
break;
}
}
return i;
};
//the package globals
pk.wait = 0x20;
pk.open = 0x10;
pk.data = 0xf;
pk.may_b = [
0x4000, 0x2000, 0x1000,
0x0800, 0x0400, 0x0200,
0x0100, 0x0080, 0x0040
];
pk.clr = scope_gen(3);
//the sud class. models a sudoku
pk.sud = function (inp) {
if (inp) {
if (typeof inp === "object") {
this.left = inp.left;
this.i_v = [];
for (var i = 0; i < 81; i += 1) {
this.i_v[i] = new pk.cell(inp.i_v[i]);
}
return;
} else inp = inp.toString()
} else inp = '123456789'
var len = inp.length
this.left = 81
this.i_v = []
var i = 0
for (; i < len && i < 81; i += 1) {
this.i_v[i] = new pk.cell(inp.charAt(i))
}
for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
arguments.callee.__out__ = []
}
pk.sud.prototype.copyIn = function (t) {
this.left = t.left;
for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
i]);
}
pk.sud.prototype.first = function () {
// first waiting cell or >=81; for ordered listing of solutions
var i = 0
for (; i < 81; i += 1) {
if (this.i_v[i].yo(pk.wait)) {
break;
}
}
return i
}
pk.sud.prototype.idea = function () {
//first open cell or >=81
var i = 0
for (; i < 81; i += 1) {
if (this.i_v[i].yo(pk.open)) {
break
}
}
return i
}
pk.sud.prototype.toString = function () {
var buf = ''
for (var i = 0; i < 81; i += 1) {
if (this.i_v[i].yo(pk.cell.open)) {
buf += '?';
} else {
buf += (1 + this.i_v[i].value());
}
}
return buf;
}
pk.sud.prototype.hook = function () {
// returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
var x, pos, val
while ((pos = this.idea()) < 81) {
val = this.i_v[pos].value()
for (x = 0; x < 20; x += 1) {
if (this.i_v[pk.clr[pos][x]].rm(val)) {
return -1;
}
}
this.i_v[pos].reset(pk.open)
if ((this.left -= 1) === 0) {
this.constructor.__out__.push(this.toString())
return this.constructor.__out__.length === this.constructor
.__n__ ? 2 : 1;
}
}
return 0
}
pk.sud.prototype.crook = function () {
var mc, cc, pos, val = 0
var copy = new pk.sud(this)
if ((pos = this.first()) < 81) {
mc = this.i_v[pos]
cc = copy.i_v[pos]
} else return 1
while ((val = mc.trial(val)) < 9) {
copy.copyIn(this)
cc.putIdea(val)
switch (copy.squash()) {
case 1:
val += 1
break
case 2:
return 2
case -1:
mc.rm(val) // should i check?
if (((pos = this.idea()) < 81) && (this.i_v[pos].value() >
val)) {
copy = null
return 0
}
}
}
copy = null
return 1
}
pk.sud.prototype.squash = function () {
var ret
do
if ((ret = this.hook()) !== 0) return ret;
while (0 === (ret = this.crook())) return ret
}
//the list class. subclass of sud.
//solution lister engine
//an iterator
pk.list = function (inp) {
// calling superclass constructor
pk.sud.call(this, inp)
this.status = function (ls, pos, val) {
this.l = new pk.list(ls)
this.p = pos
this.v = val
}
if (typeof inp === 'object') return
pk.nxt = []
switch (this.squash()) {
case -1:
break
case 2:
}
}
// subclass extends superclass
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
pk.list.prototype = Object.create(pk.sud.prototype)
pk.list.prototype.constructor = pk.list
pk.list.prototype.hook = function () {
// returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
var x, pos, val
if (pk.stata) {
if (pk.stata.length === 0) {
delete pk.stata
return 1
} else return 0
}
while ((pos = this.idea()) < 81) {
val = this.i_v[pos].value()
for (x = 0; x < 20; x += 1) {
if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
} // try removing braces
this.i_v[pos].reset(pk.open)
if ((this.left -= 1) === 0) {
pk.nxt.push(this.toString())
if (pk.nxt.length === pk.n) {
pk.stata = [] // i hope empty array is true in js
return 2
} else return 1
}
}
return 0
}
pk.list.prototype.crook = function () {
var mc, cc, pos, val = 0,
copy
if (pk.stata) {
copy = pk.stata.pop();
mc = this.i_v[copy.p];
cc = copy.l.i_v[copy.p];
} else {
if ((pos = this.first()) >= 81) return 1
else {
copy = new this.status(this, pos, 0)
mc = this.i_v[copy.p]
cc = copy.l.i_v[copy.p]
}
}
while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
if (!pk.stata) {
copy.l.copyIn(this);
cc.putIdea(copy.v);
}
switch (copy.l.squash()) {
case 1:
copy.v += 1;
break;
case 2:
pk.stata.push(copy);
return 2;
case -1:
mc.rm(copy.v); /* should i check? */
if (
((pos = this.idea()) < 81) && (this.i_v[pos].value() >
copy.v)) return 0
}
}
return 1
}
pk.list.prototype.next = function () {
if (pk.nxt.length === 0) return undefined
pk.out = pk.nxt
pk.nxt = []
this.squash()
return pk.out
}
pk.list.prototype.hasNext = function () {
return pk.nxt.length !== 0;
}
//exports
module.exports.iter = function (constraints, n) {
pk.n = n || 2
return new pk.list(constraints)
}
module.exports.list = function (constraints, n) {
var master = new pk.sud(constraints)
master.constructor.__n__ = n || 2;
switch (master.squash()) {
case -1:
console.log("no solution")
break
case 2:
}
return master.constructor.__out__
}
})();
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
| some manual prettify
| sud.js | some manual prettify | <ide><path>ud.js
<ide> //'use strict';
<ide> (function () {
<ide> var pk = {};
<del> //to not clutter global namespace. pk picks the rags ;)
<add>
<ide> function scope_gen(n) {
<ide> // for normal sudoku latin square, n is 3
<ide> // a latin square has n^4 cells
<ide> pk.cell.prototype.yo = function (mask) {
<ide> return ((this.v & mask) !== 0);
<ide> };
<del> pk.cell.prototype.reset = function (mask) { //reset the mask
<add> pk.cell.prototype.reset = function (mask) {
<add> //reset the mask
<ide> this.v &= ~mask;
<ide> };
<del> pk.cell.prototype.value = function () { //value of an open or filled cell
<add> pk.cell.prototype.value = function () {
<add> //value of an open or filled cell
<ide> return (this.v & pk.data);
<ide> };
<del> pk.cell.prototype.rm = function (i) { // returns success or failure (false or true respectively)
<del> if (this.yo(pk.may_b[i])) { //has it in probable
<add> pk.cell.prototype.rm = function (i) {
<add> // returns success or failure (false or true respectively)
<add> if (this.yo(pk.may_b[i])) {
<add> //has it in probable
<ide> if (!this.yo(pk.wait)) {
<del> return true; // it is the only probable!!
<add> return true;
<add> // it is the only probable!!
<ide> }
<ide> this.reset(pk.may_b[i]);
<ide> this.v -= 1;
<del> if (this.yo(pk.open)) { // only one probable left now
<add> if (this.yo(pk.open)) {
<add> // only one probable left now
<ide> for (i = 0; i < 9; i += 1) {
<ide> if (this.yo(pk.may_b[i])) {
<ide> break;
<ide> this.putIdea(i);
<ide> }
<ide> }
<del> return false; //removed ok
<del> };
<del> pk.cell.prototype.trial = function (i) { // returns trial value or >=9 if no trial available
<add> return false;
<add> //removed ok
<add> };
<add> pk.cell.prototype.trial = function (i) {
<add> // returns trial value or >=9 if no trial available
<ide> for (; i < 9; i += 1) {
<ide> if (this.yo(pk.may_b[i])) {
<ide> break;
<ide> return 2
<ide> case -1:
<ide> mc.rm(val) // should i check?
<del> if (((pos = this.idea()) < 81) && (this.i_v[pos].value() >
<del> val)) {
<add> if (
<add> ((pos = this.idea()) < 81)
<add> &&
<add> (this.i_v[pos].value() > val)
<add> ) {
<ide> copy = null
<ide> return 0
<ide> }
<ide> if ((this.left -= 1) === 0) {
<ide> pk.nxt.push(this.toString())
<ide> if (pk.nxt.length === pk.n) {
<del> pk.stata = [] // i hope empty array is true in js
<add> pk.stata = []
<add> // i hope empty array is true in js
<ide> return 2
<ide> } else return 1
<ide> } |
|
JavaScript | mit | 295ff4d0c9c05c7eb08674bd4656431e3fc60961 | 0 | gavinhungry/debugger.io,gavinhungry/debugger.io | module.exports = function(grunt) {
grunt.file.defaultEncoding = 'utf8';
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-yui-compressor');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-git-describe');
grunt.initConfig({
'requirejs': {
production: {
options: {
baseUrl: './public/src/js',
mainConfigFile: './public/src/js/require.config.js',
name: 'main',
out: './public/js/debuggerio.min.js',
pragmas: { bustCache: true },
findNestedDependencies: true,
preserveLicenseComments: true,
useStrict: true,
paths: {
jqueryjs: 'empty:',
underscorejs: 'empty:',
backbonejs: 'empty:',
codemirrorjs: 'empty:',
ui: 'empty:',
transit: 'empty:',
nano: 'empty:',
hammer: 'empty:',
string: 'empty:',
marked: 'empty:',
less: 'empty:',
sass: 'empty:',
coffeescript: 'empty:',
typescript: 'empty:',
gorillascript: 'empty:',
traceur: 'empty:',
codemirror_overlay: 'empty:',
codemirror_search: 'empty:',
codemirror_xml: 'empty:',
codemirror_html: 'empty:',
codemirror_markdown: 'empty:',
codemirror_gfm: 'empty:',
codemirror_css: 'empty:',
codemirror_less: 'empty:',
codemirror_js: 'empty:',
codemirror_coffeescript: 'empty:'
},
exclude: ['promise', 'inflection', 'typestring', 'traceur_api']
}
}
},
'less': {
production: {
options: { cleancss: true },
files: {
'public/css/debuggerio.light.min.css':
'public/src/less/debuggerio.light.less',
'public/css/debuggerio.dark.min.css':
'public/src/less/debuggerio.dark.less'
}
}
},
'cssmin': {
production: {
src: ['server/static/css/gfm.css'],
dest: 'server/static/css/gfm.min.css'
}
},
'clean': {
build: ['build.json'],
js: ['public/js'],
css: [
'public/css',
'server/static/css/gfm.min.css'
]
},
'git-describe': {
production: {
options: {
template: '{%=object%}',
}
}
}
});
grunt.task.registerTask('rev', function() {
grunt.event.once('git-describe', function (rev) {
grunt.file.write('./build.json', JSON.stringify({
date: grunt.template.date(new Date(), 'isoUtcDateTime'),
rev: rev.toString()
}));
});
grunt.task.run('git-describe');
});
grunt.registerTask('default', [
'clean', 'requirejs', 'less', 'cssmin', 'rev'
]);
};
| Gruntfile.js | module.exports = function(grunt) {
grunt.file.defaultEncoding = 'utf8';
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-yui-compressor');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-git-describe');
grunt.initConfig({
'requirejs': {
production: {
options: {
baseUrl: './public/src/js',
mainConfigFile: './public/src/js/require.config.js',
name: 'main',
out: './public/js/debuggerio.min.js',
pragmas: { bustCache: true },
findNestedDependencies: true,
preserveLicenseComments: true,
useStrict: true,
paths: {
jqueryjs: 'empty:',
underscorejs: 'empty:',
backbonejs: 'empty:',
codemirrorjs: 'empty:',
ui: 'empty:',
transit: 'empty:',
nano: 'empty:',
hammer: 'empty:',
string: 'empty:',
marked: 'empty:',
less: 'empty:',
coffeescript: 'empty:',
codemirror_overlay: 'empty:',
codemirror_search: 'empty:',
codemirror_xml: 'empty:',
codemirror_html: 'empty:',
codemirror_markdown: 'empty:',
codemirror_gfm: 'empty:',
codemirror_css: 'empty:',
codemirror_less: 'empty:',
codemirror_js: 'empty:',
codemirror_coffeescript: 'empty:'
},
exclude: [
'promise', 'inflection', 'sass', 'typescript', 'typestring',
'gorillascript', 'traceur', 'traceur-api'
]
}
}
},
'less': {
production: {
options: { cleancss: true },
files: {
'public/css/debuggerio.light.min.css':
'public/src/less/debuggerio.light.less',
'public/css/debuggerio.dark.min.css':
'public/src/less/debuggerio.dark.less'
}
}
},
'cssmin': {
production: {
src: ['server/static/css/gfm.css'],
dest: 'server/static/css/gfm.min.css'
}
},
'clean': {
build: ['build.json'],
js: ['public/js'],
css: [
'public/css',
'server/static/css/gfm.min.css'
]
},
'git-describe': {
production: {
options: {
template: '{%=object%}',
}
}
}
});
grunt.task.registerTask('rev', function() {
grunt.event.once('git-describe', function (rev) {
grunt.file.write('./build.json', JSON.stringify({
date: grunt.template.date(new Date(), 'isoUtcDateTime'),
rev: rev.toString()
}));
});
grunt.task.run('git-describe');
});
grunt.registerTask('default', [
'clean', 'requirejs', 'less', 'cssmin', 'rev'
]);
};
| Fix build with new libraries
| Gruntfile.js | Fix build with new libraries | <ide><path>runtfile.js
<ide>
<ide> marked: 'empty:',
<ide> less: 'empty:',
<add> sass: 'empty:',
<ide> coffeescript: 'empty:',
<add> typescript: 'empty:',
<add> gorillascript: 'empty:',
<add> traceur: 'empty:',
<ide>
<ide> codemirror_overlay: 'empty:',
<ide> codemirror_search: 'empty:',
<ide> codemirror_coffeescript: 'empty:'
<ide> },
<ide>
<del> exclude: [
<del> 'promise', 'inflection', 'sass', 'typescript', 'typestring',
<del> 'gorillascript', 'traceur', 'traceur-api'
<del> ]
<add> exclude: ['promise', 'inflection', 'typestring', 'traceur_api']
<ide> }
<ide> }
<ide> }, |
|
Java | apache-2.0 | 1951358907cda1e4a9cb4b3c1f3a5dc824c52e49 | 0 | Lyleo/google-feedserver,fbpatel/google-feedserver,fbpatel/google-feedserver,fbpatel/google-feedserver,Lyleo/google-feedserver,Lyleo/google-feedserver,fbpatel/google-feedserver,Lyleo/google-feedserver | /*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.feedserver.ibatisCallbackHandlers;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
import java.sql.SQLException;
public class StringToNumericCallback implements TypeHandlerCallback {
public Object getResult(ResultGetter getter) throws SQLException {
// TODO: May need to use Long, BigInteger or BigDecimal
return new Integer(getter.getInt()).toString();
}
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
setter.setFloat(Float.parseFloat((String) parameter));
}
public Object valueOf(String s) {
return s;
}
}
| src/java/com/google/feedserver/ibatisCallbackHandlers/StringToNumericCallback.java | /*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.feedserver.ibatisCallbackHandlers;
import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;
import java.sql.SQLException;
public class StringToNumericCallback implements TypeHandlerCallback {
public Object getResult(ResultGetter getter) throws SQLException {
// TODO: May need to use Long, BigInteger or BigDecimal
return new Integer(getter.getInt()).toString();
}
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
setter.setInt(Integer.parseInt((String) parameter));
}
public Object valueOf(String s) {
return s;
}
}
| Changed integer to float to support decimal numbers. | src/java/com/google/feedserver/ibatisCallbackHandlers/StringToNumericCallback.java | Changed integer to float to support decimal numbers. | <ide><path>rc/java/com/google/feedserver/ibatisCallbackHandlers/StringToNumericCallback.java
<ide> }
<ide>
<ide> public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
<del> setter.setInt(Integer.parseInt((String) parameter));
<add> setter.setFloat(Float.parseFloat((String) parameter));
<ide> }
<ide>
<ide> public Object valueOf(String s) { |
|
Java | apache-2.0 | 063610f4759f26b89c541b7e7b6e4f68f2ee77a3 | 0 | lsmaira/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.plugins.osgi;
import aQute.bnd.osgi.Analyzer;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.internal.DefaultManifest;
import org.gradle.api.plugins.osgi.OsgiManifest;
import org.gradle.api.specs.Spec;
import org.gradle.internal.Factory;
import org.gradle.internal.UncheckedException;
import org.gradle.util.CollectionUtils;
import org.gradle.util.WrapUtil;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.jar.Manifest;
@SuppressWarnings("deprecation")
public class DefaultOsgiManifest extends DefaultManifest implements OsgiManifest {
// Because these properties can be convention mapped we need special handling in here.
// If you add another one of these “modelled” properties, you need to update:
// - maybeAppendModelledInstruction()
// - maybePrependModelledInstruction()
// - maybeSetModelledInstruction()
// - getModelledInstructions()
// - instructionValue()
private String symbolicName;
private String name;
private String version;
private String description;
private String license;
private String vendor;
private String docURL;
private File classesDir;
private Factory<ContainedVersionAnalyzer> analyzerFactory = new DefaultAnalyzerFactory();
private Map<String, List<String>> unmodelledInstructions = new HashMap<String, List<String>>();
private FileCollection classpath;
public DefaultOsgiManifest(FileResolver fileResolver) {
super(fileResolver);
}
@Override
public DefaultManifest getEffectiveManifest() {
ContainedVersionAnalyzer analyzer = analyzerFactory.create();
DefaultManifest effectiveManifest = new DefaultManifest(null);
try {
setAnalyzerProperties(analyzer);
Manifest osgiManifest = analyzer.calcManifest();
java.util.jar.Attributes attributes = osgiManifest.getMainAttributes();
for (Map.Entry<Object, Object> entry : attributes.entrySet()) {
effectiveManifest.attributes(WrapUtil.toMap(entry.getKey().toString(), (String) entry.getValue()));
}
effectiveManifest.attributes(this.getAttributes());
for (Map.Entry<String, Attributes> ent : getSections().entrySet()) {
effectiveManifest.attributes(ent.getValue(), ent.getKey());
}
if (classesDir != null) {
long mod = classesDir.lastModified();
if (mod > 0) {
effectiveManifest.getAttributes().put(Analyzer.BND_LASTMODIFIED, mod);
}
}
} catch (Exception e) {
throw UncheckedException.throwAsUncheckedException(e);
}
return getEffectiveManifestInternal(effectiveManifest);
}
private void setAnalyzerProperties(Analyzer analyzer) throws IOException {
for (Map.Entry<String, Object> attribute : getAttributes().entrySet()) {
String key = attribute.getKey();
if (!"Manifest-Version".equals(key)) {
analyzer.setProperty(key, attribute.getValue().toString());
}
}
Map<String, List<String>> instructions = getInstructions();
Set<String> instructionNames = instructions.keySet();
if (!instructionNames.contains(Analyzer.IMPORT_PACKAGE)) {
analyzer.setProperty(Analyzer.IMPORT_PACKAGE,
"*, !org.apache.ant.*, !org.junit.*, !org.jmock.*, !org.easymock.*, !org.mockito.*");
}
if(!instructionNames.contains(Analyzer.BUNDLE_VERSION)){
analyzer.setProperty(Analyzer.BUNDLE_VERSION, getVersion());
}
if(!instructionNames.contains(Analyzer.BUNDLE_NAME)){
analyzer.setProperty(Analyzer.BUNDLE_NAME, getName());
}
if(!instructionNames.contains(Analyzer.BUNDLE_SYMBOLICNAME)){
analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, getSymbolicName());
}
if (!instructionNames.contains(Analyzer.EXPORT_PACKAGE)) {
analyzer.setProperty(Analyzer.EXPORT_PACKAGE, "*;-noimport:=false;version=" + getVersion());
}
for (String instructionName : instructionNames) {
String list = createPropertyStringFromList(instructionValue(instructionName));
if (list != null && list.length() > 0) {
analyzer.setProperty(instructionName, list);
}
}
analyzer.setJar(getClassesDir());
analyzer.setClasspath(getClasspath().getFiles().toArray(new File[0]));
}
public List<String> instructionValue(String instructionName) {
if (instructionName.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
return createListFromPropertyString(getSymbolicName());
} else if (instructionName.equals(Analyzer.BUNDLE_NAME)) {
return createListFromPropertyString(getName());
} else if (instructionName.equals(Analyzer.BUNDLE_VERSION)) {
return createListFromPropertyString(getVersion());
} else if (instructionName.equals(Analyzer.BUNDLE_DESCRIPTION)) {
return createListFromPropertyString(getDescription());
} else if (instructionName.equals(Analyzer.BUNDLE_LICENSE)) {
return createListFromPropertyString(getLicense());
} else if (instructionName.equals(Analyzer.BUNDLE_VENDOR)) {
return createListFromPropertyString(getVendor());
} else if (instructionName.equals(Analyzer.BUNDLE_DOCURL)) {
return createListFromPropertyString(getDocURL());
} else {
return unmodelledInstructions.get(instructionName);
}
}
public OsgiManifest instruction(String name, String... values) {
if (!maybeAppendModelledInstruction(name, values)) {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
unmodelledInstructions.get(name).addAll(Arrays.asList(values));
}
return this;
}
private String appendValues(String existingValues, String... toPrepend) {
List<String> parts = createListFromPropertyString(existingValues);
if (parts == null) {
return createPropertyStringFromArray(toPrepend);
} else {
parts.addAll(Arrays.asList(toPrepend));
return createPropertyStringFromList(parts);
}
}
private boolean maybeAppendModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(appendValues(getSymbolicName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(appendValues(getName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(appendValues(getVersion(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(appendValues(getDescription(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(appendValues(getLicense(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(appendValues(getVendor(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(appendValues(getDocURL(), values));
return true;
} else {
return false;
}
}
public OsgiManifest instructionFirst(String name, String... values) {
if (!maybePrependModelledInstruction(name, values)) {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
unmodelledInstructions.get(name).addAll(0, Arrays.asList(values));
}
return this;
}
private String prependValues(String existingValues, String... toPrepend) {
List<String> parts = createListFromPropertyString(existingValues);
if (parts == null) {
return createPropertyStringFromArray(toPrepend);
} else {
parts.addAll(0, Arrays.asList(toPrepend));
return createPropertyStringFromList(parts);
}
}
private boolean maybePrependModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(prependValues(getSymbolicName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(prependValues(getName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(prependValues(getVersion(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(prependValues(getDescription(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(prependValues(getLicense(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(prependValues(getVendor(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(prependValues(getDocURL(), values));
return true;
} else {
return false;
}
}
public OsgiManifest instructionReplace(String name, String... values) {
if (!maybeSetModelledInstruction(name, values)) {
if (values.length == 0 || (values.length == 1 && values[0] == null)) {
unmodelledInstructions.remove(name);
} else {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
List<String> instructionsForName = unmodelledInstructions.get(name);
instructionsForName.clear();
Collections.addAll(instructionsForName, values);
}
}
return this;
}
private boolean maybeSetModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(createPropertyStringFromArray(values));
return true;
} else {
return false;
}
}
public Map<String, List<String>> getInstructions() {
Map<String, List<String>> instructions = new HashMap<String, List<String>>();
instructions.putAll(unmodelledInstructions);
instructions.putAll(getModelledInstructions());
return instructions;
}
private String createPropertyStringFromArray(String... valueList) {
return createPropertyStringFromList(Arrays.asList(valueList));
}
private String createPropertyStringFromList(List<String> valueList) {
return valueList == null || valueList.isEmpty() ? null : CollectionUtils.join(",", valueList);
}
private List<String> createListFromPropertyString(String propertyString) {
return propertyString == null || propertyString.length() == 0 ? null : new LinkedList<String>(Arrays.asList(propertyString.split(",")));
}
private Map<String, List<String>> getModelledInstructions() {
Map<String, List<String>> modelledInstructions = new HashMap<String, List<String>>();
modelledInstructions.put(Analyzer.BUNDLE_SYMBOLICNAME, createListFromPropertyString(symbolicName));
modelledInstructions.put(Analyzer.BUNDLE_NAME, createListFromPropertyString(name));
modelledInstructions.put(Analyzer.BUNDLE_VERSION, createListFromPropertyString(version));
modelledInstructions.put(Analyzer.BUNDLE_DESCRIPTION, createListFromPropertyString(description));
modelledInstructions.put(Analyzer.BUNDLE_LICENSE, createListFromPropertyString(license));
modelledInstructions.put(Analyzer.BUNDLE_VENDOR, createListFromPropertyString(vendor));
modelledInstructions.put(Analyzer.BUNDLE_DOCURL, createListFromPropertyString(docURL));
return CollectionUtils.filter(modelledInstructions, new Spec<Map.Entry<String, List<String>>>() {
public boolean isSatisfiedBy(Map.Entry<String, List<String>> element) {
return element.getValue() != null;
}
});
}
public String getSymbolicName() {
return symbolicName;
}
public void setSymbolicName(String symbolicName) {
this.symbolicName = symbolicName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getDocURL() {
return docURL;
}
public void setDocURL(String docURL) {
this.docURL = docURL;
}
public File getClassesDir() {
return classesDir;
}
public void setClassesDir(File classesDir) {
this.classesDir = classesDir;
}
public FileCollection getClasspath() {
return classpath;
}
public void setClasspath(FileCollection classpath) {
this.classpath = classpath;
}
public Factory<ContainedVersionAnalyzer> getAnalyzerFactory() {
return analyzerFactory;
}
public void setAnalyzerFactory(Factory<ContainedVersionAnalyzer> analyzerFactory) {
this.analyzerFactory = analyzerFactory;
}
}
| subprojects/osgi/src/main/java/org/gradle/api/internal/plugins/osgi/DefaultOsgiManifest.java | /*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.plugins.osgi;
import aQute.bnd.osgi.Analyzer;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.java.archives.Attributes;
import org.gradle.api.java.archives.internal.DefaultManifest;
import org.gradle.api.plugins.osgi.OsgiManifest;
import org.gradle.api.specs.Spec;
import org.gradle.internal.Factory;
import org.gradle.internal.UncheckedException;
import org.gradle.util.CollectionUtils;
import org.gradle.util.WrapUtil;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.jar.Manifest;
public class DefaultOsgiManifest extends DefaultManifest implements OsgiManifest {
// Because these properties can be convention mapped we need special handling in here.
// If you add another one of these “modelled” properties, you need to update:
// - maybeAppendModelledInstruction()
// - maybePrependModelledInstruction()
// - maybeSetModelledInstruction()
// - getModelledInstructions()
// - instructionValue()
private String symbolicName;
private String name;
private String version;
private String description;
private String license;
private String vendor;
private String docURL;
private File classesDir;
private Factory<ContainedVersionAnalyzer> analyzerFactory = new DefaultAnalyzerFactory();
private Map<String, List<String>> unmodelledInstructions = new HashMap<String, List<String>>();
private FileCollection classpath;
public DefaultOsgiManifest(FileResolver fileResolver) {
super(fileResolver);
}
@Override
public DefaultManifest getEffectiveManifest() {
ContainedVersionAnalyzer analyzer = analyzerFactory.create();
DefaultManifest effectiveManifest = new DefaultManifest(null);
try {
setAnalyzerProperties(analyzer);
Manifest osgiManifest = analyzer.calcManifest();
java.util.jar.Attributes attributes = osgiManifest.getMainAttributes();
for (Map.Entry<Object, Object> entry : attributes.entrySet()) {
effectiveManifest.attributes(WrapUtil.toMap(entry.getKey().toString(), (String) entry.getValue()));
}
effectiveManifest.attributes(this.getAttributes());
for (Map.Entry<String, Attributes> ent : getSections().entrySet()) {
effectiveManifest.attributes(ent.getValue(), ent.getKey());
}
if (classesDir != null) {
long mod = classesDir.lastModified();
if (mod > 0) {
effectiveManifest.getAttributes().put(Analyzer.BND_LASTMODIFIED, mod);
}
}
} catch (Exception e) {
throw UncheckedException.throwAsUncheckedException(e);
}
return getEffectiveManifestInternal(effectiveManifest);
}
private void setAnalyzerProperties(Analyzer analyzer) throws IOException {
for (Map.Entry<String, Object> attribute : getAttributes().entrySet()) {
String key = attribute.getKey();
if (!"Manifest-Version".equals(key)) {
analyzer.setProperty(key, attribute.getValue().toString());
}
}
Map<String, List<String>> instructions = getInstructions();
Set<String> instructionNames = instructions.keySet();
if (!instructionNames.contains(Analyzer.IMPORT_PACKAGE)) {
analyzer.setProperty(Analyzer.IMPORT_PACKAGE,
"*, !org.apache.ant.*, !org.junit.*, !org.jmock.*, !org.easymock.*, !org.mockito.*");
}
if(!instructionNames.contains(Analyzer.BUNDLE_VERSION)){
analyzer.setProperty(Analyzer.BUNDLE_VERSION, getVersion());
}
if(!instructionNames.contains(Analyzer.BUNDLE_NAME)){
analyzer.setProperty(Analyzer.BUNDLE_NAME, getName());
}
if(!instructionNames.contains(Analyzer.BUNDLE_SYMBOLICNAME)){
analyzer.setProperty(Analyzer.BUNDLE_SYMBOLICNAME, getSymbolicName());
}
if (!instructionNames.contains(Analyzer.EXPORT_PACKAGE)) {
analyzer.setProperty(Analyzer.EXPORT_PACKAGE, "*;-noimport:=false;version=" + getVersion());
}
for (String instructionName : instructionNames) {
String list = createPropertyStringFromList(instructionValue(instructionName));
if (list != null && list.length() > 0) {
analyzer.setProperty(instructionName, list);
}
}
analyzer.setJar(getClassesDir());
analyzer.setClasspath(getClasspath().getFiles().toArray(new File[0]));
}
public List<String> instructionValue(String instructionName) {
if (instructionName.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
return createListFromPropertyString(getSymbolicName());
} else if (instructionName.equals(Analyzer.BUNDLE_NAME)) {
return createListFromPropertyString(getName());
} else if (instructionName.equals(Analyzer.BUNDLE_VERSION)) {
return createListFromPropertyString(getVersion());
} else if (instructionName.equals(Analyzer.BUNDLE_DESCRIPTION)) {
return createListFromPropertyString(getDescription());
} else if (instructionName.equals(Analyzer.BUNDLE_LICENSE)) {
return createListFromPropertyString(getLicense());
} else if (instructionName.equals(Analyzer.BUNDLE_VENDOR)) {
return createListFromPropertyString(getVendor());
} else if (instructionName.equals(Analyzer.BUNDLE_DOCURL)) {
return createListFromPropertyString(getDocURL());
} else {
return unmodelledInstructions.get(instructionName);
}
}
public OsgiManifest instruction(String name, String... values) {
if (!maybeAppendModelledInstruction(name, values)) {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
unmodelledInstructions.get(name).addAll(Arrays.asList(values));
}
return this;
}
private String appendValues(String existingValues, String... toPrepend) {
List<String> parts = createListFromPropertyString(existingValues);
if (parts == null) {
return createPropertyStringFromArray(toPrepend);
} else {
parts.addAll(Arrays.asList(toPrepend));
return createPropertyStringFromList(parts);
}
}
private boolean maybeAppendModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(appendValues(getSymbolicName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(appendValues(getName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(appendValues(getVersion(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(appendValues(getDescription(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(appendValues(getLicense(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(appendValues(getVendor(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(appendValues(getDocURL(), values));
return true;
} else {
return false;
}
}
public OsgiManifest instructionFirst(String name, String... values) {
if (!maybePrependModelledInstruction(name, values)) {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
unmodelledInstructions.get(name).addAll(0, Arrays.asList(values));
}
return this;
}
private String prependValues(String existingValues, String... toPrepend) {
List<String> parts = createListFromPropertyString(existingValues);
if (parts == null) {
return createPropertyStringFromArray(toPrepend);
} else {
parts.addAll(0, Arrays.asList(toPrepend));
return createPropertyStringFromList(parts);
}
}
private boolean maybePrependModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(prependValues(getSymbolicName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(prependValues(getName(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(prependValues(getVersion(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(prependValues(getDescription(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(prependValues(getLicense(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(prependValues(getVendor(), values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(prependValues(getDocURL(), values));
return true;
} else {
return false;
}
}
public OsgiManifest instructionReplace(String name, String... values) {
if (!maybeSetModelledInstruction(name, values)) {
if (values.length == 0 || (values.length == 1 && values[0] == null)) {
unmodelledInstructions.remove(name);
} else {
if (unmodelledInstructions.get(name) == null) {
unmodelledInstructions.put(name, new ArrayList<String>());
}
List<String> instructionsForName = unmodelledInstructions.get(name);
instructionsForName.clear();
Collections.addAll(instructionsForName, values);
}
}
return this;
}
private boolean maybeSetModelledInstruction(String name, String... values) {
if (name.equals(Analyzer.BUNDLE_SYMBOLICNAME)) {
setSymbolicName(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_NAME)) {
setName(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VERSION)) {
setVersion(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DESCRIPTION)) {
setDescription(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_LICENSE)) {
setLicense(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_VENDOR)) {
setVendor(createPropertyStringFromArray(values));
return true;
} else if (name.equals(Analyzer.BUNDLE_DOCURL)) {
setDocURL(createPropertyStringFromArray(values));
return true;
} else {
return false;
}
}
public Map<String, List<String>> getInstructions() {
Map<String, List<String>> instructions = new HashMap<String, List<String>>();
instructions.putAll(unmodelledInstructions);
instructions.putAll(getModelledInstructions());
return instructions;
}
private String createPropertyStringFromArray(String... valueList) {
return createPropertyStringFromList(Arrays.asList(valueList));
}
private String createPropertyStringFromList(List<String> valueList) {
return valueList == null || valueList.isEmpty() ? null : CollectionUtils.join(",", valueList);
}
private List<String> createListFromPropertyString(String propertyString) {
return propertyString == null || propertyString.length() == 0 ? null : new LinkedList<String>(Arrays.asList(propertyString.split(",")));
}
private Map<String, List<String>> getModelledInstructions() {
Map<String, List<String>> modelledInstructions = new HashMap<String, List<String>>();
modelledInstructions.put(Analyzer.BUNDLE_SYMBOLICNAME, createListFromPropertyString(symbolicName));
modelledInstructions.put(Analyzer.BUNDLE_NAME, createListFromPropertyString(name));
modelledInstructions.put(Analyzer.BUNDLE_VERSION, createListFromPropertyString(version));
modelledInstructions.put(Analyzer.BUNDLE_DESCRIPTION, createListFromPropertyString(description));
modelledInstructions.put(Analyzer.BUNDLE_LICENSE, createListFromPropertyString(license));
modelledInstructions.put(Analyzer.BUNDLE_VENDOR, createListFromPropertyString(vendor));
modelledInstructions.put(Analyzer.BUNDLE_DOCURL, createListFromPropertyString(docURL));
return CollectionUtils.filter(modelledInstructions, new Spec<Map.Entry<String, List<String>>>() {
public boolean isSatisfiedBy(Map.Entry<String, List<String>> element) {
return element.getValue() != null;
}
});
}
public String getSymbolicName() {
return symbolicName;
}
public void setSymbolicName(String symbolicName) {
this.symbolicName = symbolicName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getDocURL() {
return docURL;
}
public void setDocURL(String docURL) {
this.docURL = docURL;
}
public File getClassesDir() {
return classesDir;
}
public void setClassesDir(File classesDir) {
this.classesDir = classesDir;
}
public FileCollection getClasspath() {
return classpath;
}
public void setClasspath(FileCollection classpath) {
this.classpath = classpath;
}
public Factory<ContainedVersionAnalyzer> getAnalyzerFactory() {
return analyzerFactory;
}
public void setAnalyzerFactory(Factory<ContainedVersionAnalyzer> analyzerFactory) {
this.analyzerFactory = analyzerFactory;
}
}
| Suppress warnings for internal use of deprecated OSGI plugin types
| subprojects/osgi/src/main/java/org/gradle/api/internal/plugins/osgi/DefaultOsgiManifest.java | Suppress warnings for internal use of deprecated OSGI plugin types | <ide><path>ubprojects/osgi/src/main/java/org/gradle/api/internal/plugins/osgi/DefaultOsgiManifest.java
<ide> import java.util.*;
<ide> import java.util.jar.Manifest;
<ide>
<add>@SuppressWarnings("deprecation")
<ide> public class DefaultOsgiManifest extends DefaultManifest implements OsgiManifest {
<ide>
<ide> // Because these properties can be convention mapped we need special handling in here. |
|
Java | bsd-3-clause | 48cd0c4cd184a8dc8e29c1cd7eff1d555d44c6b8 | 0 | stoewer/nix-java | package org.gnode.nix.internal;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Pointer;
import java.util.ArrayList;
public class Utils {
/**
* Converts {@link IntPointer} to {@link Integer} {@link ArrayList}
*
* @param ip {@link IntPointer} pointer to be converted
* @return array list of ints
*/
public static ArrayList<Integer> convertPointerToList(IntPointer ip) {
ArrayList<Integer> intList = new ArrayList<Integer>();
if (ip != null) {
for (int i = 0; i < ip.capacity(); i++) {
intList.add(ip.get(i));
}
}
return intList;
}
/**
* Converts {@link DoublePointer} to {@link Double} {@link ArrayList}
*
* @param dp {@link DoublePointer} pointer to be converted
* @return array list of doubles
*/
public static ArrayList<Double> convertPointerToList(DoublePointer dp) {
ArrayList<Double> doubleList = new ArrayList<Double>();
if (dp != null) {
for (int i = 0; i < dp.capacity(); i++) {
doubleList.add(dp.get(i));
}
}
return doubleList;
}
/**
* Converts a {@link Pointer} type object of particular class to an {@link ArrayList}
*
* @param pointer pointer to be converted
* @param cls pointer object class
* @param <T> generic type
* @return array list of object of class cls
*/
public static <T> ArrayList<T> convertPointerToList(Pointer pointer, Class<T> cls) {
ArrayList<T> arrayList = new ArrayList<T>();
if (pointer != null) {
for (int i = 0; i < pointer.capacity(); i++) {
arrayList.add(cls.cast(pointer.position(i)));
}
}
return arrayList;
}
}
| nix/src/main/java/org/gnode/nix/internal/Utils.java | package org.gnode.nix.internal;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Pointer;
import java.util.ArrayList;
public class Utils {
/**
* Converts {@link IntPointer} to {@link Integer} {@link ArrayList}
*
* @param ip {@link IntPointer} pointer to be converted
* @return array list of ints
*/
protected static ArrayList<Integer> convertPointerToList(IntPointer ip) {
ArrayList<Integer> intList = new ArrayList<Integer>();
if (ip != null) {
for (int i = 0; i < ip.capacity(); i++) {
intList.add(ip.get(i));
}
}
return intList;
}
/**
* Converts {@link DoublePointer} to {@link Double} {@link ArrayList}
*
* @param dp {@link DoublePointer} pointer to be converted
* @return array list of doubles
*/
protected static ArrayList<Double> convertPointerToList(DoublePointer dp) {
ArrayList<Double> doubleList = new ArrayList<Double>();
if (dp != null) {
for (int i = 0; i < dp.capacity(); i++) {
doubleList.add(dp.get(i));
}
}
return doubleList;
}
/**
* Converts a {@link Pointer} type object of particular class to an {@link ArrayList}
*
* @param pointer pointer to be converted
* @param cls pointer object class
* @param <T> generic type
* @return array list of object of class cls
*/
protected static <T> ArrayList<T> convertPointerToList(Pointer pointer, Class<T> cls) {
ArrayList<T> arrayList = new ArrayList<T>();
if (pointer != null) {
for (int i = 0; i < pointer.capacity(); i++) {
arrayList.add(cls.cast(pointer.position(i)));
}
}
return arrayList;
}
}
| make util funcs public
| nix/src/main/java/org/gnode/nix/internal/Utils.java | make util funcs public | <ide><path>ix/src/main/java/org/gnode/nix/internal/Utils.java
<ide> * @param ip {@link IntPointer} pointer to be converted
<ide> * @return array list of ints
<ide> */
<del> protected static ArrayList<Integer> convertPointerToList(IntPointer ip) {
<add> public static ArrayList<Integer> convertPointerToList(IntPointer ip) {
<ide> ArrayList<Integer> intList = new ArrayList<Integer>();
<ide> if (ip != null) {
<ide> for (int i = 0; i < ip.capacity(); i++) {
<ide> * @param dp {@link DoublePointer} pointer to be converted
<ide> * @return array list of doubles
<ide> */
<del> protected static ArrayList<Double> convertPointerToList(DoublePointer dp) {
<add> public static ArrayList<Double> convertPointerToList(DoublePointer dp) {
<ide> ArrayList<Double> doubleList = new ArrayList<Double>();
<ide> if (dp != null) {
<ide> for (int i = 0; i < dp.capacity(); i++) {
<ide> * @param <T> generic type
<ide> * @return array list of object of class cls
<ide> */
<del> protected static <T> ArrayList<T> convertPointerToList(Pointer pointer, Class<T> cls) {
<add> public static <T> ArrayList<T> convertPointerToList(Pointer pointer, Class<T> cls) {
<ide> ArrayList<T> arrayList = new ArrayList<T>();
<ide> if (pointer != null) {
<ide> for (int i = 0; i < pointer.capacity(); i++) { |
|
Java | bsd-3-clause | 8a72c9d2176a108dd412a8739f552cc2b074dd45 | 0 | tangentforks/piccolo2d.java | /*
* Copyright (c) 2008-2009, Piccolo2D project, http://piccolo2d.org
* Copyright (c) 1998-2008, University of Maryland
* 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.
*
* None of the name of the University of Maryland, the name of the Piccolo2D project, or 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 edu.umd.cs.piccolo.util;
import java.awt.Dimension;
import java.awt.geom.Dimension2D;
import junit.framework.TestCase;
public class PAffineTransformTest extends TestCase {
private PAffineTransform at;
public PAffineTransformTest(String aName) {
super(aName);
}
public void setUp() {
at = new PAffineTransform();
}
public void testRotation() {
at.rotate(Math.toRadians(45));
assertEquals(at.getRotation(), Math.toRadians(45), 0.000000001);
at.setRotation(Math.toRadians(90));
assertEquals(at.getRotation(), Math.toRadians(90), 0.000000001);
}
public void testScale() {
at.scaleAboutPoint(0.45, 0, 1);
assertEquals(at.getScale(), 0.45, 0.000000001);
at.setScale(0.11);
assertEquals(at.getScale(), 0.11, 0.000000001);
}
public void testTransformRectLeavesEmptyBoundsEmpty() {
PBounds b1 = new PBounds();
at.scale(0.5, 0.5);
at.translate(100, 50);
at.transform(b1, b1);
assertTrue(b1.isEmpty());
}
public void testTransformRect() {
PBounds b1 = new PBounds(0, 0, 100, 80);
PBounds b2 = new PBounds(100, 100, 100, 80);
at.scale(0.5, 0.5);
at.translate(100, 50);
at.transform(b1, b1);
at.transform(b2, b2);
assertSameBounds(new PBounds(50, 25, 50, 40), b1);
assertSameBounds(new PBounds(100, 75, 50, 40), b2);
at.inverseTransform(b1, b1);
at.inverseTransform(b2, b2);
assertSameBounds(new PBounds(0, 0, 100, 80), b1);
assertSameBounds(new PBounds(100, 100, 100, 80), b2);
}
public void testThrowsExceptionWhenSetting0Scale() {
try {
at.setScale(0);
fail("Setting 0 scale should throw exception");
} catch (RuntimeException e) {
// expected
}
}
public void testSetOffsetLeavesRotationUntouched() {
at.setRotation(Math.PI);
at.setOffset(100, 50);
assertEquals(Math.PI, at.getRotation(), 0.001);
}
public void testTransformDimensionWorks() {
Dimension d1 = new Dimension(100, 50);
at.setScale(2);
Dimension d2 = new Dimension(0, 0);
at.transform(d1, d2);
assertEquals(new Dimension(200, 100), d2);
}
public void testTransformDimensionWorksWithSecondParamNull() {
Dimension d1 = new Dimension(100, 50);
at.setScale(2);
Dimension2D d2 = at.transform(d1, null);
assertEquals(new Dimension(200, 100), d2);
}
private final void assertSameBounds(PBounds expected, PBounds actual) {
assertSameBounds(expected, actual, 0.0000001);
}
private final void assertSameBounds(PBounds expected, PBounds actual, double errorRate) {
assertTrue("Expected " + expected + " but was " + actual, comparisonScore(expected, actual) > (1d-errorRate));
}
// % of area within full bounds covered by intersection or the two bounds.
// exactly covering would be 1 no overlap would be 0
private final double comparisonScore(PBounds b1, PBounds b2) {
PBounds intersection = new PBounds();
PBounds union = new PBounds();
PBounds.intersect(b1, b2, intersection);
PBounds.intersect(b1, b2, union);
return area(intersection) / area(union);
}
private final double area(PBounds b) {
return b.getWidth() * b.getHeight();
}
}
| core/src/test/java/edu/umd/cs/piccolo/util/PAffineTransformTest.java | /*
* Copyright (c) 2008-2009, Piccolo2D project, http://piccolo2d.org
* Copyright (c) 1998-2008, University of Maryland
* 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.
*
* None of the name of the University of Maryland, the name of the Piccolo2D project, or 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 edu.umd.cs.piccolo.util;
import junit.framework.TestCase;
import edu.umd.cs.piccolo.util.PAffineTransform;
import edu.umd.cs.piccolo.util.PBounds;
public class PAffineTransformTest extends TestCase {
public PAffineTransformTest(String aName) {
super(aName);
}
public void testRotation() {
PAffineTransform at = new PAffineTransform();
at.rotate(Math.toRadians(45));
assertEquals(at.getRotation(), Math.toRadians(45), 0.000000001);
at.setRotation(Math.toRadians(90));
assertEquals(at.getRotation(), Math.toRadians(90), 0.000000001);
}
public void testScale() {
PAffineTransform at = new PAffineTransform();
at.scaleAboutPoint(0.45, 0, 1);
assertEquals(at.getScale(), 0.45, 0.000000001);
at.setScale(0.11);
assertEquals(at.getScale(), 0.11, 0.000000001);
}
public void testTransformRect() {
PBounds b1 = new PBounds(0, 0, 100, 80);
PBounds b2 = new PBounds(100, 100, 100, 80);
PAffineTransform at = new PAffineTransform();
at.scale(0.5, 0.5);
at.translate(100, 50);
at.transform(b1, b1);
at.transform(b2, b2);
PBounds b3 = new PBounds();
PBounds b4 = new PBounds(0, 0, 100, 100);
assertTrue(at.transform(b3, b4).isEmpty());
assertEquals(b1.getX(), 50, 0.000000001);
assertEquals(b1.getY(), 25, 0.000000001);
assertEquals(b1.getWidth(), 50, 0.000000001);
assertEquals(b1.getHeight(), 40, 0.000000001);
assertEquals(b2.getX(), 100, 0.000000001);
assertEquals(b2.getY(), 75, 0.000000001);
assertEquals(b2.getWidth(), 50, 0.000000001);
assertEquals(b2.getHeight(), 40, 0.000000001);
at.inverseTransform(b1, b1);
at.inverseTransform(b2, b2);
assertEquals(b1.getX(), 0, 0.000000001);
assertEquals(b1.getY(), 0, 0.000000001);
assertEquals(b1.getWidth(), 100, 0.000000001);
assertEquals(b1.getHeight(), 80, 0.000000001);
assertEquals(b2.getX(), 100, 0.000000001);
assertEquals(b2.getY(), 100, 0.000000001);
assertEquals(b2.getWidth(), 100, 0.000000001);
assertEquals(b2.getHeight(), 80, 0.000000001);
}
}
| Added some tests for PAffineTransform
git-svn-id: d976a3fa9fd96fa05fb374ae920b691bf85e82cb@468 aadc08cf-1350-0410-9b51-cf97fce99a1b
| core/src/test/java/edu/umd/cs/piccolo/util/PAffineTransformTest.java | Added some tests for PAffineTransform | <ide><path>ore/src/test/java/edu/umd/cs/piccolo/util/PAffineTransformTest.java
<ide> */
<ide> package edu.umd.cs.piccolo.util;
<ide>
<add>import java.awt.Dimension;
<add>import java.awt.geom.Dimension2D;
<add>
<ide> import junit.framework.TestCase;
<ide>
<del>import edu.umd.cs.piccolo.util.PAffineTransform;
<del>import edu.umd.cs.piccolo.util.PBounds;
<add>public class PAffineTransformTest extends TestCase {
<ide>
<del>public class PAffineTransformTest extends TestCase {
<add> private PAffineTransform at;
<ide>
<ide> public PAffineTransformTest(String aName) {
<ide> super(aName);
<ide> }
<add>
<add> public void setUp() {
<add> at = new PAffineTransform();
<add> }
<ide>
<ide> public void testRotation() {
<del> PAffineTransform at = new PAffineTransform();
<ide> at.rotate(Math.toRadians(45));
<ide> assertEquals(at.getRotation(), Math.toRadians(45), 0.000000001);
<ide> at.setRotation(Math.toRadians(90));
<ide> assertEquals(at.getRotation(), Math.toRadians(90), 0.000000001);
<ide> }
<ide>
<del> public void testScale() {
<del> PAffineTransform at = new PAffineTransform();
<add> public void testScale() {
<ide> at.scaleAboutPoint(0.45, 0, 1);
<ide> assertEquals(at.getScale(), 0.45, 0.000000001);
<ide> at.setScale(0.11);
<ide> assertEquals(at.getScale(), 0.11, 0.000000001);
<ide> }
<ide>
<add> public void testTransformRectLeavesEmptyBoundsEmpty() {
<add> PBounds b1 = new PBounds();
<add> at.scale(0.5, 0.5);
<add> at.translate(100, 50);
<add>
<add> at.transform(b1, b1);
<add> assertTrue(b1.isEmpty());
<add> }
<add>
<ide> public void testTransformRect() {
<ide> PBounds b1 = new PBounds(0, 0, 100, 80);
<ide> PBounds b2 = new PBounds(100, 100, 100, 80);
<del>
<del> PAffineTransform at = new PAffineTransform();
<add>
<ide> at.scale(0.5, 0.5);
<ide> at.translate(100, 50);
<ide>
<ide> at.transform(b1, b1);
<ide> at.transform(b2, b2);
<del>
<del> PBounds b3 = new PBounds();
<del> PBounds b4 = new PBounds(0, 0, 100, 100);
<del>
<del> assertTrue(at.transform(b3, b4).isEmpty());
<del>
<del> assertEquals(b1.getX(), 50, 0.000000001);
<del> assertEquals(b1.getY(), 25, 0.000000001);
<del> assertEquals(b1.getWidth(), 50, 0.000000001);
<del> assertEquals(b1.getHeight(), 40, 0.000000001);
<del>
<del> assertEquals(b2.getX(), 100, 0.000000001);
<del> assertEquals(b2.getY(), 75, 0.000000001);
<del> assertEquals(b2.getWidth(), 50, 0.000000001);
<del> assertEquals(b2.getHeight(), 40, 0.000000001);
<del>
<add>
<add> assertSameBounds(new PBounds(50, 25, 50, 40), b1);
<add> assertSameBounds(new PBounds(100, 75, 50, 40), b2);
<add>
<ide> at.inverseTransform(b1, b1);
<ide> at.inverseTransform(b2, b2);
<ide>
<del> assertEquals(b1.getX(), 0, 0.000000001);
<del> assertEquals(b1.getY(), 0, 0.000000001);
<del> assertEquals(b1.getWidth(), 100, 0.000000001);
<del> assertEquals(b1.getHeight(), 80, 0.000000001);
<del>
<del> assertEquals(b2.getX(), 100, 0.000000001);
<del> assertEquals(b2.getY(), 100, 0.000000001);
<del> assertEquals(b2.getWidth(), 100, 0.000000001);
<del> assertEquals(b2.getHeight(), 80, 0.000000001);
<add> assertSameBounds(new PBounds(0, 0, 100, 80), b1);
<add> assertSameBounds(new PBounds(100, 100, 100, 80), b2);
<add> }
<add>
<add> public void testThrowsExceptionWhenSetting0Scale() {
<add> try {
<add> at.setScale(0);
<add> fail("Setting 0 scale should throw exception");
<add> } catch (RuntimeException e) {
<add> // expected
<add> }
<add> }
<add>
<add> public void testSetOffsetLeavesRotationUntouched() {
<add> at.setRotation(Math.PI);
<add> at.setOffset(100, 50);
<add> assertEquals(Math.PI, at.getRotation(), 0.001);
<add> }
<add>
<add> public void testTransformDimensionWorks() {
<add> Dimension d1 = new Dimension(100, 50);
<add> at.setScale(2);
<add> Dimension d2 = new Dimension(0, 0);
<add> at.transform(d1, d2);
<add> assertEquals(new Dimension(200, 100), d2);
<add> }
<add>
<add> public void testTransformDimensionWorksWithSecondParamNull() {
<add> Dimension d1 = new Dimension(100, 50);
<add> at.setScale(2);
<add> Dimension2D d2 = at.transform(d1, null);
<add> assertEquals(new Dimension(200, 100), d2);
<add> }
<add>
<add> private final void assertSameBounds(PBounds expected, PBounds actual) {
<add> assertSameBounds(expected, actual, 0.0000001);
<add> }
<add>
<add> private final void assertSameBounds(PBounds expected, PBounds actual, double errorRate) {
<add> assertTrue("Expected " + expected + " but was " + actual, comparisonScore(expected, actual) > (1d-errorRate));
<add> }
<add>
<add>
<add> // % of area within full bounds covered by intersection or the two bounds.
<add> // exactly covering would be 1 no overlap would be 0
<add> private final double comparisonScore(PBounds b1, PBounds b2) {
<add> PBounds intersection = new PBounds();
<add> PBounds union = new PBounds();
<add> PBounds.intersect(b1, b2, intersection);
<add> PBounds.intersect(b1, b2, union);
<add>
<add> return area(intersection) / area(union);
<add> }
<add>
<add> private final double area(PBounds b) {
<add> return b.getWidth() * b.getHeight();
<ide> }
<ide> } |
|
Java | apache-2.0 | 7309fe9f2e18e32f531c8c7bd4549cb863fb2399 | 0 | spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework,spring-projects/spring-framework | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import org.springframework.lang.Nullable;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 1.1.3
*/
public abstract class CollectionUtils {
/**
* Default load factor for {@link HashMap}/{@link LinkedHashMap} variants.
* @see #newHashMap(int)
* @see #newLinkedHashMap(int)
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* Return {@code true} if the supplied Collection is {@code null} or empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(@Nullable Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return {@code true} if the supplied Map is {@code null} or empty.
* Otherwise, return {@code false}.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(@Nullable Map<?, ?> map) {
return (map == null || map.isEmpty());
}
/**
* Instantiate a new {@link HashMap} with an initial capacity
* that can accommodate the specified number of elements without
* any immediate resize/rehash operations to be expected.
* <p>This differs from the regular {@link HashMap} constructor
* which takes an initial capacity relative to a load factor
* but is effectively aligned with the JDK's
* {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int)}.
* @param expectedSize the expected number of elements (with a corresponding
* capacity to be derived so that no resize/rehash operations are needed)
* @since 5.3
* @see #newLinkedHashMap(int)
*/
public static <K, V> HashMap<K, V> newHashMap(int expectedSize) {
return new HashMap<>(computeMapInitialCapacity(expectedSize), DEFAULT_LOAD_FACTOR);
}
/**
* Instantiate a new {@link LinkedHashMap} with an initial capacity
* that can accommodate the specified number of elements without
* any immediate resize/rehash operations to be expected.
* <p>This differs from the regular {@link LinkedHashMap} constructor
* which takes an initial capacity relative to a load factor but is
* aligned with Spring's own {@link LinkedCaseInsensitiveMap} and
* {@link LinkedMultiValueMap} constructor semantics as of 5.3.
* @param expectedSize the expected number of elements (with a corresponding
* capacity to be derived so that no resize/rehash operations are needed)
* @since 5.3
* @see #newHashMap(int)
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int expectedSize) {
return new LinkedHashMap<>(computeMapInitialCapacity(expectedSize), DEFAULT_LOAD_FACTOR);
}
private static int computeMapInitialCapacity(int expectedSize) {
return (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
}
/**
* Convert the supplied array into a List. A primitive array gets converted
* into a List of the appropriate wrapper type.
* <p><b>NOTE:</b> Generally prefer the standard {@link Arrays#asList} method.
* This {@code arrayToList} method is just meant to deal with an incoming Object
* value that might be an {@code Object[]} or a primitive array at runtime.
* <p>A {@code null} source value will be converted to an empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
* @see Arrays#asList(Object[])
*/
public static List<?> arrayToList(@Nullable Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be {@code null})
* @param collection the target Collection to merge the array into
*/
@SuppressWarnings("unchecked")
public static <E> void mergeArrayIntoCollection(@Nullable Object array, Collection<E> collection) {
Object[] arr = ObjectUtils.toObjectArray(array);
for (Object elem : arr) {
collection.add((E) elem);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(@Nullable Properties props, Map<K, V> map) {
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean contains(@Nullable Iterator<?> iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean contains(@Nullable Enumeration<?> enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* {@code true} for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean containsInstance(@Nullable Collection<?> collection, Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return {@code true} if any element in '{@code candidates}' is
* contained in '{@code source}'; otherwise returns {@code false}.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
return findFirstMatch(source, candidates) != null;
}
/**
* Return the first element in '{@code candidates}' that is contained in
* '{@code source}'. If no element in '{@code candidates}' is present in
* '{@code source}' returns {@code null}. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or {@code null} if not found
*/
@SuppressWarnings("unchecked")
@Nullable
public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return (E) candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@SuppressWarnings("unchecked")
@Nullable
public static <T> T findValueOfType(Collection<?> collection, @Nullable Class<T> type) {
if (isEmpty(collection)) {
return null;
}
T value = null;
for (Object element : collection) {
if (type == null || type.isInstance(element)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = (T) element;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@Nullable
public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (Class<?> type : types) {
Object value = findValueOfType(collection, type);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return {@code true} if the collection contains a single reference or
* multiple references to the same instance, {@code false} otherwise
*/
public static boolean hasUniqueObject(Collection<?> collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Object elem : collection) {
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
/**
* Find the common element type of the given Collection, if any.
* @param collection the Collection to check
* @return the common element type, or {@code null} if no clear
* common type has been found (or the collection was empty)
*/
@Nullable
public static Class<?> findCommonElementType(Collection<?> collection) {
if (isEmpty(collection)) {
return null;
}
Class<?> candidate = null;
for (Object val : collection) {
if (val != null) {
if (candidate == null) {
candidate = val.getClass();
}
else if (candidate != val.getClass()) {
return null;
}
}
}
return candidate;
}
/**
* Retrieve the first element of the given Set, using {@link SortedSet#first()}
* or otherwise using the iterator.
* @param set the Set to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
* @since 5.2.3
* @see SortedSet
* @see LinkedHashMap#keySet()
* @see java.util.LinkedHashSet
*/
@Nullable
public static <T> T firstElement(@Nullable Set<T> set) {
if (isEmpty(set)) {
return null;
}
if (set instanceof SortedSet) {
return ((SortedSet<T>) set).first();
}
Iterator<T> it = set.iterator();
T first = null;
if (it.hasNext()) {
first = it.next();
}
return first;
}
/**
* Retrieve the first element of the given List, accessing the zero index.
* @param list the List to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
* @since 5.2.3
*/
@Nullable
public static <T> T firstElement(@Nullable List<T> list) {
if (isEmpty(list)) {
return null;
}
return list.get(0);
}
/**
* Retrieve the last element of the given Set, using {@link SortedSet#last()}
* or otherwise iterating over all elements (assuming a linked set).
* @param set the Set to check (may be {@code null} or empty)
* @return the last element, or {@code null} if none
* @since 5.0.3
* @see SortedSet
* @see LinkedHashMap#keySet()
* @see java.util.LinkedHashSet
*/
@Nullable
public static <T> T lastElement(@Nullable Set<T> set) {
if (isEmpty(set)) {
return null;
}
if (set instanceof SortedSet) {
return ((SortedSet<T>) set).last();
}
// Full iteration necessary...
Iterator<T> it = set.iterator();
T last = null;
while (it.hasNext()) {
last = it.next();
}
return last;
}
/**
* Retrieve the last element of the given List, accessing the highest index.
* @param list the List to check (may be {@code null} or empty)
* @return the last element, or {@code null} if none
* @since 5.0.3
*/
@Nullable
public static <T> T lastElement(@Nullable List<T> list) {
if (isEmpty(list)) {
return null;
}
return list.get(list.size() - 1);
}
/**
* Marshal the elements from the given enumeration into an array of the given type.
* Enumeration elements must be assignable to the type of the given array. The array
* returned will be a different instance than the array given.
*/
public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
ArrayList<A> elements = new ArrayList<>();
while (enumeration.hasMoreElements()) {
elements.add(enumeration.nextElement());
}
return elements.toArray(array);
}
/**
* Adapt an {@link Enumeration} to an {@link Iterator}.
* @param enumeration the original {@code Enumeration}
* @return the adapted {@code Iterator}
*/
public static <E> Iterator<E> toIterator(@Nullable Enumeration<E> enumeration) {
return (enumeration != null ? new EnumerationIterator<>(enumeration) : Collections.emptyIterator());
}
/**
* Adapt a {@code Map<K, List<V>>} to an {@code MultiValueMap<K, V>}.
* @param targetMap the original map
* @return the adapted multi-value map (wrapping the original map)
* @since 3.1
*/
public static <K, V> MultiValueMap<K, V> toMultiValueMap(Map<K, List<V>> targetMap) {
return new MultiValueMapAdapter<>(targetMap);
}
/**
* Return an unmodifiable view of the specified multi-value map.
* @param targetMap the map for which an unmodifiable view is to be returned.
* @return an unmodifiable view of the specified multi-value map
* @since 3.1
*/
@SuppressWarnings("unchecked")
public static <K, V> MultiValueMap<K, V> unmodifiableMultiValueMap(
MultiValueMap<? extends K, ? extends V> targetMap) {
Assert.notNull(targetMap, "'targetMap' must not be null");
Map<K, List<V>> result = newLinkedHashMap(targetMap.size());
targetMap.forEach((key, value) -> {
List<? extends V> values = Collections.unmodifiableList(value);
result.put(key, (List<V>) values);
});
Map<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);
return toMultiValueMap(unmodifiableMap);
}
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private final Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
@Override
public boolean hasNext() {
return this.enumeration.hasMoreElements();
}
@Override
public E next() {
return this.enumeration.nextElement();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
}
| spring-core/src/main/java/org/springframework/util/CollectionUtils.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import org.springframework.lang.Nullable;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 1.1.3
*/
public abstract class CollectionUtils {
/**
* Default load factor for {@link HashMap}/{@link LinkedHashMap} variants.
* @see #newHashMap(int)
* @see #newLinkedHashMap(int)
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* Return {@code true} if the supplied Collection is {@code null} or empty.
* Otherwise, return {@code false}.
* @param collection the Collection to check
* @return whether the given Collection is empty
*/
public static boolean isEmpty(@Nullable Collection<?> collection) {
return (collection == null || collection.isEmpty());
}
/**
* Return {@code true} if the supplied Map is {@code null} or empty.
* Otherwise, return {@code false}.
* @param map the Map to check
* @return whether the given Map is empty
*/
public static boolean isEmpty(@Nullable Map<?, ?> map) {
return (map == null || map.isEmpty());
}
/**
* Instantiate a new {@link HashMap} with an initial capacity
* that can accommodate the specified number of elements without
* any immediate resize/rehash operations to be expected.
* <p>This differs from the regular {@link HashMap} constructor
* which takes an initial capacity relative to a load factor
* but is effectively aligned with the JDK's
* {@link java.util.concurrent.ConcurrentHashMap#ConcurrentHashMap(int)}.
* @param expectedSize the expected number of elements (with a corresponding
* capacity to be derived so that no resize/rehash operations are needed)
* @since 5.3
* @see #newLinkedHashMap(int)
*/
public static <K, V> HashMap<K, V> newHashMap(int expectedSize) {
int capacity = (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
return new HashMap<>(capacity, DEFAULT_LOAD_FACTOR);
}
/**
* Instantiate a new {@link LinkedHashMap} with an initial capacity
* that can accommodate the specified number of elements without
* any immediate resize/rehash operations to be expected.
* <p>This differs from the regular {@link LinkedHashMap} constructor
* which takes an initial capacity relative to a load factor but is
* aligned with Spring's own {@link LinkedCaseInsensitiveMap} and
* {@link LinkedMultiValueMap} constructor semantics as of 5.3.
* @param expectedSize the expected number of elements (with a corresponding
* capacity to be derived so that no resize/rehash operations are needed)
* @since 5.3
* @see #newHashMap(int)
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int expectedSize) {
int capacity = (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
return new LinkedHashMap<>(capacity, DEFAULT_LOAD_FACTOR);
}
/**
* Convert the supplied array into a List. A primitive array gets converted
* into a List of the appropriate wrapper type.
* <p><b>NOTE:</b> Generally prefer the standard {@link Arrays#asList} method.
* This {@code arrayToList} method is just meant to deal with an incoming Object
* value that might be an {@code Object[]} or a primitive array at runtime.
* <p>A {@code null} source value will be converted to an empty List.
* @param source the (potentially primitive) array
* @return the converted List result
* @see ObjectUtils#toObjectArray(Object)
* @see Arrays#asList(Object[])
*/
public static List<?> arrayToList(@Nullable Object source) {
return Arrays.asList(ObjectUtils.toObjectArray(source));
}
/**
* Merge the given array into the given Collection.
* @param array the array to merge (may be {@code null})
* @param collection the target Collection to merge the array into
*/
@SuppressWarnings("unchecked")
public static <E> void mergeArrayIntoCollection(@Nullable Object array, Collection<E> collection) {
Object[] arr = ObjectUtils.toObjectArray(array);
for (Object elem : arr) {
collection.add((E) elem);
}
}
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(@Nullable Properties props, Map<K, V> map) {
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
/**
* Check whether the given Iterator contains the given element.
* @param iterator the Iterator to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean contains(@Nullable Iterator<?> iterator, Object element) {
if (iterator != null) {
while (iterator.hasNext()) {
Object candidate = iterator.next();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Enumeration contains the given element.
* @param enumeration the Enumeration to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean contains(@Nullable Enumeration<?> enumeration, Object element) {
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
Object candidate = enumeration.nextElement();
if (ObjectUtils.nullSafeEquals(candidate, element)) {
return true;
}
}
}
return false;
}
/**
* Check whether the given Collection contains the given element instance.
* <p>Enforces the given instance to be present, rather than returning
* {@code true} for an equal element as well.
* @param collection the Collection to check
* @param element the element to look for
* @return {@code true} if found, {@code false} otherwise
*/
public static boolean containsInstance(@Nullable Collection<?> collection, Object element) {
if (collection != null) {
for (Object candidate : collection) {
if (candidate == element) {
return true;
}
}
}
return false;
}
/**
* Return {@code true} if any element in '{@code candidates}' is
* contained in '{@code source}'; otherwise returns {@code false}.
* @param source the source Collection
* @param candidates the candidates to search for
* @return whether any of the candidates has been found
*/
public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
return findFirstMatch(source, candidates) != null;
}
/**
* Return the first element in '{@code candidates}' that is contained in
* '{@code source}'. If no element in '{@code candidates}' is present in
* '{@code source}' returns {@code null}. Iteration order is
* {@link Collection} implementation specific.
* @param source the source Collection
* @param candidates the candidates to search for
* @return the first present object, or {@code null} if not found
*/
@SuppressWarnings("unchecked")
@Nullable
public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return null;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return (E) candidate;
}
}
return null;
}
/**
* Find a single value of the given type in the given Collection.
* @param collection the Collection to search
* @param type the type to look for
* @return a value of the given type found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@SuppressWarnings("unchecked")
@Nullable
public static <T> T findValueOfType(Collection<?> collection, @Nullable Class<T> type) {
if (isEmpty(collection)) {
return null;
}
T value = null;
for (Object element : collection) {
if (type == null || type.isInstance(element)) {
if (value != null) {
// More than one value found... no clear single value.
return null;
}
value = (T) element;
}
}
return value;
}
/**
* Find a single value of one of the given types in the given Collection:
* searching the Collection for a value of the first type, then
* searching for a value of the second type, etc.
* @param collection the collection to search
* @param types the types to look for, in prioritized order
* @return a value of one of the given types found if there is a clear match,
* or {@code null} if none or more than one such value found
*/
@Nullable
public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
return null;
}
for (Class<?> type : types) {
Object value = findValueOfType(collection, type);
if (value != null) {
return value;
}
}
return null;
}
/**
* Determine whether the given Collection only contains a single unique object.
* @param collection the Collection to check
* @return {@code true} if the collection contains a single reference or
* multiple references to the same instance, {@code false} otherwise
*/
public static boolean hasUniqueObject(Collection<?> collection) {
if (isEmpty(collection)) {
return false;
}
boolean hasCandidate = false;
Object candidate = null;
for (Object elem : collection) {
if (!hasCandidate) {
hasCandidate = true;
candidate = elem;
}
else if (candidate != elem) {
return false;
}
}
return true;
}
/**
* Find the common element type of the given Collection, if any.
* @param collection the Collection to check
* @return the common element type, or {@code null} if no clear
* common type has been found (or the collection was empty)
*/
@Nullable
public static Class<?> findCommonElementType(Collection<?> collection) {
if (isEmpty(collection)) {
return null;
}
Class<?> candidate = null;
for (Object val : collection) {
if (val != null) {
if (candidate == null) {
candidate = val.getClass();
}
else if (candidate != val.getClass()) {
return null;
}
}
}
return candidate;
}
/**
* Retrieve the first element of the given Set, using {@link SortedSet#first()}
* or otherwise using the iterator.
* @param set the Set to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
* @since 5.2.3
* @see SortedSet
* @see LinkedHashMap#keySet()
* @see java.util.LinkedHashSet
*/
@Nullable
public static <T> T firstElement(@Nullable Set<T> set) {
if (isEmpty(set)) {
return null;
}
if (set instanceof SortedSet) {
return ((SortedSet<T>) set).first();
}
Iterator<T> it = set.iterator();
T first = null;
if (it.hasNext()) {
first = it.next();
}
return first;
}
/**
* Retrieve the first element of the given List, accessing the zero index.
* @param list the List to check (may be {@code null} or empty)
* @return the first element, or {@code null} if none
* @since 5.2.3
*/
@Nullable
public static <T> T firstElement(@Nullable List<T> list) {
if (isEmpty(list)) {
return null;
}
return list.get(0);
}
/**
* Retrieve the last element of the given Set, using {@link SortedSet#last()}
* or otherwise iterating over all elements (assuming a linked set).
* @param set the Set to check (may be {@code null} or empty)
* @return the last element, or {@code null} if none
* @since 5.0.3
* @see SortedSet
* @see LinkedHashMap#keySet()
* @see java.util.LinkedHashSet
*/
@Nullable
public static <T> T lastElement(@Nullable Set<T> set) {
if (isEmpty(set)) {
return null;
}
if (set instanceof SortedSet) {
return ((SortedSet<T>) set).last();
}
// Full iteration necessary...
Iterator<T> it = set.iterator();
T last = null;
while (it.hasNext()) {
last = it.next();
}
return last;
}
/**
* Retrieve the last element of the given List, accessing the highest index.
* @param list the List to check (may be {@code null} or empty)
* @return the last element, or {@code null} if none
* @since 5.0.3
*/
@Nullable
public static <T> T lastElement(@Nullable List<T> list) {
if (isEmpty(list)) {
return null;
}
return list.get(list.size() - 1);
}
/**
* Marshal the elements from the given enumeration into an array of the given type.
* Enumeration elements must be assignable to the type of the given array. The array
* returned will be a different instance than the array given.
*/
public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
ArrayList<A> elements = new ArrayList<>();
while (enumeration.hasMoreElements()) {
elements.add(enumeration.nextElement());
}
return elements.toArray(array);
}
/**
* Adapt an {@link Enumeration} to an {@link Iterator}.
* @param enumeration the original {@code Enumeration}
* @return the adapted {@code Iterator}
*/
public static <E> Iterator<E> toIterator(@Nullable Enumeration<E> enumeration) {
return (enumeration != null ? new EnumerationIterator<>(enumeration) : Collections.emptyIterator());
}
/**
* Adapt a {@code Map<K, List<V>>} to an {@code MultiValueMap<K, V>}.
* @param targetMap the original map
* @return the adapted multi-value map (wrapping the original map)
* @since 3.1
*/
public static <K, V> MultiValueMap<K, V> toMultiValueMap(Map<K, List<V>> targetMap) {
return new MultiValueMapAdapter<>(targetMap);
}
/**
* Return an unmodifiable view of the specified multi-value map.
* @param targetMap the map for which an unmodifiable view is to be returned.
* @return an unmodifiable view of the specified multi-value map
* @since 3.1
*/
@SuppressWarnings("unchecked")
public static <K, V> MultiValueMap<K, V> unmodifiableMultiValueMap(
MultiValueMap<? extends K, ? extends V> targetMap) {
Assert.notNull(targetMap, "'targetMap' must not be null");
Map<K, List<V>> result = newLinkedHashMap(targetMap.size());
targetMap.forEach((key, value) -> {
List<? extends V> values = Collections.unmodifiableList(value);
result.put(key, (List<V>) values);
});
Map<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);
return toMultiValueMap(unmodifiableMap);
}
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private final Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
@Override
public boolean hasNext() {
return this.enumeration.hasMoreElements();
}
@Override
public E next() {
return this.enumeration.nextElement();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
}
| Polish "Avoid resizing of Maps created by CollectionUtils"
See gh-29190
| spring-core/src/main/java/org/springframework/util/CollectionUtils.java | Polish "Avoid resizing of Maps created by CollectionUtils" | <ide><path>pring-core/src/main/java/org/springframework/util/CollectionUtils.java
<ide> * @see #newLinkedHashMap(int)
<ide> */
<ide> public static <K, V> HashMap<K, V> newHashMap(int expectedSize) {
<del> int capacity = (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
<del> return new HashMap<>(capacity, DEFAULT_LOAD_FACTOR);
<add> return new HashMap<>(computeMapInitialCapacity(expectedSize), DEFAULT_LOAD_FACTOR);
<ide> }
<ide>
<ide> /**
<ide> * @see #newHashMap(int)
<ide> */
<ide> public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int expectedSize) {
<del> int capacity = (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
<del> return new LinkedHashMap<>(capacity, DEFAULT_LOAD_FACTOR);
<add> return new LinkedHashMap<>(computeMapInitialCapacity(expectedSize), DEFAULT_LOAD_FACTOR);
<add> }
<add>
<add> private static int computeMapInitialCapacity(int expectedSize) {
<add> return (int) Math.ceil(expectedSize / (double) DEFAULT_LOAD_FACTOR);
<ide> }
<ide>
<ide> /** |
|
Java | mit | aef67b768c19ba6917d464fbd51d02cf3da64377 | 0 | simon816/Mixin,SpongePowered/Mixin | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* Information about a class, used as a way of keeping track of class hierarchy
* information needed to support more complex mixin behaviour such as detached
* superclass and mixin inheritance.
*/
class ClassInfo extends TreeInfo {
/**
* <p>To all intents and purposes, the "real" class hierarchy and the mixin
* class hierarchy exist in parallel, this means that for some hierarchy
* validation operations we need to walk <em>across</em> to the other
* hierarchy in order to allow meaningful validation to occur.</p>
*
* <p>This enum defines the type of traversal operations which are allowed
* for a particular lookup.</p>
*
* <p>Each traversal type has a <code>next</code> property which defines
* the traversal type to use on the <em>next</em> step of the hierarchy
* validation. For example, the type {@link #IMMEDIATE} which requires an
* immediate match falls through to {@link #NONE} on the next step, which
* prevents further traversals from occurring in the lookup.</p>
*/
static enum Traversal {
/**
* No traversals are allowed.
*/
NONE(null, false),
/**
* Traversal is allowed at all stages.
*/
ALL(null, true),
/**
* Traversal is allowed at the bottom of the hierarchy but no further.
*/
IMMEDIATE(Traversal.NONE, true),
/**
* Traversal is allowed only on superclasses and not at the bottom of
* the hierarchy.
*/
SUPER(Traversal.ALL, false);
private final Traversal next;
private final boolean traverse;
private Traversal(Traversal next, boolean traverse) {
this.next = next != null ? next : this;
this.traverse = traverse;
}
public Traversal next() {
return this.next;
}
public boolean canTraverse() {
return this.traverse;
}
}
/**
* Information about a member in this class
*/
abstract static class Member {
static enum Type {
METHOD,
FIELD
}
/**
* Member type
*/
private final Type type;
/**
* The original name of the member
*/
private final String memberName;
/**
* The member's signature
*/
private final String memberDesc;
/**
* True if this member was injected by a mixin, false if it was
* originally part of the class
*/
private final boolean isInjected;
/**
* Access modifiers
*/
private final int modifiers;
/**
* Current name of the member, may be different from {@link #memberName}
* if the member has been renamed
*/
private String currentName;
protected Member(Member member) {
this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected);
this.currentName = member.currentName;
}
protected Member(Type type, String name, String desc, int access) {
this(type, name, desc, access, false);
}
protected Member(Type type, String name, String desc, int access, boolean injected) {
this.type = type;
this.memberName = name;
this.memberDesc = desc;
this.isInjected = injected;
this.currentName = name;
this.modifiers = access;
}
public String getOriginalName() {
return this.memberName;
}
public String getName() {
return this.currentName;
}
public String getDesc() {
return this.memberDesc;
}
public boolean isInjected() {
return this.isInjected;
}
public boolean isRenamed() {
return this.currentName != this.memberName;
}
public boolean isPrivate() {
return (this.modifiers & Opcodes.ACC_PRIVATE) != 0;
}
// Abstract because this has to be static in order to contain the enum
public abstract ClassInfo getOwner();
public int getAccess() {
return this.modifiers;
}
public void renameTo(String name) {
this.currentName = name;
}
public boolean equals(String name, String desc) {
return (this.memberName.equals(name)
|| this.currentName.equals(name))
&& this.memberDesc.equals(desc);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Member)) {
return false;
}
Member other = (Member)obj;
return (other.memberName.equals(this.memberName)
|| other.currentName.equals(this.currentName))
&& other.memberDesc.equals(this.memberDesc);
}
@Override
public int hashCode() {
return this.toString().hashCode();
}
@Override
public String toString() {
return this.memberName + this.memberDesc;
}
}
/**
* A method
*/
class Method extends Member {
public Method(Member member) {
super(member);
}
public Method(MethodNode method) {
this(method, false);
}
public Method(MethodNode method, boolean injected) {
super(Type.METHOD, method.name, method.desc, method.access, injected);
}
public Method(String name, String desc) {
super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false);
}
public Method(String name, String desc, int access) {
super(Type.METHOD, name, desc, access, false);
}
public Method(String name, String desc, int access, boolean injected) {
super(Type.METHOD, name, desc, access, injected);
}
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Method)) {
return false;
}
return super.equals(obj);
}
}
/**
* A field
*/
class Field extends Member {
public Field(Member member) {
super(member);
}
public Field(FieldNode field) {
this(field, false);
}
public Field(FieldNode field, boolean injected) {
super(Type.FIELD, field.name, field.desc, field.access, injected);
}
public Field(String name, String desc, int access) {
super(Type.FIELD, name, desc, access, false);
}
public Field(String name, String desc, int access, boolean injected) {
super(Type.FIELD, name, desc, access, injected);
}
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Field)) {
return false;
}
return super.equals(obj);
}
}
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
/**
* Loading and parsing classes is expensive, so keep a cache of all the
* information we generate
*/
private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>();
private static final ClassInfo OBJECT = new ClassInfo();
static {
ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT);
}
/**
* Class name (binary name)
*/
private final String name;
/**
* Class superclass name (binary name)
*/
private final String superName;
/**
* Outer class name
*/
private final String outerName;
/**
* True either if this is not an inner class or if it is an inner class but
* does not contain a reference to its outer class.
*/
private final boolean isProbablyStatic;
/**
* Interfaces
*/
private final List<String> interfaces;
/**
* Public and protected methods (instance) methods in this class
*/
private final Set<Method> methods;
/**
* Public and protected fields in this class
*/
private final Set<Field> fields;
/**
* Mixins which target this class
*/
private final Set<MixinInfo> mixins = new HashSet<MixinInfo>();
/**
* Map of mixin types to corresponding supertypes, to avoid repeated
* lookups
*/
private final Map<ClassInfo, ClassInfo> correspondingTypes = new HashMap<ClassInfo, ClassInfo>();
/**
* Mixin info if this class is a mixin itself
*/
private final MixinInfo mixin;
/**
* True if this is a mixin rather than a class
*/
private final boolean isMixin;
/**
* True if this is an interface
*/
private final boolean isInterface;
/**
* Access flags
*/
private final int access;
/**
* Superclass reference, not initialised until required
*/
private ClassInfo superClass;
/**
* Outer class reference, not initialised until required
*/
private ClassInfo outerClass;
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
*/
private ClassInfo() {
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.outerName = null;
this.isProbablyStatic = true;
this.methods = ImmutableSet.<Method>of(
new Method("getClass", "()Ljava/lang/Class;"),
new Method("hashCode", "()I"),
new Method("equals", "(Ljava/lang/Object;)Z"),
new Method("clone", "()Ljava/lang/Object;"),
new Method("toString", "()Ljava/lang/String;"),
new Method("notify", "()V"),
new Method("notifyAll", "()V"),
new Method("wait", "(J)V"),
new Method("wait", "(JI)V"),
new Method("wait", "()V"),
new Method("finalize", "()V")
);
this.fields = Collections.<Field>emptySet();
this.isInterface = false;
this.interfaces = Collections.<String>emptyList();
this.access = Opcodes.ACC_PUBLIC;
this.isMixin = false;
this.mixin = null;
}
/**
* Initialise a ClassInfo from the supplied {@link ClassNode}
*
* @param classNode Class node to inspect
*/
private ClassInfo(ClassNode classNode) {
this.name = classNode.name;
this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT;
this.methods = new HashSet<Method>();
this.fields = new HashSet<Field>();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = Collections.<String>unmodifiableList(classNode.interfaces);
this.access = classNode.access;
this.isMixin = classNode instanceof MixinClassNode;
this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
for (MethodNode method : classNode.methods) {
this.addMethod(method, this.isMixin);
}
boolean isProbablyStatic = true;
String outerName = classNode.outerClass;
if (outerName == null) {
for (FieldNode field : classNode.fields) {
if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) {
if (field.name.startsWith("this$")) {
isProbablyStatic = false;
outerName = field.desc;
if (outerName.startsWith("L")) {
outerName = outerName.substring(1, outerName.length() - 1);
}
}
}
if ((field.access & Opcodes.ACC_STATIC) == 0) {
this.fields.add(new Field(field, this.isMixin));
}
}
}
this.isProbablyStatic = isProbablyStatic;
this.outerName = outerName;
}
void addMethod(MethodNode method) {
this.addMethod(method, true);
}
private void addMethod(MethodNode method, boolean injected) {
if (!method.name.startsWith("<") && (method.access & Opcodes.ACC_STATIC) == 0) {
this.methods.add(new Method(method, injected));
}
}
/**
* Add a mixin which targets this class
*/
void addMixin(MixinInfo mixin) {
if (this.isMixin) {
throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin");
}
this.mixins.add(mixin);
}
/**
* Get all mixins which target this class
*/
public Set<MixinInfo> getMixins() {
return Collections.<MixinInfo>unmodifiableSet(this.mixins);
}
/**
* Get whether this class is a mixin
*/
public boolean isMixin() {
return this.isMixin;
}
/**
* Get whether this class has ACC_PUBLIC
*/
public boolean isPublic() {
return (this.access & Opcodes.ACC_PUBLIC) != 0;
}
/**
* Get whether this class has ACC_ABSTRACT
*/
public boolean isAbstract() {
return (this.access & Opcodes.ACC_ABSTRACT) != 0;
}
/**
* Get whether this class has ACC_SYNTHETIC
*/
public boolean isSynthetic() {
return (this.access & Opcodes.ACC_SYNTHETIC) != 0;
}
/**
* Get whether this class is probably static (or is not an inner class)
*/
public boolean isProbablyStatic() {
return this.isProbablyStatic;
}
/**
* Get whether this class is an inner class
*/
public boolean isInner() {
return this.outerName != null;
}
/**
* Get whether this is an interface or not
*/
public boolean isInterface() {
return this.isInterface;
}
/**
* Returns the answer to life, the universe and everything
*/
public List<String> getInterfaces() {
return this.interfaces;
}
@Override
public String toString() {
return this.name;
}
public int getAccess() {
return this.access;
}
/**
* Get the class name (binary name)
*/
public String getName() {
return this.name;
}
/**
* Get the superclass name (binary name)
*/
public String getSuperName() {
return this.superName;
}
/**
* Get the superclass info, can return null if the superclass cannot be
* resolved
*/
public ClassInfo getSuperClass() {
if (this.superClass == null && this.superName != null) {
this.superClass = ClassInfo.forName(this.superName);
}
return this.superClass;
}
/**
* Get the name of the outer class, or null if this is not an inner class
*/
public String getOuterName() {
return this.outerName;
}
/**
* Get the outer class info, can return null if the outer class cannot be
* resolved or if this is not an inner class
*/
public ClassInfo getOuterClass() {
if (this.outerClass == null && this.outerName != null) {
this.outerClass = ClassInfo.forName(this.outerName);
}
return this.outerClass;
}
/**
* Class targets
*/
protected List<ClassInfo> getTargets() {
if (this.mixin != null) {
List<ClassInfo> targets = new ArrayList<ClassInfo>();
targets.add(this);
targets.addAll(this.mixin.getTargets());
return targets;
}
return ImmutableList.<ClassInfo>of(this);
}
/**
* Get class/interface methods
*
* @return read-only view of class methods
*/
public Set<Method> getMethods() {
return Collections.<Method>unmodifiableSet(this.methods);
}
/**
* If this is an interface, returns a set containing all methods in this
* interface and all super interfaces. If this is a class, returns a set
* containing all methods for all interfaces implemented by this class and
* all super interfaces of those interfaces.
*
* @return read-only view of class methods
*/
public Set<Method> getInterfaceMethods() {
Set<Method> methods = new HashSet<Method>();
ClassInfo superClass = this.addMethodsRecursive(methods);
if (!this.isInterface) {
while (superClass != null && superClass != ClassInfo.OBJECT) {
superClass = superClass.addMethodsRecursive(methods);
}
}
return Collections.<Method>unmodifiableSet(methods);
}
/**
* Recursive function used by {@link #getInterfaceMethods} to add all
* interface methods to the supplied set
*
* @param methods Method set to add to
* @return superclass reference, used to make the code above more fluent
*/
private ClassInfo addMethodsRecursive(Set<Method> methods) {
if (this.isInterface) {
methods.addAll(this.methods);
} else if (!this.isMixin) {
for (MixinInfo mixin : this.mixins) {
mixin.getClassInfo().addMethodsRecursive(methods);
}
}
for (String iface : this.interfaces) {
ClassInfo.forName(iface).addMethodsRecursive(methods);
}
return this.getSuperClass();
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Name of the superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(String superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Name of the superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(String superClass, Traversal traversal) {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
return true;
}
return this.findSuperClass(superClass, traversal) != null;
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) {
if (ClassInfo.OBJECT == superClass) {
return true;
}
return this.findSuperClass(superClass.name, traversal) != null;
}
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
*
* @param superClass Superclass name to search for
* @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass) {
return this.findSuperClass(superClass, Traversal.NONE);
}
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
*
* @param superClass Superclass name to search for
* @param traversal Traversal type to allow during this lookup
* @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass, Traversal traversal) {
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
List<ClassInfo> targets = superClassInfo.getTargets();
for (ClassInfo superTarget : targets) {
if (superClass.equals(superTarget.getName())) {
return superClassInfo;
}
ClassInfo found = superTarget.findSuperClass(superClass, traversal.next());
if (found != null) {
return found;
}
}
}
if (traversal.canTraverse()) {
for (MixinInfo mixin : this.mixins) {
ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal);
if (targetSuper != null) {
return targetSuper;
}
}
}
return null;
}
/**
* Walks up this class's hierarchy to find the first class targetted by the
* specified mixin. This is used during mixin application to translate a
* mixin reference to a "real class" reference <em>in the context of <b>this
* </b> class</em>.
*
* @param mixin Mixin class to search for
* @return corresponding (target) class for the specified mixin or null if
* no corresponding mixin was found
*/
ClassInfo findCorrespondingType(ClassInfo mixin) {
if (mixin == null || !mixin.isMixin || this.isMixin) {
return null;
}
ClassInfo correspondingType = this.correspondingTypes.get(mixin);
if (correspondingType == null) {
correspondingType = this.findSuperTypeForMixin(mixin);
this.correspondingTypes.put(mixin, correspondingType);
}
return correspondingType;
}
/* (non-Javadoc)
* Only used by findCorrespondingType(), used as a convenience so that
* sanity checks and caching can be handled more elegantly
*/
private ClassInfo findSuperTypeForMixin(ClassInfo mixin) {
ClassInfo superClass = this;
while (superClass != null && superClass != ClassInfo.OBJECT) {
for (MixinInfo minion : superClass.mixins) {
if (minion.getClassInfo().equals(mixin)) {
return superClass;
}
}
superClass = superClass.getSuperClass();
}
return null;
}
/**
* Find out whether this (mixin) class has another mixin in its superclass
* hierarchy. This method always returns false for non-mixin classes.
*
* @return true if and only if one or more mixins are found in the hierarchy
* of this mixin
*/
public boolean hasMixinInHierarchy() {
if (!this.isMixin) {
return false;
}
ClassInfo superClass = this.getSuperClass();
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.isMixin) {
return true;
}
superClass = superClass.getSuperClass();
}
return false;
}
/**
* Find out whether this (non-mixin) class has a mixin targetting
* <em>any</em> of its superclasses. This method always returns false for
* mixin classes.
*
* @return true if and only if one or more classes in this class's hierarchy
* are targetted by a mixin
*/
public boolean hasMixinTargetInHierarchy() {
if (this.isMixin) {
return false;
}
ClassInfo superClass = this.getSuperClass();
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.mixins.size() > 0) {
return true;
}
superClass = superClass.getSuperClass();
}
return false;
}
/**
* Finds the specified private or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified private or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, boolean includePrivate) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, boolean includePrivate) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass) {
return this.findMethodInHierarchy(name, desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, false);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.METHOD);
}
/**
* Finds the specified private or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified private or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, boolean includePrivate) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, boolean includePrivate) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass) {
return this.findFieldInHierarchy(name, desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, false);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.FIELD);
}
/**
* Finds a public or protected member in the hierarchy of this class which
* matches the supplied details
*
* @param name Member name to search
* @param desc Member descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param priv Include private members in the search
* @param type Type of member to search for (field or method)
* @return the discovered member or null if the member could not be resolved
*/
private <M extends Member> M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean priv, Type type) {
if (includeThisClass) {
M member = this.findMember(name, desc, priv, type);
if (member != null) {
return member;
}
if (traversal.canTraverse()) {
for (MixinInfo mixin : this.mixins) {
M mixinMember = mixin.getClassInfo().findMember(name, desc, priv, type);
if (mixinMember != null) {
return this.cloneMember(mixinMember);
}
}
}
}
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
for (ClassInfo superTarget : superClassInfo.getTargets()) {
// Do not search for private members in superclasses, pass priv as false
M member = superTarget.findInHierarchy(name, desc, true, traversal.next(), false, type);
if (member != null) {
return member;
}
}
}
return null;
}
/**
* Effectively a clone method for member, placed here so that the enclosing
* instance for the inner class is this class and not the enclosing instance
* of the existing class. Basically creates a cloned member with this
* ClassInfo as its parent.
*
* @param member
* @return
*/
@SuppressWarnings("unchecked")
private <M extends Member> M cloneMember(M member) {
if (member instanceof Method) {
return (M)new Method(member);
}
return (M)new Field(member);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodNode method) {
return this.findMethod(method.name, method.desc, false);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodNode method, boolean includePrivate) {
return this.findMethod(method.name, method.desc, includePrivate);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodInsnNode method) {
return this.findMethod(method.name, method.desc, false);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodInsnNode method, boolean includePrivate) {
return this.findMethod(method.name, method.desc, includePrivate);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method name to search for
* @param desc Method signature to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(String name, String desc, boolean includePrivate) {
return this.findMember(name, desc, includePrivate, Type.METHOD);
}
/**
* Finds the specified field in this class
*
* @param field Field to search for
* @return the field object or null if the field could not be resolved
*/
public Field findField(FieldNode field) {
return this.findField(field.name, field.desc, (field.access & Opcodes.ACC_PRIVATE) != 0);
}
/**
* Finds the specified public or protected method in this class
*
* @param field Field to search for
* @param includePrivate also search private fields
* @return the field object or null if the field could not be resolved
*/
public Field findField(FieldInsnNode field, boolean includePrivate) {
return this.findField(field.name, field.desc, includePrivate);
}
/**
* Finds the specified field in this class
*
* @param name Field name to search for
* @param desc Field signature to search for
* @param includePrivate also search private fields
* @return the field object or null if the field could not be resolved
*/
public Field findField(String name, String desc, boolean includePrivate) {
return this.findMember(name, desc, includePrivate, Type.FIELD);
}
/**
* Finds the specified member in this class
*
* @param name Field name to search for
* @param desc Field signature to search for
* @param includePrivate also search private fields
* @param memberType Type of member list to search
* @return the field object or null if the field could not be resolved
*/
private <M extends Member> M findMember(String name, String desc, boolean includePrivate, Type memberType) {
@SuppressWarnings("unchecked")
Set<M> members = (Set<M>)(memberType == Type.METHOD ? this.methods : this.fields);
for (M member : members) {
if (member.equals(name, desc) && (includePrivate || !member.isPrivate())) {
return member;
}
}
return null;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof ClassInfo)) {
return false;
}
return ((ClassInfo)other).name.equals(this.name);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
/**
* Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for
* the class was already defined, then the original ClassInfo is returned
* from the internal cache. Otherwise a new ClassInfo is created and
* returned.
*
* @param classNode
* @return
*/
public static ClassInfo fromClassNode(ClassNode classNode) {
ClassInfo info = ClassInfo.cache.get(classNode.name);
if (info == null) {
info = new ClassInfo(classNode);
ClassInfo.cache.put(classNode.name, info);
}
return info;
}
/**
* Return a ClassInfo for the specified class name, fetches the ClassInfo
* from the cache where possible
*
* @param className Binary name of the class to look up
* @return ClassInfo for the specified class name or null if the specified
* name cannot be resolved for some reason
*/
public static ClassInfo forName(String className) {
className = className.replace('.', '/');
ClassInfo info = ClassInfo.cache.get(className);
if (info == null) {
try {
ClassNode classNode = TreeInfo.getClassNode(className);
info = new ClassInfo(classNode);
} catch (Exception ex) {
ex.printStackTrace();
}
// Put null in the cache if load failed
ClassInfo.cache.put(className, info);
}
return info;
}
}
| src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
* Information about a class, used as a way of keeping track of class hierarchy
* information needed to support more complex mixin behaviour such as detached
* superclass and mixin inheritance.
*/
class ClassInfo extends TreeInfo {
/**
* <p>To all intents and purposes, the "real" class hierarchy and the mixin
* class hierarchy exist in parallel, this means that for some hierarchy
* validation operations we need to walk <em>across</em> to the other
* hierarchy in order to allow meaningful validation to occur.</p>
*
* <p>This enum defines the type of traversal operations which are allowed
* for a particular lookup.</p>
*
* <p>Each traversal type has a <code>next</code> property which defines
* the traversal type to use on the <em>next</em> step of the hierarchy
* validation. For example, the type {@link #IMMEDIATE} which requires an
* immediate match falls through to {@link #NONE} on the next step, which
* prevents further traversals from occurring in the lookup.</p>
*/
static enum Traversal {
/**
* No traversals are allowed.
*/
NONE(null, false),
/**
* Traversal is allowed at all stages.
*/
ALL(null, true),
/**
* Traversal is allowed at the bottom of the hierarchy but no further.
*/
IMMEDIATE(Traversal.NONE, true),
/**
* Traversal is allowed only on superclasses and not at the bottom of
* the hierarchy.
*/
SUPER(Traversal.ALL, false);
private final Traversal next;
private final boolean traverse;
private Traversal(Traversal next, boolean traverse) {
this.next = next != null ? next : this;
this.traverse = traverse;
}
public Traversal next() {
return this.next;
}
public boolean canTraverse() {
return this.traverse;
}
}
/**
* Information about a member in this class
*/
abstract static class Member {
static enum Type {
METHOD,
FIELD
}
/**
* Member type
*/
private final Type type;
/**
* The original name of the member
*/
private final String memberName;
/**
* The member's signature
*/
private final String memberDesc;
/**
* True if this member was injected by a mixin, false if it was
* originally part of the class
*/
private final boolean isInjected;
/**
* Access modifiers
*/
private final int modifiers;
/**
* Current name of the member, may be different from {@link #memberName}
* if the member has been renamed
*/
private String currentName;
protected Member(Member member) {
this(member.type, member.memberName, member.memberDesc, member.modifiers, member.isInjected);
this.currentName = member.currentName;
}
protected Member(Type type, String name, String desc, int access) {
this(type, name, desc, access, false);
}
protected Member(Type type, String name, String desc, int access, boolean injected) {
this.type = type;
this.memberName = name;
this.memberDesc = desc;
this.isInjected = injected;
this.currentName = name;
this.modifiers = access;
}
public String getOriginalName() {
return this.memberName;
}
public String getName() {
return this.currentName;
}
public String getDesc() {
return this.memberDesc;
}
public boolean isInjected() {
return this.isInjected;
}
public boolean isRenamed() {
return this.currentName != this.memberName;
}
public boolean isPrivate() {
return (this.modifiers & Opcodes.ACC_PRIVATE) != 0;
}
// Abstract because this has to be static in order to contain the enum
public abstract ClassInfo getOwner();
public int getAccess() {
return this.modifiers;
}
public void renameTo(String name) {
this.currentName = name;
}
public boolean equals(String name, String desc) {
return (this.memberName.equals(name)
|| this.currentName.equals(name))
&& this.memberDesc.equals(desc);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Member)) {
return false;
}
Member other = (Member)obj;
return (other.memberName.equals(this.memberName)
|| other.currentName.equals(this.currentName))
&& other.memberDesc.equals(this.memberDesc);
}
@Override
public int hashCode() {
return this.toString().hashCode();
}
@Override
public String toString() {
return this.memberName + this.memberDesc;
}
}
/**
* A method
*/
class Method extends Member {
public Method(Member member) {
super(member);
}
public Method(MethodNode method) {
this(method, false);
}
public Method(MethodNode method, boolean injected) {
super(Type.METHOD, method.name, method.desc, method.access, injected);
}
public Method(String name, String desc) {
super(Type.METHOD, name, desc, Opcodes.ACC_PUBLIC, false);
}
public Method(String name, String desc, int access) {
super(Type.METHOD, name, desc, access, false);
}
public Method(String name, String desc, int access, boolean injected) {
super(Type.METHOD, name, desc, access, injected);
}
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Method)) {
return false;
}
return super.equals(obj);
}
}
/**
* A field
*/
class Field extends Member {
public Field(Member member) {
super(member);
}
public Field(FieldNode field) {
this(field, false);
}
public Field(FieldNode field, boolean injected) {
super(Type.FIELD, field.name, field.desc, field.access, injected);
}
public Field(String name, String desc, int access) {
super(Type.FIELD, name, desc, access, false);
}
public Field(String name, String desc, int access, boolean injected) {
super(Type.FIELD, name, desc, access, injected);
}
@Override
public ClassInfo getOwner() {
return ClassInfo.this;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Field)) {
return false;
}
return super.equals(obj);
}
}
private static final String JAVA_LANG_OBJECT = "java/lang/Object";
/**
* Loading and parsing classes is expensive, so keep a cache of all the
* information we generate
*/
private static final Map<String, ClassInfo> cache = new HashMap<String, ClassInfo>();
private static final ClassInfo OBJECT = new ClassInfo();
static {
ClassInfo.cache.put(ClassInfo.JAVA_LANG_OBJECT, ClassInfo.OBJECT);
}
/**
* Class name (binary name)
*/
private final String name;
/**
* Class superclass name (binary name)
*/
private final String superName;
/**
* Outer class name
*/
private final String outerName;
/**
* True either if this is not an inner class or if it is an inner class but
* does not contain a reference to its outer class.
*/
private final boolean isProbablyStatic;
/**
* Interfaces
*/
private final List<String> interfaces;
/**
* Public and protected methods (instance) methods in this class
*/
private final Set<Method> methods;
/**
* Public and protected fields in this class
*/
private final Set<Field> fields;
/**
* Mixins which target this class
*/
private final Set<MixinInfo> mixins = new HashSet<MixinInfo>();
/**
* Map of mixin types to corresponding supertypes, to avoid repeated
* lookups
*/
private final Map<ClassInfo, ClassInfo> correspondingTypes = new HashMap<ClassInfo, ClassInfo>();
/**
* Mixin info if this class is a mixin itself
*/
private final MixinInfo mixin;
/**
* True if this is a mixin rather than a class
*/
private final boolean isMixin;
/**
* True if this is an interface
*/
private final boolean isInterface;
/**
* Access flags
*/
private final int access;
/**
* Superclass reference, not initialised until required
*/
private ClassInfo superClass;
/**
* Outer class reference, not initialised until required
*/
private ClassInfo outerClass;
/**
* Private constructor used to initialise the ClassInfo for {@link Object}
*/
private ClassInfo() {
this.name = ClassInfo.JAVA_LANG_OBJECT;
this.superName = null;
this.outerName = null;
this.isProbablyStatic = true;
this.methods = ImmutableSet.<Method>of(
new Method("getClass", "()Ljava/lang/Class;"),
new Method("hashCode", "()I"),
new Method("equals", "(Ljava/lang/Object;)Z"),
new Method("clone", "()Ljava/lang/Object;"),
new Method("toString", "()Ljava/lang/String;"),
new Method("notify", "()V"),
new Method("notifyAll", "()V"),
new Method("wait", "(J)V"),
new Method("wait", "(JI)V"),
new Method("wait", "()V"),
new Method("finalize", "()V")
);
this.fields = Collections.<Field>emptySet();
this.isInterface = false;
this.interfaces = Collections.<String>emptyList();
this.access = Opcodes.ACC_PUBLIC;
this.isMixin = false;
this.mixin = null;
}
/**
* Initialise a ClassInfo from the supplied {@link ClassNode}
*
* @param classNode Class node to inspect
*/
private ClassInfo(ClassNode classNode) {
this.name = classNode.name;
this.superName = classNode.superName != null ? classNode.superName : ClassInfo.JAVA_LANG_OBJECT;
this.methods = new HashSet<Method>();
this.fields = new HashSet<Field>();
this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
this.interfaces = Collections.unmodifiableList(classNode.interfaces);
this.access = classNode.access;
this.isMixin = classNode instanceof MixinClassNode;
this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
for (MethodNode method : classNode.methods) {
this.addMethod(method, this.isMixin);
}
boolean isProbablyStatic = true;
String outerName = classNode.outerClass;
if (outerName == null) {
for (FieldNode field : classNode.fields) {
if ((field.access & Opcodes.ACC_SYNTHETIC) != 0) {
if (field.name.startsWith("this$")) {
isProbablyStatic = false;
outerName = field.desc;
if (outerName.startsWith("L")) {
outerName = outerName.substring(1, outerName.length() - 1);
}
}
}
if ((field.access & Opcodes.ACC_STATIC) == 0) {
this.fields.add(new Field(field, this.isMixin));
}
}
}
this.isProbablyStatic = isProbablyStatic;
this.outerName = outerName;
}
void addMethod(MethodNode method) {
this.addMethod(method, true);
}
private void addMethod(MethodNode method, boolean injected) {
if (!method.name.startsWith("<") && (method.access & Opcodes.ACC_STATIC) == 0) {
this.methods.add(new Method(method, injected));
}
}
/**
* Add a mixin which targets this class
*/
void addMixin(MixinInfo mixin) {
if (this.isMixin) {
throw new IllegalArgumentException("Cannot add target " + this.name + " for " + mixin.getClassName() + " because the target is a mixin");
}
this.mixins.add(mixin);
}
/**
* Get all mixins which target this class
*/
public Set<MixinInfo> getMixins() {
return Collections.unmodifiableSet(this.mixins);
}
/**
* Get whether this class is a mixin
*/
public boolean isMixin() {
return this.isMixin;
}
/**
* Get whether this class has ACC_PUBLIC
*/
public boolean isPublic() {
return (this.access & Opcodes.ACC_PUBLIC) != 0;
}
/**
* Get whether this class has ACC_SYNTHETIC
*/
public boolean isSynthetic() {
return (this.access & Opcodes.ACC_SYNTHETIC) != 0;
}
/**
* Get whether this class is probably static (or is not an inner class)
*/
public boolean isProbablyStatic() {
return this.isProbablyStatic;
}
/**
* Get whether this class is an inner class
*/
public boolean isInner() {
return this.outerName != null;
}
/**
* Get whether this is an interface or not
*/
public boolean isInterface() {
return this.isInterface;
}
/**
* Returns the answer to life, the universe and everything
*/
public List<String> getInterfaces() {
return this.interfaces;
}
@Override
public String toString() {
return this.name;
}
public int getAccess() {
return this.access;
}
/**
* Get the class name (binary name)
*/
public String getName() {
return this.name;
}
/**
* Get the superclass name (binary name)
*/
public String getSuperName() {
return this.superName;
}
/**
* Get the superclass info, can return null if the superclass cannot be
* resolved
*/
public ClassInfo getSuperClass() {
if (this.superClass == null && this.superName != null) {
this.superClass = ClassInfo.forName(this.superName);
}
return this.superClass;
}
/**
* Get the name of the outer class, or null if this is not an inner class
*/
public String getOuterName() {
return this.outerName;
}
/**
* Get the outer class info, can return null if the outer class cannot be
* resolved or if this is not an inner class
*/
public ClassInfo getOuterClass() {
if (this.outerClass == null && this.outerName != null) {
this.outerClass = ClassInfo.forName(this.outerName);
}
return this.outerClass;
}
/**
* Class targets
*/
protected List<ClassInfo> getTargets() {
if (this.mixin != null) {
List<ClassInfo> targets = new ArrayList<ClassInfo>();
targets.add(this);
targets.addAll(this.mixin.getTargets());
return targets;
}
return ImmutableList.<ClassInfo>of(this);
}
/**
* Get class/interface methods
*
* @return read-only view of class methods
*/
public Set<Method> getMethods() {
return Collections.unmodifiableSet(this.methods);
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Name of the superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(String superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Name of the superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(String superClass, Traversal traversal) {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
return true;
}
return this.findSuperClass(superClass, traversal) != null;
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
}
/**
* Test whether this class has the specified superclass in its hierarchy
*
* @param superClass Superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) {
if (ClassInfo.OBJECT == superClass) {
return true;
}
return this.findSuperClass(superClass.name, traversal) != null;
}
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
*
* @param superClass Superclass name to search for
* @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass) {
return this.findSuperClass(superClass, Traversal.NONE);
}
/**
* Search for the specified superclass in this class's hierarchy. If found
* returns the ClassInfo, otherwise returns null
*
* @param superClass Superclass name to search for
* @param traversal Traversal type to allow during this lookup
* @return Matched superclass or null if not found
*/
public ClassInfo findSuperClass(String superClass, Traversal traversal) {
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
List<ClassInfo> targets = superClassInfo.getTargets();
for (ClassInfo superTarget : targets) {
if (superClass.equals(superTarget.getName())) {
return superClassInfo;
}
ClassInfo found = superTarget.findSuperClass(superClass, traversal.next());
if (found != null) {
return found;
}
}
}
if (traversal.canTraverse()) {
for (MixinInfo mixin : this.mixins) {
ClassInfo targetSuper = mixin.getClassInfo().findSuperClass(superClass, traversal);
if (targetSuper != null) {
return targetSuper;
}
}
}
return null;
}
/**
* Walks up this class's hierarchy to find the first class targetted by the
* specified mixin. This is used during mixin application to translate a
* mixin reference to a "real class" reference <em>in the context of <b>this
* </b> class</em>.
*
* @param mixin Mixin class to search for
* @return corresponding (target) class for the specified mixin or null if
* no corresponding mixin was found
*/
ClassInfo findCorrespondingType(ClassInfo mixin) {
if (mixin == null || !mixin.isMixin || this.isMixin) {
return null;
}
ClassInfo correspondingType = this.correspondingTypes.get(mixin);
if (correspondingType == null) {
correspondingType = this.findSuperTypeForMixin(mixin);
this.correspondingTypes.put(mixin, correspondingType);
}
return correspondingType;
}
/* (non-Javadoc)
* Only used by findCorrespondingType(), used as a convenience so that
* sanity checks and caching can be handled more elegantly
*/
private ClassInfo findSuperTypeForMixin(ClassInfo mixin) {
ClassInfo superClass = this;
while (superClass != null && superClass != ClassInfo.OBJECT) {
for (MixinInfo minion : superClass.mixins) {
if (minion.getClassInfo().equals(mixin)) {
return superClass;
}
}
superClass = superClass.getSuperClass();
}
return null;
}
/**
* Find out whether this (mixin) class has another mixin in its superclass
* hierarchy. This method always returns false for non-mixin classes.
*
* @return true if and only if one or more mixins are found in the hierarchy
* of this mixin
*/
public boolean hasMixinInHierarchy() {
if (!this.isMixin) {
return false;
}
ClassInfo superClass = this.getSuperClass();
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.isMixin) {
return true;
}
superClass = superClass.getSuperClass();
}
return false;
}
/**
* Find out whether this (non-mixin) class has a mixin targetting
* <em>any</em> of its superclasses. This method always returns false for
* mixin classes.
*
* @return true if and only if one or more classes in this class's hierarchy
* are targetted by a mixin
*/
public boolean hasMixinTargetInHierarchy() {
if (this.isMixin) {
return false;
}
ClassInfo superClass = this.getSuperClass();
while (superClass != null && superClass != ClassInfo.OBJECT) {
if (superClass.mixins.size() > 0) {
return true;
}
superClass = superClass.getSuperClass();
}
return false;
}
/**
* Finds the specified private or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified private or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodNode method, boolean includeThisClass, boolean includePrivate) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param method Method to search for
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(MethodInsnNode method, boolean includeThisClass, boolean includePrivate) {
return this.findMethodInHierarchy(method.name, method.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass) {
return this.findMethodInHierarchy(name, desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findMethodInHierarchy(name, desc, includeThisClass, traversal, false);
}
/**
* Finds the specified public or protected method in this class's hierarchy
*
* @param name Method name to search for
* @param desc Method descriptor
* @param includeThisClass True to return this class if the method exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param includePrivate Include private members in the search
* @return the method object or null if the method could not be resolved
*/
public Method findMethodInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.METHOD);
}
/**
* Finds the specified private or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified private or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldNode field, boolean includeThisClass, boolean includePrivate) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param field Field to search for
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(FieldInsnNode field, boolean includeThisClass, boolean includePrivate) {
return this.findFieldInHierarchy(field.name, field.desc, includeThisClass, Traversal.NONE, includePrivate);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass) {
return this.findFieldInHierarchy(name, desc, includeThisClass, Traversal.NONE);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal) {
return this.findFieldInHierarchy(name, desc, includeThisClass, traversal, false);
}
/**
* Finds the specified public or protected field in this class's hierarchy
*
* @param name Field name to search for
* @param desc Field descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param includePrivate Include private members in the search
* @return the field object or null if the field could not be resolved
*/
public Field findFieldInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean includePrivate) {
return this.findInHierarchy(name, desc, includeThisClass, traversal, includePrivate, Type.FIELD);
}
/**
* Finds a public or protected member in the hierarchy of this class which
* matches the supplied details
*
* @param name Member name to search
* @param desc Member descriptor
* @param includeThisClass True to return this class if the field exists
* here, or false to search only superclasses
* @param traversal Traversal type to allow during this lookup
* @param priv Include private members in the search
* @param type Type of member to search for (field or method)
* @return the discovered member or null if the member could not be resolved
*/
private <M extends Member> M findInHierarchy(String name, String desc, boolean includeThisClass, Traversal traversal, boolean priv, Type type) {
if (includeThisClass) {
M member = this.findMember(name, desc, priv, type);
if (member != null) {
return member;
}
if (traversal.canTraverse()) {
for (MixinInfo mixin : this.mixins) {
M mixinMember = mixin.getClassInfo().findMember(name, desc, priv, type);
if (mixinMember != null) {
return this.cloneMember(mixinMember);
}
}
}
}
ClassInfo superClassInfo = this.getSuperClass();
if (superClassInfo != null) {
for (ClassInfo superTarget : superClassInfo.getTargets()) {
// Do not search for private members in superclasses, pass priv as false
M member = superTarget.findInHierarchy(name, desc, true, traversal.next(), false, type);
if (member != null) {
return member;
}
}
}
return null;
}
/**
* Effectively a clone method for member, placed here so that the enclosing
* instance for the inner class is this class and not the enclosing instance
* of the existing class. Basically creates a cloned member with this
* ClassInfo as its parent.
*
* @param member
* @return
*/
@SuppressWarnings("unchecked")
private <M extends Member> M cloneMember(M member) {
if (member instanceof Method) {
return (M)new Method(member);
}
return (M)new Field(member);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodNode method) {
return this.findMethod(method.name, method.desc, false);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodNode method, boolean includePrivate) {
return this.findMethod(method.name, method.desc, includePrivate);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodInsnNode method) {
return this.findMethod(method.name, method.desc, false);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(MethodInsnNode method, boolean includePrivate) {
return this.findMethod(method.name, method.desc, includePrivate);
}
/**
* Finds the specified public or protected method in this class
*
* @param method Method name to search for
* @param desc Method signature to search for
* @param includePrivate also search private fields
* @return the method object or null if the method could not be resolved
*/
public Method findMethod(String name, String desc, boolean includePrivate) {
return this.findMember(name, desc, includePrivate, Type.METHOD);
}
/**
* Finds the specified field in this class
*
* @param field Field to search for
* @return the field object or null if the field could not be resolved
*/
public Field findField(FieldNode field) {
return this.findField(field.name, field.desc, (field.access & Opcodes.ACC_PRIVATE) != 0);
}
/**
* Finds the specified public or protected method in this class
*
* @param field Field to search for
* @param includePrivate also search private fields
* @return the field object or null if the field could not be resolved
*/
public Field findField(FieldInsnNode field, boolean includePrivate) {
return this.findField(field.name, field.desc, includePrivate);
}
/**
* Finds the specified field in this class
*
* @param name Field name to search for
* @param desc Field signature to search for
* @param includePrivate also search private fields
* @return the field object or null if the field could not be resolved
*/
public Field findField(String name, String desc, boolean includePrivate) {
return this.findMember(name, desc, includePrivate, Type.FIELD);
}
/**
* Finds the specified member in this class
*
* @param name Field name to search for
* @param desc Field signature to search for
* @param includePrivate also search private fields
* @param memberType Type of member list to search
* @return the field object or null if the field could not be resolved
*/
private <M extends Member> M findMember(String name, String desc, boolean includePrivate, Type memberType) {
@SuppressWarnings("unchecked")
Set<M> members = (Set<M>)(memberType == Type.METHOD ? this.methods : this.fields);
for (M member : members) {
if (member.equals(name, desc) && (includePrivate || !member.isPrivate())) {
return member;
}
}
return null;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof ClassInfo)) {
return false;
}
return ((ClassInfo)other).name.equals(this.name);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
/**
* Return a ClassInfo for the supplied {@link ClassNode}. If a ClassInfo for
* the class was already defined, then the original ClassInfo is returned
* from the internal cache. Otherwise a new ClassInfo is created and
* returned.
*
* @param classNode
* @return
*/
public static ClassInfo fromClassNode(ClassNode classNode) {
ClassInfo info = ClassInfo.cache.get(classNode.name);
if (info == null) {
info = new ClassInfo(classNode);
ClassInfo.cache.put(classNode.name, info);
}
return info;
}
/**
* Return a ClassInfo for the specified class name, fetches the ClassInfo
* from the cache where possible
*
* @param className Binary name of the class to look up
* @return ClassInfo for the specified class name or null if the specified
* name cannot be resolved for some reason
*/
public static ClassInfo forName(String className) {
className = className.replace('.', '/');
ClassInfo info = ClassInfo.cache.get(className);
if (info == null) {
try {
ClassNode classNode = TreeInfo.getClassNode(className);
info = new ClassInfo(classNode);
} catch (Exception ex) {
ex.printStackTrace();
}
// Put null in the cache if load failed
ClassInfo.cache.put(className, info);
}
return info;
}
}
| Add method to ClassInfo to fetch all interface methods recursively | src/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java | Add method to ClassInfo to fetch all interface methods recursively | <ide><path>rc/main/java/org/spongepowered/asm/mixin/transformer/ClassInfo.java
<ide> this.methods = new HashSet<Method>();
<ide> this.fields = new HashSet<Field>();
<ide> this.isInterface = ((classNode.access & Opcodes.ACC_INTERFACE) != 0);
<del> this.interfaces = Collections.unmodifiableList(classNode.interfaces);
<add> this.interfaces = Collections.<String>unmodifiableList(classNode.interfaces);
<ide> this.access = classNode.access;
<ide> this.isMixin = classNode instanceof MixinClassNode;
<ide> this.mixin = this.isMixin ? ((MixinClassNode)classNode).getMixin() : null;
<ide> * Get all mixins which target this class
<ide> */
<ide> public Set<MixinInfo> getMixins() {
<del> return Collections.unmodifiableSet(this.mixins);
<add> return Collections.<MixinInfo>unmodifiableSet(this.mixins);
<ide> }
<ide>
<ide> /**
<ide> public boolean isPublic() {
<ide> return (this.access & Opcodes.ACC_PUBLIC) != 0;
<ide> }
<del>
<add>
<add> /**
<add> * Get whether this class has ACC_ABSTRACT
<add> */
<add> public boolean isAbstract() {
<add> return (this.access & Opcodes.ACC_ABSTRACT) != 0;
<add> }
<add>
<ide> /**
<ide> * Get whether this class has ACC_SYNTHETIC
<ide> */
<ide> * @return read-only view of class methods
<ide> */
<ide> public Set<Method> getMethods() {
<del> return Collections.unmodifiableSet(this.methods);
<add> return Collections.<Method>unmodifiableSet(this.methods);
<add> }
<add>
<add> /**
<add> * If this is an interface, returns a set containing all methods in this
<add> * interface and all super interfaces. If this is a class, returns a set
<add> * containing all methods for all interfaces implemented by this class and
<add> * all super interfaces of those interfaces.
<add> *
<add> * @return read-only view of class methods
<add> */
<add> public Set<Method> getInterfaceMethods() {
<add> Set<Method> methods = new HashSet<Method>();
<add>
<add> ClassInfo superClass = this.addMethodsRecursive(methods);
<add> if (!this.isInterface) {
<add> while (superClass != null && superClass != ClassInfo.OBJECT) {
<add> superClass = superClass.addMethodsRecursive(methods);
<add> }
<add> }
<add>
<add> return Collections.<Method>unmodifiableSet(methods);
<add> }
<add>
<add> /**
<add> * Recursive function used by {@link #getInterfaceMethods} to add all
<add> * interface methods to the supplied set
<add> *
<add> * @param methods Method set to add to
<add> * @return superclass reference, used to make the code above more fluent
<add> */
<add> private ClassInfo addMethodsRecursive(Set<Method> methods) {
<add> if (this.isInterface) {
<add> methods.addAll(this.methods);
<add> } else if (!this.isMixin) {
<add> for (MixinInfo mixin : this.mixins) {
<add> mixin.getClassInfo().addMethodsRecursive(methods);
<add> }
<add> }
<add>
<add> for (String iface : this.interfaces) {
<add> ClassInfo.forName(iface).addMethodsRecursive(methods);
<add> }
<add>
<add> return this.getSuperClass();
<ide> }
<ide>
<ide> /** |
|
Java | bsd-2-clause | 0d848b5dbce4a04b762f9b296ede3f926fac154f | 0 | highsource/jsonix-schema-compiler,highsource/jsonix-schema-compiler,highsource/jsonix-schema-compiler | package org.hisrc.jsonix.xml.xsom;
import static com.sun.tools.xjc.model.Multiplicity.ONE;
import java.math.BigInteger;
import com.sun.tools.xjc.model.Multiplicity;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSModelGroup;
import com.sun.xml.xsom.XSModelGroupDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSWildcard;
import com.sun.xml.xsom.visitor.XSTermFunction;
public class MultiplicityCounterNG implements XSTermFunction<Multiplicity> {
public static final XSTermFunction<Multiplicity> INSTANCE = new MultiplicityCounterNG();
private MultiplicityCounterNG() {
}
public Multiplicity particle(XSParticle p) {
Multiplicity m = p.getTerm().apply(this);
BigInteger max;
if (m == null
|| m.max == null
|| (BigInteger.valueOf(XSParticle.UNBOUNDED).equals(p
.getMaxOccurs())))
max = null;
else
max = p.getMaxOccurs();
return Multiplicity.multiply(m,
Multiplicity.create(p.getMinOccurs(), max));
}
public Multiplicity wildcard(XSWildcard wc) {
return ONE;
}
public Multiplicity modelGroupDecl(XSModelGroupDecl decl) {
return modelGroup(decl.getModelGroup());
}
public Multiplicity modelGroup(XSModelGroup group) {
boolean isChoice = group.getCompositor() == XSModelGroup.CHOICE;
Multiplicity r = null;
for (XSParticle p : group.getChildren()) {
Multiplicity m = particle(p);
if (r == null) {
r = m;
continue;
}
if (isChoice) {
r = Multiplicity.choice(r, m);
} else {
r = Multiplicity.group(r, m);
}
}
return r;
}
public Multiplicity elementDecl(XSElementDecl decl) {
return ONE;
}
}
| compiler/src/main/java/org/hisrc/jsonix/xml/xsom/MultiplicityCounterNG.java | package org.hisrc.jsonix.xml.xsom;
import static com.sun.tools.xjc.model.Multiplicity.ONE;
import static com.sun.tools.xjc.model.Multiplicity.ZERO;
import java.math.BigInteger;
import com.sun.tools.xjc.model.Multiplicity;
import com.sun.xml.xsom.XSElementDecl;
import com.sun.xml.xsom.XSModelGroup;
import com.sun.xml.xsom.XSModelGroupDecl;
import com.sun.xml.xsom.XSParticle;
import com.sun.xml.xsom.XSWildcard;
import com.sun.xml.xsom.visitor.XSTermFunction;
public class MultiplicityCounterNG implements XSTermFunction<Multiplicity> {
public static final XSTermFunction<Multiplicity> INSTANCE = new MultiplicityCounterNG();
private MultiplicityCounterNG() {
}
public Multiplicity particle(XSParticle p) {
Multiplicity m = p.getTerm().apply(this);
BigInteger max;
if (m.max == null
|| (BigInteger.valueOf(XSParticle.UNBOUNDED).equals(p
.getMaxOccurs())))
max = null;
else
max = p.getMaxOccurs();
return Multiplicity.multiply(m,
Multiplicity.create(p.getMinOccurs(), max));
}
public Multiplicity wildcard(XSWildcard wc) {
return ONE;
}
public Multiplicity modelGroupDecl(XSModelGroupDecl decl) {
return modelGroup(decl.getModelGroup());
}
public Multiplicity modelGroup(XSModelGroup group) {
boolean isChoice = group.getCompositor() == XSModelGroup.CHOICE;
Multiplicity r = null;
for (XSParticle p : group.getChildren()) {
Multiplicity m = particle(p);
if (r == null) {
r = m;
continue;
}
if (isChoice) {
r = Multiplicity.choice(r, m);
} else {
r = Multiplicity.group(r, m);
}
}
return r;
}
public Multiplicity elementDecl(XSElementDecl decl) {
return ONE;
}
}
| Issue #62. | compiler/src/main/java/org/hisrc/jsonix/xml/xsom/MultiplicityCounterNG.java | Issue #62. | <ide><path>ompiler/src/main/java/org/hisrc/jsonix/xml/xsom/MultiplicityCounterNG.java
<ide> package org.hisrc.jsonix.xml.xsom;
<ide>
<ide> import static com.sun.tools.xjc.model.Multiplicity.ONE;
<del>import static com.sun.tools.xjc.model.Multiplicity.ZERO;
<ide>
<ide> import java.math.BigInteger;
<ide>
<ide> Multiplicity m = p.getTerm().apply(this);
<ide>
<ide> BigInteger max;
<del> if (m.max == null
<add> if (m == null
<add> || m.max == null
<ide> || (BigInteger.valueOf(XSParticle.UNBOUNDED).equals(p
<ide> .getMaxOccurs())))
<ide> max = null; |
|
Java | mit | c616eb38a4208ee56d28a620e71dd4ca6ccafe2f | 0 | t3ddftw/DroidIBus | package net.littlebigisland.droidibus.ibus;
/**
* Implements functions of the BoardMonitor. For the most part
* we won't be doing any message parsing here since the BoardMonitor
* is more of an input interface than anything.
*/
public class BoardMonitorSystemCommand extends IBusSystemCommand {
// Main Systems
private byte boardMonitor = DeviceAddress.OnBoardMonitor.toByte();
private byte gfxDriver = DeviceAddress.GraphicsNavigationDriver.toByte();
private byte IKESystem = DeviceAddress.InstrumentClusterElectronics.toByte();
private byte RadioSystem = DeviceAddress.Radio.toByte();
// OBC Functions
private byte OBCRequest = 0x41;
private byte OBCRequestGet = 0x01;
private byte OBCRequestReset = 0x10;
/**
* Generate an IKE message requesting a value reset for the given system.
* @param system The hex value of the system in question
* @param checksum The hex value of the message checksum
* @return Byte array of message to send to IBus
*/
private byte[] IKEGetRequest(int system, int checksum){
return new byte[] {
gfxDriver, 0x05, IKESystem,
OBCRequest, (byte)system, OBCRequestGet, (byte)checksum
};
}
/**
* Generate an IKE message requesting the value for the given system.
* @param system The hex value of the system in question
* @param checksum The hex value of the message checksum
* @return Byte array of message to send to IBus
*/
private byte[] IKEResetRequest(int system, int checksum){
return new byte[] {
gfxDriver, 0x05, IKESystem,
OBCRequest, (byte)system, OBCRequestReset, (byte)checksum
};
}
/**
* Issue a Get request for the "Time" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getTime(){
return IKEGetRequest(0x01, 0xFF);
}
/**
* Issue a Get request for the "Date" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getDate(){
return IKEGetRequest(0x02, 0xFC);
}
/**
* Issue a Get request for the "Outdoor Temp" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getOutdoorTemp(){
return IKEGetRequest(0x03, 0xFD);
}
/**
* Issue a Get request for the "Consumption 1" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getFuel1(){
return IKEGetRequest(0x04, 0xFA);
}
/**
* Issue a Get request for the "Consumption 2" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getFuel2(){
return IKEGetRequest(0x05, 0xFB);
}
/**
* Issue a Get request for the "Fuel Tank Range" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getRange(){
return IKEGetRequest(0x06, 0xF8);
}
/**
* Issue a Get request for the "Avg. Speed" Value.
* @return Byte array of message to send to IBus
*/
public byte[] getAvgSpeed(){
return IKEGetRequest(0x06, 0xF4);
}
/**
* Reset the "Consumption 1" IKE metric
* @return Byte array of message to send to IBus
*/
public byte[] resetFuel1(){
return IKEResetRequest(0x04, 0xEB);
}
/**
* Reset the "Consumption 2" IKE metric
* @return Byte array of message to send to IBus
*/
public byte[] resetFuel2(){
return IKEResetRequest(0x05, 0xEA);
}
/**
* Reset the "Avg. Speed" IKE metric
* @return Byte array of message to send to IBus
*/
public byte[] resetAvgSpeed(){
return IKEResetRequest(0x0A, 0xE5);
}
// Radio Buttons
public byte[] sendModePress(){
return new byte[]{
boardMonitor, 0x04, RadioSystem, 0x48, 0x23, (byte)0xF7
};
}
public byte[] sendModeRelease(){
return new byte[]{
boardMonitor, 0x04, RadioSystem, 0x48, (byte)0xA3, (byte)0xFF
};
}
}
| src/net/littlebigisland/droidibus/ibus/BoardMonitorSystemCommand.java | package net.littlebigisland.droidibus.ibus;
import java.util.ArrayList;
public class BoardMonitorSystemCommand extends IBusSystemCommand {
private byte BoardMonitorSystem = DeviceAddress.GraphicsNavigationDriver.toByte();
private byte IKESystem = DeviceAddress.InstrumentClusterElectronics.toByte();
// OBC Functions
private byte OBCRequest = 0x41;
private byte OBCRequestGet = 0x01;
private byte OBCRequestReset = 0x10;
public void mapReceived(ArrayList<Byte> msg) {
// TODO Auto-generated method stub
}
public byte[] getFuel1(){
return new byte[] {
BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x04, OBCRequestGet, (byte)0xFA
};
}
public byte[] resetFuel1(){
return new byte[] {
BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x04, OBCRequestReset, (byte)0xEB
};
}
public byte[] resetAvgSpeed(){
return new byte[] {
BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x0A, OBCRequestReset, (byte)0xE5
};
}
}
| Added many BM functions
| src/net/littlebigisland/droidibus/ibus/BoardMonitorSystemCommand.java | Added many BM functions | <ide><path>rc/net/littlebigisland/droidibus/ibus/BoardMonitorSystemCommand.java
<ide> package net.littlebigisland.droidibus.ibus;
<ide>
<del>import java.util.ArrayList;
<add>/**
<add> * Implements functions of the BoardMonitor. For the most part
<add> * we won't be doing any message parsing here since the BoardMonitor
<add> * is more of an input interface than anything.
<add> */
<add>public class BoardMonitorSystemCommand extends IBusSystemCommand {
<ide>
<del>public class BoardMonitorSystemCommand extends IBusSystemCommand {
<del>
<del> private byte BoardMonitorSystem = DeviceAddress.GraphicsNavigationDriver.toByte();
<add> // Main Systems
<add> private byte boardMonitor = DeviceAddress.OnBoardMonitor.toByte();
<add> private byte gfxDriver = DeviceAddress.GraphicsNavigationDriver.toByte();
<ide> private byte IKESystem = DeviceAddress.InstrumentClusterElectronics.toByte();
<add> private byte RadioSystem = DeviceAddress.Radio.toByte();
<ide>
<ide> // OBC Functions
<ide> private byte OBCRequest = 0x41;
<ide> private byte OBCRequestGet = 0x01;
<ide> private byte OBCRequestReset = 0x10;
<del>
<del> public void mapReceived(ArrayList<Byte> msg) {
<del> // TODO Auto-generated method stub
<del>
<del> }
<ide>
<del> public byte[] getFuel1(){
<add> /**
<add> * Generate an IKE message requesting a value reset for the given system.
<add> * @param system The hex value of the system in question
<add> * @param checksum The hex value of the message checksum
<add> * @return Byte array of message to send to IBus
<add> */
<add> private byte[] IKEGetRequest(int system, int checksum){
<ide> return new byte[] {
<del> BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x04, OBCRequestGet, (byte)0xFA
<add> gfxDriver, 0x05, IKESystem,
<add> OBCRequest, (byte)system, OBCRequestGet, (byte)checksum
<ide> };
<ide> }
<ide>
<del> public byte[] resetFuel1(){
<add> /**
<add> * Generate an IKE message requesting the value for the given system.
<add> * @param system The hex value of the system in question
<add> * @param checksum The hex value of the message checksum
<add> * @return Byte array of message to send to IBus
<add> */
<add> private byte[] IKEResetRequest(int system, int checksum){
<ide> return new byte[] {
<del> BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x04, OBCRequestReset, (byte)0xEB
<add> gfxDriver, 0x05, IKESystem,
<add> OBCRequest, (byte)system, OBCRequestReset, (byte)checksum
<ide> };
<ide> }
<ide>
<add> /**
<add> * Issue a Get request for the "Time" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getTime(){
<add> return IKEGetRequest(0x01, 0xFF);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Date" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getDate(){
<add> return IKEGetRequest(0x02, 0xFC);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Outdoor Temp" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getOutdoorTemp(){
<add> return IKEGetRequest(0x03, 0xFD);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Consumption 1" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getFuel1(){
<add> return IKEGetRequest(0x04, 0xFA);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Consumption 2" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getFuel2(){
<add> return IKEGetRequest(0x05, 0xFB);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Fuel Tank Range" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getRange(){
<add> return IKEGetRequest(0x06, 0xF8);
<add> }
<add>
<add> /**
<add> * Issue a Get request for the "Avg. Speed" Value.
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] getAvgSpeed(){
<add> return IKEGetRequest(0x06, 0xF4);
<add> }
<add>
<add> /**
<add> * Reset the "Consumption 1" IKE metric
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] resetFuel1(){
<add> return IKEResetRequest(0x04, 0xEB);
<add> }
<add>
<add> /**
<add> * Reset the "Consumption 2" IKE metric
<add> * @return Byte array of message to send to IBus
<add> */
<add> public byte[] resetFuel2(){
<add> return IKEResetRequest(0x05, 0xEA);
<add> }
<add>
<add> /**
<add> * Reset the "Avg. Speed" IKE metric
<add> * @return Byte array of message to send to IBus
<add> */
<ide> public byte[] resetAvgSpeed(){
<del> return new byte[] {
<del> BoardMonitorSystem, 0x05, IKESystem, OBCRequest, 0x0A, OBCRequestReset, (byte)0xE5
<add> return IKEResetRequest(0x0A, 0xE5);
<add> }
<add>
<add> // Radio Buttons
<add>
<add> public byte[] sendModePress(){
<add> return new byte[]{
<add> boardMonitor, 0x04, RadioSystem, 0x48, 0x23, (byte)0xF7
<ide> };
<ide> }
<del>
<add>
<add> public byte[] sendModeRelease(){
<add> return new byte[]{
<add> boardMonitor, 0x04, RadioSystem, 0x48, (byte)0xA3, (byte)0xFF
<add> };
<add> }
<ide> } |
|
Java | apache-2.0 | 969b5266c7389d700978170a81bc6252be54aa20 | 0 | cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x,cbeams-archive/spring-framework-2.5.x | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jpa.config;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.Conventions;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter;
import org.springframework.util.StringUtils;
/**
* @author Costin Leau
* @since 2.0
*/
public class JpaNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("entityManagerFactory", new ConfigBeanDefinitionParser());
}
private class ConfigBeanDefinitionParser implements BeanDefinitionParser {
private static final String VENDOR = "vendor";
private static final String VENDOR_PROVIDED = "provided";
private static final String VENDOR_CUSTOM = "custom";
private static final String ID_ATTRIBUTE = "id";
private static final String LOAD_TIME_WEAVER = "load-time-weaver";
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(LocalEntityManagerFactoryBean.class);
builder.setSource(parserContext.extractSource(element));
configureAttributes(parserContext, element, builder);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String localName = node.getLocalName();
if (VENDOR.equals(localName)) {
parseVendor((Element) node, parserContext, builder);
}
}
}
BeanDefinitionRegistry registry = parserContext.getRegistry();
AbstractBeanDefinition def = builder.getBeanDefinition();
String id = resolveId(def, parserContext, element);
registry.registerBeanDefinition(id, def);
return null;
}
private void configureAttributes(ParserContext parserContext, Element element, BeanDefinitionBuilder builder) {
NamedNodeMap attributes = element.getAttributes();
for (int x = 0; x < attributes.getLength(); x++) {
Attr attribute = (Attr) attributes.item(x);
String name = attribute.getLocalName();
if (ID_ATTRIBUTE.equals(name)) {
continue;
}
if (LOAD_TIME_WEAVER.equals(name)) {
builder.getBeanDefinition().setBeanClass(LocalContainerEntityManagerFactoryBean.class);
}
builder.addPropertyValue(extractPropertyName(name), attribute.getValue());
}
}
private String resolveId(AbstractBeanDefinition definition, ParserContext parserContext, Element element) {
if (false) {
return BeanDefinitionReaderUtils.generateBeanName(
definition, parserContext.getRegistry(), parserContext.isNested());
}
else {
return extractId(element);
}
}
protected String extractId(Element element) {
return element.getAttribute(ID_ATTRIBUTE);
}
private String extractPropertyName(String attributeName) {
return Conventions.attributeNameToPropertyName(attributeName);
}
private void parseVendor(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
BeanDefinitionBuilder vendorBuilder = BeanDefinitionBuilder.rootBeanDefinition(JpaVendorAdapter.class);
configureAttributes(parserContext, element, vendorBuilder);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String localName = node.getLocalName();
if (VENDOR_PROVIDED.equals(localName)) {
String name = ((Element) node).getAttribute("name");
if (StringUtils.hasText(name)) {
if ("toplink".equals(name))
vendorBuilder.getBeanDefinition().setBeanClass(TopLinkJpaVendorAdapter.class);
else if ("hibernate".equals(name))
vendorBuilder.getBeanDefinition().setBeanClass(HibernateJpaVendorAdapter.class);
}
}
else if (VENDOR_CUSTOM.equals(localName)) {
String clazz = ((Element) node).getAttribute("class");
if (StringUtils.hasText(clazz))
vendorBuilder.getBeanDefinition().setBeanClassName(clazz);
}
}
}
builder.addPropertyValue("jpaVendorAdapter", vendorBuilder.getBeanDefinition());
}
}
}
| sandbox/src/org/springframework/orm/jpa/config/JpaNamespaceHandler.java | /*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.orm.jpa.config;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.Conventions;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.LocalEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter;
import org.springframework.util.StringUtils;
/**
* @author Costin Leau
* @since 2.0
*/
public class JpaNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
registerBeanDefinitionParser("entityManagerFactory", new ConfigBeanDefinitionParser());
}
private class ConfigBeanDefinitionParser implements BeanDefinitionParser {
private static final String VENDOR = "vendor";
private static final String VENDOR_PROVIDED = "provided";
private static final String VENDOR_CUSTOM = "custom";
private static final String ID_ATTRIBUTE = "id";
private static final String LOAD_TIME_WEAVER = "load-time-weaver";
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(LocalEntityManagerFactoryBean.class);
builder.setSource(parserContext.extractSource(element));
configureAttributes(parserContext, element, builder);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String localName = node.getLocalName();
if (VENDOR.equals(localName)) {
parseVendor((Element) node, parserContext, builder);
}
}
}
BeanDefinitionRegistry registry = parserContext.getRegistry();
BeanDefinition def = builder.getBeanDefinition();
String id = resolveId(def, parserContext, element);
registry.registerBeanDefinition(id, def);
return null;
}
private void configureAttributes(ParserContext parserContext, Element element, BeanDefinitionBuilder builder) {
NamedNodeMap attributes = element.getAttributes();
for (int x = 0; x < attributes.getLength(); x++) {
Attr attribute = (Attr) attributes.item(x);
String name = attribute.getLocalName();
if (ID_ATTRIBUTE.equals(name)) {
continue;
}
if (LOAD_TIME_WEAVER.equals(name)) {
builder.getBeanDefinition().setBeanClass(LocalContainerEntityManagerFactoryBean.class);
}
builder.addPropertyValue(extractPropertyName(name), attribute.getValue());
}
}
private String resolveId(BeanDefinition definition, ParserContext parserContext, Element element) {
if (false) {
return BeanDefinitionReaderUtils.generateBeanName((AbstractBeanDefinition) definition,
parserContext.getRegistry(), parserContext.isNested());
}
else {
return extractId(element);
}
}
protected String extractId(Element element) {
return element.getAttribute(ID_ATTRIBUTE);
}
private String extractPropertyName(String attributeName) {
return Conventions.attributeNameToPropertyName(attributeName);
}
private void parseVendor(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
BeanDefinitionBuilder vendorBuilder = BeanDefinitionBuilder.rootBeanDefinition(JpaVendorAdapter.class);
configureAttributes(parserContext, element, vendorBuilder);
NodeList childNodes = element.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
String localName = node.getLocalName();
if (VENDOR_PROVIDED.equals(localName)) {
String name = ((Element) node).getAttribute("name");
if (StringUtils.hasText(name)) {
if ("toplink".equals(name))
vendorBuilder.getBeanDefinition().setBeanClass(TopLinkJpaVendorAdapter.class);
else if ("hibernate".equals(name))
vendorBuilder.getBeanDefinition().setBeanClass(HibernateJpaVendorAdapter.class);
}
}
else if (VENDOR_CUSTOM.equals(localName)) {
String clazz = ((Element) node).getAttribute("class");
if (StringUtils.hasText(clazz))
vendorBuilder.getBeanDefinition().setBeanClassName(clazz);
}
}
}
builder.addPropertyValue("jpaVendorAdapter", vendorBuilder.getBeanDefinition());
}
}
}
| resolved unnecessary cast to AbstractBeanDefinition
git-svn-id: b619a0c99665f88f1afe72824344cefe9a1c8c90@12039 fd5a2b45-1f63-4059-99e9-3c7cb7fd75c8
| sandbox/src/org/springframework/orm/jpa/config/JpaNamespaceHandler.java | resolved unnecessary cast to AbstractBeanDefinition | <ide><path>andbox/src/org/springframework/orm/jpa/config/JpaNamespaceHandler.java
<ide> }
<ide>
<ide> BeanDefinitionRegistry registry = parserContext.getRegistry();
<del> BeanDefinition def = builder.getBeanDefinition();
<add> AbstractBeanDefinition def = builder.getBeanDefinition();
<ide> String id = resolveId(def, parserContext, element);
<ide> registry.registerBeanDefinition(id, def);
<ide>
<ide> }
<ide> }
<ide>
<del> private String resolveId(BeanDefinition definition, ParserContext parserContext, Element element) {
<add> private String resolveId(AbstractBeanDefinition definition, ParserContext parserContext, Element element) {
<ide> if (false) {
<del> return BeanDefinitionReaderUtils.generateBeanName((AbstractBeanDefinition) definition,
<del> parserContext.getRegistry(), parserContext.isNested());
<add> return BeanDefinitionReaderUtils.generateBeanName(
<add> definition, parserContext.getRegistry(), parserContext.isNested());
<ide> }
<ide> else {
<ide> return extractId(element); |
|
Java | apache-2.0 | b9aa84f3838dd550bf2e336ba7f01316c241a274 | 0 | GDeviceLab/DeviceLab,GDeviceLab/DeviceLab,GDeviceLab/DeviceLab,GDeviceLab/DeviceLab | /*
* 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 eu.revevol.calendar.constants;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import eu.revevol.calendar.pojo.PojoEmail;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.gson.Gson;
import eu.revevol.calendar.model.Location;
import eu.revevol.calendar.model.Person;
import eu.revevol.calendar.util.Methods;
/**
*
* @author Revevol
*/
public class EmailTemplate {
/**
* Send an email to location admins where a new user ask to access to their location
*/
public static void adviseByEmailLocationAdmins(Person p, Location locationObj, String emailArrayString) {
PojoEmail pojo = new PojoEmail();
pojo.setEmails(emailArrayString);
pojo.setSubject("New user asks to access to location");
String message = "Dear location Admin,<br>"+
"the user <a href='mailto:"+Methods.notNullText(p.mail)+"'>"+
Methods.notNullText(p.name)+"</a> "+
"from " +
Methods.notNullText(p.startupName) +" asks to apply to " +
Methods.notNullText(locationObj.name) + ".<br>" +
"Please, access to <a href='"+Params.APPLICATION_ADDRESS+"/desktop/#/location/edit/"+locationObj.id+"' target='_blank'>"+Params.SENDER_EMAIL_APPLICATION_NAME+"</a> to approve or reject the user." +
"<br><br>"+
"***Automatic message, do not answer***";
pojo.setMessageBody(message);
Queue queue = QueueFactory.getQueue("sendEmail");
queue.add(withUrl("/task/TaskSendEmail").payload(new Gson().toJson(pojo)));
}
/**
* Send email to advice the user for the acceptance of the ACL by local admin
*/
public static void adviseByEmailUserAcceptedForLocation(Person p, Location locationObj, String emailArrayString) {
PojoEmail pojo = new PojoEmail();
pojo.setEmails(emailArrayString);
pojo.setSubject("Your startup "+p.startupName+" has been approved");
String message = "Dear "+ p.name +",<br>"+
"your startup "+p.startupName+" has been approved for using the DeviceLab at location "+locationObj.name+".<br>"+
"Log to <a href='"+Params.APPLICATION_ADDRESS+"' target='_blank'>"+Params.SENDER_EMAIL_APPLICATION_NAME+"</a> and enjoy"+
"<br><br>"+
"***Automatic message, do not answer***";
pojo.setMessageBody(message);
Queue queue = QueueFactory.getQueue("sendEmail");
queue.add(withUrl("/task/TaskSendEmail").payload(new Gson().toJson(pojo)));
}
}
| src/main/java/eu/revevol/calendar/constants/EmailTemplate.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 eu.revevol.calendar.constants;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import eu.revevol.calendar.pojo.PojoEmail;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.gson.Gson;
import eu.revevol.calendar.model.Location;
import eu.revevol.calendar.model.Person;
import eu.revevol.calendar.util.Methods;
/**
*
* @author Revevol
*/
public class EmailTemplate {
/**
* Send an email to location admins where a new user ask to access to their location
*/
public static void adviseByEmailLocationAdmins(Person p, Location locationObj, String emailArrayString) {
PojoEmail pojo = new PojoEmail();
pojo.setEmails(emailArrayString);
pojo.setSubject("New user asks to access to location");
String message = "Dear location Admin,<br>"+
"the user BB <a href='mailto:"+Methods.notNullText(p.mail)+"'>"+
Methods.notNullText(p.name)+"</a> "+
"from " +
Methods.notNullText(p.startupName) +" asks to apply to " +
Methods.notNullText(locationObj.name) + ".<br>" +
"Please, access to <a href='"+Params.APPLICATION_ADDRESS+"/desktop/#/location/edit/"+locationObj.id+"' target='_blank'>"+Params.SENDER_EMAIL_APPLICATION_NAME+"</a> to approve or reject the user." +
"<br><br>"+
"***Automatic message, do not answer***";
pojo.setMessageBody(message);
Queue queue = QueueFactory.getQueue("sendEmail");
queue.add(withUrl("/task/TaskSendEmail").payload(new Gson().toJson(pojo)));
}
/**
* Send email to advice the user for the acceptance of the ACL by local admin
*/
public static void adviseByEmailUserAcceptedForLocation(Person p, Location locationObj, String emailArrayString) {
PojoEmail pojo = new PojoEmail();
pojo.setEmails(emailArrayString);
pojo.setSubject("Your startup "+p.startupName+" has been approved");
String message = "Dear "+ p.name +",<br>"+
"your startup "+p.startupName+" has been approved for using the DeviceLab at location "+locationObj.name+".<br>"+
"Log to <a href='"+Params.APPLICATION_ADDRESS+"' target='_blank'>"+Params.SENDER_EMAIL_APPLICATION_NAME+"</a> and enjoy"+
"<br><br>"+
"***Automatic message, do not answer***";
pojo.setMessageBody(message);
Queue queue = QueueFactory.getQueue("sendEmail");
queue.add(withUrl("/task/TaskSendEmail").payload(new Gson().toJson(pojo)));
}
}
| fix #121
| src/main/java/eu/revevol/calendar/constants/EmailTemplate.java | fix #121 | <ide><path>rc/main/java/eu/revevol/calendar/constants/EmailTemplate.java
<ide> pojo.setEmails(emailArrayString);
<ide> pojo.setSubject("New user asks to access to location");
<ide> String message = "Dear location Admin,<br>"+
<del> "the user BB <a href='mailto:"+Methods.notNullText(p.mail)+"'>"+
<add> "the user <a href='mailto:"+Methods.notNullText(p.mail)+"'>"+
<ide> Methods.notNullText(p.name)+"</a> "+
<ide> "from " +
<ide> Methods.notNullText(p.startupName) +" asks to apply to " + |
|
Java | mit | 39b756ccdf65cffe67daf17849a84cc3cc393f66 | 0 | oaplatform/oap,oaplatform/oap | /*
* The MIT License (MIT)
*
* Copyright (c) Open Application Platform Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oap.io;
import oap.testng.AbstractPerformance;
import oap.testng.Env;
import org.apache.commons.lang3.RandomStringUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
/**
* Created by Igor Petrenko on 08.04.2016.
*/
@Test( enabled = false )
public class FilesPerformance extends AbstractPerformance {
public static final int SAMPLES = 100;
@BeforeMethod
@Override
public void beforeMethod() {
super.beforeMethod();
IntStream
.range( 0, 2000 )
.forEach( i -> {
final Path path = Env.tmpPath( "tt/test" + i );
Files.writeString( path, RandomStringUtils.random( 10 ) );
} );
}
@Test
public void testLastModificationTime1() {
final long[] size = { 0 };
final Path tt = Env.tmpPath( "tt" );
benchmark( "java.nio.file.Files.getLastModifiedTime()", SAMPLES, 5, ( x ) -> {
try( DirectoryStream<Path> stream = java.nio.file.Files.newDirectoryStream( tt ) ) {
for( Path p : stream ) {
size[0] += java.nio.file.Files.getLastModifiedTime( p ).to( TimeUnit.NANOSECONDS );
}
}
} );
System.out.println( size[0] );
}
@Test
public void testLastModificationTime2() {
final long[] size = { 0 };
final File tt = Env.tmpPath( "tt" ).toFile();
benchmark( "java.io.File.lastModified()", SAMPLES, 5, ( x ) -> {
for( File file : tt.listFiles() ) {
size[0] += file.lastModified();
}
} );
System.out.println( size[0] );
}
}
| oap-stdlib/src/test/java/oap/io/FilesPerformance.java | /*
* The MIT License (MIT)
*
* Copyright (c) Open Application Platform Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oap.io;
import oap.testng.AbstractPerformance;
import oap.testng.Env;
import org.apache.commons.lang3.RandomStringUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.util.stream.IntStream;
/**
* Created by Igor Petrenko on 08.04.2016.
*/
@Test( enabled = false )
public class FilesPerformance extends AbstractPerformance {
public static final int SAMPLES = 100;
@BeforeMethod
@Override
public void beforeMethod() {
super.beforeMethod();
IntStream
.range( 0, 2000 )
.forEach( i -> {
final Path path = Env.tmpPath( "tt/test" + i );
Files.writeString( path, RandomStringUtils.random( 10 ) );
} );
}
@Test
public void testLastModificationTime1() {
final long[] size = { 0 };
final Path tt = Env.tmpPath( "tt" );
benchmark( "java.io.File.lastModified()", SAMPLES, 5, ( x ) -> {
try( DirectoryStream<Path> stream = java.nio.file.Files.newDirectoryStream( tt ) ) {
for( Path p : stream ) {
size[0] += java.nio.file.Files.getLastModifiedTime( p ).toMillis();
}
}
} );
System.out.println( size[0] );
}
@Test
public void testLastModificationTime2() {
final long[] size = { 0 };
final File tt = Env.tmpPath( "tt" ).toFile();
benchmark( "java.io.File.lastModified()", SAMPLES, 5, ( x ) -> {
for( File file : tt.listFiles() ) {
size[0] += file.lastModified();
}
} );
System.out.println( size[0] );
}
}
| update
| oap-stdlib/src/test/java/oap/io/FilesPerformance.java | update | <ide><path>ap-stdlib/src/test/java/oap/io/FilesPerformance.java
<ide> import java.io.File;
<ide> import java.nio.file.DirectoryStream;
<ide> import java.nio.file.Path;
<add>import java.util.concurrent.TimeUnit;
<ide> import java.util.stream.IntStream;
<ide>
<ide> /**
<ide> final long[] size = { 0 };
<ide> final Path tt = Env.tmpPath( "tt" );
<ide>
<del> benchmark( "java.io.File.lastModified()", SAMPLES, 5, ( x ) -> {
<add> benchmark( "java.nio.file.Files.getLastModifiedTime()", SAMPLES, 5, ( x ) -> {
<ide> try( DirectoryStream<Path> stream = java.nio.file.Files.newDirectoryStream( tt ) ) {
<ide> for( Path p : stream ) {
<del> size[0] += java.nio.file.Files.getLastModifiedTime( p ).toMillis();
<add> size[0] += java.nio.file.Files.getLastModifiedTime( p ).to( TimeUnit.NANOSECONDS );
<ide> }
<ide> }
<ide> } ); |
|
Java | mit | 2f9f1e081896dab131bf57168ebf051546abd272 | 0 | conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5 | package com.conveyal.r5.profile;
import com.conveyal.r5.analyst.cluster.TaskStatistics;
import com.conveyal.r5.analyst.scenario.RemoveTrip;
import com.conveyal.r5.analyst.scenario.Scenario;
import com.conveyal.r5.publish.StaticPropagatedTimesStore;
import com.conveyal.r5.streets.StreetRouter;
import com.conveyal.r5.transit.RouteInfo;
import com.conveyal.r5.transit.TransportNetwork;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Stream;
/**
* A profile router that finds some number of suboptimal paths.
*/
public class SuboptimalPathProfileRouter {
private static final Logger LOG = LoggerFactory.getLogger(SuboptimalPathProfileRouter.class);
/**
* how many minutes to search past the end of the time window and then discard.
* We do this because the searches earlier in the time window have their transfers "pre-compressed" because they
* would be dominated by trips later in the time window, but this does not hold for trips near the end of the time
* window. See extensive discussion in https://github.com/conveyal/r5/issues/42.
*/
public static final int OVERSEARCH_MINUTES = 30;
public final TransportNetwork transportNetwork;
public final ProfileRequest req;
public final int TIMEOUT_MS = 5000;
private Set<PathWithTimes> paths = new HashSet<>();
private TIntIntMap stopsNearOrigin;
private TIntIntMap stopsNearDestination;
private Queue<TIntSet> patternsToBan = new ArrayDeque<>();
// if an option has a min time less than this, retain it
private int worstTimeToAccept = Integer.MAX_VALUE;
public SuboptimalPathProfileRouter(TransportNetwork network, ProfileRequest req) {
this.transportNetwork = network;
this.req = req;
}
/** Find paths (options) that could be used */
public Collection<PathWithTimes> route () {
LOG.info("Performing access search");
StreetRouter access = new StreetRouter(transportNetwork.streetLayer);
access.setOrigin(req.fromLat, req.fromLon);
// TODO origin search with multiple modes
// TODO true time limit (important for driving)
access.distanceLimitMeters = (int) (req.walkSpeed * req.maxWalkTime * 60);
access.route();
stopsNearOrigin = access.getReachedStops();
LOG.info("Performing egress search");
// FIXME for now, egress search is always by walking
StreetRouter egress = new StreetRouter(transportNetwork.streetLayer);
// TODO reverse search (doesn't really matter for peds)
egress.setOrigin(req.toLat, req.toLon);
egress.distanceLimitMeters = (int) (req.walkSpeed * req.maxWalkTime * 60);
egress.route();
stopsNearDestination = egress.getReachedStops();
LOG.info("Performing transit search for optimal routes");
Set<PathWithTimes> optimalPaths = findPaths(null);
// no need to filter, all optimal paths are optimal at some point so they by definition overlap with the best option
this.paths.addAll(optimalPaths);
worstTimeToAccept = optimalPaths.stream().mapToInt(p -> p.max + req.suboptimalMinutes).min().getAsInt();
LOG.info("Found {} optimal paths", optimalPaths.size());
TIntSet patternsUsed = new TIntHashSet();
paths.forEach(p -> patternsUsed.addAll(p.patterns));
patternsUsed.forEach(i -> {
TIntHashSet set = new TIntHashSet(1);
set.add(i);
patternsToBan.add(set);
return true;
});
paths.forEach(p -> patternsToBan.add(new TIntHashSet(p.patterns)));
LOG.info("Running up to {} searches for suboptimal paths", this.patternsToBan.size());
long startTime = System.currentTimeMillis();
while (!patternsToBan.isEmpty() && !disjointOptionsPresent() && System.currentTimeMillis() < startTime + TIMEOUT_MS) {
Set<PathWithTimes> paths = findPaths(patternsToBan.remove());
paths.stream().filter(p -> p.min < worstTimeToAccept).forEach(this.paths::add);
}
if (!disjointOptionsPresent()) LOG.warn("Found no disjoint options!");
LOG.info("done");
// TODO once this all works, comment out
dump();
return this.paths;
}
/** are there any disjoint options (options which do not share patterns)? */
private boolean disjointOptionsPresent () {
// count how many times each pattern is used
TIntIntMap routeUsage = new TIntIntHashMap();
for (PathWithTimes path : paths) {
for (int pattern : path.patterns) {
routeUsage.adjustOrPutValue(transportNetwork.transitLayer.tripPatterns.get(pattern).routeIndex, 1, 1);
}
}
// check if any path is disjoint
PATHS: for (PathWithTimes path : paths) {
for (int pattern : path.patterns) {
if (routeUsage.get(transportNetwork.transitLayer.tripPatterns.get(pattern).routeIndex) > 1) continue PATHS; // not disjoint
}
// this path is disjoint
return true;
}
return false;
}
/** find paths and add them to the set of possible paths, respecting banned patterns */
private Set<PathWithTimes> findPaths (TIntSet bannedPatterns) {
Set<PathWithTimes> paths = new HashSet<>();
// make defensive copy, eventually this may be called in parallel
ProfileRequest req = this.req.clone();
req.scenario = new Scenario(0);
req.scenario.modifications = new ArrayList<>();
if (this.req.scenario != null && this.req.scenario.modifications != null)
req.scenario.modifications.addAll(this.req.scenario.modifications);
// extend the time window because the end of the time window has trips with accurate times but without transfer
// compression.
req.toTime += OVERSEARCH_MINUTES * 60;
// remove appropriate trips
if (bannedPatterns != null && !bannedPatterns.isEmpty()) {
RemoveTrip rt = new RemoveTrip();
rt.tripId = new ArrayList<>();
rt.patternIds = bannedPatterns;
req.scenario.modifications.add(rt);
}
TransportNetwork modified = req.scenario.applyToTransportNetwork(transportNetwork);
RaptorWorker worker = new RaptorWorker(modified.transitLayer, null, req);
StaticPropagatedTimesStore pts = (StaticPropagatedTimesStore) worker.runRaptor(stopsNearOrigin, null, new TaskStatistics());
// chop off the last few minutes of the time window so we don't get a lot of unoptimized
// trips without transfer compression near the end of the time window. See https://github.com/conveyal/r5/issues/42
int iterations = pts.times.length - OVERSEARCH_MINUTES;
int stops = pts.times[0].length;
// only find a single optimal path each minute
PathWithTimes[] optimalPathsEachIteration = new PathWithTimes[iterations];
int[] optimalTimesEachIteration = new int[iterations];
Arrays.fill(optimalTimesEachIteration, Integer.MAX_VALUE);
for (int stop = 0; stop < stops; stop++) {
if (!stopsNearDestination.containsKey(stop)) continue;
for (int iter = 0; iter < iterations; iter++) {
RaptorState state = worker.statesEachIteration.get(iter);
// only compute a path if this stop was reached
if (state.bestNonTransferTimes[stop] != RaptorWorker.UNREACHED &&
state.bestNonTransferTimes[stop] + stopsNearDestination.get(stop) < optimalTimesEachIteration[iter]) {
optimalTimesEachIteration[iter] = state.bestNonTransferTimes[stop] + stopsNearDestination.get(stop);
PathWithTimes path = new PathWithTimes(state, stop, modified, req, stopsNearOrigin, stopsNearDestination);
optimalPathsEachIteration[iter] = path;
}
}
}
// map pattern ids back to the original transport network
Stream.of(optimalPathsEachIteration).forEach(path -> {
for (int pidx = 0; pidx < path.length; pidx++) {
path.patterns[pidx] = modified.transitLayer.tripPatterns.get(path.patterns[pidx]).originalId;
}
});
Stream.of(optimalPathsEachIteration).filter(p -> p != null).forEach(paths::add);
return paths;
}
public void dump () {
LOG.info("BEGIN DUMP OF PROFILE ROUTES");
for (PathWithTimes pwt : this.paths) {
StringBuilder sb = new StringBuilder();
sb.append("min/avg/max ");
sb.append(pwt.min / 60);
sb.append('/');
sb.append(pwt.avg / 60);
sb.append('/');
sb.append(pwt.max / 60);
sb.append(' ');
for (int i = 0; i < pwt.length; i++) {
int routeIdx = transportNetwork.transitLayer.tripPatterns.get(pwt.patterns[i]).routeIndex;
RouteInfo ri = transportNetwork.transitLayer.routes.get(routeIdx);
sb.append(ri.route_short_name != null ? ri.route_short_name : ri.route_long_name);
sb.append(" -> ");
}
System.out.println(sb.toString());
}
LOG.info("END DUMP OF PROFILE ROUTES");
}
}
| src/main/java/com/conveyal/r5/profile/SuboptimalPathProfileRouter.java | package com.conveyal.r5.profile;
import com.conveyal.r5.analyst.cluster.TaskStatistics;
import com.conveyal.r5.analyst.scenario.RemoveTrip;
import com.conveyal.r5.analyst.scenario.Scenario;
import com.conveyal.r5.publish.StaticPropagatedTimesStore;
import com.conveyal.r5.streets.StreetRouter;
import com.conveyal.r5.transit.RouteInfo;
import com.conveyal.r5.transit.TransportNetwork;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Stream;
/**
* A profile router that finds some number of suboptimal paths.
*/
public class SuboptimalPathProfileRouter {
private static final Logger LOG = LoggerFactory.getLogger(SuboptimalPathProfileRouter.class);
/**
* how many minutes to search past the end of the time window and then discard.
* We do this because the searches earlier in the time window have their transfers "pre-compressed" because they
* would be dominated by trips later in the time window, but this does not hold for trips near the end of the time
* window. See extensive discussion in https://github.com/conveyal/r5/issues/42.
*/
public static final int OVERSEARCH_MINUTES = 30;
public final TransportNetwork transportNetwork;
public final ProfileRequest req;
public final int TIMEOUT_MS = 5000;
private Set<PathWithTimes> paths = new HashSet<>();
private TIntIntMap stopsNearOrigin;
private TIntIntMap stopsNearDestination;
private Queue<TIntSet> patternsToBan = new ArrayDeque<>();
// if an option has a min time less than this, retain it
private int worstTimeToAccept = Integer.MAX_VALUE;
public SuboptimalPathProfileRouter(TransportNetwork network, ProfileRequest req) {
this.transportNetwork = network;
this.req = req;
}
/** Find paths (options) that could be used */
public Collection<PathWithTimes> route () {
LOG.info("Performing access search");
StreetRouter access = new StreetRouter(transportNetwork.streetLayer);
access.setOrigin(req.fromLat, req.fromLon);
// TODO origin search with multiple modes
// TODO true time limit (important for driving)
access.distanceLimitMeters = (int) (req.walkSpeed * req.maxWalkTime * 60);
access.route();
stopsNearOrigin = access.getReachedStops();
LOG.info("Performing egress search");
// FIXME for now, egress search is always by walking
StreetRouter egress = new StreetRouter(transportNetwork.streetLayer);
// TODO reverse search (doesn't really matter for peds)
egress.setOrigin(req.toLat, req.toLon);
egress.distanceLimitMeters = (int) (req.walkSpeed * req.maxWalkTime * 60);
egress.route();
stopsNearDestination = egress.getReachedStops();
LOG.info("Performing transit search for optimal routes");
Set<PathWithTimes> optimalPaths = findPaths(null);
// no need to filter, all optimal paths are optimal at some point so they by definition overlap with the best option
this.paths.addAll(optimalPaths);
worstTimeToAccept = optimalPaths.stream().mapToInt(p -> p.max + req.suboptimalMinutes).min().getAsInt();
LOG.info("Found {} optimal paths", optimalPaths.size());
TIntSet patternsUsed = new TIntHashSet();
paths.forEach(p -> patternsUsed.addAll(p.patterns));
patternsUsed.forEach(i -> {
TIntHashSet set = new TIntHashSet(1);
set.add(i);
patternsToBan.add(set);
return true;
});
paths.forEach(p -> patternsToBan.add(new TIntHashSet(p.patterns)));
LOG.info("Running up to {} searches for suboptimal paths", this.patternsToBan.size());
long startTime = System.currentTimeMillis();
while (!patternsToBan.isEmpty() && !disjointOptionsPresent() && System.currentTimeMillis() < startTime + TIMEOUT_MS) {
Set<PathWithTimes> paths = findPaths(patternsToBan.remove());
paths.stream().filter(p -> p.min < worstTimeToAccept).forEach(this.paths::add);
}
if (!disjointOptionsPresent()) LOG.warn("Found no disjoint options!");
LOG.info("done");
// TODO once this all works, comment out
dump();
return this.paths;
}
/** are there any disjoint options (options which do not share patterns)? */
private boolean disjointOptionsPresent () {
// count how many times each pattern is used
TIntIntMap patternUsage = new TIntIntHashMap();
for (PathWithTimes path : paths) {
for (int pattern : path.patterns) {
patternUsage.adjustOrPutValue(pattern, 1, 1);
}
}
// check if any path is disjoint
PATHS: for (PathWithTimes path : paths) {
for (int pattern : path.patterns) {
if (patternUsage.get(pattern) > 1) continue PATHS; // not disjoint
}
// this path is disjoint
return true;
}
return false;
}
/** find paths and add them to the set of possible paths, respecting banned patterns */
private Set<PathWithTimes> findPaths (TIntSet bannedPatterns) {
Set<PathWithTimes> paths = new HashSet<>();
// make defensive copy, eventually this may be called in parallel
ProfileRequest req = this.req.clone();
req.scenario = new Scenario(0);
req.scenario.modifications = new ArrayList<>();
if (this.req.scenario != null && this.req.scenario.modifications != null)
req.scenario.modifications.addAll(this.req.scenario.modifications);
// extend the time window because the end of the time window has trips with accurate times but without transfer
// compression.
req.toTime += OVERSEARCH_MINUTES * 60;
// remove appropriate trips
if (bannedPatterns != null && !bannedPatterns.isEmpty()) {
RemoveTrip rt = new RemoveTrip();
rt.tripId = new ArrayList<>();
rt.patternIds = bannedPatterns;
req.scenario.modifications.add(rt);
}
TransportNetwork modified = req.scenario.applyToTransportNetwork(transportNetwork);
RaptorWorker worker = new RaptorWorker(modified.transitLayer, null, req);
StaticPropagatedTimesStore pts = (StaticPropagatedTimesStore) worker.runRaptor(stopsNearOrigin, null, new TaskStatistics());
// chop off the last few minutes of the time window so we don't get a lot of unoptimized
// trips without transfer compression near the end of the time window. See https://github.com/conveyal/r5/issues/42
int iterations = pts.times.length - OVERSEARCH_MINUTES;
int stops = pts.times[0].length;
// only find a single optimal path each minute
PathWithTimes[] optimalPathsEachIteration = new PathWithTimes[iterations];
int[] optimalTimesEachIteration = new int[iterations];
Arrays.fill(optimalTimesEachIteration, Integer.MAX_VALUE);
for (int stop = 0; stop < stops; stop++) {
if (!stopsNearDestination.containsKey(stop)) continue;
for (int iter = 0; iter < iterations; iter++) {
RaptorState state = worker.statesEachIteration.get(iter);
// only compute a path if this stop was reached
if (state.bestNonTransferTimes[stop] != RaptorWorker.UNREACHED &&
state.bestNonTransferTimes[stop] + stopsNearDestination.get(stop) < optimalTimesEachIteration[iter]) {
optimalTimesEachIteration[iter] = state.bestNonTransferTimes[stop] + stopsNearDestination.get(stop);
PathWithTimes path = new PathWithTimes(state, stop, modified, req, stopsNearOrigin, stopsNearDestination);
optimalPathsEachIteration[iter] = path;
}
}
}
// map pattern ids back to the original transport network
Stream.of(optimalPathsEachIteration).forEach(path -> {
for (int pidx = 0; pidx < path.length; pidx++) {
path.patterns[pidx] = modified.transitLayer.tripPatterns.get(path.patterns[pidx]).originalId;
}
});
Stream.of(optimalPathsEachIteration).filter(p -> p != null).forEach(paths::add);
return paths;
}
public void dump () {
LOG.info("BEGIN DUMP OF PROFILE ROUTES");
for (PathWithTimes pwt : this.paths) {
StringBuilder sb = new StringBuilder();
sb.append("min/avg/max ");
sb.append(pwt.min / 60);
sb.append('/');
sb.append(pwt.avg / 60);
sb.append('/');
sb.append(pwt.max / 60);
sb.append(' ');
for (int i = 0; i < pwt.length; i++) {
int routeIdx = transportNetwork.transitLayer.tripPatterns.get(pwt.patterns[i]).routeIndex;
RouteInfo ri = transportNetwork.transitLayer.routes.get(routeIdx);
sb.append(ri.route_short_name != null ? ri.route_short_name : ri.route_long_name);
sb.append(" -> ");
}
System.out.println(sb.toString());
}
LOG.info("END DUMP OF PROFILE ROUTES");
}
}
| try to find optimal paths with disjoint route sequences.
| src/main/java/com/conveyal/r5/profile/SuboptimalPathProfileRouter.java | try to find optimal paths with disjoint route sequences. | <ide><path>rc/main/java/com/conveyal/r5/profile/SuboptimalPathProfileRouter.java
<ide> import com.conveyal.r5.transit.RouteInfo;
<ide> import com.conveyal.r5.transit.TransportNetwork;
<ide> import gnu.trove.map.TIntIntMap;
<add>import gnu.trove.map.TObjectIntMap;
<ide> import gnu.trove.map.hash.TIntIntHashMap;
<add>import gnu.trove.map.hash.TObjectIntHashMap;
<ide> import gnu.trove.set.TIntSet;
<ide> import gnu.trove.set.hash.TIntHashSet;
<ide> import org.slf4j.Logger;
<ide> /** are there any disjoint options (options which do not share patterns)? */
<ide> private boolean disjointOptionsPresent () {
<ide> // count how many times each pattern is used
<del> TIntIntMap patternUsage = new TIntIntHashMap();
<add> TIntIntMap routeUsage = new TIntIntHashMap();
<ide> for (PathWithTimes path : paths) {
<ide> for (int pattern : path.patterns) {
<del> patternUsage.adjustOrPutValue(pattern, 1, 1);
<add> routeUsage.adjustOrPutValue(transportNetwork.transitLayer.tripPatterns.get(pattern).routeIndex, 1, 1);
<ide> }
<ide> }
<ide>
<ide> // check if any path is disjoint
<ide> PATHS: for (PathWithTimes path : paths) {
<ide> for (int pattern : path.patterns) {
<del> if (patternUsage.get(pattern) > 1) continue PATHS; // not disjoint
<add> if (routeUsage.get(transportNetwork.transitLayer.tripPatterns.get(pattern).routeIndex) > 1) continue PATHS; // not disjoint
<ide> }
<ide>
<ide> // this path is disjoint |
|
Java | epl-1.0 | 6d2aad21fbe8eef903b2649ceb4f9bf7d0967c09 | 0 | shisoft/Nebuchadnezzar,shisoft/Nebuchadnezzar | package org.shisoft.neb.utils;
import org.shisoft.neb.io.type_lengths;
import sun.misc.Unsafe;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.StampedLock;
/**
* Created by shisoft on 8/8/2016.
*/
// Concurrent hash map dedicated to cell index
public class UnsafeConcurrentLongLongHashMap {
private static final int INITIAL_BUCKETS = 1024; // Must be power of 2
private static final int MAXIMUM_BUCKETS = INITIAL_BUCKETS * 10240; // 80 MB total, must be power of 2 either
private static final int LONG_LEN = type_lengths.longLen;
private static final int LOCKS = 32;
private static final Unsafe u = UnsafeUtils.unsafe;
private static final int KEY_LOC = 0;
private static final int VAL_LOC = LONG_LEN;
private static final int NXT_LOC = LONG_LEN * 2;
private StampedLock[] locks;
private StampedLock masterLock;
private AtomicLong size;
private volatile long bucketsIndex;
private volatile long buckets;
private volatile float bucketsT;
private void setBuckets (long buckets) {
this.buckets = buckets;
this.bucketsT = 1 / (float) buckets;
}
private long[] writeLockAll() {
long[] stamps = new long[locks.length];
for (int i = 0; i < locks.length; i++) {
stamps[i] = locks[i].writeLock();
}
return stamps;
}
private void writeUnlockAll(long[] stamps){
assert stamps.length == locks.length;
for (int i = 0; i < stamps.length; i++) {
locks[i].unlockWrite(stamps[i]);
}
}
private float getAvgBucketItems () {
return (float) size.longValue() * bucketsT;
}
public boolean resizeRequired() {
return getAvgBucketItems() > 10 && buckets < MAXIMUM_BUCKETS;
}
private void checkResize() {
if (resizeRequired()) {
long masterStamp = masterLock.writeLock();
try {
if (!resizeRequired()) return; // recheck for lock
long originalBucketsIndex = bucketsIndex;
long originalBuckets = buckets;
long originalBucketsSize = originalBuckets * LONG_LEN;
long originalBucketsEnds = originalBucketsIndex + originalBucketsSize;
buckets = buckets * 2;
initBuckets();
for (long bucketAddr = originalBucketsIndex; bucketAddr < originalBucketsEnds; bucketAddr += LONG_LEN) {
long cellLoc = u.getLong(bucketAddr);
while (true) {
if (cellLoc < 0) break;
long next = u.getLong(cellLoc + NXT_LOC);
long k = u.getLong(cellLoc + KEY_LOC);
long v = u.getLong(cellLoc + VAL_LOC);
put_lockfree(k, v);
u.freeMemory(cellLoc);
cellLoc = next;
}
}
u.freeMemory(originalBucketsIndex);
} finally {
masterLock.unlockWrite(masterStamp);
}
}
}
private long getFromBucket(long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
if (addr < 0) return -1;
while (true) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
return u.getLong(addr + VAL_LOC);
} else {
addr = u.getLong(addr + NXT_LOC);
if (addr < 0) {
return -1;
}
}
}
}
private long writeBucket (long addr, long k, long v) {
long head = u.allocateMemory(LONG_LEN * 3);
u.putLong(head + KEY_LOC, k);
u.putLong(head + VAL_LOC, v);
u.putLong(head + NXT_LOC, addr);
size.incrementAndGet();
return head;
}
private long removeBucketCell(long root, long parent, long addr) {
long next = u.getLong(addr + NXT_LOC);
if (parent > 0) {
u.putLong(parent + NXT_LOC, next);
}
u.freeMemory(addr);
size.decrementAndGet();
return root == addr ? next : root;
}
private long removeBucketCellByKey (long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
long parent = -1;
long root = addr;
while (true) {
if (addr > 0) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
long newHeader = removeBucketCell(root, parent, addr);
u.putLong(bucketLoc, newHeader);
return newHeader;
}
addr = u.getLong(addr + NXT_LOC);
}
if (addr < 0) {
return -1;
}
parent = addr;
}
}
private long setBucketByKeyValue (long bucketLoc, long k, long v) {
long addr = u.getLong(bucketLoc);
long root = addr;
while (true) {
if (addr > 0) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
u.putLong(addr + VAL_LOC, v);
return root;
}
addr = u.getLong(addr + NXT_LOC);
}
if (addr < 0) {
break;
}
}
long newHeader = writeBucket(root, k, v);
u.putLong(bucketLoc, newHeader);
return newHeader;
}
private boolean containsBucketKey (long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
while (true) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
return true;
} else {
addr = u.getLong(addr + NXT_LOC);
if (addr < 0) {
return false;
}
}
}
}
private int locateBuckeyByKey(long key) {
return (int) (key & (buckets - 1));
}
private StampedLock locateLockByBucketId(int id) {
return locks[id & (LOCKS - 1)];
}
private long getBucketLocationByID(int bucketId) {
return bucketsIndex + bucketId * LONG_LEN;
}
private long getBucketsLocationByKey(long key) {
return getBucketLocationByID(locateBuckeyByKey(key));
}
public UnsafeConcurrentLongLongHashMap() {
this.locks = new StampedLock[LOCKS];
this.size = new AtomicLong();
this.masterLock = new StampedLock();
setBuckets(INITIAL_BUCKETS);
initBuckets();
for (int li = 0; li < LOCKS; li++) {
locks[li]= new StampedLock();
}
}
public long size() {
return size.longValue();
}
public boolean isEmpty() {
return size.longValue() == 0;
}
public boolean containsKey(long key) {
return containsBucketKey(getBucketsLocationByKey(key), key);
}
public long get(long key) {
long masterStamp = masterLock.readLock();
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.readLock();
try {
return getFromBucket(getBucketLocationByID(bucketId), key);
} finally {
lock.unlockRead(stamp);
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public long put_lockfree(long key, long value){
long bucketLoc = getBucketLocationByID(locateBuckeyByKey(key));
return setBucketByKeyValue(bucketLoc, key, value);
}
public long put_(long key, long value) {
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.writeLock();
try {
long bucketLoc = getBucketLocationByID(bucketId);
return setBucketByKeyValue(bucketLoc, key, value);
} finally {
lock.unlockWrite(stamp);
}
}
public long put(long key, long value) {
long masterStamp = masterLock.readLock();
try {
return put_(key, value);
} finally {
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public Object remove(long key) {
long masterStamp = masterLock.readLock();
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.writeLock();
try {
long bucketLoc = getBucketLocationByID(bucketId);
return removeBucketCellByKey(bucketLoc, key);
} finally {
lock.unlockWrite(stamp);
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public void putAll(Map<Long, Long> m) {
for (Map.Entry<Long, Long> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
private void initBuckets(){
long bucketsSize = buckets * LONG_LEN;
bucketsIndex = u.allocateMemory(bucketsSize);
long bucketsEnds = bucketsIndex + bucketsSize;
for (long i = bucketsIndex; i < bucketsEnds; i += LONG_LEN) {
u.putLong(i, -1L);
}
}
private void clear_(){
long bucketsSize = buckets * LONG_LEN;
long bucketsEnds = bucketsIndex + bucketsSize;
for (long i = bucketsIndex; i < bucketsEnds; i += LONG_LEN) {
long cellLoc = u.getLong(i);
if (cellLoc < 0) continue;
while (true) {
if (cellLoc < 0) break;
long next = u.getLong(cellLoc + NXT_LOC);
u.freeMemory(cellLoc);
cellLoc = next;
}
u.putLong(i, -1L);
}
size.set(0);
}
public void clear() {
long masterStamp = masterLock.writeLock();
try {
clear_();
} finally {
masterLock.unlockWrite(masterStamp);
}
}
public void dispose(){
long masterStamp = masterLock.writeLock();
try {
clear_();
u.freeMemory(bucketsIndex);
} finally {
masterLock.unlockWrite(masterStamp);
}
}
public long getBuckets() {
return buckets;
}
public long getInitialBuckets () {
return INITIAL_BUCKETS;
}
}
| src/java/org/shisoft/neb/utils/UnsafeConcurrentLongLongHashMap.java | package org.shisoft.neb.utils;
import org.shisoft.neb.io.type_lengths;
import sun.misc.Unsafe;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.StampedLock;
/**
* Created by shisoft on 8/8/2016.
*/
// Concurrent hash map dedicated to cell index
public class UnsafeConcurrentLongLongHashMap {
private static final int INITIAL_BUCKETS = 1024; // Must be power of 2
private static final int LONG_LEN = type_lengths.longLen;
private static final int LOCKS = 32;
private static final Unsafe u = UnsafeUtils.unsafe;
private static final int KEY_LOC = 0;
private static final int VAL_LOC = LONG_LEN;
private static final int NXT_LOC = LONG_LEN * 2;
private StampedLock[] locks;
private StampedLock masterLock;
private AtomicLong size;
private volatile long bucketsIndex;
private volatile long buckets;
private volatile float bucketsT;
private void setBuckets (long buckets) {
this.buckets = buckets;
this.bucketsT = 1 / (float) buckets;
}
private long[] writeLockAll() {
long[] stamps = new long[locks.length];
for (int i = 0; i < locks.length; i++) {
stamps[i] = locks[i].writeLock();
}
return stamps;
}
private void writeUnlockAll(long[] stamps){
assert stamps.length == locks.length;
for (int i = 0; i < stamps.length; i++) {
locks[i].unlockWrite(stamps[i]);
}
}
private float getAvgBucketItems () {
return (float) size.longValue() * bucketsT;
}
public boolean resizeRequired() {
return getAvgBucketItems() > 10 && buckets < INITIAL_BUCKETS * 1024;
}
private void checkResize() {
if (resizeRequired()) {
long masterStamp = masterLock.writeLock();
try {
if (!resizeRequired()) return; // recheck for lock
long originalBucketsIndex = bucketsIndex;
long originalBuckets = buckets;
long originalBucketsSize = originalBuckets * LONG_LEN;
long originalBucketsEnds = originalBucketsIndex + originalBucketsSize;
buckets = buckets * 2;
initBuckets();
for (long bucketAddr = originalBucketsIndex; bucketAddr < originalBucketsEnds; bucketAddr += LONG_LEN) {
long cellLoc = u.getLong(bucketAddr);
while (true) {
if (cellLoc < 0) break;
long next = u.getLong(cellLoc + NXT_LOC);
long k = u.getLong(cellLoc + KEY_LOC);
long v = u.getLong(cellLoc + VAL_LOC);
put_lockfree(k, v);
u.freeMemory(cellLoc);
cellLoc = next;
}
}
u.freeMemory(originalBucketsIndex);
} finally {
masterLock.unlockWrite(masterStamp);
}
}
}
private long getFromBucket(long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
if (addr < 0) return -1;
while (true) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
return u.getLong(addr + VAL_LOC);
} else {
addr = u.getLong(addr + NXT_LOC);
if (addr < 0) {
return -1;
}
}
}
}
private long writeBucket (long addr, long k, long v) {
long head = u.allocateMemory(LONG_LEN * 3);
u.putLong(head + KEY_LOC, k);
u.putLong(head + VAL_LOC, v);
u.putLong(head + NXT_LOC, addr);
size.incrementAndGet();
return head;
}
private long removeBucketCell(long root, long parent, long addr) {
long next = u.getLong(addr + NXT_LOC);
if (parent > 0) {
u.putLong(parent + NXT_LOC, next);
}
u.freeMemory(addr);
size.decrementAndGet();
return root == addr ? next : root;
}
private long removeBucketCellByKey (long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
long parent = -1;
long root = addr;
while (true) {
if (addr > 0) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
long newHeader = removeBucketCell(root, parent, addr);
u.putLong(bucketLoc, newHeader);
return newHeader;
}
addr = u.getLong(addr + NXT_LOC);
}
if (addr < 0) {
return -1;
}
parent = addr;
}
}
private long setBucketByKeyValue (long bucketLoc, long k, long v) {
long addr = u.getLong(bucketLoc);
long root = addr;
while (true) {
if (addr > 0) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
u.putLong(addr + VAL_LOC, v);
return root;
}
addr = u.getLong(addr + NXT_LOC);
}
if (addr < 0) {
break;
}
}
long newHeader = writeBucket(root, k, v);
u.putLong(bucketLoc, newHeader);
return newHeader;
}
private boolean containsBucketKey (long bucketLoc, long k) {
long addr = u.getLong(bucketLoc);
while (true) {
long key = u.getLong(addr + KEY_LOC);
if (key == k) {
return true;
} else {
addr = u.getLong(addr + NXT_LOC);
if (addr < 0) {
return false;
}
}
}
}
private int locateBuckeyByKey(long key) {
return (int) (key & (buckets - 1));
}
private StampedLock locateLockByBucketId(int id) {
return locks[id & (LOCKS - 1)];
}
private long getBucketLocationByID(int bucketId) {
return bucketsIndex + bucketId * LONG_LEN;
}
private long getBucketsLocationByKey(long key) {
return getBucketLocationByID(locateBuckeyByKey(key));
}
public UnsafeConcurrentLongLongHashMap() {
this.locks = new StampedLock[LOCKS];
this.size = new AtomicLong();
this.masterLock = new StampedLock();
setBuckets(INITIAL_BUCKETS);
initBuckets();
for (int li = 0; li < LOCKS; li++) {
locks[li]= new StampedLock();
}
}
public long size() {
return size.longValue();
}
public boolean isEmpty() {
return size.longValue() == 0;
}
public boolean containsKey(long key) {
return containsBucketKey(getBucketsLocationByKey(key), key);
}
public long get(long key) {
long masterStamp = masterLock.readLock();
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.readLock();
try {
return getFromBucket(getBucketLocationByID(bucketId), key);
} finally {
lock.unlockRead(stamp);
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public long put_lockfree(long key, long value){
long bucketLoc = getBucketLocationByID(locateBuckeyByKey(key));
return setBucketByKeyValue(bucketLoc, key, value);
}
public long put_(long key, long value) {
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.writeLock();
try {
long bucketLoc = getBucketLocationByID(bucketId);
return setBucketByKeyValue(bucketLoc, key, value);
} finally {
lock.unlockWrite(stamp);
}
}
public long put(long key, long value) {
long masterStamp = masterLock.readLock();
try {
return put_(key, value);
} finally {
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public Object remove(long key) {
long masterStamp = masterLock.readLock();
int bucketId = locateBuckeyByKey(key);
StampedLock lock = locateLockByBucketId(bucketId);
long stamp = lock.writeLock();
try {
long bucketLoc = getBucketLocationByID(bucketId);
return removeBucketCellByKey(bucketLoc, key);
} finally {
lock.unlockWrite(stamp);
masterLock.unlockRead(masterStamp);
checkResize();
}
}
public void putAll(Map<Long, Long> m) {
for (Map.Entry<Long, Long> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
private void initBuckets(){
long bucketsSize = buckets * LONG_LEN;
bucketsIndex = u.allocateMemory(bucketsSize);
long bucketsEnds = bucketsIndex + bucketsSize;
for (long i = bucketsIndex; i < bucketsEnds; i += LONG_LEN) {
u.putLong(i, -1L);
}
}
private void clear_(){
long bucketsSize = buckets * LONG_LEN;
long bucketsEnds = bucketsIndex + bucketsSize;
for (long i = bucketsIndex; i < bucketsEnds; i += LONG_LEN) {
long cellLoc = u.getLong(i);
if (cellLoc < 0) continue;
while (true) {
if (cellLoc < 0) break;
long next = u.getLong(cellLoc + NXT_LOC);
u.freeMemory(cellLoc);
cellLoc = next;
}
u.putLong(i, -1L);
}
size.set(0);
}
public void clear() {
long masterStamp = masterLock.writeLock();
try {
clear_();
} finally {
masterLock.unlockWrite(masterStamp);
}
}
public void dispose(){
long masterStamp = masterLock.writeLock();
try {
clear_();
u.freeMemory(bucketsIndex);
} finally {
masterLock.unlockWrite(masterStamp);
}
}
public long getBuckets() {
return buckets;
}
public long getInitialBuckets () {
return INITIAL_BUCKETS;
}
}
| MAXIMUM_BUCKETS adjustment
| src/java/org/shisoft/neb/utils/UnsafeConcurrentLongLongHashMap.java | MAXIMUM_BUCKETS adjustment | <ide><path>rc/java/org/shisoft/neb/utils/UnsafeConcurrentLongLongHashMap.java
<ide>
<ide>
<ide> private static final int INITIAL_BUCKETS = 1024; // Must be power of 2
<add> private static final int MAXIMUM_BUCKETS = INITIAL_BUCKETS * 10240; // 80 MB total, must be power of 2 either
<ide>
<ide> private static final int LONG_LEN = type_lengths.longLen;
<ide> private static final int LOCKS = 32;
<ide> }
<ide>
<ide> public boolean resizeRequired() {
<del> return getAvgBucketItems() > 10 && buckets < INITIAL_BUCKETS * 1024;
<add> return getAvgBucketItems() > 10 && buckets < MAXIMUM_BUCKETS;
<ide> }
<ide>
<ide> private void checkResize() { |
|
Java | mit | 754e57caa9f29f2b17691e80637a61ed04743b8e | 0 | thesebas/opacclient,johan12345/opacclient,hurzl/opacclient,johan12345/opacclient,hurzl/opacclient,ruediger-w/opacclient,opacapp/opacclient,johan12345/opacclient,simon04/opacclient,raphaelm/opacclient,raphaelm/opacclient,opacapp/opacclient,hurzl/opacclient,ruediger-w/opacclient,thesebas/opacclient,johan12345/opacclient,geomcmaster/opacclient,simon04/opacclient,geomcmaster/opacclient,opacapp/opacclient,ruediger-w/opacclient,johan12345/opacclient,raphaelm/opacclient,ruediger-w/opacclient,simon04/opacclient,geomcmaster/opacclient,opacapp/opacclient,opacapp/opacclient,ruediger-w/opacclient,thesebas/opacclient | /**
* Copyright (C) 2013 by Johan von Forstner under the MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package de.geeksfactory.opacclient.apis;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.objects.SearchResult.Status;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
/**
* Implementation of Fleischmann iOpac, including account support Seems to work in all the libraries
* currently supported without any modifications.
*
* @author Johan von Forstner, 17.09.2013
*/
public class IOpac extends BaseApi implements OpacApi {
protected static HashMap<String, MediaType> defaulttypes = new HashMap<>();
static {
defaulttypes.put("b", MediaType.BOOK);
defaulttypes.put("o", MediaType.BOOK);
defaulttypes.put("e", MediaType.BOOK);
defaulttypes.put("p", MediaType.BOOK);
defaulttypes.put("j", MediaType.BOOK);
defaulttypes.put("g", MediaType.BOOK);
defaulttypes.put("k", MediaType.BOOK);
defaulttypes.put("a", MediaType.BOOK);
defaulttypes.put("c", MediaType.AUDIOBOOK);
defaulttypes.put("u", MediaType.AUDIOBOOK);
defaulttypes.put("l", MediaType.AUDIOBOOK);
defaulttypes.put("q", MediaType.CD_SOFTWARE);
defaulttypes.put("r", MediaType.CD_SOFTWARE);
defaulttypes.put("v", MediaType.MOVIE);
defaulttypes.put("d", MediaType.CD_MUSIC);
defaulttypes.put("n", MediaType.SCORE_MUSIC);
defaulttypes.put("s", MediaType.BOARDGAME);
defaulttypes.put("z", MediaType.MAGAZINE);
defaulttypes.put("x", MediaType.MAGAZINE);
}
protected String opac_url = "";
protected String dir = "/iopac";
protected JSONObject data;
protected String reusehtml;
protected String rechnr;
protected int results_total;
protected int maxProlongCount = -1;
protected boolean newShareLinks;
@Override
public void init(Library lib) {
super.init(lib);
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
if (data.has("maxprolongcount")) {
this.maxProlongCount = data.getInt("maxprolongcount");
}
if (data.has("dir")) {
this.dir = data.getString("dir");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
protected int addParameters(SearchQuery query, List<NameValuePair> params,
int index) {
if (query.getValue().equals("")) {
return index;
}
params.add(new BasicNameValuePair(query.getKey(), query.getValue()));
return index + 1;
}
@Override
public SearchRequestResult search(List<SearchQuery> queries)
throws IOException, OpacErrorException {
if (!initialised) {
start();
}
List<NameValuePair> params = new ArrayList<>();
int index = 0;
start();
for (SearchQuery query : queries) {
index = addParameters(query, params, index);
}
params.add(new BasicNameValuePair("Anzahl", "10"));
params.add(new BasicNameValuePair("pshStart", "Suchen"));
if (index == 0) {
throw new OpacErrorException(
stringProvider.getString(StringProvider.NO_CRITERIA_INPUT));
}
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
return parse_search(html, 1);
}
protected SearchRequestResult parse_search(String html, int page)
throws OpacErrorException, NotReachableException {
Document doc = Jsoup.parse(html);
if (doc.select("h4").size() > 0) {
if (doc.select("h4").text().trim().startsWith("0 gefundene Medien")) {
// nothing found
return new SearchRequestResult(new ArrayList<SearchResult>(),
0, 1, 1);
} else if (!doc.select("h4").text().trim()
.contains("gefundene Medien")
&& !doc.select("h4").text().trim()
.contains("Es wurden mehr als")) {
// error
throw new OpacErrorException(doc.select("h4").text().trim());
}
} else if (doc.select("h1").size() > 0) {
if (doc.select("h1").text().trim().contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(stringProvider.getFormattedString(
StringProvider.UNKNOWN_ERROR_WITH_DESCRIPTION, doc
.select("h1").text().trim()));
}
} else {
return null;
}
updateRechnr(doc);
reusehtml = html;
results_total = -1;
if (doc.select("h4").text().trim().contains("Es wurden mehr als")) {
results_total = 200;
} else {
String resultnumstr = doc.select("h4").first().text();
resultnumstr = resultnumstr.substring(0, resultnumstr.indexOf(" "))
.trim();
results_total = Integer.parseInt(resultnumstr);
}
List<SearchResult> results = new ArrayList<>();
Elements tables = doc.select("table").first().select("tr:has(td)");
Map<String, Integer> colmap = new HashMap<>();
Element thead = doc.select("table").first().select("tr:has(th)")
.first();
int j = 0;
for (Element th : thead.select("th")) {
String text = th.text().trim().toLowerCase(Locale.GERMAN);
if (text.contains("cover")) {
colmap.put("cover", j);
} else if (text.contains("titel")) {
colmap.put("title", j);
} else if (text.contains("verfasser")) {
colmap.put("author", j);
} else if (text.contains("mtyp")) {
colmap.put("category", j);
} else if (text.contains("jahr")) {
colmap.put("year", j);
} else if (text.contains("signatur")) {
colmap.put("shelfmark", j);
} else if (text.contains("info")) {
colmap.put("info", j);
} else if (text.contains("abteilung")) {
colmap.put("department", j);
} else if (text.contains("verliehen") || text.contains("verl.")) {
colmap.put("returndate", j);
} else if (text.contains("anz.res")) {
colmap.put("reservations", j);
}
j++;
}
if (colmap.size() == 0) {
colmap.put("cover", 0);
colmap.put("title", 1);
colmap.put("author", 2);
colmap.put("publisher", 3);
colmap.put("year", 4);
colmap.put("department", 5);
colmap.put("shelfmark", 6);
colmap.put("returndate", 7);
colmap.put("category", 8);
}
for (int i = 0; i < tables.size(); i++) {
Element tr = tables.get(i);
SearchResult sr = new SearchResult();
if (tr.select("td").get(colmap.get("cover")).select("img").size() > 0) {
String imgUrl = tr.select("td").get(colmap.get("cover"))
.select("img").first().attr("src");
sr.setCover(imgUrl);
}
// Media Type
if (colmap.get("category") != null) {
String mType = tr.select("td").get(colmap.get("category"))
.text().trim().replace("\u00a0", "");
if (data.has("mediatypes")) {
try {
sr.setType(MediaType.valueOf(data.getJSONObject(
"mediatypes").getString(
mType.toLowerCase(Locale.GERMAN))));
} catch (JSONException | IllegalArgumentException e) {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
} else {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
}
// Title and additional info
String title;
String additionalInfo = "";
if (colmap.get("info") != null) {
Element info = tr.select("td").get(colmap.get("info"));
title = info.select("a[title=Details-Info]").text().trim();
String authorIn = info.text().substring(0,
info.text().indexOf(title));
if (authorIn.contains(":")) {
authorIn = authorIn.replaceFirst("^([^:]*):(.*)$", "$1");
additionalInfo += " - " + authorIn;
}
} else {
title = tr.select("td").get(colmap.get("title")).text().trim()
.replace("\u00a0", "");
if (title.contains("(") && title.indexOf("(") > 0) {
additionalInfo += title.substring(title.indexOf("("));
title = title.substring(0, title.indexOf("(") - 1).trim();
}
// Author
if (colmap.containsKey("author")) {
String author = tr.select("td").get(colmap.get("author"))
.text().trim().replace("\u00a0", "");
additionalInfo += " - " + author;
}
}
// Publisher
if (colmap.containsKey("publisher")) {
String publisher = tr.select("td").get(colmap.get("publisher"))
.text().trim().replace("\u00a0", "");
additionalInfo += " (" + publisher;
}
// Year
if (colmap.containsKey("year")) {
String year = tr.select("td").get(colmap.get("year")).text()
.trim().replace("\u00a0", "");
additionalInfo += ", " + year + ")";
}
sr.setInnerhtml("<b>" + title + "</b><br>" + additionalInfo);
// Status
String status = tr.select("td").get(colmap.get("returndate"))
.text().trim().replace("\u00a0", "");
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
try {
df.parse(status);
// this is a return date
sr.setStatus(Status.RED);
sr.setInnerhtml(sr.getInnerhtml() + "<br><i>"
+ stringProvider.getString(StringProvider.LENT_UNTIL)
+ " " + status + "</i>");
} catch (ParseException e) {
// this is a different status text
String lc = status.toLowerCase(Locale.GERMAN);
if ((lc.equals("")
|| lc.toLowerCase(Locale.GERMAN).contains("onleihe")
|| lc.contains("verleihbar") || lc.contains("entleihbar")
|| lc.contains("ausleihbar")) && !lc.contains("nicht")) {
sr.setStatus(Status.GREEN);
} else {
sr.setStatus(Status.YELLOW);
sr.setInnerhtml(sr.getInnerhtml() + "<br><i>" + status + "</i>");
}
}
// In some libraries (for example search for "atelier" in Preetz)
// the results are sorted differently than their numbers suggest, so
// we need to detect the number ("recno") from the link
String link = tr.select("a[href^=/cgi-bin/di.exe?page=]").attr(
"href");
Map<String, String> params = getQueryParamsFirst(link);
if (params.containsKey("recno")) {
int recno = Integer.valueOf(params.get("recno"));
sr.setNr(recno - 1);
} else {
// the above should work, but fall back to this if it doesn't
sr.setNr(10 * (page - 1) + i);
}
// In some libraries (for example Preetz) we can detect the media ID
// here using another link present in the search results
Elements idLinks = tr.select("a[href^=/cgi-bin/di.exe?cMedNr]");
if (idLinks.size() > 0) {
Map<String, String> idParams = getQueryParamsFirst(idLinks
.first().attr("href"));
String id = idParams.get("cMedNr");
sr.setId(id);
} else {
sr.setId(null);
}
results.add(sr);
}
return new SearchRequestResult(results, results_total, page);
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
OpacErrorException {
if (!initialised) {
start();
}
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&FilNr=",
getDefaultEncoding());
return parse_search(html, page);
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException {
return null;
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException {
if (!initialised) {
start();
}
if (id == null && reusehtml != null) {
return parse_result(reusehtml);
}
String html = httpGet(opac_url + "/cgi-bin/di.exe?cMedNr=" + id
+ "&mode=23", getDefaultEncoding());
return parse_result(html);
}
@Override
public DetailledItem getResult(int position) throws IOException {
if (!initialised) {
start();
}
int page = Double.valueOf(Math.floor(position / 10)).intValue() + 1;
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&recno=" + (position + 1)
+ "&FilNr=", getDefaultEncoding());
return parse_result(html);
}
protected DetailledItem parse_result(String html) throws IOException {
Document doc = Jsoup.parse(html);
DetailledItem result = new DetailledItem();
String id;
if (doc.select("input[name=mednr]").size() > 0) {
id = doc.select("input[name=mednr]").first().val().trim();
} else {
String href = doc.select("a[href*=mednr]").first().attr("href");
id = getQueryParamsFirst(href).get("mednr").trim();
}
result.setId(id);
// check if new share button is available (allows to share a link to the standard
// frameset of the OPAC instead of only the detail frame)
newShareLinks = doc.select("#sharebutton").size() > 0;
Elements table = doc.select("table").get(1).select("tr");
// GET COVER IMAGE
String imgUrl = table.get(0)
.select("img[src~=^https?://(:?images(?:-[^\\.]*)?\\.|[^\\.]*\\" +
".images-)amazon\\.com]")
.attr("src");
result.setCover(imgUrl);
// GET INFORMATION
Map<String, String> e = new HashMap<>();
for (Element element : table) {
String detail = element.select("td").text().trim()
.replace("\u00a0", "");
String title = element.select("th").text().trim()
.replace("\u00a0", "");
if (!title.equals("")) {
if (title.contains("verliehen bis")) {
if (detail.equals("")) {
e.put(DetailledItem.KEY_COPY_STATUS, "verfügbar");
} else {
e.put(DetailledItem.KEY_COPY_STATUS, "verliehen bis "
+ detail);
}
} else if (title.contains("Abteilung")) {
e.put(DetailledItem.KEY_COPY_DEPARTMENT, detail);
} else if (title.contains("Signatur")) {
e.put(DetailledItem.KEY_COPY_SHELFMARK, detail);
} else if (title.contains("Titel")) {
result.setTitle(detail);
} else if (!title.contains("Cover")) {
result.addDetail(new Detail(title, detail));
}
}
}
// GET RESERVATION INFO
if ("verfügbar".equals(e.get(DetailledItem.KEY_COPY_STATUS))
|| doc.select(
"a[href^=/cgi-bin/di.exe?mode=10], input.resbutton")
.size() == 0) {
result.setReservable(false);
} else {
result.setReservable(true);
if (doc.select("a[href^=/cgi-bin/di.exe?mode=10]").size() > 0) {
// Reservation via link
result.setReservation_info(doc
.select("a[href^=/cgi-bin/di.exe?mode=10]").first()
.attr("href").substring(1).replace(" ", ""));
} else {
// Reservation via form (method="get")
Element form = doc.select("input.resbutton").first().parent();
result.setReservation_info(generateQuery(form));
}
}
if (e.size() > 0) result.addCopy(e);
return result;
}
private String generateQuery(Element form)
throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(form.attr("action").substring(1));
int i = 0;
for (Element input : form.select("input")) {
builder.append(i == 0 ? "?" : "&");
builder.append(input.attr("name")).append("=")
.append(URLEncoder.encode(input.attr("value"), "UTF-8"));
i++;
}
return builder.toString();
}
@Override
public ReservationResult reservation(DetailledItem item, Account account,
int useraction, String selection) throws IOException {
String reservation_info = item.getReservation_info();
// STEP 1: Login page
String html = httpGet(opac_url + "/" + reservation_info,
getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table").first().text().contains("kann nicht")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
}
if (doc.select("form[name=form1]").size() == 0) {
return new ReservationResult(MultiStepResult.Status.ERROR);
}
Element form = doc.select("form[name=form1]").first();
List<BasicNameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Reservieren"));
for (Element input : form.select("input[type=hidden]")) {
params.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
// STEP 2: Confirmation page
html = httpPost(opac_url + "/cgi-bin/di.exe", new UrlEncodedFormEntity(
params), getDefaultEncoding());
doc = Jsoup.parse(html);
if (doc.select("form[name=form1]").size() > 0) {
// STEP 3: There is another confirmation needed
form = doc.select("form[name=form1]").first();
html = httpGet(opac_url + "/" + generateQuery(form),
getDefaultEncoding());
doc = Jsoup.parse(html);
}
if (doc.text().contains("fehlgeschlagen")
|| doc.text().contains("Achtung") || doc.text().contains("nicht m")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
} else {
return new ReservationResult(MultiStepResult.Status.OK);
}
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String Selection) throws IOException {
// internal convention: We add "NEW" to the media ID to show that we have the new iOPAC
// version
if (media.startsWith("NEW")) {
String mediaNr = media.substring(3);
String html = httpGet(opac_url + "/cgi-bin/di.exe?mode=42&MedNrVerlAll=" +
URLEncoder.encode(mediaNr, "UTF-8"), getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.text().contains("1 Medium wurde verl")) {
return new ProlongResult(MultiStepResult.Status.OK);
} else {
return new ProlongResult(MultiStepResult.Status.ERROR, doc.text());
}
} else {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table th").size() > 0) {
if (doc.select("h1").size() > 0) {
if (doc.select("h1").first().text().contains("Hinweis")) {
return new ProlongResult(MultiStepResult.Status.ERROR, doc
.select("table th").first().text());
}
}
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=8&kndnr="
+ account.getName() + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Verl%C3%A4ngern",
getDefaultEncoding());
return new ProlongResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction,
String selection) throws IOException {
Document doc = getAccountPage(account);
// Check if the iOPAC verion supports this feature
if (doc.select("button.verlallbutton").size() > 0) {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("mode", "42"));
for (Element checkbox : doc.select("input.VerlAllCheckboxOK")) {
params.add(new BasicNameValuePair("MedNrVerlAll", checkbox.val()));
}
String html = httpGet(
opac_url + "/cgi-bin/di.exe?" + URLEncodedUtils.format(params, "UTF-8"),
getDefaultEncoding());
Document doc2 = Jsoup.parse(html);
Pattern pattern = Pattern.compile("(\\d+ Medi(?:en|um) wurden? verl.ngert)\\s*(\\d+ " +
"Medi(?:en|um) wurden? nicht verl.ngert)?");
Matcher matcher = pattern.matcher(doc2.text());
if (matcher.find()) {
String text1 = matcher.group(1);
String text2 = matcher.group(2);
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
// TODO: We are abusing the ProlongAllResult.KEY_LINE_ ... keys here because we
// do not get information about all the media
map1.put(ProlongAllResult.KEY_LINE_TITLE, text1);
list.add(map1);
if (!text2.equals("")) {
Map<String, String> map2 = new HashMap<>();
map2.put(ProlongAllResult.KEY_LINE_TITLE, text2);
list.add(map2);
}
return new ProlongAllResult(MultiStepResult.Status.OK, list);
} else {
return new ProlongAllResult(MultiStepResult.Status.ERROR, doc2.text());
}
} else {
return new ProlongAllResult(MultiStepResult.Status.ERROR,
stringProvider.getString(StringProvider.UNSUPPORTED_IN_LIBRARY));
}
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String kndnr = form.select("input[name=kndnr]").attr("value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=9&kndnr="
+ kndnr + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Stornieren", getDefaultEncoding());
return new CancelResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
throw new NotReachableException();
}
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
if (!initialised) {
start();
}
Document doc = getAccountPage(account);
AccountData res = new AccountData(account.getId());
List<Map<String, String>> media = new ArrayList<>();
List<Map<String, String>> reserved = new ArrayList<>();
if (doc.select("a[name=AUS]").size() > 0) {
parse_medialist(media, doc);
}
if (doc.select("a[name=RES]").size() > 0) {
parse_reslist(reserved, doc);
}
res.setLent(media);
res.setReservations(reserved);
if (doc.select("h4:contains(Kontostand)").size() > 0) {
Element h4 = doc.select("h4:contains(Kontostand)").first();
Pattern regex = Pattern.compile("Kontostand (-?\\d+\\.\\d\\d EUR)");
Matcher matcher = regex.matcher(h4.text());
if (matcher.find()) res.setPendingFees(matcher.group(1));
}
if (doc.select("h4:contains(Ausweis g)").size() > 0) {
Element h4 = doc.select("h4:contains(Ausweis g)").first();
Pattern regex =
Pattern.compile("Ausweis g.+ltig bis\\s*.\\s*(\\d\\d.\\d\\d.\\d\\d\\d\\d)");
Matcher matcher = regex.matcher(h4.text());
if (matcher.find()) res.setValidUntil(matcher.group(1));
}
if (media.isEmpty() && reserved.isEmpty()) {
if (doc.select("h1").size() > 0) {
//noinspection StatementWithEmptyBody
if (doc.select("h4").text().trim()
.contains("keine ausgeliehenen Medien")) {
// There is no lent media, but the server is working
// correctly
} else if (doc.select("h1").text().trim()
.contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(
stringProvider
.getFormattedString(
StringProvider.UNKNOWN_ERROR_ACCOUNT_WITH_DESCRIPTION,
doc.select("h1").text().trim()));
}
} else {
throw new OpacErrorException(
stringProvider
.getString(StringProvider.UNKNOWN_ERROR_ACCOUNT));
}
}
return res;
}
private Document getAccountPage(Account account) throws IOException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Login"));
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
return Jsoup.parse(html);
}
public void checkAccountData(Account account) throws IOException,
OpacErrorException {
Document doc = getAccountPage(account);
if (doc.select("h1").text().contains("fehlgeschlagen")) {
throw new OpacErrorException(doc.select("h1, th").text());
}
}
protected void parse_medialist(List<Map<String, String>> media,
Document doc) {
Elements copytrs = doc.select("a[name=AUS] ~ table, a[name=AUS] ~ form table").first()
.select("tr");
doc.setBaseUri(opac_url);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
int trs = copytrs.size();
if (trs < 2) {
return;
}
assert (trs > 0);
JSONObject copymap = new JSONObject();
try {
if (data.has("accounttable")) {
copymap = data.getJSONObject("accounttable");
}
} catch (JSONException e) {
}
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<>();
if (copymap.optInt("title", 0) >= 0) {
e.put(AccountData.KEY_LENT_TITLE,
tr.child(copymap.optInt("title", 0)).text().trim()
.replace("\u00a0", ""));
}
if (copymap.optInt("author", 0) >= 1) {
e.put(AccountData.KEY_LENT_AUTHOR,
tr.child(copymap.optInt("author", 1)).text().trim()
.replace("\u00a0", ""));
}
if (copymap.optInt("format", -1) >= 0) {
e.put(AccountData.KEY_LENT_FORMAT,
tr.child(copymap.optInt("format", -1)).text().trim()
.replace("\u00a0", ""));
}
int prolongCount = 0;
if (copymap.optInt("prolongcount", 3) >= 0) {
prolongCount = Integer.parseInt(tr
.child(copymap.optInt("prolongcount", 3)).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_LENT_STATUS, String.valueOf(prolongCount) + "x verl.");
}
if (maxProlongCount != -1) {
e.put(AccountData.KEY_LENT_RENEWABLE,
prolongCount < maxProlongCount ? "Y" : "N");
}
if (copymap.optInt("deadline", 4) >= 0) {
e.put(AccountData.KEY_LENT_DEADLINE,
tr.child(copymap.optInt("deadline", 4)).text().trim()
.replace("\u00a0", ""));
}
try {
e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String
.valueOf(sdf
.parse(e.get(AccountData.KEY_LENT_DEADLINE))
.getTime()));
} catch (ParseException e1) {
e1.printStackTrace();
}
if (copymap.optInt("prolongurl", 5) >= 0) {
if (tr.children().size() > copymap.optInt("prolongurl", 5)) {
Element cell = tr.child(copymap.optInt("prolongurl", 5));
if (cell.select("input[name=MedNrVerlAll]").size() > 0) {
// new iOPAC Version 1.45 - checkboxes to prolong multiple items
// internal convention: We add "NEW" to the media ID to show that we have
// the new iOPAC version
Element input = cell.select("input[name=MedNrVerlAll]").first();
String value = input.val();
e.put(AccountData.KEY_LENT_LINK, "NEW" + value);
e.put(AccountData.KEY_LENT_ID, value.split(";")[0]);
if (input.hasAttr("disabled")) {
e.put(AccountData.KEY_LENT_RENEWABLE, "N");
}
} else {
// previous versions - link for prolonging on every medium
String link = cell.select("a").attr("href");
e.put(AccountData.KEY_LENT_LINK, link);
// find media number with regex
Pattern pattern = Pattern.compile("mednr=([^&]*)&");
Matcher matcher = pattern.matcher(link);
if (matcher.find() && matcher.group() != null) {
e.put(AccountData.KEY_LENT_ID, matcher.group(1));
}
}
}
}
media.add(e);
}
assert (media.size() == trs - 1);
}
protected void parse_reslist(List<Map<String, String>> media,
Document doc) {
Elements copytrs = doc.select("a[name=RES] ~ table:contains(Titel)")
.first().select("tr");
doc.setBaseUri(opac_url);
int trs = copytrs.size();
if (trs < 2) {
return;
}
assert (trs > 0);
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<>();
e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(0).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_AUTHOR, tr.child(1).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_READY, tr.child(4).text().trim()
.replace("\u00a0", ""));
if (tr.select("a").size() > 0) {
e.put(AccountData.KEY_RESERVATION_CANCEL, tr.select("a").last()
.attr("href"));
}
media.add(e);
}
assert (media.size() == trs - 1);
}
private SearchField createSearchField(Element descTd, Element inputTd) {
String name = descTd.select("span, blockquote").text().replace(":", "")
.trim().replace("\u00a0", "");
if (inputTd.select("select").size() > 0
&& !name.equals("Treffer/Seite") && !name.equals("Medientypen")
&& !name.equals("Medientyp")
&& !name.equals("Treffer pro Seite")) {
Element select = inputTd.select("select").first();
DropdownSearchField field = new DropdownSearchField();
field.setDisplayName(name);
field.setId(select.attr("name"));
List<Map<String, String>> options = new ArrayList<>();
for (Element option : select.select("option")) {
Map<String, String> map = new HashMap<>();
map.put("key", option.attr("value"));
map.put("value", option.text());
options.add(map);
}
field.setDropdownValues(options);
return field;
} else if (inputTd.select("input").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = inputTd.select("input").first();
field.setDisplayName(name);
field.setId(input.attr("name"));
field.setHint("");
return field;
} else {
return null;
}
}
@Override
public List<SearchField> getSearchFields() throws IOException {
List<SearchField> fields = new ArrayList<>();
// Extract all search fields, except media types
String html;
try {
html = httpGet(opac_url + dir + "/search_expert.htm",
getDefaultEncoding());
} catch (NotReachableException e) {
html = httpGet(opac_url + dir + "/iopacie.htm",
getDefaultEncoding());
}
Document doc = Jsoup.parse(html);
Elements trs = doc
.select("form tr:has(input:not([type=submit], [type=reset])), form tr:has(select)");
for (Element tr : trs) {
Elements tds = tr.children();
if (tds.size() == 4) {
// Two search fields next to each other in one row
SearchField field1 = createSearchField(tds.get(0), tds.get(1));
SearchField field2 = createSearchField(tds.get(2), tds.get(3));
if (field1 != null) {
fields.add(field1);
}
if (field2 != null) {
fields.add(field2);
}
} else if (tds.size() == 2
|| (tds.size() == 3 && tds.get(2).children().size() == 0)) {
SearchField field = createSearchField(tds.get(0), tds.get(1));
if (field != null) {
fields.add(field);
}
}
}
if (fields.size() == 0 && doc.select("[name=sleStichwort]").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = doc.select("input[name=sleStichwort]").first();
field.setDisplayName(stringProvider
.getString(StringProvider.FREE_SEARCH));
field.setId(input.attr("name"));
field.setHint("");
fields.add(field);
}
// Extract available media types.
// We have to parse JavaScript. Doing this with RegEx is evil.
// But not as evil as including a JavaScript VM into the app.
// And I honestly do not see another way.
Pattern pattern_key = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"typ\"\\] = \"([^\"]+)\";");
Pattern pattern_value = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"bez\"\\] = \"([^\"]+)\";");
List<Map<String, String>> mediatypes = new ArrayList<>();
try {
html = httpGet(opac_url + dir + "/mtyp.js", getDefaultEncoding());
String[] parts = html.split("new Array\\(\\);");
for (String part : parts) {
Matcher matcher1 = pattern_key.matcher(part);
String key = "";
String value = "";
if (matcher1.find()) {
key = matcher1.group(1);
}
Matcher matcher2 = pattern_value.matcher(part);
if (matcher2.find()) {
value = matcher2.group(1);
}
if (!value.equals("")) {
Map<String, String> mediatype = new HashMap<>();
mediatype.put("key", key);
mediatype.put("value", value);
mediatypes.add(mediatype);
}
}
} catch (IOException e) {
try {
html = httpGet(opac_url + dir
+ "/frames/search_form.php?bReset=1?bReset=1",
getDefaultEncoding());
doc = Jsoup.parse(html);
for (Element opt : doc.select("#imtyp option")) {
Map<String, String> mediatype = new HashMap<>();
mediatype.put("key", opt.attr("value"));
mediatype.put("value", opt.text());
mediatypes.add(mediatype);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (mediatypes.size() > 0) {
DropdownSearchField mtyp = new DropdownSearchField();
mtyp.setDisplayName("Medientypen");
mtyp.setId("Medientyp");
mtyp.setDropdownValues(mediatypes);
fields.add(mtyp);
}
return fields;
}
@Override
public boolean isAccountSupported(Library library) {
return library.isAccountSupported();
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account account) throws IOException {
return null;
}
@Override
public String getShareUrl(String id, String title) {
if (newShareLinks) {
return opac_url + dir + "/?mednr=" + id;
} else {
return opac_url + "/cgi-bin/di.exe?cMedNr=" + id + "&mode=23";
}
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT |
SUPPORT_FLAG_ACCOUNT_PROLONG_ALL;
}
public void updateRechnr(Document doc) {
String url = null;
for (Element a : doc.select("table a")) {
if (a.attr("href").contains("rechnr=")) {
url = a.attr("href");
break;
}
}
if (url == null) {
return;
}
Integer rechnrPosition = url.indexOf("rechnr=") + 7;
rechnr = url
.substring(rechnrPosition, url.indexOf("&", rechnrPosition));
}
@Override
public void setLanguage(String language) {
// TODO Auto-generated method stub
}
@Override
public Set<String> getSupportedLanguages() throws IOException {
// TODO Auto-generated method stub
return null;
}
}
| opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/IOpac.java | /**
* Copyright (C) 2013 by Johan von Forstner under the MIT license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package de.geeksfactory.opacclient.apis;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.geeksfactory.opacclient.NotReachableException;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailledItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.objects.SearchResult.Status;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
/**
* Implementation of Fleischmann iOpac, including account support Seems to work in all the libraries
* currently supported without any modifications.
*
* @author Johan von Forstner, 17.09.2013
*/
public class IOpac extends BaseApi implements OpacApi {
protected static HashMap<String, MediaType> defaulttypes = new HashMap<>();
static {
defaulttypes.put("b", MediaType.BOOK);
defaulttypes.put("o", MediaType.BOOK);
defaulttypes.put("e", MediaType.BOOK);
defaulttypes.put("p", MediaType.BOOK);
defaulttypes.put("j", MediaType.BOOK);
defaulttypes.put("g", MediaType.BOOK);
defaulttypes.put("k", MediaType.BOOK);
defaulttypes.put("a", MediaType.BOOK);
defaulttypes.put("c", MediaType.AUDIOBOOK);
defaulttypes.put("u", MediaType.AUDIOBOOK);
defaulttypes.put("l", MediaType.AUDIOBOOK);
defaulttypes.put("q", MediaType.CD_SOFTWARE);
defaulttypes.put("r", MediaType.CD_SOFTWARE);
defaulttypes.put("v", MediaType.MOVIE);
defaulttypes.put("d", MediaType.CD_MUSIC);
defaulttypes.put("n", MediaType.SCORE_MUSIC);
defaulttypes.put("s", MediaType.BOARDGAME);
defaulttypes.put("z", MediaType.MAGAZINE);
defaulttypes.put("x", MediaType.MAGAZINE);
}
protected String opac_url = "";
protected String dir = "/iopac";
protected JSONObject data;
protected String reusehtml;
protected String rechnr;
protected int results_total;
protected int maxProlongCount = -1;
protected boolean newShareLinks;
@Override
public void init(Library lib) {
super.init(lib);
this.data = lib.getData();
try {
this.opac_url = data.getString("baseurl");
if (data.has("maxprolongcount")) {
this.maxProlongCount = data.getInt("maxprolongcount");
}
if (data.has("dir")) {
this.dir = data.getString("dir");
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
protected int addParameters(SearchQuery query, List<NameValuePair> params,
int index) {
if (query.getValue().equals("")) {
return index;
}
params.add(new BasicNameValuePair(query.getKey(), query.getValue()));
return index + 1;
}
@Override
public SearchRequestResult search(List<SearchQuery> queries)
throws IOException, OpacErrorException {
if (!initialised) {
start();
}
List<NameValuePair> params = new ArrayList<>();
int index = 0;
start();
for (SearchQuery query : queries) {
index = addParameters(query, params, index);
}
params.add(new BasicNameValuePair("Anzahl", "10"));
params.add(new BasicNameValuePair("pshStart", "Suchen"));
if (index == 0) {
throw new OpacErrorException(
stringProvider.getString(StringProvider.NO_CRITERIA_INPUT));
}
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
return parse_search(html, 1);
}
protected SearchRequestResult parse_search(String html, int page)
throws OpacErrorException, NotReachableException {
Document doc = Jsoup.parse(html);
if (doc.select("h4").size() > 0) {
if (doc.select("h4").text().trim().startsWith("0 gefundene Medien")) {
// nothing found
return new SearchRequestResult(new ArrayList<SearchResult>(),
0, 1, 1);
} else if (!doc.select("h4").text().trim()
.contains("gefundene Medien")
&& !doc.select("h4").text().trim()
.contains("Es wurden mehr als")) {
// error
throw new OpacErrorException(doc.select("h4").text().trim());
}
} else if (doc.select("h1").size() > 0) {
if (doc.select("h1").text().trim().contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(stringProvider.getFormattedString(
StringProvider.UNKNOWN_ERROR_WITH_DESCRIPTION, doc
.select("h1").text().trim()));
}
} else {
return null;
}
updateRechnr(doc);
reusehtml = html;
results_total = -1;
if (doc.select("h4").text().trim().contains("Es wurden mehr als")) {
results_total = 200;
} else {
String resultnumstr = doc.select("h4").first().text();
resultnumstr = resultnumstr.substring(0, resultnumstr.indexOf(" "))
.trim();
results_total = Integer.parseInt(resultnumstr);
}
List<SearchResult> results = new ArrayList<>();
Elements tables = doc.select("table").first().select("tr:has(td)");
Map<String, Integer> colmap = new HashMap<>();
Element thead = doc.select("table").first().select("tr:has(th)")
.first();
int j = 0;
for (Element th : thead.select("th")) {
String text = th.text().trim().toLowerCase(Locale.GERMAN);
if (text.contains("cover")) {
colmap.put("cover", j);
} else if (text.contains("titel")) {
colmap.put("title", j);
} else if (text.contains("verfasser")) {
colmap.put("author", j);
} else if (text.contains("mtyp")) {
colmap.put("category", j);
} else if (text.contains("jahr")) {
colmap.put("year", j);
} else if (text.contains("signatur")) {
colmap.put("shelfmark", j);
} else if (text.contains("info")) {
colmap.put("info", j);
} else if (text.contains("abteilung")) {
colmap.put("department", j);
} else if (text.contains("verliehen") || text.contains("verl.")) {
colmap.put("returndate", j);
} else if (text.contains("anz.res")) {
colmap.put("reservations", j);
}
j++;
}
if (colmap.size() == 0) {
colmap.put("cover", 0);
colmap.put("title", 1);
colmap.put("author", 2);
colmap.put("publisher", 3);
colmap.put("year", 4);
colmap.put("department", 5);
colmap.put("shelfmark", 6);
colmap.put("returndate", 7);
colmap.put("category", 8);
}
for (int i = 0; i < tables.size(); i++) {
Element tr = tables.get(i);
SearchResult sr = new SearchResult();
if (tr.select("td").get(colmap.get("cover")).select("img").size() > 0) {
String imgUrl = tr.select("td").get(colmap.get("cover"))
.select("img").first().attr("src");
sr.setCover(imgUrl);
}
// Media Type
if (colmap.get("category") != null) {
String mType = tr.select("td").get(colmap.get("category"))
.text().trim().replace("\u00a0", "");
if (data.has("mediatypes")) {
try {
sr.setType(MediaType.valueOf(data.getJSONObject(
"mediatypes").getString(
mType.toLowerCase(Locale.GERMAN))));
} catch (JSONException | IllegalArgumentException e) {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
} else {
sr.setType(defaulttypes.get(mType
.toLowerCase(Locale.GERMAN)));
}
}
// Title and additional info
String title;
String additionalInfo = "";
if (colmap.get("info") != null) {
Element info = tr.select("td").get(colmap.get("info"));
title = info.select("a[title=Details-Info]").text().trim();
String authorIn = info.text().substring(0,
info.text().indexOf(title));
if (authorIn.contains(":")) {
authorIn = authorIn.replaceFirst("^([^:]*):(.*)$", "$1");
additionalInfo += " - " + authorIn;
}
} else {
title = tr.select("td").get(colmap.get("title")).text().trim()
.replace("\u00a0", "");
if (title.contains("(") && title.indexOf("(") > 0) {
additionalInfo += title.substring(title.indexOf("("));
title = title.substring(0, title.indexOf("(") - 1).trim();
}
// Author
if (colmap.containsKey("author")) {
String author = tr.select("td").get(colmap.get("author"))
.text().trim().replace("\u00a0", "");
additionalInfo += " - " + author;
}
}
// Publisher
if (colmap.containsKey("publisher")) {
String publisher = tr.select("td").get(colmap.get("publisher"))
.text().trim().replace("\u00a0", "");
additionalInfo += " (" + publisher;
}
// Year
if (colmap.containsKey("year")) {
String year = tr.select("td").get(colmap.get("year")).text()
.trim().replace("\u00a0", "");
additionalInfo += ", " + year + ")";
}
sr.setInnerhtml("<b>" + title + "</b><br>" + additionalInfo);
// Status
String status = tr.select("td").get(colmap.get("returndate"))
.text().trim().replace("\u00a0", "");
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
try {
df.parse(status);
// this is a return date
sr.setStatus(Status.RED);
sr.setInnerhtml(sr.getInnerhtml() + "<br><i>"
+ stringProvider.getString(StringProvider.LENT_UNTIL)
+ " " + status + "</i>");
} catch (ParseException e) {
// this is a different status text
String lc = status.toLowerCase(Locale.GERMAN);
if ((lc.equals("")
|| lc.toLowerCase(Locale.GERMAN).contains("onleihe")
|| lc.contains("verleihbar") || lc.contains("entleihbar")
|| lc.contains("ausleihbar")) && !lc.contains("nicht")) {
sr.setStatus(Status.GREEN);
} else {
sr.setStatus(Status.YELLOW);
sr.setInnerhtml(sr.getInnerhtml() + "<br><i>" + status + "</i>");
}
}
// In some libraries (for example search for "atelier" in Preetz)
// the results are sorted differently than their numbers suggest, so
// we need to detect the number ("recno") from the link
String link = tr.select("a[href^=/cgi-bin/di.exe?page=]").attr(
"href");
Map<String, String> params = getQueryParamsFirst(link);
if (params.containsKey("recno")) {
int recno = Integer.valueOf(params.get("recno"));
sr.setNr(recno - 1);
} else {
// the above should work, but fall back to this if it doesn't
sr.setNr(10 * (page - 1) + i);
}
// In some libraries (for example Preetz) we can detect the media ID
// here using another link present in the search results
Elements idLinks = tr.select("a[href^=/cgi-bin/di.exe?cMedNr]");
if (idLinks.size() > 0) {
Map<String, String> idParams = getQueryParamsFirst(idLinks
.first().attr("href"));
String id = idParams.get("cMedNr");
sr.setId(id);
} else {
sr.setId(null);
}
results.add(sr);
}
return new SearchRequestResult(results, results_total, page);
}
@Override
public SearchRequestResult searchGetPage(int page) throws IOException,
OpacErrorException {
if (!initialised) {
start();
}
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&FilNr=",
getDefaultEncoding());
return parse_search(html, page);
}
@Override
public SearchRequestResult filterResults(Filter filter, Option option)
throws IOException {
return null;
}
@Override
public DetailledItem getResultById(String id, String homebranch)
throws IOException {
if (!initialised) {
start();
}
if (id == null && reusehtml != null) {
return parse_result(reusehtml);
}
String html = httpGet(opac_url + "/cgi-bin/di.exe?cMedNr=" + id
+ "&mode=23", getDefaultEncoding());
return parse_result(html);
}
@Override
public DetailledItem getResult(int position) throws IOException {
if (!initialised) {
start();
}
int page = Double.valueOf(Math.floor(position / 10)).intValue() + 1;
String html = httpGet(opac_url + "/cgi-bin/di.exe?page=" + page
+ "&rechnr=" + rechnr + "&Anzahl=10&recno=" + (position + 1)
+ "&FilNr=", getDefaultEncoding());
return parse_result(html);
}
protected DetailledItem parse_result(String html) throws IOException {
Document doc = Jsoup.parse(html);
DetailledItem result = new DetailledItem();
String id;
if (doc.select("input[name=mednr]").size() > 0) {
id = doc.select("input[name=mednr]").first().val().trim();
} else {
String href = doc.select("a[href*=mednr]").first().attr("href");
id = getQueryParamsFirst(href).get("mednr").trim();
}
result.setId(id);
// check if new share button is available (allows to share a link to the standard
// frameset of the OPAC instead of only the detail frame)
newShareLinks = doc.select("#sharebutton").size() > 0;
Elements table = doc.select("table").get(1).select("tr");
// GET COVER IMAGE
String imgUrl = table.get(0)
.select("img[src~=^https?://(:?images(?:-[^\\.]*)?\\.|[^\\.]*\\" +
".images-)amazon\\.com]")
.attr("src");
result.setCover(imgUrl);
// GET INFORMATION
Map<String, String> e = new HashMap<>();
for (Element element : table) {
String detail = element.select("td").text().trim()
.replace("\u00a0", "");
String title = element.select("th").text().trim()
.replace("\u00a0", "");
if (!title.equals("")) {
if (title.contains("verliehen bis")) {
if (detail.equals("")) {
e.put(DetailledItem.KEY_COPY_STATUS, "verfügbar");
} else {
e.put(DetailledItem.KEY_COPY_STATUS, "verliehen bis "
+ detail);
}
} else if (title.contains("Abteilung")) {
e.put(DetailledItem.KEY_COPY_DEPARTMENT, detail);
} else if (title.contains("Signatur")) {
e.put(DetailledItem.KEY_COPY_SHELFMARK, detail);
} else if (title.contains("Titel")) {
result.setTitle(detail);
} else if (!title.contains("Cover")) {
result.addDetail(new Detail(title, detail));
}
}
}
// GET RESERVATION INFO
if ("verfügbar".equals(e.get(DetailledItem.KEY_COPY_STATUS))
|| doc.select(
"a[href^=/cgi-bin/di.exe?mode=10], input.resbutton")
.size() == 0) {
result.setReservable(false);
} else {
result.setReservable(true);
if (doc.select("a[href^=/cgi-bin/di.exe?mode=10]").size() > 0) {
// Reservation via link
result.setReservation_info(doc
.select("a[href^=/cgi-bin/di.exe?mode=10]").first()
.attr("href").substring(1).replace(" ", ""));
} else {
// Reservation via form (method="get")
Element form = doc.select("input.resbutton").first().parent();
result.setReservation_info(generateQuery(form));
}
}
if (e.size() > 0) result.addCopy(e);
return result;
}
private String generateQuery(Element form)
throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(form.attr("action").substring(1));
int i = 0;
for (Element input : form.select("input")) {
builder.append(i == 0 ? "?" : "&");
builder.append(input.attr("name")).append("=")
.append(URLEncoder.encode(input.attr("value"), "UTF-8"));
i++;
}
return builder.toString();
}
@Override
public ReservationResult reservation(DetailledItem item, Account account,
int useraction, String selection) throws IOException {
String reservation_info = item.getReservation_info();
// STEP 1: Login page
String html = httpGet(opac_url + "/" + reservation_info,
getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table").first().text().contains("kann nicht")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
}
if (doc.select("form[name=form1]").size() == 0) {
return new ReservationResult(MultiStepResult.Status.ERROR);
}
Element form = doc.select("form[name=form1]").first();
List<BasicNameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Reservieren"));
for (Element input : form.select("input[type=hidden]")) {
params.add(new BasicNameValuePair(input.attr("name"), input
.attr("value")));
}
// STEP 2: Confirmation page
html = httpPost(opac_url + "/cgi-bin/di.exe", new UrlEncodedFormEntity(
params), getDefaultEncoding());
doc = Jsoup.parse(html);
if (doc.select("form[name=form1]").size() > 0) {
// STEP 3: There is another confirmation needed
form = doc.select("form[name=form1]").first();
html = httpGet(opac_url + "/" + generateQuery(form),
getDefaultEncoding());
doc = Jsoup.parse(html);
}
if (doc.text().contains("fehlgeschlagen")
|| doc.text().contains("Achtung") || doc.text().contains("nicht m")) {
return new ReservationResult(MultiStepResult.Status.ERROR, doc
.select("table").first().text().trim());
} else {
return new ReservationResult(MultiStepResult.Status.OK);
}
}
@Override
public ProlongResult prolong(String media, Account account, int useraction,
String Selection) throws IOException {
// internal convention: We add "NEW" to the media ID to show that we have the new iOPAC
// version
if (media.startsWith("NEW")) {
String mediaNr = media.substring(3);
String html = httpGet(opac_url + "/cgi-bin/di.exe?mode=42&MedNrVerlAll=" +
URLEncoder.encode(mediaNr, "UTF-8"), getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.text().contains("1 Medium wurde verl")) {
return new ProlongResult(MultiStepResult.Status.OK);
} else {
return new ProlongResult(MultiStepResult.Status.ERROR, doc.text());
}
} else {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
if (doc.select("table th").size() > 0) {
if (doc.select("h1").size() > 0) {
if (doc.select("h1").first().text().contains("Hinweis")) {
return new ProlongResult(MultiStepResult.Status.ERROR, doc
.select("table th").first().text());
}
}
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=8&kndnr="
+ account.getName() + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Verl%C3%A4ngern",
getDefaultEncoding());
return new ProlongResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
return new ProlongResult(MultiStepResult.Status.ERROR);
}
}
@Override
public ProlongAllResult prolongAll(Account account, int useraction,
String selection) throws IOException {
Document doc = getAccountPage(account);
// Check if the iOPAC verion supports this feature
if (doc.select("button.verlallbutton").size() > 0) {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("mode", "42"));
for (Element checkbox : doc.select("input.VerlAllCheckboxOK")) {
params.add(new BasicNameValuePair("MedNrVerlAll", checkbox.val()));
}
String html = httpGet(
opac_url + "/cgi-bin/di.exe?" + URLEncodedUtils.format(params, "UTF-8"),
getDefaultEncoding());
Document doc2 = Jsoup.parse(html);
Pattern pattern = Pattern.compile("(\\d+ Medi(?:en|um) wurden? verl.ngert)\\s*(\\d+ " +
"Medi(?:en|um) wurden? nicht verl.ngert)?");
Matcher matcher = pattern.matcher(doc2.text());
if (matcher.find()) {
String text1 = matcher.group(1);
String text2 = matcher.group(2);
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> map1 = new HashMap<>();
// TODO: We are abusing the ProlongAllResult.KEY_LINE_ ... keys here because we
// do not get information about all the media
map1.put(ProlongAllResult.KEY_LINE_TITLE, text1);
list.add(map1);
if (!text2.equals("")) {
Map<String, String> map2 = new HashMap<>();
map2.put(ProlongAllResult.KEY_LINE_TITLE, text2);
list.add(map2);
}
return new ProlongAllResult(MultiStepResult.Status.OK, list);
} else {
return new ProlongAllResult(MultiStepResult.Status.ERROR, doc2.text());
}
} else {
return new ProlongAllResult(MultiStepResult.Status.ERROR,
stringProvider.getString(StringProvider.UNSUPPORTED_IN_LIBRARY));
}
}
@Override
public CancelResult cancel(String media, Account account, int useraction,
String selection) throws IOException, OpacErrorException {
String html = httpGet(opac_url + "/" + media, getDefaultEncoding());
Document doc = Jsoup.parse(html);
try {
Element form = doc.select("form[name=form1]").first();
String sessionid = form.select("input[name=sessionid]").attr(
"value");
String kndnr = form.select("input[name=kndnr]").attr("value");
String mednr = form.select("input[name=mednr]").attr("value");
httpGet(opac_url + "/cgi-bin/di.exe?mode=9&kndnr="
+ kndnr + "&mednr=" + mednr + "&sessionid="
+ sessionid + "&psh100=Stornieren", getDefaultEncoding());
return new CancelResult(MultiStepResult.Status.OK);
} catch (Throwable e) {
e.printStackTrace();
throw new NotReachableException();
}
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
if (!initialised) {
start();
}
Document doc = getAccountPage(account);
AccountData res = new AccountData(account.getId());
List<Map<String, String>> media = new ArrayList<>();
List<Map<String, String>> reserved = new ArrayList<>();
if (doc.select("a[name=AUS]").size() > 0) {
parse_medialist(media, doc);
}
if (doc.select("a[name=RES]").size() > 0) {
parse_reslist(reserved, doc);
}
res.setLent(media);
res.setReservations(reserved);
if (doc.select("h4:contains(Kontostand)").size() > 0) {
Element h4 = doc.select("h4:contains(Kontostand)").first();
Pattern regex = Pattern.compile("Kontostand (-?\\d+\\.\\d\\d EUR)");
Matcher matcher = regex.matcher(h4.text());
if (matcher.find()) res.setPendingFees(matcher.group(1));
}
if (doc.select("h4:contains(Ausweis g)").size() > 0) {
Element h4 = doc.select("h4:contains(Ausweis g)").first();
Pattern regex =
Pattern.compile("Ausweis g.+ltig bis\\s*.\\s*(\\d\\d.\\d\\d.\\d\\d\\d\\d)");
Matcher matcher = regex.matcher(h4.text());
if (matcher.find()) res.setValidUntil(matcher.group(1));
}
if (media.isEmpty() && reserved.isEmpty()) {
if (doc.select("h1").size() > 0) {
//noinspection StatementWithEmptyBody
if (doc.select("h4").text().trim()
.contains("keine ausgeliehenen Medien")) {
// There is no lent media, but the server is working
// correctly
} else if (doc.select("h1").text().trim()
.contains("RUNTIME ERROR")) {
// Server Error
throw new NotReachableException();
} else {
throw new OpacErrorException(
stringProvider
.getFormattedString(
StringProvider.UNKNOWN_ERROR_ACCOUNT_WITH_DESCRIPTION,
doc.select("h1").text().trim()));
}
} else {
throw new OpacErrorException(
stringProvider
.getString(StringProvider.UNKNOWN_ERROR_ACCOUNT));
}
}
return res;
}
private Document getAccountPage(Account account) throws IOException {
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sleKndNr", account.getName()));
params.add(new BasicNameValuePair("slePw", account.getPassword()));
params.add(new BasicNameValuePair("pshLogin", "Login"));
String html = httpPost(opac_url + "/cgi-bin/di.exe",
new UrlEncodedFormEntity(params, "iso-8859-1"),
getDefaultEncoding());
return Jsoup.parse(html);
}
public void checkAccountData(Account account) throws IOException,
OpacErrorException {
Document doc = getAccountPage(account);
if (doc.select("h1").text().contains("fehlgeschlagen")) {
throw new OpacErrorException(doc.select("h1, th").text());
}
}
protected void parse_medialist(List<Map<String, String>> media,
Document doc) {
Elements copytrs = doc.select("a[name=AUS] ~ table, a[name=AUS] ~ form table").first()
.select("tr");
doc.setBaseUri(opac_url);
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
int trs = copytrs.size();
if (trs < 2) {
return;
}
assert (trs > 0);
JSONObject copymap = new JSONObject();
try {
if (data.has("accounttable")) {
copymap = data.getJSONObject("accounttable");
}
} catch (JSONException e) {
}
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<>();
if (copymap.optInt("title", 0) >= 0) {
e.put(AccountData.KEY_LENT_TITLE,
tr.child(copymap.optInt("title", 0)).text().trim()
.replace("\u00a0", ""));
}
if (copymap.optInt("author", 0) >= 1) {
e.put(AccountData.KEY_LENT_AUTHOR,
tr.child(copymap.optInt("author", 1)).text().trim()
.replace("\u00a0", ""));
}
if (copymap.optInt("format", -1) >= 0) {
e.put(AccountData.KEY_LENT_FORMAT,
tr.child(copymap.optInt("format", -1)).text().trim()
.replace("\u00a0", ""));
}
int prolongCount = 0;
if (copymap.optInt("prolongcount", 3) >= 0) {
prolongCount = Integer.parseInt(tr
.child(copymap.optInt("prolongcount", 3)).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_LENT_STATUS, String.valueOf(prolongCount) + "x verl.");
}
if (maxProlongCount != -1) {
e.put(AccountData.KEY_LENT_RENEWABLE,
prolongCount < maxProlongCount ? "Y" : "N");
}
if (copymap.optInt("deadline", 4) >= 0) {
e.put(AccountData.KEY_LENT_DEADLINE,
tr.child(copymap.optInt("deadline", 4)).text().trim()
.replace("\u00a0", ""));
}
try {
e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, String
.valueOf(sdf
.parse(e.get(AccountData.KEY_LENT_DEADLINE))
.getTime()));
} catch (ParseException e1) {
e1.printStackTrace();
}
if (copymap.optInt("prolongurl", 5) >= 0) {
if (tr.children().size() > copymap.optInt("prolongurl", 5)) {
Element cell = tr.child(copymap.optInt("prolongurl", 5));
if (cell.select("input.VerlAllCheckboxOK").size() > 0) {
// new iOPAC Version 1.45 - checkboxes to prolong multiple items
// internal convention: We add "NEW" to the media ID to show that we have
// the new iOPAC version
String value = cell.select("input.VerlAllCheckboxOK").first().val();
e.put(AccountData.KEY_LENT_LINK, "NEW" + value);
e.put(AccountData.KEY_LENT_ID, value.split(";")[0]);
if (cell.select("input.VerlAllCheckboxOK").hasAttr("disabled")) {
e.put(AccountData.KEY_LENT_RENEWABLE, "N");
}
} else {
// previous versions - link for prolonging on every medium
String link = cell.select("a").attr("href");
e.put(AccountData.KEY_LENT_LINK, link);
// find media number with regex
Pattern pattern = Pattern.compile("mednr=([^&]*)&");
Matcher matcher = pattern.matcher(link);
if (matcher.find() && matcher.group() != null) {
e.put(AccountData.KEY_LENT_ID, matcher.group(1));
}
}
}
}
media.add(e);
}
assert (media.size() == trs - 1);
}
protected void parse_reslist(List<Map<String, String>> media,
Document doc) {
Elements copytrs = doc.select("a[name=RES] ~ table:contains(Titel)")
.first().select("tr");
doc.setBaseUri(opac_url);
int trs = copytrs.size();
if (trs < 2) {
return;
}
assert (trs > 0);
for (int i = 1; i < trs; i++) {
Element tr = copytrs.get(i);
Map<String, String> e = new HashMap<>();
e.put(AccountData.KEY_RESERVATION_TITLE, tr.child(0).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_AUTHOR, tr.child(1).text().trim()
.replace("\u00a0", ""));
e.put(AccountData.KEY_RESERVATION_READY, tr.child(4).text().trim()
.replace("\u00a0", ""));
if (tr.select("a").size() > 0) {
e.put(AccountData.KEY_RESERVATION_CANCEL, tr.select("a").last()
.attr("href"));
}
media.add(e);
}
assert (media.size() == trs - 1);
}
private SearchField createSearchField(Element descTd, Element inputTd) {
String name = descTd.select("span, blockquote").text().replace(":", "")
.trim().replace("\u00a0", "");
if (inputTd.select("select").size() > 0
&& !name.equals("Treffer/Seite") && !name.equals("Medientypen")
&& !name.equals("Medientyp")
&& !name.equals("Treffer pro Seite")) {
Element select = inputTd.select("select").first();
DropdownSearchField field = new DropdownSearchField();
field.setDisplayName(name);
field.setId(select.attr("name"));
List<Map<String, String>> options = new ArrayList<>();
for (Element option : select.select("option")) {
Map<String, String> map = new HashMap<>();
map.put("key", option.attr("value"));
map.put("value", option.text());
options.add(map);
}
field.setDropdownValues(options);
return field;
} else if (inputTd.select("input").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = inputTd.select("input").first();
field.setDisplayName(name);
field.setId(input.attr("name"));
field.setHint("");
return field;
} else {
return null;
}
}
@Override
public List<SearchField> getSearchFields() throws IOException {
List<SearchField> fields = new ArrayList<>();
// Extract all search fields, except media types
String html;
try {
html = httpGet(opac_url + dir + "/search_expert.htm",
getDefaultEncoding());
} catch (NotReachableException e) {
html = httpGet(opac_url + dir + "/iopacie.htm",
getDefaultEncoding());
}
Document doc = Jsoup.parse(html);
Elements trs = doc
.select("form tr:has(input:not([type=submit], [type=reset])), form tr:has(select)");
for (Element tr : trs) {
Elements tds = tr.children();
if (tds.size() == 4) {
// Two search fields next to each other in one row
SearchField field1 = createSearchField(tds.get(0), tds.get(1));
SearchField field2 = createSearchField(tds.get(2), tds.get(3));
if (field1 != null) {
fields.add(field1);
}
if (field2 != null) {
fields.add(field2);
}
} else if (tds.size() == 2
|| (tds.size() == 3 && tds.get(2).children().size() == 0)) {
SearchField field = createSearchField(tds.get(0), tds.get(1));
if (field != null) {
fields.add(field);
}
}
}
if (fields.size() == 0 && doc.select("[name=sleStichwort]").size() > 0) {
TextSearchField field = new TextSearchField();
Element input = doc.select("input[name=sleStichwort]").first();
field.setDisplayName(stringProvider
.getString(StringProvider.FREE_SEARCH));
field.setId(input.attr("name"));
field.setHint("");
fields.add(field);
}
// Extract available media types.
// We have to parse JavaScript. Doing this with RegEx is evil.
// But not as evil as including a JavaScript VM into the app.
// And I honestly do not see another way.
Pattern pattern_key = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"typ\"\\] = \"([^\"]+)\";");
Pattern pattern_value = Pattern
.compile("mtyp\\[[0-9]+\\]\\[\"bez\"\\] = \"([^\"]+)\";");
List<Map<String, String>> mediatypes = new ArrayList<>();
try {
html = httpGet(opac_url + dir + "/mtyp.js", getDefaultEncoding());
String[] parts = html.split("new Array\\(\\);");
for (String part : parts) {
Matcher matcher1 = pattern_key.matcher(part);
String key = "";
String value = "";
if (matcher1.find()) {
key = matcher1.group(1);
}
Matcher matcher2 = pattern_value.matcher(part);
if (matcher2.find()) {
value = matcher2.group(1);
}
if (!value.equals("")) {
Map<String, String> mediatype = new HashMap<>();
mediatype.put("key", key);
mediatype.put("value", value);
mediatypes.add(mediatype);
}
}
} catch (IOException e) {
try {
html = httpGet(opac_url + dir
+ "/frames/search_form.php?bReset=1?bReset=1",
getDefaultEncoding());
doc = Jsoup.parse(html);
for (Element opt : doc.select("#imtyp option")) {
Map<String, String> mediatype = new HashMap<>();
mediatype.put("key", opt.attr("value"));
mediatype.put("value", opt.text());
mediatypes.add(mediatype);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (mediatypes.size() > 0) {
DropdownSearchField mtyp = new DropdownSearchField();
mtyp.setDisplayName("Medientypen");
mtyp.setId("Medientyp");
mtyp.setDropdownValues(mediatypes);
fields.add(mtyp);
}
return fields;
}
@Override
public boolean isAccountSupported(Library library) {
return library.isAccountSupported();
}
@Override
public boolean isAccountExtendable() {
return false;
}
@Override
public String getAccountExtendableInfo(Account account) throws IOException {
return null;
}
@Override
public String getShareUrl(String id, String title) {
if (newShareLinks) {
return opac_url + dir + "/?mednr=" + id;
} else {
return opac_url + "/cgi-bin/di.exe?cMedNr=" + id + "&mode=23";
}
}
@Override
public int getSupportFlags() {
return SUPPORT_FLAG_ENDLESS_SCROLLING | SUPPORT_FLAG_CHANGE_ACCOUNT |
SUPPORT_FLAG_ACCOUNT_PROLONG_ALL;
}
public void updateRechnr(Document doc) {
String url = null;
for (Element a : doc.select("table a")) {
if (a.attr("href").contains("rechnr=")) {
url = a.attr("href");
break;
}
}
if (url == null) {
return;
}
Integer rechnrPosition = url.indexOf("rechnr=") + 7;
rechnr = url
.substring(rechnrPosition, url.indexOf("&", rechnrPosition));
}
@Override
public void setLanguage(String language) {
// TODO Auto-generated method stub
}
@Override
public Set<String> getSupportedLanguages() throws IOException {
// TODO Auto-generated method stub
return null;
}
}
| Correctly detect non-prolongable items in new iOPAC version
| opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/IOpac.java | Correctly detect non-prolongable items in new iOPAC version | <ide><path>pacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/IOpac.java
<ide> if (copymap.optInt("prolongurl", 5) >= 0) {
<ide> if (tr.children().size() > copymap.optInt("prolongurl", 5)) {
<ide> Element cell = tr.child(copymap.optInt("prolongurl", 5));
<del> if (cell.select("input.VerlAllCheckboxOK").size() > 0) {
<add> if (cell.select("input[name=MedNrVerlAll]").size() > 0) {
<ide> // new iOPAC Version 1.45 - checkboxes to prolong multiple items
<ide> // internal convention: We add "NEW" to the media ID to show that we have
<ide> // the new iOPAC version
<del> String value = cell.select("input.VerlAllCheckboxOK").first().val();
<add> Element input = cell.select("input[name=MedNrVerlAll]").first();
<add> String value = input.val();
<ide> e.put(AccountData.KEY_LENT_LINK, "NEW" + value);
<ide> e.put(AccountData.KEY_LENT_ID, value.split(";")[0]);
<del> if (cell.select("input.VerlAllCheckboxOK").hasAttr("disabled")) {
<add> if (input.hasAttr("disabled")) {
<ide> e.put(AccountData.KEY_LENT_RENEWABLE, "N");
<ide> }
<ide> } else { |
|
JavaScript | apache-2.0 | 11745fa6d5ed80c5db20a14a6612ecff83a8e3a9 | 0 | adamtootle/servizi,adamtootle/servizi | const { accounts } = require('./database');
const config = require('../../config');
const keys = require('./keys');
const Promise = require('bluebird');
const simpleOauth2 = require('simple-oauth2');
const request = require('request-promise');
function Auth() {
//
// properties
//
this.oauthClient = simpleOauth2.create({
client: {
id: config.oauthClientId,
secret: config.oauthClientSecret,
},
auth: {
tokenHost: 'https://api.planningcenteronline.com',
},
});
this.authorizationUrl = this.oauthClient.authorizationCode.authorizeURL({
redirect_uri: 'servizi://oauth/callback',
scope: 'services',
});
//
// public methods
//
this.checkIfShouldRefreshToken = function shouldRefreshToken(_tokenRecord) {
const tokenRecord = _tokenRecord;
return new Promise((resolve) => {
if (tokenRecord === null) {
resolve(null);
return;
}
const timeDifference = Math.floor(Date.now() / 1000) - tokenRecord.token.created_at;
if (timeDifference >= tokenRecord.token.expires_in) {
tokenRecord.should_refresh = true;
} else {
tokenRecord.should_refresh = false;
}
resolve(tokenRecord);
});
};
this.shouldRefreshToken = function shouldRefreshToken(token) {
if (!token) {
return true;
}
const timeDifference = Math.floor(Date.now() / 1000) - token.created_at;
if (timeDifference >= token.expires_in - 300) {
return true;
}
return false;
};
this.refreshSelectedAccountTokenIfNecessary = (tokenRecord) => {
return new Promise((resolve, reject) => {
accounts.findOne({ selected: true }, (err, existingTokenResult) => {
if (!existingTokenResult) {
reject();
} else if (err) {
reject(err);
}
if (this.shouldRefreshToken(existingTokenResult.tokenInfo.token)) {
const oauthToken = this.oauthClient.accessToken.create(existingTokenResult.tokenInfo.token);
oauthToken.refresh()
.then((tokenResponse) => {
const newTokenInfo = {
redirect_uri: existingTokenResult.tokenInfo.redirect_uri,
token: tokenResponse.token,
};
accounts.update(
{ _id: existingTokenResult._id },
{ $set: { tokenInfo: newTokenInfo } },
{ upsert: true },
() => {
resolve();
}
);
})
.catch(reject);
} else {
resolve();
}
});
// if (tokenRecord === null) {
// resolve(null);
// return;
// }
// const tokenObject = {
// access_token: tokenRecord.token.access_token,
// refresh_token: tokenRecord.token.refresh_token,
// expires_in: tokenRecord.token.expires_in,
// };
// token.refresh()
// .then((tokenResponse) => {
// database.findOne({ key: 'oauth_token' }, (err, doc) => {
// database.update(
// { _id: doc._id },
// { key: 'oauth_token', value: tokenResponse },
// { multi: false },
// () => resolve(tokenResponse)
// );
// });
// })
// .catch(reject);
});
};
}
module.exports = new Auth();
| app/main/auth.js | const { accounts } = require('./database');
const config = require('../../config');
const keys = require('./keys');
const Promise = require('bluebird');
const simpleOauth2 = require('simple-oauth2');
const request = require('request-promise');
function Auth() {
//
// properties
//
this.oauthClient = simpleOauth2.create({
client: {
id: config.oauthClientId,
secret: config.oauthClientSecret,
},
auth: {
tokenHost: 'https://api.planningcenteronline.com',
},
});
this.authorizationUrl = this.oauthClient.authorizationCode.authorizeURL({
redirect_uri: 'servizi://oauth/callback',
scope: 'services',
});
//
// public methods
//
this.checkIfShouldRefreshToken = function shouldRefreshToken(_tokenRecord) {
const tokenRecord = _tokenRecord;
return new Promise((resolve) => {
if (tokenRecord === null) {
resolve(null);
return;
}
const timeDifference = Math.floor(Date.now() / 1000) - tokenRecord.token.created_at;
if (timeDifference >= tokenRecord.token.expires_in) {
tokenRecord.should_refresh = true;
} else {
tokenRecord.should_refresh = false;
}
resolve(tokenRecord);
});
};
this.shouldRefreshToken = function shouldRefreshToken(token) {
if (!token) {
return true;
}
const timeDifference = Math.floor(Date.now() / 1000) - token.created_at;
if (timeDifference >= token.expires_in - 300) {
return true;
}
return false;
};
this.refreshSelectedAccountTokenIfNecessary = (tokenRecord) => {
return new Promise((resolve, reject) => {
accounts.findOne({ selected: true }, (err, existingTokenResult) => {
if (!existingTokenResult) {
reject();
} else if (err) {
reject(err);
}
if (this.shouldRefreshToken(existingTokenResult.tokenInfo.token)) {
const oauthToken = this.oauthClient.accessToken.create(existingTokenResult.tokenInfo.token);
oauthToken.refresh()
.then((tokenResponse) => {
const newTokenInfo = {
redirect_uri: existingTokenResult.tokenInfo.redirect_uri,
token: tokenResponse,
};
accounts.update(
{ _id: existingTokenResult._id },
{ $set: { tokenInfo: newTokenInfo } },
{ upsert: true },
() => {
resolve();
}
);
})
.catch(reject);
} else {
resolve();
}
});
// if (tokenRecord === null) {
// resolve(null);
// return;
// }
// const tokenObject = {
// access_token: tokenRecord.token.access_token,
// refresh_token: tokenRecord.token.refresh_token,
// expires_in: tokenRecord.token.expires_in,
// };
// token.refresh()
// .then((tokenResponse) => {
// database.findOne({ key: 'oauth_token' }, (err, doc) => {
// database.update(
// { _id: doc._id },
// { key: 'oauth_token', value: tokenResponse },
// { multi: false },
// () => resolve(tokenResponse)
// );
// });
// })
// .catch(reject);
});
};
}
module.exports = new Auth();
| Small tweak to the oauth token refreshing.
| app/main/auth.js | Small tweak to the oauth token refreshing. | <ide><path>pp/main/auth.js
<ide> .then((tokenResponse) => {
<ide> const newTokenInfo = {
<ide> redirect_uri: existingTokenResult.tokenInfo.redirect_uri,
<del> token: tokenResponse,
<add> token: tokenResponse.token,
<ide> };
<ide> accounts.update(
<ide> { _id: existingTokenResult._id }, |
|
Java | apache-2.0 | 3ef5cfebb5ff987781aaff677a6fe48c7ca8cdff | 0 | bladecoder/bladecoder-adventure-engine,bladecoder/bladecoder-adventure-engine | package com.bladecoder.engine.model;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.anim.MusicVolumeTween;
import com.bladecoder.engine.assets.AssetConsumer;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.engine.util.InterpolationMode;
/**
* Simple music engine.
*
* Plays a music file, if another music is playing, stops it before playing the
* new music.
*
* @author rgarcia
*/
public class MusicManager implements Serializable, AssetConsumer {
private MusicDesc desc = null;
private Music music = null;
private float currentMusicDelay = 0;
private boolean isPlayingSer = false;
private float musicPosSer = 0;
transient private boolean isPaused = false;
private MusicVolumeTween volumeTween;
// the global configurable by user volume
public static float VOLUME_MULTIPLIER = 1f;
private final Task backgroundLoadingTask = new Task() {
@Override
public void run() {
if (!EngineAssetManager.getInstance().isLoading()) {
cancel();
retrieveAssets();
}
}
};
public void playMusic() {
if (music != null && !music.isPlaying()) {
try {
music.play();
music.setLooping(desc.isLoop());
music.setVolume(desc.getVolume() * VOLUME_MULTIPLIER);
} catch (Exception e) {
// DEAL WITH OPENAL BUG
if (Gdx.app.getType() == ApplicationType.Desktop && e.getMessage().contains("40963")) {
EngineLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!ERROR playing music trying again...!!!!!!!!!!!!!!!");
MusicDesc desc2 = desc;
desc = null;
setMusic(desc2);
return;
}
EngineLogger.error("Error Playing music: " + desc.getFilename(), e);
}
}
}
public void pauseMusic() {
if (music != null && music.isPlaying()) {
music.pause();
isPaused = true;
}
}
public void resumeMusic() {
if (music != null && isPaused) {
music.play();
isPaused = false;
}
}
public void stopMusic() {
if (music != null)
music.stop();
}
public void setMusic(MusicDesc d) {
if (desc != null && d != null && d.getFilename() != null && d.getFilename().equals(desc.getFilename())) {
EngineLogger.debug(">>>NOT SETTING MUSIC: This music file is already playing.");
return;
}
EngineLogger.debug(">>>SETTING MUSIC.");
stopMusic();
volumeTween = null;
currentMusicDelay = 0;
if (d != null) {
if (desc != null) {
dispose();
}
desc = new MusicDesc(d);
// Load the music file in background to avoid
// blocking the UI
loadTask();
} else {
dispose();
desc = null;
}
}
private void loadTask() {
loadAssets();
backgroundLoadingTask.cancel();
Timer.schedule(backgroundLoadingTask, 0, 0);
}
public void setVolume(float volume) {
if (desc != null)
desc.setVolume(volume);
if (music != null && music.isPlaying())
music.setVolume(volume * VOLUME_MULTIPLIER);
}
public float getVolume() {
if (desc != null)
return desc.getVolume();
return 1f;
}
public void leaveScene(MusicDesc newMusicDesc) {
if (desc != null && !desc.isStopWhenLeaving()
&& (newMusicDesc == null || newMusicDesc.getFilename().equals(desc.getFilename())))
return;
if (desc != null) {
currentMusicDelay = 0f;
stopMusic();
dispose();
}
if (newMusicDesc != null) {
desc = new MusicDesc(newMusicDesc);
} else {
desc = null;
}
}
public void update(float delta) {
// music delay update
if (music != null) {
if (!music.isPlaying()) {
boolean initialTime = false;
if (currentMusicDelay <= desc.getInitialDelay())
initialTime = true;
currentMusicDelay += delta;
if (initialTime) {
if (currentMusicDelay > desc.getInitialDelay())
playMusic();
} else {
if (desc.getRepeatDelay() >= 0
&& currentMusicDelay > desc.getRepeatDelay() + desc.getInitialDelay()) {
currentMusicDelay = desc.getInitialDelay();
playMusic();
}
}
}
if (volumeTween != null) {
volumeTween.update(delta);
if (volumeTween != null && volumeTween.isComplete()) {
volumeTween = null;
}
}
}
}
@Override
public void dispose() {
if (music != null) {
EngineLogger.debug("DISPOSING MUSIC: " + desc.getFilename());
EngineAssetManager.getInstance().disposeMusic(desc.getFilename());
music = null;
desc = null;
volumeTween = null;
}
}
@Override
public void loadAssets() {
if (music == null && desc != null) {
EngineLogger.debug("LOADING MUSIC: " + desc.getFilename());
EngineAssetManager.getInstance().loadMusic(desc.getFilename());
}
}
@Override
public void retrieveAssets() {
if (music == null && desc != null) {
// Check if not loaded, this happens when setting a cached scene
if (!EngineAssetManager.getInstance().isLoaded(EngineAssetManager.MUSIC_DIR + desc.getFilename())) {
// Load the music file in background to avoid
// blocking the UI
loadTask();
return;
}
EngineLogger.debug("RETRIEVING MUSIC: " + desc.getFilename());
music = EngineAssetManager.getInstance().getMusic(desc.getFilename());
if (isPlayingSer) {
playMusic();
if (music != null) {
music.setPosition(musicPosSer);
musicPosSer = 0f;
}
isPlayingSer = false;
}
}
}
public void fade(float volume, float duration, ActionCallback cb) {
if (music != null) {
volumeTween = new MusicVolumeTween();
volumeTween.start(this, volume, duration, InterpolationMode.FADE, cb);
} else if (cb != null) {
cb.resume();
}
}
@Override
public void write(Json json) {
json.writeValue("desc", desc);
json.writeValue("currentMusicDelay", currentMusicDelay);
json.writeValue("isPlaying", music != null && (music.isPlaying() || isPaused));
json.writeValue("musicPos", music != null && (music.isPlaying() || isPaused) ? music.getPosition() : 0f);
if (volumeTween != null)
json.writeValue("volumeTween", volumeTween);
}
@Override
public void read(Json json, JsonValue jsonData) {
desc = json.readValue("desc", MusicDesc.class, jsonData);
currentMusicDelay = json.readValue("currentMusicDelay", float.class, jsonData);
isPlayingSer = json.readValue("isPlaying", boolean.class, jsonData);
musicPosSer = json.readValue("musicPos", float.class, jsonData);
volumeTween = json.readValue("volumeTween", MusicVolumeTween.class, jsonData);
if (volumeTween != null) {
volumeTween.setTarget(this);
}
}
}
| blade-engine/src/com/bladecoder/engine/model/MusicManager.java | package com.bladecoder.engine.model;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.utils.Json;
import com.badlogic.gdx.utils.Json.Serializable;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
import com.bladecoder.engine.actions.ActionCallback;
import com.bladecoder.engine.anim.MusicVolumeTween;
import com.bladecoder.engine.assets.AssetConsumer;
import com.bladecoder.engine.assets.EngineAssetManager;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.engine.util.InterpolationMode;
/**
* Simple music engine.
*
* Plays a music file, if another music is playing, stops it before playing the
* new music.
*
* @author rgarcia
*/
public class MusicManager implements Serializable, AssetConsumer {
private MusicDesc desc = null;
private Music music = null;
private float currentMusicDelay = 0;
private boolean isPlayingSer = false;
private float musicPosSer = 0;
transient private boolean isPaused = false;
private MusicVolumeTween volumeTween;
// the global configurable by user volume
public static float VOLUME_MULTIPLIER = 1f;
private final Task backgroundLoadingTask = new Task() {
@Override
public void run() {
if (!EngineAssetManager.getInstance().isLoading()) {
cancel();
retrieveAssets();
}
}
};
public void playMusic() {
if (music != null && !music.isPlaying()) {
try {
music.play();
music.setLooping(desc.isLoop());
music.setVolume(desc.getVolume() * VOLUME_MULTIPLIER);
} catch (Exception e) {
// DEAL WITH OPENAL BUG
if (Gdx.app.getType() == ApplicationType.Desktop && e.getMessage().contains("40963")) {
EngineLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!ERROR playing music trying again...!!!!!!!!!!!!!!!");
setMusic(desc);
return;
}
EngineLogger.error("Error Playing music: " + desc.getFilename(), e);
}
}
}
public void pauseMusic() {
if (music != null && music.isPlaying()) {
music.pause();
isPaused = true;
}
}
public void resumeMusic() {
if (music != null && isPaused) {
music.play();
isPaused = false;
}
}
public void stopMusic() {
if (music != null)
music.stop();
}
public void setMusic(MusicDesc d) {
if (desc != null && d != null && d.getFilename() != null && d.getFilename().equals(desc.getFilename())) {
EngineLogger.debug(">>>NOT SETTING MUSIC: This music file is already playing.");
return;
}
EngineLogger.debug(">>>SETTING MUSIC.");
stopMusic();
volumeTween = null;
currentMusicDelay = 0;
if (d != null) {
if (desc != null) {
dispose();
}
desc = new MusicDesc(d);
// Load the music file in background to avoid
// blocking the UI
loadTask();
} else {
dispose();
desc = null;
}
}
private void loadTask() {
loadAssets();
backgroundLoadingTask.cancel();
Timer.schedule(backgroundLoadingTask, 0, 0);
}
public void setVolume(float volume) {
if (desc != null)
desc.setVolume(volume);
if (music != null && music.isPlaying())
music.setVolume(volume * VOLUME_MULTIPLIER);
}
public float getVolume() {
if (desc != null)
return desc.getVolume();
return 1f;
}
public void leaveScene(MusicDesc newMusicDesc) {
if (desc != null && !desc.isStopWhenLeaving()
&& (newMusicDesc == null || newMusicDesc.getFilename().equals(desc.getFilename())))
return;
if (desc != null) {
currentMusicDelay = 0f;
stopMusic();
dispose();
}
if (newMusicDesc != null) {
desc = new MusicDesc(newMusicDesc);
} else {
desc = null;
}
}
public void update(float delta) {
// music delay update
if (music != null) {
if (!music.isPlaying()) {
boolean initialTime = false;
if (currentMusicDelay <= desc.getInitialDelay())
initialTime = true;
currentMusicDelay += delta;
if (initialTime) {
if (currentMusicDelay > desc.getInitialDelay())
playMusic();
} else {
if (desc.getRepeatDelay() >= 0
&& currentMusicDelay > desc.getRepeatDelay() + desc.getInitialDelay()) {
currentMusicDelay = desc.getInitialDelay();
playMusic();
}
}
}
if (volumeTween != null) {
volumeTween.update(delta);
if (volumeTween != null && volumeTween.isComplete()) {
volumeTween = null;
}
}
}
}
@Override
public void dispose() {
if (music != null) {
EngineLogger.debug("DISPOSING MUSIC: " + desc.getFilename());
EngineAssetManager.getInstance().disposeMusic(desc.getFilename());
music = null;
desc = null;
volumeTween = null;
}
}
@Override
public void loadAssets() {
if (music == null && desc != null) {
EngineLogger.debug("LOADING MUSIC: " + desc.getFilename());
EngineAssetManager.getInstance().loadMusic(desc.getFilename());
}
}
@Override
public void retrieveAssets() {
if (music == null && desc != null) {
// Check if not loaded, this happens when setting a cached scene
if (!EngineAssetManager.getInstance().isLoaded(EngineAssetManager.MUSIC_DIR + desc.getFilename())) {
// Load the music file in background to avoid
// blocking the UI
loadTask();
return;
}
EngineLogger.debug("RETRIEVING MUSIC: " + desc.getFilename());
music = EngineAssetManager.getInstance().getMusic(desc.getFilename());
if (isPlayingSer) {
playMusic();
if (music != null) {
music.setPosition(musicPosSer);
musicPosSer = 0f;
}
isPlayingSer = false;
}
}
}
public void fade(float volume, float duration, ActionCallback cb) {
if (music != null) {
volumeTween = new MusicVolumeTween();
volumeTween.start(this, volume, duration, InterpolationMode.FADE, cb);
} else if (cb != null) {
cb.resume();
}
}
@Override
public void write(Json json) {
json.writeValue("desc", desc);
json.writeValue("currentMusicDelay", currentMusicDelay);
json.writeValue("isPlaying", music != null && (music.isPlaying() || isPaused));
json.writeValue("musicPos", music != null && (music.isPlaying() || isPaused) ? music.getPosition() : 0f);
if (volumeTween != null)
json.writeValue("volumeTween", volumeTween);
}
@Override
public void read(Json json, JsonValue jsonData) {
desc = json.readValue("desc", MusicDesc.class, jsonData);
currentMusicDelay = json.readValue("currentMusicDelay", float.class, jsonData);
isPlayingSer = json.readValue("isPlaying", boolean.class, jsonData);
musicPosSer = json.readValue("musicPos", float.class, jsonData);
volumeTween = json.readValue("volumeTween", MusicVolumeTween.class, jsonData);
if (volumeTween != null) {
volumeTween.setTarget(this);
}
}
}
| Better dealing with music OpenAL bug.
| blade-engine/src/com/bladecoder/engine/model/MusicManager.java | Better dealing with music OpenAL bug. | <ide><path>lade-engine/src/com/bladecoder/engine/model/MusicManager.java
<ide> // DEAL WITH OPENAL BUG
<ide> if (Gdx.app.getType() == ApplicationType.Desktop && e.getMessage().contains("40963")) {
<ide> EngineLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!ERROR playing music trying again...!!!!!!!!!!!!!!!");
<del> setMusic(desc);
<add>
<add> MusicDesc desc2 = desc;
<add> desc = null;
<add> setMusic(desc2);
<ide>
<ide> return;
<ide> } |
|
JavaScript | isc | 6159b663a7adb0ac47479911522702a0159e965a | 0 | evanx/chronica,evanx/chronica-active | // Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redex/LICENSE
import * as YamlAsserts from '../lib/YamlAsserts';
export default class HtmlMonitor {
constructor(config, logger, context) {
this.config = config;
this.logger = logger;
this.context = context;
this.init();
}
init() {
for (let name in this.config.services) {
this.logger.info('service', name);
let service = this.config.services[name];
service.name = 'html:' + name;
service.type = 'html';
assert(service.url, 'service.url');
assert(service.name, 'service.name');
if (!service.content) {
this.logger.warn('no content requirements', service.name);
}
if (!service.label) {
service.label = service.name;
}
this.context.stores.service.add(service);
}
}
async checkServices() {
for (const [name, service] of this.context.stores.service.services) {
if (service.type === 'html') {
await this.checkService(service);
}
}
}
checkContent(service, response, content) {
assert(!lodash.isEmpty(content), 'content');
assert(lodash.startsWith(response.headers['content-type'], 'text/html'), 'content type');
let contentLength = response.headers['content-length'];
if (!contentLength) {
this.logger.verbose('response.headers', service.name, Object.keys(response.headers).join(', '));
} else {
this.logger.verbose('content', service.name, contentLength, content.length);
if (false) {
assert.equal(parseInt(contentLength), content.toString().length, 'content length');
}
}
if (service.content) {
if (service.content.title) {
let titleMatcher = content.match(/<title>(.+)<\/title>/);
assert(titleMatcher && titleMatcher.length > 1, 'title');
let title = lodash.trim(titleMatcher[1]);
service.debug.title = title;
assert.equal(title, service.content.title, 'title');
} else {
this.logger.debug('checkService', service.name, content.length);
}
}
}
async checkService(service) {
try {
this.logger.verbose('checkService', service.name);
let options = {
url: service.url,
method: 'get',
timeout: this.config.timeout
};
service.debug.url = service.url;
if (service.headers) {
options.headers = service.headers;
service.debug['User-Agent'] = service.headers['User-Agent'];
this.logger.verbose('request', options);
}
let [response, content] = await Requests.response(options);
this.logger.verbose('response', service.name, response.statusCode, service.headers);
if (service.statusCode) {
service.debug.statusCode = response.statusCode;
assert.equal(response.statusCode, service.statusCode, 'statusCode: ' + service.statusCode);
} else {
assert.equal(response.statusCode, 200, 'statusCode');
}
if (response.statusCode === 200) {
this.checkContent(service, response, content);
}
await this.context.components.tracker.processStatus(service, 'OK');
} catch (err) {
service.debug.error = {
message: err.message,
time: new Date()
};
this.logger.verbose('checkService', service.name, err);
this.context.components.tracker.processStatus(service, 'WARN', err.message);
}
}
async pub() {
return { };
}
async start() {
this.logger.info('started');
}
async end() {
}
async scheduledTimeout() {
this.logger.verbose('scheduledTimeout');
await this.checkServices();
}
async scheduledInterval() {
this.logger.verbose('scheduledInterval');
await this.checkServices();
}
}
| components/HtmlMonitor.js | // Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redex/LICENSE
import * as YamlAsserts from '../lib/YamlAsserts';
export default class HtmlMonitor {
constructor(config, logger, context) {
this.config = config;
this.logger = logger;
this.context = context;
this.init();
}
init() {
for (let name in this.config.services) {
this.logger.info('service', name);
let service = this.config.services[name];
service.name = 'html:' + name;
service.type = 'html';
assert(service.url, 'service.url');
assert(service.name, 'service.name');
if (!service.content) {
this.logger.warn('no content requirements', service.name);
}
if (!service.label) {
service.label = service.name;
}
this.context.stores.service.add(service);
}
}
async checkServices() {
for (const [name, service] of this.context.stores.service.services) {
if (service.type === 'html') {
await this.checkService(service);
}
}
}
checkContent(service, response, content) {
assert(!lodash.isEmpty(content), 'content');
assert(lodash.startsWith(response.headers['content-type'], 'text/html'), 'content type');
let contentLength = response.headers['content-length'];
if (!contentLength) {
this.logger.verbose('response.headers', service.name, Object.keys(response.headers).join(', '));
} else {
this.logger.verbose('content', service.name, contentLength, content.length);
if (false) {
assert.equal(parseInt(contentLength), content.toString().length, 'content length');
}
}
if (service.content) {
if (service.content.title) {
let titleMatcher = content.match(/<title>(.+)<\/title>/);
assert(titleMatcher && titleMatcher.length > 1, 'title');
let title = lodash.trim(titleMatcher[1]);
service.debug.title = title;
assert.equal(title, service.content.title, 'title');
} else {
this.logger.debug('checkService', service.name, content.length);
}
}
}
async checkService(service) {
try {
this.logger.verbose('checkService', service.name);
let options = {
url: service.url,
method: 'get',
timeout: this.config.timeout
};
if (service.headers) {
options.headers = service.headers;
this.logger.verbose('request', options);
}
let [response, content] = await Requests.response(options);
this.logger.verbose('response', service.name, response.statusCode, service.headers);
if (service.statusCode) {
service.debug.statusCode = response.statusCode;
assert.equal(response.statusCode, service.statusCode, 'statusCode: ' + service.statusCode);
} else {
assert.equal(response.statusCode, 200, 'statusCode');
}
if (response.statusCode === 200) {
this.checkContent(service, response, content);
}
await this.context.components.tracker.processStatus(service, 'OK');
} catch (err) {
service.debug.error = {
message: err.message,
time: new Date()
};
this.logger.verbose('checkService', service.name, err);
this.context.components.tracker.processStatus(service, 'WARN', err.message);
}
}
async pub() {
return { };
}
async start() {
this.logger.info('started');
}
async end() {
}
async scheduledTimeout() {
this.logger.verbose('scheduledTimeout');
await this.checkServices();
}
async scheduledInterval() {
this.logger.verbose('scheduledInterval');
await this.checkServices();
}
}
| update commit script
| components/HtmlMonitor.js | update commit script | <ide><path>omponents/HtmlMonitor.js
<ide> method: 'get',
<ide> timeout: this.config.timeout
<ide> };
<add> service.debug.url = service.url;
<ide> if (service.headers) {
<ide> options.headers = service.headers;
<add> service.debug['User-Agent'] = service.headers['User-Agent'];
<ide> this.logger.verbose('request', options);
<ide> }
<ide> let [response, content] = await Requests.response(options); |
|
Java | apache-2.0 | 4e6c07049849221a1db03d79fe72df0fbe97b0f5 | 0 | EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci | package uk.ac.ebi.spot.goci.curation.controller;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import uk.ac.ebi.spot.goci.curation.component.EnsemblMappingPipeline;
import uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException;
import uk.ac.ebi.spot.goci.curation.model.AssociationFormErrorView;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn;
import uk.ac.ebi.spot.goci.curation.model.SnpFormRow;
import uk.ac.ebi.spot.goci.curation.service.AssociationBatchLoaderService;
import uk.ac.ebi.spot.goci.curation.service.AssociationDownloadService;
import uk.ac.ebi.spot.goci.curation.service.AssociationFormErrorViewService;
import uk.ac.ebi.spot.goci.curation.service.AssociationReportService;
import uk.ac.ebi.spot.goci.curation.service.AssociationViewService;
import uk.ac.ebi.spot.goci.curation.service.LociAttributesService;
import uk.ac.ebi.spot.goci.curation.service.SingleSnpMultiSnpAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpGenomicContextMappingService;
import uk.ac.ebi.spot.goci.curation.service.SnpInteractionAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpLocationMappingService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.AssociationReport;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.GenomicContext;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Locus;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationReportRepository;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.LocusRepository;
import uk.ac.ebi.spot.goci.repository.SingleNucleotidePolymorphismRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by emma on 06/01/15.
*
* @author emma
* <p>
* Association controller, interpret user input and transform it into a snp/association model that is
* represented to the user by the associated HTML page. Used to view, add and edit existing snp/assocaition
* information.
*/
@Controller
public class AssociationController {
// Repositories
private AssociationRepository associationRepository;
private StudyRepository studyRepository;
private EfoTraitRepository efoTraitRepository;
private LocusRepository locusRepository;
private SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository;
private AssociationReportRepository associationReportRepository;
// Services
private AssociationBatchLoaderService associationBatchLoaderService;
private AssociationDownloadService associationDownloadService;
private AssociationViewService associationViewService;
private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService;
private SnpInteractionAssociationService snpInteractionAssociationService;
private LociAttributesService lociAttributesService;
private AssociationFormErrorViewService associationFormErrorViewService;
private SnpLocationMappingService snpLocationMappingService;
private SnpGenomicContextMappingService snpGenomicContextMappingService;
private AssociationReportService associationReportService;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public AssociationController(AssociationRepository associationRepository,
StudyRepository studyRepository,
EfoTraitRepository efoTraitRepository,
LocusRepository locusRepository,
SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository,
AssociationReportRepository associationReportRepository,
AssociationBatchLoaderService associationBatchLoaderService,
AssociationDownloadService associationDownloadService,
AssociationViewService associationViewService,
SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService,
SnpInteractionAssociationService snpInteractionAssociationService,
LociAttributesService lociAttributesService,
AssociationFormErrorViewService associationFormErrorViewService,
SnpLocationMappingService snpLocationMappingService,
SnpGenomicContextMappingService snpGenomicContextMappingService,
AssociationReportService associationReportService) {
this.associationRepository = associationRepository;
this.studyRepository = studyRepository;
this.efoTraitRepository = efoTraitRepository;
this.locusRepository = locusRepository;
this.singleNucleotidePolymorphismRepository = singleNucleotidePolymorphismRepository;
this.associationReportRepository = associationReportRepository;
this.associationBatchLoaderService = associationBatchLoaderService;
this.associationDownloadService = associationDownloadService;
this.associationViewService = associationViewService;
this.singleSnpMultiSnpAssociationService = singleSnpMultiSnpAssociationService;
this.snpInteractionAssociationService = snpInteractionAssociationService;
this.lociAttributesService = lociAttributesService;
this.associationFormErrorViewService = associationFormErrorViewService;
this.snpLocationMappingService = snpLocationMappingService;
this.snpGenomicContextMappingService = snpGenomicContextMappingService;
this.associationReportService = associationReportService;
}
/* Study SNP/Associations */
// Generate list of SNP associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewStudySnps(Model model, @PathVariable Long studyId) {
// Get all associations for a study
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView =
associationViewService.createSnpAssociationTableView(association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortpvalue",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByPvalue(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByPvalueExponentAndMantissaAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId,
sortByPvalueExponentAndMantissaDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortrsid",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByRsid(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
// Sorting will not work for multi-snp haplotype or snp interactions so need to check for that
Boolean sortValues = true;
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
// Cannot sort multi field values
if (snpAssociationTableView.getMultiSnpHaplotype() != null) {
if (snpAssociationTableView.getMultiSnpHaplotype().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
if (snpAssociationTableView.getSnpInteraction() != null) {
if (snpAssociationTableView.getSnpInteraction().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
snpAssociationTableViews.add(snpAssociationTableView);
}
// Only return sorted results if its not a multi-snp haplotype or snp interaction
if (sortValues) {
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
else {
return "redirect:/studies/" + studyId + "/associations";
}
}
// Upload a spreadsheet of snp association information
@RequestMapping(value = "/studies/{studyId}/associations/upload",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String uploadStudySnps(@RequestParam("file") MultipartFile file, @PathVariable Long studyId, Model model) {
// Establish our study object
Study study = studyRepository.findOne(studyId);
if (!file.isEmpty()) {
// Save the uploaded file received in a multipart request as a file in the upload directory
// The default temporary-file directory is specified by the system property java.io.tmpdir.
String uploadDir =
System.getProperty("java.io.tmpdir") + File.separator + "gwas_batch_upload" + File.separator;
// Create file
File uploadedFile = new File(uploadDir + file.getOriginalFilename());
uploadedFile.getParentFile().mkdirs();
// Copy contents of multipart request to newly created file
try {
file.transferTo(uploadedFile);
}
catch (IOException e) {
throw new RuntimeException(
"Unable to to upload file ", e);
}
String uploadedFilePath = uploadedFile.getAbsolutePath();
// Set permissions
uploadedFile.setExecutable(true, false);
uploadedFile.setReadable(true, false);
uploadedFile.setWritable(true, false);
// Send file, including path, to SNP batch loader process
Collection<Association> newAssociations = new ArrayList<>();
try {
newAssociations = associationBatchLoaderService.processData(uploadedFilePath);
}
catch (InvalidOperationException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (InvalidFormatException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (IOException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (RuntimeException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "data_upload_problem";
}
// Create our associations
if (!newAssociations.isEmpty()) {
for (Association newAssociation : newAssociations) {
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
}
}
return "redirect:/studies/" + studyId + "/associations";
}
else {
// File is empty so let user know
model.addAttribute("study", studyRepository.findOne(studyId));
return "empty_snpfile_upload_warning";
}
}
// Generate a empty form page to add standard snp
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addStandardSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
// Add one row by default and set description
emptyForm.getSnpFormRows().add(new SnpFormRow());
emptyForm.setMultiSnpHaplotypeDescr("Single variant");
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_standard_snp_association";
}
// Generate a empty form page to add multi-snp haplotype
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addMultiSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
emptyForm.setMultiSnpHaplotype(true);
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Generate a empty form page to add a interaction association
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addSnpInteraction(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationInteractionForm emptyForm = new SnpAssociationInteractionForm();
model.addAttribute("snpAssociationInteractionForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRows"})
public String addRows(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows--;
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCols"})
public String addRows(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
Integer numberOfCols = snpAssociationInteractionForm.getNumOfInteractions();
// Add number of cols curator selected
while (numberOfCols != 0) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
numberOfCols--;
}
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add single row to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRow"})
public String addRow(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCol"})
public String addCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"removeRow"})
public String removeRow(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"removeCol"})
public String removeCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add new standard association/snp information to a study
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addStandardSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addMultiSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addSnpInteraction(@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
/* Existing association information */
// View association information
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewAssociation(Model model, @PathVariable Long associationId) {
// Return association with that ID
Association associationToView = associationRepository.findOne(associationId);
// Return any association errors
AssociationFormErrorView associationFormErrorView = associationFormErrorViewService.checkAssociationForErrors(
associationToView);
model.addAttribute("errors", associationFormErrorView);
// Establish study
Long studyId = associationToView.getStudy().getId();
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
if (associationToView.getSnpInteraction() != null && associationToView.getSnpInteraction()) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else if (associationToView.getMultiSnpHaplotype() != null && associationToView.getMultiSnpHaplotype()) {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
return "edit_multi_snp_association";
}
// If attributes haven't been set determine based on locus count and risk allele count
else {
Integer locusCount = associationToView.getLoci().size();
List<RiskAllele> riskAlleles = new ArrayList<>();
for (Locus locus : associationToView.getLoci()) {
for (RiskAllele riskAllele : locus.getStrongestRiskAlleles()) {
riskAlleles.add(riskAllele);
}
}
// Case where we have SNP interaction
if (locusCount > 1) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
// If editing multi-snp haplotype
if (riskAlleles.size() > 1) {
return "edit_multi_snp_association";
}
else {
return "edit_standard_snp_association";
}
}
}
}
//Edit existing association
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String editAssociation(@ModelAttribute SnpAssociationForm snpAssociationForm,
@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long associationId,
@RequestParam(value = "associationtype", required = true) String associationType) {
//Create association
Association editedAssociation = null;
// Request parameter determines how to process form and also which form to process
if (associationType.equalsIgnoreCase("interaction")) {
editedAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
}
else if (associationType.equalsIgnoreCase("standardormulti")) {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// default to standard view
else {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// Set ID of new association to the ID of the association we're currently editing
editedAssociation.setId(associationId);
// Set study to one currently linked to association
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
editedAssociation.setStudy(associationStudy);
// Save our association information
associationRepository.save(editedAssociation);
/*
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm != null) {
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
}
if (snpAssociationInteractionForm != null) {
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
}
*/
return "redirect:/associations/" + associationId;
}
// Add multiple rows to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRows"})
public String addRowsEditMode(SnpAssociationForm snpAssociationForm,
Model model,
@PathVariable Long associationId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows--;
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single row to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRow"})
public String addRowEditMode(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long associationId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/associations/{associationId}", params = {"addCol"})
public String addColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model, @PathVariable Long associationId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeRow"})
public String removeRowEditMode(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeCol"})
public String removeColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Delete all associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations/delete_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String deleteAllAssociations(Model model, @PathVariable Long studyId) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// For each association get the loci
Collection<Locus> loci = new ArrayList<Locus>();
for (Association association : studyAssociations) {
loci.addAll(association.getLoci());
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
// Delete checked SNP associations
@RequestMapping(value = "/studies/{studyId}/associations/delete_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> deleteChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
Collection<Locus> loci = new ArrayList<Locus>();
Collection<Association> studyAssociations = new ArrayList<Association>();
// For each association get the loci attached
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
loci.addAll(association.getLoci());
studyAssociations.add(association);
count++;
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
message = "Successfully deleted " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
// Approve a single SNP association
@RequestMapping(value = "associations/{associationId}/approve",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveSnpAssociation(@PathVariable Long associationId,
RedirectAttributes redirectAttributes) {
Association association = associationRepository.findOne(associationId);
AssociationReport associationReport = associationReportRepository.findByAssociationId(associationId);
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
String message = "Cannot approve a SNP association until errors are marked as checked";
redirectAttributes.addFlashAttribute("approvalStopped", message);
}
}
return "redirect:/studies/" + association.getStudy().getId() + "/associations";
}
// Approve checked SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> approveChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
Integer errorCount = 0;
// For each one set snpChecked attribute to true
for (String associationId : associationsIds) {
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
Association association = associationRepository.findOne(Long.valueOf(associationId));
AssociationReport associationReport =
associationReportRepository.findByAssociationId(Long.valueOf(associationId));
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
count++;
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
errorCount++;
}
}
}
if (errorCount > 0) {
message = "Successfully updated " + count + " association(s)." + errorCount +
" association(s) contains unchecked errors, these have not been approved";
}
else {
message = "Successfully updated " + count + " associations.";
}
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
// Approve all SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveAll(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
Integer errorCount = 0;
// For each one set snpChecked attribute to true
for (Association association : studyAssociations) {
AssociationReport associationReport = associationReportRepository.findByAssociationId(association.getId());
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
errorCount++;
}
}
}
if (errorCount > 0) {
String message = "Some SNP association(s) cannot be approved until errors are marked as checked";
redirectAttributes.addFlashAttribute("approvalStopped", message);
}
return "redirect:/studies/" + studyId + "/associations";
}
/**
* Run mapping pipeline on all SNPs in a study
*
* @param studyId Study ID in database
* @param redirectAttributes attributes for a redirect scenario
*/
@RequestMapping(value = "/studies/{studyId}/associations/validate_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String validateAll(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// For the study get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// Maps to store returned location data, this is used as
// snpLocationMappingService process all locations linked
// to a single snp in one go
Map<String, Set<Location>> snpToLocationsMap = new HashMap<>();
// Collection to store all genomic contexts
Collection<GenomicContext> allGenomicContexts = new ArrayList<>();
// For each association get the loci
for (Association studyAssociation : studyAssociations) {
// Collection to store all errors for one association
Collection<String> associationPipelineErrors = new ArrayList<>();
Collection<Locus> studyAssociationLoci = studyAssociation.getLoci();
// For each loci get the get the SNP and author reported genes
for (Locus associationLocus : studyAssociationLoci) {
Long locusId = associationLocus.getId();
Collection<SingleNucleotidePolymorphism> snpsLinkedToLocus =
singleNucleotidePolymorphismRepository.findByRiskAllelesLociId(locusId);
Collection<Gene> authorReportedGenesLinkedToSnp = associationLocus.getAuthorReportedGenes();
// Get gene names
Collection<String> authorReportedGeneNamesLinkedToSnp = new ArrayList<>();
for (Gene authorReportedGeneLinkedToSnp : authorReportedGenesLinkedToSnp) {
authorReportedGeneNamesLinkedToSnp.add(authorReportedGeneLinkedToSnp.getGeneName());
}
// Pass rs_id and author reported genes to mapping component
for (SingleNucleotidePolymorphism snpLinkedToLocus : snpsLinkedToLocus) {
String snpRsId = snpLinkedToLocus.getRsId();
EnsemblMappingPipeline ensemblMappingPipeline =
new EnsemblMappingPipeline(snpRsId, authorReportedGeneNamesLinkedToSnp);
ensemblMappingPipeline.run_pipeline();
Collection<Location> locations = ensemblMappingPipeline.getLocations();
Collection<GenomicContext> snpGenomicContexts = ensemblMappingPipeline.getGenomicContexts();
ArrayList<String> pipelineErrors = ensemblMappingPipeline.getPipelineErrors();
// Store location information for SNP
if (!locations.isEmpty()) {
for (Location location : locations) {
// Next time we see SNP, add location to set
// This would only occur is SNP has multiple locations
if (snpToLocationsMap.containsKey(snpRsId)) {
snpToLocationsMap.get(snpRsId).add(location);
}
// First time we see a SNP store the location
else {
Set<Location> snpLocation = new HashSet<>();
snpLocation.add(location);
snpToLocationsMap.put(snpRsId, snpLocation);
}
}
}
// Store genomic context data for snp
if (!snpGenomicContexts.isEmpty()) {
allGenomicContexts.addAll(snpGenomicContexts);
}
if (!pipelineErrors.isEmpty()) {
associationPipelineErrors.addAll(pipelineErrors);
}
}
}
// Create association report based on whether there is errors or not
if (!associationPipelineErrors.isEmpty()) {
associationReportService.processAssociationErrors(studyAssociation, associationPipelineErrors);
}
else {
associationReportService.updateAssociationReportDetails(studyAssociation);
}
}
// Save data
if (!snpToLocationsMap.isEmpty()) {
getLog().info("Adding/updating location details for SNPs" + snpToLocationsMap.keySet().toString() +
", in study " + studyId);
snpLocationMappingService.storeSnpLocation(snpToLocationsMap);
}
if (!allGenomicContexts.isEmpty()) {
getLog().info(
"Adding/updating genomic context for SNPs" + snpToLocationsMap.keySet().toString() + ", in study " +
studyId);
snpGenomicContextMappingService.processGenomicContext(allGenomicContexts);
}
String message = "Mapping complete, please check for any errors displayed in the 'Errors' column";
redirectAttributes.addFlashAttribute("mappingComplete", message);
return "redirect:/studies/" + studyId + "/associations";
}
/**
* Mark errors for a particular association as checked, this involves updating the linked association report
*
* @param associationsIds List of association IDs to mark as errors checked
*/
@RequestMapping(value = "/studies/{studyId}/associations/errors_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> associationErrorsChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
// For each one set snpChecked attribute to true
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
AssociationReport associationReport = association.getAssociationReport();
associationReport.setErrorCheckedByCurator(true);
associationReportRepository.save(associationReport);
count++;
}
message = "Successfully updated " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
@RequestMapping(value = "/studies/{studyId}/associations/download",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String downloadStudySnps(HttpServletResponse response, Model model, @PathVariable Long studyId)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
if (associations.size() == 0) {
model.addAttribute("study", study);
return "no_association_download_warning";
}
else {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String now = dateFormat.format(date);
String fileName =
study.getAuthor().concat("-").concat(study.getPubmedId()).concat("-").concat(now).concat(".tsv");
response.setContentType("text/tsv");
response.setHeader("Content-Disposition", "attachement; filename=" + fileName);
associationDownloadService.createDownloadFile(response.getOutputStream(), associations);
return "redirect:/studies/" + studyId + "/associations";
}
}
@RequestMapping(value = "/studies/{studyId}/associations/applyefotraits",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String applyStudyEFOtraitToSnps(Model model, @PathVariable Long studyId,
@RequestParam(value = "e",
required = false,
defaultValue = "false") boolean existing,
@RequestParam(value = "o",
required = false,
defaultValue = "true") boolean overwrite)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
Collection<EfoTrait> efoTraits = study.getEfoTraits();
if (associations.size() == 0 || efoTraits.size() == 0) {
model.addAttribute("study", study);
return "no_association_efo_trait_warning";
}
else {
if (!existing) {
for (Association association : associations) {
if (association.getEfoTraits().size() != 0) {
model.addAttribute("study", study);
return "existing_efo_traits_warning";
}
}
}
Collection<EfoTrait> associationTraits = new ArrayList<EfoTrait>();
for (EfoTrait efoTrait : efoTraits) {
associationTraits.add(efoTrait);
}
for (Association association : associations) {
if (association.getEfoTraits().size() != 0 && !overwrite) {
for (EfoTrait trait : associationTraits) {
if (!association.getEfoTraits().contains(trait)) {
association.addEfoTrait(trait);
}
}
}
else {
association.setEfoTraits(associationTraits);
}
associationRepository.save(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
}
/* Exception handling */
@ExceptionHandler(DataIntegrityException.class)
public String handleDataIntegrityException(DataIntegrityException dataIntegrityException, Model model) {
return dataIntegrityException.getMessage();
}
// @ExceptionHandler(InvalidFormatException.class)
// public String handleInvalidFormatException(InvalidFormatException invalidFormatException, Model model, Study study){
// getLog().error("Invalid format exception", invalidFormatException);
// model.addAttribute("study", study);
// return "wrong_file_format_warning";
//
// }
//
// @ExceptionHandler(InvalidOperationException.class)
// public String handleInvalidOperationException(InvalidOperationException invalidOperationException){
// getLog().error("Invalid operation exception", invalidOperationException);
//// model.addAttribute("study", study);
// System.out.println("Caught the exception but couldn't quite handle it");
// return "wrong_file_format_warning";
//
// }
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEfoTraits() {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Sort options
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
private Sort sortByPvalueExponentAndMantissaAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "pvalueExponent"),
new Sort.Order(Sort.Direction.ASC, "pvalueMantissa"));
}
private Sort sortByPvalueExponentAndMantissaDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "pvalueExponent"),
new Sort.Order(Sort.Direction.DESC, "pvalueMantissa"));
}
private Sort sortByRsidAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "loci.strongestRiskAlleles.snp.rsId"));
}
private Sort sortByRsidDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "loci.strongestRiskAlleles.snp.rsId"));
}
/**
* Review association report for common error types
*
* @param associationReport Association report to review for errors
*/
private Boolean checkForAssociationErrors(AssociationReport associationReport) {
Boolean errorFound = false;
if (associationReport != null) {
if (associationReport.getSnpError() != null && !associationReport.getSnpError().isEmpty()) {
errorFound = true;
}
if (associationReport.getGeneNotOnGenome() != null &&
!associationReport.getGeneNotOnGenome().isEmpty()) {
errorFound = true;
}
if (associationReport.getSnpGeneOnDiffChr() != null &&
!associationReport.getSnpGeneOnDiffChr().isEmpty()) {
errorFound = true;
}
if (associationReport.getNoGeneForSymbol() != null &&
!associationReport.getNoGeneForSymbol().isEmpty()) {
errorFound = true;
}
}
return errorFound;
}
}
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/AssociationController.java | package uk.ac.ebi.spot.goci.curation.controller;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.InvalidOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import uk.ac.ebi.spot.goci.curation.component.EnsemblMappingPipeline;
import uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException;
import uk.ac.ebi.spot.goci.curation.model.AssociationFormErrorView;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.curation.model.SnpFormColumn;
import uk.ac.ebi.spot.goci.curation.model.SnpFormRow;
import uk.ac.ebi.spot.goci.curation.service.AssociationBatchLoaderService;
import uk.ac.ebi.spot.goci.curation.service.AssociationDownloadService;
import uk.ac.ebi.spot.goci.curation.service.AssociationFormErrorViewService;
import uk.ac.ebi.spot.goci.curation.service.AssociationReportService;
import uk.ac.ebi.spot.goci.curation.service.AssociationViewService;
import uk.ac.ebi.spot.goci.curation.service.LociAttributesService;
import uk.ac.ebi.spot.goci.curation.service.SingleSnpMultiSnpAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpGenomicContextMappingService;
import uk.ac.ebi.spot.goci.curation.service.SnpInteractionAssociationService;
import uk.ac.ebi.spot.goci.curation.service.SnpLocationMappingService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.AssociationReport;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Gene;
import uk.ac.ebi.spot.goci.model.GenomicContext;
import uk.ac.ebi.spot.goci.model.Location;
import uk.ac.ebi.spot.goci.model.Locus;
import uk.ac.ebi.spot.goci.model.RiskAllele;
import uk.ac.ebi.spot.goci.model.SingleNucleotidePolymorphism;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationReportRepository;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.LocusRepository;
import uk.ac.ebi.spot.goci.repository.SingleNucleotidePolymorphismRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by emma on 06/01/15.
*
* @author emma
* <p>
* Association controller, interpret user input and transform it into a snp/association model that is
* represented to the user by the associated HTML page. Used to view, add and edit existing snp/assocaition
* information.
*/
@Controller
public class AssociationController {
// Repositories
private AssociationRepository associationRepository;
private StudyRepository studyRepository;
private EfoTraitRepository efoTraitRepository;
private LocusRepository locusRepository;
private SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository;
private AssociationReportRepository associationReportRepository;
// Services
private AssociationBatchLoaderService associationBatchLoaderService;
private AssociationDownloadService associationDownloadService;
private AssociationViewService associationViewService;
private SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService;
private SnpInteractionAssociationService snpInteractionAssociationService;
private LociAttributesService lociAttributesService;
private AssociationFormErrorViewService associationFormErrorViewService;
private SnpLocationMappingService snpLocationMappingService;
private SnpGenomicContextMappingService snpGenomicContextMappingService;
private AssociationReportService associationReportService;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public AssociationController(AssociationRepository associationRepository,
StudyRepository studyRepository,
EfoTraitRepository efoTraitRepository,
LocusRepository locusRepository,
SingleNucleotidePolymorphismRepository singleNucleotidePolymorphismRepository,
AssociationReportRepository associationReportRepository,
AssociationBatchLoaderService associationBatchLoaderService,
AssociationDownloadService associationDownloadService,
AssociationViewService associationViewService,
SingleSnpMultiSnpAssociationService singleSnpMultiSnpAssociationService,
SnpInteractionAssociationService snpInteractionAssociationService,
LociAttributesService lociAttributesService,
AssociationFormErrorViewService associationFormErrorViewService,
SnpLocationMappingService snpLocationMappingService,
SnpGenomicContextMappingService snpGenomicContextMappingService,
AssociationReportService associationReportService) {
this.associationRepository = associationRepository;
this.studyRepository = studyRepository;
this.efoTraitRepository = efoTraitRepository;
this.locusRepository = locusRepository;
this.singleNucleotidePolymorphismRepository = singleNucleotidePolymorphismRepository;
this.associationReportRepository = associationReportRepository;
this.associationBatchLoaderService = associationBatchLoaderService;
this.associationDownloadService = associationDownloadService;
this.associationViewService = associationViewService;
this.singleSnpMultiSnpAssociationService = singleSnpMultiSnpAssociationService;
this.snpInteractionAssociationService = snpInteractionAssociationService;
this.lociAttributesService = lociAttributesService;
this.associationFormErrorViewService = associationFormErrorViewService;
this.snpLocationMappingService = snpLocationMappingService;
this.snpGenomicContextMappingService = snpGenomicContextMappingService;
this.associationReportService = associationReportService;
}
/* Study SNP/Associations */
// Generate list of SNP associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewStudySnps(Model model, @PathVariable Long studyId) {
// Get all associations for a study
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView =
associationViewService.createSnpAssociationTableView(association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortpvalue",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByPvalue(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByPvalueExponentAndMantissaAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId,
sortByPvalueExponentAndMantissaDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
snpAssociationTableViews.add(snpAssociationTableView);
}
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
@RequestMapping(value = "/studies/{studyId}/associations/sortrsid",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String sortStudySnpsByRsid(Model model,
@PathVariable Long studyId,
@RequestParam(required = true) String direction) {
// Get all associations for a study and perform relevant sorting
Collection<Association> associations = new ArrayList<>();
// Sorting will not work for multi-snp haplotype or snp interactions so need to check for that
Boolean sortValues = true;
switch (direction) {
case "asc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidAsc()));
break;
case "desc":
associations.addAll(associationRepository.findByStudyId(studyId, sortByRsidDesc()));
break;
default:
associations.addAll(associationRepository.findByStudyId(studyId));
break;
}
// For our associations create a table view object and return
Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
for (Association association : associations) {
SnpAssociationTableView snpAssociationTableView = associationViewService.createSnpAssociationTableView(
association);
// Cannot sort multi field values
if (snpAssociationTableView.getMultiSnpHaplotype() != null) {
if (snpAssociationTableView.getMultiSnpHaplotype().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
if (snpAssociationTableView.getSnpInteraction() != null) {
if (snpAssociationTableView.getSnpInteraction().equalsIgnoreCase("Yes")) {
sortValues = false;
}
}
snpAssociationTableViews.add(snpAssociationTableView);
}
// Only return sorted results if its not a multi-snp haplotype or snp interaction
if (sortValues) {
model.addAttribute("snpAssociationTableViews", snpAssociationTableViews);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "study_association";
}
else {
return "redirect:/studies/" + studyId + "/associations";
}
}
// Upload a spreadsheet of snp association information
@RequestMapping(value = "/studies/{studyId}/associations/upload",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String uploadStudySnps(@RequestParam("file") MultipartFile file, @PathVariable Long studyId, Model model) {
// Establish our study object
Study study = studyRepository.findOne(studyId);
if (!file.isEmpty()) {
// Save the uploaded file received in a multipart request as a file in the upload directory
// The default temporary-file directory is specified by the system property java.io.tmpdir.
String uploadDir =
System.getProperty("java.io.tmpdir") + File.separator + "gwas_batch_upload" + File.separator;
// Create file
File uploadedFile = new File(uploadDir + file.getOriginalFilename());
uploadedFile.getParentFile().mkdirs();
// Copy contents of multipart request to newly created file
try {
file.transferTo(uploadedFile);
}
catch (IOException e) {
throw new RuntimeException(
"Unable to to upload file ", e);
}
String uploadedFilePath = uploadedFile.getAbsolutePath();
// Set permissions
uploadedFile.setExecutable(true, false);
uploadedFile.setReadable(true, false);
uploadedFile.setWritable(true, false);
// Send file, including path, to SNP batch loader process
Collection<Association> newAssociations = new ArrayList<>();
try {
newAssociations = associationBatchLoaderService.processData(uploadedFilePath);
}
catch (InvalidOperationException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (InvalidFormatException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (IOException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "wrong_file_format_warning";
}
catch (RuntimeException e) {
e.printStackTrace();
model.addAttribute("study", studyRepository.findOne(studyId));
return "data_upload_problem";
}
// Create our associations
if (!newAssociations.isEmpty()) {
for (Association newAssociation : newAssociations) {
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
}
}
return "redirect:/studies/" + studyId + "/associations";
}
else {
// File is empty so let user know
model.addAttribute("study", studyRepository.findOne(studyId));
return "empty_snpfile_upload_warning";
}
}
// Generate a empty form page to add standard snp
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addStandardSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
// Add one row by default and set description
emptyForm.getSnpFormRows().add(new SnpFormRow());
emptyForm.setMultiSnpHaplotypeDescr("Single variant");
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_standard_snp_association";
}
// Generate a empty form page to add multi-snp haplotype
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addMultiSnps(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationForm emptyForm = new SnpAssociationForm();
emptyForm.setMultiSnpHaplotype(true);
model.addAttribute("snpAssociationForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Generate a empty form page to add a interaction association
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String addSnpInteraction(Model model, @PathVariable Long studyId) {
// Return form object
SnpAssociationInteractionForm emptyForm = new SnpAssociationInteractionForm();
model.addAttribute("snpAssociationInteractionForm", emptyForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRows"})
public String addRows(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows--;
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add multiple rows to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCols"})
public String addRows(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
Integer numberOfCols = snpAssociationInteractionForm.getNumOfInteractions();
// Add number of cols curator selected
while (numberOfCols != 0) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
numberOfCols--;
}
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add single row to table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"addRow"})
public String addRow(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long studyId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"addCol"})
public String addCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model,
@PathVariable Long studyId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/studies/{studyId}/associations/add_multi", params = {"removeRow"})
public String removeRow(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", params = {"removeCol"})
public String removeCol(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long studyId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
return "add_snp_interaction_association";
}
// Add new standard association/snp information to a study
@RequestMapping(value = "/studies/{studyId}/associations/add_standard",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addStandardSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_multi",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addMultiSnps(@ModelAttribute SnpAssociationForm snpAssociationForm, @PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
@RequestMapping(value = "/studies/{studyId}/associations/add_interaction",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String addSnpInteraction(@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long studyId) {
// Get our study object
Study study = studyRepository.findOne(studyId);
// Create an association object from details in returned form
Association newAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
// Set the study ID for our association
newAssociation.setStudy(study);
// Save our association information
associationRepository.save(newAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
return "redirect:/associations/" + newAssociation.getId();
}
/* Existing association information */
// View association information
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String viewAssociation(Model model, @PathVariable Long associationId) {
// Return association with that ID
Association associationToView = associationRepository.findOne(associationId);
// Return any association errors
AssociationFormErrorView associationFormErrorView = associationFormErrorViewService.checkAssociationForErrors(
associationToView);
model.addAttribute("errors", associationFormErrorView);
// Establish study
Long studyId = associationToView.getStudy().getId();
// Also passes back study object to view so we can create links back to main study page
model.addAttribute("study", studyRepository.findOne(studyId));
if (associationToView.getSnpInteraction() != null && associationToView.getSnpInteraction()) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else if (associationToView.getMultiSnpHaplotype() != null && associationToView.getMultiSnpHaplotype()) {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
return "edit_multi_snp_association";
}
// If attributes haven't been set determine based on locus count and risk allele count
else {
Integer locusCount = associationToView.getLoci().size();
List<RiskAllele> riskAlleles = new ArrayList<>();
for (Locus locus : associationToView.getLoci()) {
for (RiskAllele riskAllele : locus.getStrongestRiskAlleles()) {
riskAlleles.add(riskAllele);
}
}
// Case where we have SNP interaction
if (locusCount > 1) {
SnpAssociationInteractionForm snpAssociationInteractionForm =
snpInteractionAssociationService.createSnpAssociationInteractionForm(associationToView);
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
return "edit_snp_interaction_association";
}
else {
// Create form and return to user
SnpAssociationForm snpAssociationForm = singleSnpMultiSnpAssociationService.createSnpAssociationForm(
associationToView);
model.addAttribute("snpAssociationForm", snpAssociationForm);
// If editing multi-snp haplotype
if (riskAlleles.size() > 1) {
return "edit_multi_snp_association";
}
else {
return "edit_standard_snp_association";
}
}
}
}
//Edit existing association
@RequestMapping(value = "/associations/{associationId}",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String editAssociation(@ModelAttribute SnpAssociationForm snpAssociationForm,
@ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm,
@PathVariable Long associationId,
@RequestParam(value = "associationtype", required = true) String associationType) {
//Create association
Association editedAssociation = null;
// Request parameter determines how to process form and also which form to process
if (associationType.equalsIgnoreCase("interaction")) {
editedAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
}
else if (associationType.equalsIgnoreCase("standardormulti")) {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// default to standard view
else {
editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationForm);
}
// Set ID of new association to the ID of the association we're currently editing
editedAssociation.setId(associationId);
// Set study to one currently linked to association
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
editedAssociation.setStudy(associationStudy);
// Save our association information
associationRepository.save(editedAssociation);
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationForm != null) {
if (snpAssociationForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationForm.getGenomicContexts());
}
}
if (snpAssociationInteractionForm != null) {
// Store mapped location data, do this after the SNP objects have been created
if (snpAssociationInteractionForm.getSnpMappingForms().size() > 0) {
snpLocationMappingService.processMappingForms(snpAssociationInteractionForm.getSnpMappingForms());
}
// Store genomic context information associated with curator entered RS_IDs
if (snpAssociationInteractionForm.getGenomicContexts().size() > 0) {
snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
}
}
return "redirect:/associations/" + associationId;
}
// Add multiple rows to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRows"})
public String addRowsEditMode(SnpAssociationForm snpAssociationForm,
Model model,
@PathVariable Long associationId) {
Integer numberOfRows = snpAssociationForm.getMultiSnpHaplotypeNum();
// Add number of rows curator selected
while (numberOfRows != 0) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
numberOfRows--;
}
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single row to table
@RequestMapping(value = "/associations/{associationId}", params = {"addRow"})
public String addRowEditMode(SnpAssociationForm snpAssociationForm, Model model, @PathVariable Long associationId) {
snpAssociationForm.getSnpFormRows().add(new SnpFormRow());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Add single column to table
@RequestMapping(value = "/associations/{associationId}", params = {"addCol"})
public String addColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
Model model, @PathVariable Long associationId) {
snpAssociationInteractionForm.getSnpFormColumns().add(new SnpFormColumn());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Remove row from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeRow"})
public String removeRowEditMode(SnpAssociationForm snpAssociationForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
// Remove row
snpAssociationForm.getSnpFormRows().remove(rowId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationForm", snpAssociationForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_multi_snp_association";
}
// Remove column from table
@RequestMapping(value = "/associations/{associationId}", params = {"removeCol"})
public String removeColEditMode(SnpAssociationInteractionForm snpAssociationInteractionForm,
HttpServletRequest req,
Model model,
@PathVariable Long associationId) {
//Index of value to remove
final Integer colId = Integer.valueOf(req.getParameter("removeCol"));
// Remove col
snpAssociationInteractionForm.getSnpFormColumns().remove(colId.intValue());
// Pass back updated form
model.addAttribute("snpAssociationInteractionForm", snpAssociationInteractionForm);
// Also passes back study object to view so we can create links back to main study page
Association currentAssociation = associationRepository.findOne(associationId);
Study associationStudy = currentAssociation.getStudy();
Long studyId = associationStudy.getId();
model.addAttribute("study", studyRepository.findOne(studyId));
return "edit_snp_interaction_association";
}
// Delete all associations linked to a study
@RequestMapping(value = "/studies/{studyId}/associations/delete_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String deleteAllAssociations(Model model, @PathVariable Long studyId) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// For each association get the loci
Collection<Locus> loci = new ArrayList<Locus>();
for (Association association : studyAssociations) {
loci.addAll(association.getLoci());
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
// Delete checked SNP associations
@RequestMapping(value = "/studies/{studyId}/associations/delete_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> deleteChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
Collection<Locus> loci = new ArrayList<Locus>();
Collection<Association> studyAssociations = new ArrayList<Association>();
// For each association get the loci attached
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
loci.addAll(association.getLoci());
studyAssociations.add(association);
count++;
}
// Delete each locus and risk allele, which in turn deletes link to genes via author_reported_gene table,
// Snps are not deleted as they may be used in other associations
for (Locus locus : loci) {
Collection<RiskAllele> locusRiskAlleles = locus.getStrongestRiskAlleles();
locus.setStrongestRiskAlleles(new ArrayList<>());
for (RiskAllele riskAllele : locusRiskAlleles) {
lociAttributesService.deleteRiskAllele(riskAllele);
}
locusRepository.delete(locus);
}
// Delete associations
for (Association association : studyAssociations) {
associationRepository.delete(association);
}
message = "Successfully deleted " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
// Approve a single SNP association
@RequestMapping(value = "associations/{associationId}/approve",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveSnpAssociation(@PathVariable Long associationId,
RedirectAttributes redirectAttributes) {
Association association = associationRepository.findOne(associationId);
AssociationReport associationReport = associationReportRepository.findByAssociationId(associationId);
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
String message = "Cannot approve a SNP association until errors are marked as checked";
redirectAttributes.addFlashAttribute("approvalStopped", message);
}
}
return "redirect:/studies/" + association.getStudy().getId() + "/associations";
}
// Approve checked SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> approveChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
Integer errorCount = 0;
// For each one set snpChecked attribute to true
for (String associationId : associationsIds) {
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
Association association = associationRepository.findOne(Long.valueOf(associationId));
AssociationReport associationReport =
associationReportRepository.findByAssociationId(Long.valueOf(associationId));
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
count++;
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
errorCount++;
}
}
}
if (errorCount > 0) {
message = "Successfully updated " + count + " association(s)." + errorCount +
" association(s) contains unchecked errors, these have not been approved";
}
else {
message = "Successfully updated " + count + " associations.";
}
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
// Approve all SNPs
@RequestMapping(value = "/studies/{studyId}/associations/approve_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String approveAll(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// Get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
Integer errorCount = 0;
// For each one set snpChecked attribute to true
for (Association association : studyAssociations) {
AssociationReport associationReport = associationReportRepository.findByAssociationId(association.getId());
// Assume errors have been checked by a curator at this stage
Boolean errorsChecked = true;
Boolean errorsFound = false;
if (associationReport != null) {
errorsFound = checkForAssociationErrors(associationReport);
if (associationReport.getErrorCheckedByCurator() != null) {
errorsChecked = associationReport.getErrorCheckedByCurator();
}
}
// If no errors were recorded for this association
if (!errorsFound) {
// Set snpChecked attribute to true
association.setSnpApproved(true);
associationRepository.save(association);
}
else {
// Errors have not been checked by a curator
if (!errorsChecked) {
errorCount++;
}
}
}
if (errorCount > 0) {
String message = "Some SNP association(s) cannot be approved until errors are marked as checked";
redirectAttributes.addFlashAttribute("approvalStopped", message);
}
return "redirect:/studies/" + studyId + "/associations";
}
/**
* Run mapping pipeline on all SNPs in a study
*
* @param studyId Study ID in database
* @param redirectAttributes attributes for a redirect scenario
*/
@RequestMapping(value = "/studies/{studyId}/associations/validate_all",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String validateAll(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// For the study get all associations
Collection<Association> studyAssociations = associationRepository.findByStudyId(studyId);
// Maps to store returned location data, this is used as
// snpLocationMappingService process all locations linked
// to a single snp in one go
Map<String, Set<Location>> snpToLocationsMap = new HashMap<>();
// Collection to store all genomic contexts
Collection<GenomicContext> allGenomicContexts = new ArrayList<>();
// For each association get the loci
for (Association studyAssociation : studyAssociations) {
// Collection to store all errors for one association
Collection<String> associationPipelineErrors = new ArrayList<>();
Collection<Locus> studyAssociationLoci = studyAssociation.getLoci();
// For each loci get the get the SNP and author reported genes
for (Locus associationLocus : studyAssociationLoci) {
Long locusId = associationLocus.getId();
Collection<SingleNucleotidePolymorphism> snpsLinkedToLocus =
singleNucleotidePolymorphismRepository.findByRiskAllelesLociId(locusId);
Collection<Gene> authorReportedGenesLinkedToSnp = associationLocus.getAuthorReportedGenes();
// Get gene names
Collection<String> authorReportedGeneNamesLinkedToSnp = new ArrayList<>();
for (Gene authorReportedGeneLinkedToSnp : authorReportedGenesLinkedToSnp) {
authorReportedGeneNamesLinkedToSnp.add(authorReportedGeneLinkedToSnp.getGeneName());
}
// Pass rs_id and author reported genes to mapping component
for (SingleNucleotidePolymorphism snpLinkedToLocus : snpsLinkedToLocus) {
String snpRsId = snpLinkedToLocus.getRsId();
EnsemblMappingPipeline ensemblMappingPipeline =
new EnsemblMappingPipeline(snpRsId, authorReportedGeneNamesLinkedToSnp);
ensemblMappingPipeline.run_pipeline();
Collection<Location> locations = ensemblMappingPipeline.getLocations();
Collection<GenomicContext> snpGenomicContexts = ensemblMappingPipeline.getGenomicContexts();
ArrayList<String> pipelineErrors = ensemblMappingPipeline.getPipelineErrors();
// Store location information for SNP
if (!locations.isEmpty()) {
for (Location location : locations) {
// Next time we see SNP, add location to set
// This would only occur is SNP has multiple locations
if (snpToLocationsMap.containsKey(snpRsId)) {
snpToLocationsMap.get(snpRsId).add(location);
}
// First time we see a SNP store the location
else {
Set<Location> snpLocation = new HashSet<>();
snpLocation.add(location);
snpToLocationsMap.put(snpRsId, snpLocation);
}
}
}
// Store genomic context data for snp
if (!snpGenomicContexts.isEmpty()) {
allGenomicContexts.addAll(snpGenomicContexts);
}
if (!pipelineErrors.isEmpty()) {
associationPipelineErrors.addAll(pipelineErrors);
}
}
}
// Create association report based on whether there is errors or not
if (!associationPipelineErrors.isEmpty()) {
associationReportService.processAssociationErrors(studyAssociation, associationPipelineErrors);
}
else {
associationReportService.updateAssociationReportDetails(studyAssociation);
}
}
// Save data
if (!snpToLocationsMap.isEmpty()) {
getLog().info("Adding/updating location details for SNPs" + snpToLocationsMap.keySet().toString() +
", in study " + studyId);
snpLocationMappingService.storeSnpLocation(snpToLocationsMap);
}
if (!allGenomicContexts.isEmpty()) {
getLog().info(
"Adding/updating genomic context for SNPs" + snpToLocationsMap.keySet().toString() + ", in study " +
studyId);
snpGenomicContextMappingService.processGenomicContext(allGenomicContexts);
}
String message = "Mapping complete, please check for any errors displayed in the 'Errors' column";
redirectAttributes.addFlashAttribute("mappingComplete", message);
return "redirect:/studies/" + studyId + "/associations";
}
/**
* Mark errors for a particular association as checked, this involves updating the linked association report
*
* @param associationsIds List of association IDs to mark as errors checked
*/
@RequestMapping(value = "/studies/{studyId}/associations/errors_checked",
produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
public @ResponseBody
Map<String, String> associationErrorsChecked(@RequestParam(value = "associationIds[]") String[] associationsIds) {
String message = "";
Integer count = 0;
// For each one set snpChecked attribute to true
for (String associationId : associationsIds) {
Association association = associationRepository.findOne(Long.valueOf(associationId));
AssociationReport associationReport = association.getAssociationReport();
associationReport.setErrorCheckedByCurator(true);
associationReportRepository.save(associationReport);
count++;
}
message = "Successfully updated " + count + " associations";
Map<String, String> result = new HashMap<>();
result.put("message", message);
return result;
}
@RequestMapping(value = "/studies/{studyId}/associations/download",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String downloadStudySnps(HttpServletResponse response, Model model, @PathVariable Long studyId)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
if (associations.size() == 0) {
model.addAttribute("study", study);
return "no_association_download_warning";
}
else {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String now = dateFormat.format(date);
String fileName =
study.getAuthor().concat("-").concat(study.getPubmedId()).concat("-").concat(now).concat(".tsv");
response.setContentType("text/tsv");
response.setHeader("Content-Disposition", "attachement; filename=" + fileName);
associationDownloadService.createDownloadFile(response.getOutputStream(), associations);
return "redirect:/studies/" + studyId + "/associations";
}
}
@RequestMapping(value = "/studies/{studyId}/associations/applyefotraits",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.GET)
public String applyStudyEFOtraitToSnps(Model model, @PathVariable Long studyId,
@RequestParam(value = "e",
required = false,
defaultValue = "false") boolean existing,
@RequestParam(value = "o",
required = false,
defaultValue = "true") boolean overwrite)
throws IOException {
Collection<Association> associations = new ArrayList<>();
associations.addAll(associationRepository.findByStudyId(studyId));
Study study = studyRepository.findOne((studyId));
Collection<EfoTrait> efoTraits = study.getEfoTraits();
if (associations.size() == 0 || efoTraits.size() == 0) {
model.addAttribute("study", study);
return "no_association_efo_trait_warning";
}
else {
if (!existing) {
for (Association association : associations) {
if (association.getEfoTraits().size() != 0) {
model.addAttribute("study", study);
return "existing_efo_traits_warning";
}
}
}
Collection<EfoTrait> associationTraits = new ArrayList<EfoTrait>();
for (EfoTrait efoTrait : efoTraits) {
associationTraits.add(efoTrait);
}
for (Association association : associations) {
if (association.getEfoTraits().size() != 0 && !overwrite) {
for (EfoTrait trait : associationTraits) {
if (!association.getEfoTraits().contains(trait)) {
association.addEfoTrait(trait);
}
}
}
else {
association.setEfoTraits(associationTraits);
}
associationRepository.save(association);
}
return "redirect:/studies/" + studyId + "/associations";
}
}
/* Exception handling */
@ExceptionHandler(DataIntegrityException.class)
public String handleDataIntegrityException(DataIntegrityException dataIntegrityException, Model model) {
return dataIntegrityException.getMessage();
}
// @ExceptionHandler(InvalidFormatException.class)
// public String handleInvalidFormatException(InvalidFormatException invalidFormatException, Model model, Study study){
// getLog().error("Invalid format exception", invalidFormatException);
// model.addAttribute("study", study);
// return "wrong_file_format_warning";
//
// }
//
// @ExceptionHandler(InvalidOperationException.class)
// public String handleInvalidOperationException(InvalidOperationException invalidOperationException){
// getLog().error("Invalid operation exception", invalidOperationException);
//// model.addAttribute("study", study);
// System.out.println("Caught the exception but couldn't quite handle it");
// return "wrong_file_format_warning";
//
// }
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEfoTraits() {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Sort options
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
private Sort sortByPvalueExponentAndMantissaAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "pvalueExponent"),
new Sort.Order(Sort.Direction.ASC, "pvalueMantissa"));
}
private Sort sortByPvalueExponentAndMantissaDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "pvalueExponent"),
new Sort.Order(Sort.Direction.DESC, "pvalueMantissa"));
}
private Sort sortByRsidAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "loci.strongestRiskAlleles.snp.rsId"));
}
private Sort sortByRsidDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC, "loci.strongestRiskAlleles.snp.rsId"));
}
/**
* Review association report for common error types
*
* @param associationReport Association report to review for errors
*/
private Boolean checkForAssociationErrors(AssociationReport associationReport) {
Boolean errorFound = false;
if (associationReport != null) {
if (associationReport.getSnpError() != null && !associationReport.getSnpError().isEmpty()) {
errorFound = true;
}
if (associationReport.getGeneNotOnGenome() != null &&
!associationReport.getGeneNotOnGenome().isEmpty()) {
errorFound = true;
}
if (associationReport.getSnpGeneOnDiffChr() != null &&
!associationReport.getSnpGeneOnDiffChr().isEmpty()) {
errorFound = true;
}
if (associationReport.getNoGeneForSymbol() != null &&
!associationReport.getNoGeneForSymbol().isEmpty()) {
errorFound = true;
}
}
return errorFound;
}
}
| Commented out saving location data from webform until we have reviewed webform code
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/AssociationController.java | Commented out saving location data from webform until we have reviewed webform code | <ide><path>oci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/AssociationController.java
<ide> // Save our association information
<ide> associationRepository.save(editedAssociation);
<ide>
<add>/*
<ide> // Store mapped location data, do this after the SNP objects have been created
<ide> if (snpAssociationForm != null) {
<ide> if (snpAssociationForm.getSnpMappingForms().size() > 0) {
<ide> snpGenomicContextMappingService.processGenomicContext(snpAssociationInteractionForm.getGenomicContexts());
<ide> }
<ide> }
<add>*/
<ide>
<ide> return "redirect:/associations/" + associationId;
<ide> } |
|
Java | lgpl-2.1 | 158bbb9fbe65ad9822acf8a721c9dac42a3cbe50 | 0 | ebner/collaborilla,ebner/collaborilla | /* $Id$
*
* Copyright (c) 2006, KMR group at KTH (Royal Institute of Technology)
* Licensed under the GNU GPL. For full terms see the file LICENSE.
*/
package se.kth.nada.kmr.collaborilla.ldap;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import com.novell.ldap.util.Base64;
/**
* Provides methods to do basic conversions and manipulations of URI and LDAP
* Distinctive Name (DN) Strings.
* <p>
* All methods are also statically accessible.
*
* @author Hannes Ebner
* @version $Id$
*/
public class LDAPStringHelper {
private String uri;
private String serverDN;
private String entryMainID = "ou";
private String root = null;
/**
* Using Base64 requires JLDAP to be in the classpath. It is in the package
* com.novell.ldap.util.Base64.
*/
private static final int ENCODING_BASE64 = 1;
private static final int ENCODING_ESCAPE = 2;
private static final int ENCODING = ENCODING_ESCAPE;
/*
* Constructors
*/
/**
* Initializes the object with the Distinctive Name (DN) of the LDAP server
* connection and the URI which should be converted.
*
* @param serverDN
* Distinctive Name (DN) of the server connection
* @param uri
* URI
*/
public LDAPStringHelper(String serverDN, String uri) {
this.serverDN = serverDN;
this.uri = uri;
}
/**
* Initializes the object with the Distinctive Name (DN) of the LDAP server
* connection, the URI which should be converted and the ID of the leaf
* entry.
*
* @param serverDN
* Distinctive Name (DN) of the server connection
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
*/
public LDAPStringHelper(String root, String serverDN, String uri, String entryMainID) {
this(serverDN, uri);
this.entryMainID = entryMainID;
this.root = root;
}
/*
* Setters for the private variables
*/
/**
* Sets the URI.
*
* @param uri
* URI
*/
public void setUri(String uri) {
this.uri = uri;
}
/**
* Sets the Server Distinctive Name (DN).
*
* @param serverDN
* Server Distinctive Name (DN). Example: "dc=test,dc=com"
*/
public void setServerDN(String serverDN) {
this.serverDN = serverDN;
}
/*
* Getters for the private variables
*/
/**
* Returns the current URI.
*
* @return URI
*/
public String getUri() {
return this.uri;
}
/**
* Returns the current server Distinctive Name (DN).
*
* @return Server Distinctive Name (DN)
*/
public String getServerDN() {
return this.serverDN;
}
/**
* Returns the Distinctive Name (DN) of the parent entry of the current URI.
*
* @return DN of the parent entry
*/
public String getParentDN() {
return dnToParentDN(this.getBaseDN());
}
/**
* Returns the Distinctive Name (DN) of the parent entry.
*
* @param dn
* DN of which the parent DN is demanded
* @return DN of the parent entry
*/
public static String dnToParentDN(String dn) {
return dn.substring(dn.indexOf(",") + 1);
}
/**
* Converts a URI to a Distinctive Name (DN) and returns the parent DN.
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Parent Distinctive Name (DN)
*/
public static String uriToParentDN(String root, String serverDN, String uri, String entryMainID) {
return dnToParentDN(uriToBaseDN(root, serverDN, uri, entryMainID));
}
/**
* Get the ID of the LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @return Relative DN of the LDAP entry
*/
public String getEntryID() {
return dnToEntryID(this.getBaseDN());
}
/**
* Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @param dn
* Full Distinctive Name (DN)
* @return Relative Distinctive Name (DN)
*/
public static String dnToEntryID(String dn) {
return dn.substring(dn.indexOf("=") + 1, dn.indexOf(","));
}
/**
* Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Relative Distinctive Name (DN)
*/
public static String uriToEntryID(String root, String serverDN, String uri, String entryMainID) {
return dnToEntryID(uriToBaseDN(root, serverDN, uri, entryMainID));
}
/*
* URI helpers
*/
/**
* Constructs the parent out of a given URI.
*
* @param uri
* A valid URI.
* @return Returns a parent URI to the given one. Returns null if the URI is
* toplevel already, or if the URI is invalid.
*/
public static String getParentURI(String uri) {
String tmp = uri;
// Perform a check whether this URI is valid: we convert it to a Java
// URI and check for an exception.
try {
new URI(uri);
} catch (URISyntaxException e) {
// throw new IllegalArgumentException("Given parameter is not a
// valid URI.");
// We just return null for now
return null;
}
if (tmp.endsWith("/")) {
tmp = tmp.substring(0, tmp.length() - 2);
}
if (tmp.indexOf("/") == tmp.lastIndexOf("/")) {
return null;
}
tmp = tmp.substring(0, tmp.lastIndexOf("/"));
return tmp;
}
/*
* URI -> DN conversion
*/
/**
* Returns a Distinctive Name (DN).
*
* @return Base Distinctive Name (DN)
*/
public String getBaseDN() {
return this.uriToBaseDN();
}
/**
* Converts a URI to a Distinctive Name (DN).
*
* @return Base Distinctive Name (DN)
*/
public String uriToBaseDN() {
return uriToBaseDN(this.root, this.serverDN, this.uri, this.entryMainID);
}
/**
* Converts a URI to a Distinctive Name (DN).
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uriIn
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Base Distinctive Name (DN)
*/
public static String uriToBaseDN(String root, String serverDN, String uriIn, String entryMainID) {
String checkSep1 = "://";
String checkSep2 = ":/";
String sep = checkSep2;
String uri = null;
int pos = -1;
if (uriIn.indexOf("/") == -1) {
return null;
}
if (uriIn.indexOf(checkSep1) > -1) {
sep = checkSep1;
}
// workaround to avoid and IndexOutOfBoundsException
String uriToConvert = uriIn + "/";
if ((pos = uriToConvert.indexOf(sep)) > -1) {
/* construct a suitable uri out of a generic <type>:/[/]<path> */
/* get the type */
String type = uriToConvert.substring(0, pos);
/* get the path and the host */
uri = uriToConvert.substring(pos + sep.length());
String hostPart = uri.substring(0, uri.indexOf("/"));
uri = uri.substring(uri.indexOf("/"));
/* split the host into TLD, second level domain, subdomain, etc */
StringTokenizer stHostPart = new StringTokenizer(hostPart, ".");
while (stHostPart.hasMoreTokens()) {
uri = "d:" + stHostPart.nextToken() + "/" + uri;
}
/* construct the generic uri */
uri = "/_" + type + "/" + uri;
} else if (uriToConvert.startsWith("/")) {
/* we already get a "good" uri */
uri = "/_generic" + uriToConvert;
} else {
return null;
}
if ((root != null) && (root.length() > 0)) {
/* we prepend the root entry */
uri = "/" + root + uri;
}
/* finally we construct an LDAP Base DN */
String baseDN = new String();
StringTokenizer st = new StringTokenizer(uri, "/");
while (st.hasMoreTokens()) {
baseDN = entryMainID + "=" + st.nextToken() + "," + baseDN;
}
return baseDN += serverDN;
}
/*
* Other helpers
*/
/**
* Encodes a given String. The type of "encoding" is hard-wired in the
* header of this class.
*
* @param input
* String in normal representation.
* @return Encoded string.
*/
public static String encode(String input) {
if (input == null) {
return null;
}
switch (ENCODING) {
case ENCODING_BASE64:
String encodedString = Base64.encode(input.getBytes());
String escapedString = encodedString.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
return escapedString;
case ENCODING_ESCAPE:
return input.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
default:
return input;
}
}
/**
* Decodes a given String to the original representation. The type of
* "encoding" is hard-wired in the header of this class.
*
* @param input
* Encoded string.
* @return Decoded string.
*/
public static String decode(String input) {
if (input == null) {
return null;
}
switch (ENCODING) {
case ENCODING_BASE64:
String unescapedString = input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r");
String decodedString = new String(Base64.decode(unescapedString));
return decodedString;
case ENCODING_ESCAPE:
return input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r");
default:
return input;
}
}
/**
* Parses an X.208 formatted timestamp and creates a Date object.
*
* @param utcTimestamp
* X.208 formatted timestamp.
* @return Converted Date object.
*/
public static Date parseTimestamp(String utcTimestamp) {
Date date = null;
// Setup a generalized X.208 date/time formatter
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
try {
// parse UTC into Date
date = formatter.parse(utcTimestamp);
} catch (ParseException pe) {
}
return date;
}
}
| src/se/kth/nada/kmr/collaborilla/ldap/LDAPStringHelper.java | /* $Id$
*
* Copyright (c) 2006, KMR group at KTH (Royal Institute of Technology)
* Licensed under the GNU GPL. For full terms see the file LICENSE.
*/
package se.kth.nada.kmr.collaborilla.ldap;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import com.novell.ldap.util.Base64;
/**
* Provides methods to do basic conversions and manipulations of URI and LDAP
* Distinctive Name (DN) Strings.
* <p>
* All methods are also statically accessible.
*
* @author Hannes Ebner
* @version $Id$
*/
public class LDAPStringHelper {
private String uri;
private String serverDN;
private String entryMainID = "ou";
private String root = null;
private static final int ENCODING_BASE64 = 1;
private static final int ENCODING_ESCAPE = 2;
private static final int ENCODING = ENCODING_BASE64;
/*
* Constructors
*/
/**
* Initializes the object with the Distinctive Name (DN) of the LDAP server
* connection and the URI which should be converted.
*
* @param serverDN
* Distinctive Name (DN) of the server connection
* @param uri
* URI
*/
public LDAPStringHelper(String serverDN, String uri) {
this.serverDN = serverDN;
this.uri = uri;
}
/**
* Initializes the object with the Distinctive Name (DN) of the LDAP server
* connection, the URI which should be converted and the ID of the leaf
* entry.
*
* @param serverDN
* Distinctive Name (DN) of the server connection
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
*/
public LDAPStringHelper(String root, String serverDN, String uri, String entryMainID) {
this(serverDN, uri);
this.entryMainID = entryMainID;
this.root = root;
}
/*
* Setters for the private variables
*/
/**
* Sets the URI.
*
* @param uri
* URI
*/
public void setUri(String uri) {
this.uri = uri;
}
/**
* Sets the Server Distinctive Name (DN).
*
* @param serverDN
* Server Distinctive Name (DN). Example: "dc=test,dc=com"
*/
public void setServerDN(String serverDN) {
this.serverDN = serverDN;
}
/*
* Getters for the private variables
*/
/**
* Returns the current URI.
*
* @return URI
*/
public String getUri() {
return this.uri;
}
/**
* Returns the current server Distinctive Name (DN).
*
* @return Server Distinctive Name (DN)
*/
public String getServerDN() {
return this.serverDN;
}
/**
* Returns the Distinctive Name (DN) of the parent entry of the current URI.
*
* @return DN of the parent entry
*/
public String getParentDN() {
return dnToParentDN(this.getBaseDN());
}
/**
* Returns the Distinctive Name (DN) of the parent entry.
*
* @param dn
* DN of which the parent DN is demanded
* @return DN of the parent entry
*/
public static String dnToParentDN(String dn) {
return dn.substring(dn.indexOf(",") + 1);
}
/**
* Converts a URI to a Distinctive Name (DN) and returns the parent DN.
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Parent Distinctive Name (DN)
*/
public static String uriToParentDN(String root, String serverDN, String uri, String entryMainID) {
return dnToParentDN(uriToBaseDN(root, serverDN, uri, entryMainID));
}
/**
* Get the ID of the LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @return Relative DN of the LDAP entry
*/
public String getEntryID() {
return dnToEntryID(this.getBaseDN());
}
/**
* Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @param dn
* Full Distinctive Name (DN)
* @return Relative Distinctive Name (DN)
*/
public static String dnToEntryID(String dn) {
return dn.substring(dn.indexOf("=") + 1, dn.indexOf(","));
}
/**
* Get the ID of an LDAP Distinctive Name (DN) out of a URI or DN. Returns
* for example "test", and not "cn=test".
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uri
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Relative Distinctive Name (DN)
*/
public static String uriToEntryID(String root, String serverDN, String uri, String entryMainID) {
return dnToEntryID(uriToBaseDN(root, serverDN, uri, entryMainID));
}
/*
* URI helpers
*/
/**
* Constructs the parent out of a given URI.
*
* @param uri
* A valid URI.
* @return Returns a parent URI to the given one. Returns null if the URI is
* toplevel already, or if the URI is invalid.
*/
public static String getParentURI(String uri) {
String tmp = uri;
// Perform a check whether this URI is valid: we convert it to a Java
// URI and check for an exception.
try {
new URI(uri);
} catch (URISyntaxException e) {
// throw new IllegalArgumentException("Given parameter is not a
// valid URI.");
// We just return null for now
return null;
}
if (tmp.endsWith("/")) {
tmp = tmp.substring(0, tmp.length() - 2);
}
if (tmp.indexOf("/") == tmp.lastIndexOf("/")) {
return null;
}
tmp = tmp.substring(0, tmp.lastIndexOf("/"));
return tmp;
}
/*
* URI -> DN conversion
*/
/**
* Returns a Distinctive Name (DN).
*
* @return Base Distinctive Name (DN)
*/
public String getBaseDN() {
return this.uriToBaseDN();
}
/**
* Converts a URI to a Distinctive Name (DN).
*
* @return Base Distinctive Name (DN)
*/
public String uriToBaseDN() {
return uriToBaseDN(this.root, this.serverDN, this.uri, this.entryMainID);
}
/**
* Converts a URI to a Distinctive Name (DN).
*
* @param serverDN
* Server Distinctive Name (DN)
* @param uriIn
* URI
* @param entryMainID
* Identifier of the leaf entry. Example: "cn"
* @return Base Distinctive Name (DN)
*/
public static String uriToBaseDN(String root, String serverDN, String uriIn, String entryMainID) {
String checkSep1 = "://";
String checkSep2 = ":/";
String sep = checkSep2;
String uri = null;
int pos = -1;
if (uriIn.indexOf("/") == -1) {
return null;
}
if (uriIn.indexOf(checkSep1) > -1) {
sep = checkSep1;
}
// workaround to avoid and IndexOutOfBoundsException
String uriToConvert = uriIn + "/";
if ((pos = uriToConvert.indexOf(sep)) > -1) {
/* construct a suitable uri out of a generic <type>:/[/]<path> */
/* get the type */
String type = uriToConvert.substring(0, pos);
/* get the path and the host */
uri = uriToConvert.substring(pos + sep.length());
String hostPart = uri.substring(0, uri.indexOf("/"));
uri = uri.substring(uri.indexOf("/"));
/* split the host into TLD, second level domain, subdomain, etc */
StringTokenizer stHostPart = new StringTokenizer(hostPart, ".");
while (stHostPart.hasMoreTokens()) {
uri = "d:" + stHostPart.nextToken() + "/" + uri;
}
/* construct the generic uri */
uri = "/_" + type + "/" + uri;
} else if (uriToConvert.startsWith("/")) {
/* we already get a "good" uri */
uri = "/_generic" + uriToConvert;
} else {
return null;
}
if ((root != null) && (root.length() > 0)) {
/* we prepend the root entry */
uri = "/" + root + uri;
}
/* finally we construct an LDAP Base DN */
String baseDN = new String();
StringTokenizer st = new StringTokenizer(uri, "/");
while (st.hasMoreTokens()) {
baseDN = entryMainID + "=" + st.nextToken() + "," + baseDN;
}
return baseDN += serverDN;
}
/*
* Other helpers
*/
/**
* Encodes a given String. The type of "encoding" is hard-wired in the
* header of this class.
*
* @param input
* String in normal representation.
* @return Encoded string.
*/
public static String encode(String input) {
if (input == null) {
return null;
}
switch (ENCODING) {
case ENCODING_BASE64:
String encodedString = Base64.encode(input.getBytes());
String escapedString = encodedString.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
return escapedString;
case ENCODING_ESCAPE:
return input.replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r");
default:
return input;
}
}
/**
* Decodes a given String to the original representation. The type of
* "encoding" is hard-wired in the header of this class.
*
* @param input
* Encoded string.
* @return Decoded string.
*/
public static String decode(String input) {
if (input == null) {
return null;
}
switch (ENCODING) {
case ENCODING_BASE64:
String unescapedString = input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r");
String decodedString = new String(Base64.decode(unescapedString));
return decodedString;
case ENCODING_ESCAPE:
return input.replaceAll("\\\\n", "\n").replaceAll("\\\\r", "\r");
default:
return input;
}
}
/**
* Parses an X.208 formatted timestamp and creates a Date object.
*
* @param utcTimestamp
* X.208 formatted timestamp.
* @return Converted Date object.
*/
public static Date parseTimestamp(String utcTimestamp) {
Date date = null;
// Setup a generalized X.208 date/time formatter
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
try {
// parse UTC into Date
date = formatter.parse(utcTimestamp);
} catch (ParseException pe) {
}
return date;
}
}
| Deactivated Base64 again as it required com.novell.ldap.util.Base64 also on the client side. Right now we don't really want to deliver JLDAP as well. (Too many libs otherwise)
| src/se/kth/nada/kmr/collaborilla/ldap/LDAPStringHelper.java | Deactivated Base64 again as it required com.novell.ldap.util.Base64 also on the client side. Right now we don't really want to deliver JLDAP as well. (Too many libs otherwise) | <ide><path>rc/se/kth/nada/kmr/collaborilla/ldap/LDAPStringHelper.java
<ide>
<ide> private String root = null;
<ide>
<add> /**
<add> * Using Base64 requires JLDAP to be in the classpath. It is in the package
<add> * com.novell.ldap.util.Base64.
<add> */
<ide> private static final int ENCODING_BASE64 = 1;
<ide>
<ide> private static final int ENCODING_ESCAPE = 2;
<ide>
<del> private static final int ENCODING = ENCODING_BASE64;
<add> private static final int ENCODING = ENCODING_ESCAPE;
<ide>
<ide> /*
<ide> * Constructors |
|
Java | mit | 2a901d8f66a257802827ac845974909b941510c7 | 0 | curtbinder/AndroidStatus | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Curt Binder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package info.curtbinder.reefangel.phone;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import info.curtbinder.reefangel.controller.Controller;
import info.curtbinder.reefangel.db.StatusTable;
/**
* Created by binder on 7/26/14.
*/
public class PageDCPumpFragment extends Fragment
implements PageRefreshInterface, View.OnLongClickListener {
private static final String TAG = PageDCPumpFragment.class.getSimpleName();
private TextView[] dcpumpText = new TextView[Controller.MAX_DCPUMP_VALUES];
private short[] dcpumpValues = new short[Controller.MAX_DCPUMP_VALUES];
public static PageDCPumpFragment newInstance() {
return new PageDCPumpFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page_dcpump, container, false);
findViews(rootView);
return rootView;
}
private void findViews(View root) {
TableRow tr;
tr = (TableRow) root.findViewById(R.id.rowMode);
dcpumpText[0] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelMode);
tr = (TableRow) root.findViewById(R.id.rowSpeed);
dcpumpText[1] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelSpeed);
tr = (TableRow) root.findViewById(R.id.rowDuration);
dcpumpText[2] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelDuration);
tr = (TableRow) root.findViewById(R.id.rowThreshold);
dcpumpText[3] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelThreshold);
// for ( int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
// dcpumpText[i].setLongClickable(true);
// dcpumpText[i].setOnLongClickListener(this);
// }
}
private void setRowTitle(TableRow row, int labelId) {
((TextView) row.findViewById(R.id.rowTitle)).setText(labelId);
}
@Override
public void onResume() {
super.onResume();
refreshData();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public boolean onLongClick(View v) {
View parent = (View) v.getParent();
StatusFragment f = (StatusFragment) getParentFragment();
switch (parent.getId()) {
default:
return false;
case R.id.rowMode:
//f.displayVortechDialog(Controller.VORTECH_MODE, dcpumpValues[Controller.DCPUMP_MODE]);
break;
case R.id.rowSpeed:
//f.displayVortechDialog(Controller.VORTECH_SPEED, dcpumpValues[Controller.DCPUMP_SPEED]);
break;
case R.id.rowDuration:
//f.displayVortechDialog(Controller.VORTECH_DURATION, dcpumpValues[Controller.DCPUMP_DURATION]);
break;
case R.id.rowThreshold:
//f.displayOverrideDialog(Globals.OVERRIDE_RF_GREEN, dcpumpValues[Controller.DCPUMP_THRESHOLD]);
break;
}
return true;
}
private String[] getValues(Cursor c) {
String sa[] = new String[Controller.MAX_DCPUMP_VALUES];
dcpumpValues[Controller.DCPUMP_MODE] = c.getShort(c.getColumnIndex(StatusTable.COL_DCM));
sa[Controller.DCPUMP_MODE] = dcpumpValues[Controller.DCPUMP_MODE] + "";
dcpumpValues[Controller.DCPUMP_SPEED] = c.getShort(c.getColumnIndex(StatusTable.COL_DCS));
sa[Controller.DCPUMP_SPEED] = dcpumpValues[Controller.DCPUMP_SPEED] + "%";
dcpumpValues[Controller.DCPUMP_DURATION] = c.getShort(c.getColumnIndex(StatusTable.COL_DCD));
sa[Controller.DCPUMP_DURATION] = dcpumpValues[Controller.DCPUMP_DURATION] + "";
dcpumpValues[Controller.DCPUMP_THRESHOLD] = c.getShort(c.getColumnIndex(StatusTable.COL_DCT));
sa[Controller.DCPUMP_THRESHOLD] = dcpumpValues[Controller.DCPUMP_THRESHOLD] + "";
return sa;
}
@Override
public void refreshData() {
Activity a = getActivity();
if ( a == null ) {
return;
}
// only update if the activity exists
StatusFragment f = ((StatusFragment) getParentFragment());
Cursor c = f.getLatestDataCursor();
String updateStatus;
String[] v;
if (c.moveToFirst()) {
updateStatus = c.getString(c.getColumnIndex(StatusTable.COL_LOGDATE));
v = getValues(c);
} else {
updateStatus = getString(R.string.messageNever);
v = ((StatusFragment) getParentFragment()).getNeverValues(Controller.MAX_DCPUMP_VALUES);
}
c.close();
f.updateDisplayText(updateStatus);
for (int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
dcpumpText[i].setText(v[i]);
}
}
}
| app/src/main/java/info/curtbinder/reefangel/phone/PageDCPumpFragment.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Curt Binder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package info.curtbinder.reefangel.phone;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TableRow;
import android.widget.TextView;
import info.curtbinder.reefangel.controller.Controller;
import info.curtbinder.reefangel.db.StatusTable;
/**
* Created by binder on 7/26/14.
*/
public class PageDCPumpFragment extends Fragment
implements PageRefreshInterface, View.OnLongClickListener {
private static final String TAG = PageDCPumpFragment.class.getSimpleName();
private TextView[] dcpumpText = new TextView[Controller.MAX_DCPUMP_VALUES];
private short[] dcpumpValues = new short[Controller.MAX_DCPUMP_VALUES];
public static PageDCPumpFragment newInstance() {
return new PageDCPumpFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page_dcpump, container, false);
findViews(rootView);
return rootView;
}
private void findViews(View root) {
TableRow tr;
tr = (TableRow) root.findViewById(R.id.rowMode);
dcpumpText[0] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelMode);
tr = (TableRow) root.findViewById(R.id.rowSpeed);
dcpumpText[1] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelSpeed);
tr = (TableRow) root.findViewById(R.id.rowDuration);
dcpumpText[2] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelDuration);
tr = (TableRow) root.findViewById(R.id.rowThreshold);
dcpumpText[3] = (TextView) tr.findViewById(R.id.rowValue);
setRowTitle(tr, R.string.labelThreshold);
for ( int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
dcpumpText[i].setLongClickable(true);
dcpumpText[i].setOnLongClickListener(this);
}
}
private void setRowTitle(TableRow row, int labelId) {
((TextView) row.findViewById(R.id.rowTitle)).setText(labelId);
}
@Override
public void onResume() {
super.onResume();
refreshData();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public boolean onLongClick(View v) {
View parent = (View) v.getParent();
StatusFragment f = (StatusFragment) getParentFragment();
switch (parent.getId()) {
default:
return false;
case R.id.rowMode:
f.displayVortechDialog(Controller.VORTECH_MODE, dcpumpValues[Controller.DCPUMP_MODE]);
break;
case R.id.rowSpeed:
f.displayVortechDialog(Controller.VORTECH_SPEED, dcpumpValues[Controller.DCPUMP_SPEED]);
break;
case R.id.rowDuration:
f.displayVortechDialog(Controller.VORTECH_DURATION, dcpumpValues[Controller.DCPUMP_DURATION]);
break;
case R.id.rowThreshold:
//f.displayOverrideDialog(Globals.OVERRIDE_RF_GREEN, dcpumpValues[Controller.DCPUMP_THRESHOLD]);
break;
}
return true;
}
private String[] getValues(Cursor c) {
String sa[] = new String[Controller.MAX_DCPUMP_VALUES];
dcpumpValues[Controller.DCPUMP_MODE] = c.getShort(c.getColumnIndex(StatusTable.COL_DCM));
sa[Controller.DCPUMP_MODE] = dcpumpValues[Controller.DCPUMP_MODE] + "";
dcpumpValues[Controller.DCPUMP_SPEED] = c.getShort(c.getColumnIndex(StatusTable.COL_DCS));
sa[Controller.DCPUMP_SPEED] = dcpumpValues[Controller.DCPUMP_SPEED] + "%";
dcpumpValues[Controller.DCPUMP_DURATION] = c.getShort(c.getColumnIndex(StatusTable.COL_DCD));
sa[Controller.DCPUMP_DURATION] = dcpumpValues[Controller.DCPUMP_DURATION] + "";
dcpumpValues[Controller.DCPUMP_THRESHOLD] = c.getShort(c.getColumnIndex(StatusTable.COL_DCT));
sa[Controller.DCPUMP_THRESHOLD] = dcpumpValues[Controller.DCPUMP_THRESHOLD] + "";
return sa;
}
@Override
public void refreshData() {
Activity a = getActivity();
if ( a == null ) {
return;
}
// only update if the activity exists
StatusFragment f = ((StatusFragment) getParentFragment());
Cursor c = f.getLatestDataCursor();
String updateStatus;
String[] v;
if (c.moveToFirst()) {
updateStatus = c.getString(c.getColumnIndex(StatusTable.COL_LOGDATE));
v = getValues(c);
} else {
updateStatus = getString(R.string.messageNever);
v = ((StatusFragment) getParentFragment()).getNeverValues(Controller.MAX_DCPUMP_VALUES);
}
c.close();
f.updateDisplayText(updateStatus);
for (int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
dcpumpText[i].setText(v[i]);
}
}
}
| Removed dc pump page long clickable events
Removed the events to allow for further improvements to the dialog box that will be displayed upon long clicking. This will prevent any confusion on displaying the box.
| app/src/main/java/info/curtbinder/reefangel/phone/PageDCPumpFragment.java | Removed dc pump page long clickable events | <ide><path>pp/src/main/java/info/curtbinder/reefangel/phone/PageDCPumpFragment.java
<ide> dcpumpText[3] = (TextView) tr.findViewById(R.id.rowValue);
<ide> setRowTitle(tr, R.string.labelThreshold);
<ide>
<del> for ( int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
<del> dcpumpText[i].setLongClickable(true);
<del> dcpumpText[i].setOnLongClickListener(this);
<del> }
<add>// for ( int i = 0; i < Controller.MAX_DCPUMP_VALUES; i++ ) {
<add>// dcpumpText[i].setLongClickable(true);
<add>// dcpumpText[i].setOnLongClickListener(this);
<add>// }
<ide> }
<ide>
<ide> private void setRowTitle(TableRow row, int labelId) {
<ide> default:
<ide> return false;
<ide> case R.id.rowMode:
<del> f.displayVortechDialog(Controller.VORTECH_MODE, dcpumpValues[Controller.DCPUMP_MODE]);
<add> //f.displayVortechDialog(Controller.VORTECH_MODE, dcpumpValues[Controller.DCPUMP_MODE]);
<ide> break;
<ide> case R.id.rowSpeed:
<del> f.displayVortechDialog(Controller.VORTECH_SPEED, dcpumpValues[Controller.DCPUMP_SPEED]);
<add> //f.displayVortechDialog(Controller.VORTECH_SPEED, dcpumpValues[Controller.DCPUMP_SPEED]);
<ide> break;
<ide> case R.id.rowDuration:
<del> f.displayVortechDialog(Controller.VORTECH_DURATION, dcpumpValues[Controller.DCPUMP_DURATION]);
<add> //f.displayVortechDialog(Controller.VORTECH_DURATION, dcpumpValues[Controller.DCPUMP_DURATION]);
<ide> break;
<ide> case R.id.rowThreshold:
<ide> //f.displayOverrideDialog(Globals.OVERRIDE_RF_GREEN, dcpumpValues[Controller.DCPUMP_THRESHOLD]); |
|
Java | epl-1.0 | ef9999476c4e3f3baa334b482e7397350444a9c4 | 0 | Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1 | /*******************************************************************************
* Copyright (c) 2004, 2010 Actuate Corporation.
* 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
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl.index;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.archive.RAOutputStream;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
public class SerializableDataSetNumberIndex<T> implements IIndexSerializer
{
private static int BLOCKNUMBER = 5000;
private Map<T, List<Integer>> numberAndIndex = new HashMap<T, List<Integer>>( );
private RAOutputStream output;
public SerializableDataSetNumberIndex( RAOutputStream stream )
{
this.output = stream;
}
/**
* Put a value into index
*
* @param number
* @param index
* @throws DataException
*/
public Object put( Object number, Object index ) throws DataException
{
if ( this.numberAndIndex.containsKey( number ) )
{
this.numberAndIndex.get( number ).add( (Integer)index );
}
else
{
List<Integer> list = new ArrayList<Integer>( );
list.add( (Integer) index );
this.numberAndIndex.put( (T)number, list );
}
return null;
}
public void close( ) throws DataException
{
try
{
List<T> keyList = new LinkedList<T>( );
keyList.addAll( this.numberAndIndex.keySet( ) );
if ( keyList.size( ) == 0 )
{
output.close( );
return;
}
Collections.sort( keyList, new NumberComparator<T>( ) );
int segs = ( keyList.size( ) - 1 ) / BLOCKNUMBER + 1;
IOUtil.writeInt( output, segs );
long intOffset = output.getOffset( );
DataOutputStream dout = new DataOutputStream( output );
long[] offsets = new long[segs];
Object[] boundaryValues = new Object[segs];
for ( int i = 0; i < segs; i++ )
{
IOUtil.writeLong( dout, 0 );
boundaryValues[i] = keyList.get( i * BLOCKNUMBER );
}
for ( int i = 0; i < boundaryValues.length; i++ )
{
IOUtil.writeObject( dout, boundaryValues[i] );
}
for ( int i = 0; i < segs; i++ )
{
offsets[i] = output.getOffset( );
IOUtil.writeInt( dout, i == segs - 1? keyList.size( )%BLOCKNUMBER : BLOCKNUMBER );
for ( int j = i * BLOCKNUMBER; j < ( i + 1 ) * BLOCKNUMBER && j < keyList.size( ); j++ )
{
IOUtil.writeObject( dout, keyList.get( j ) );
IOUtil.writeList( dout,
numberAndIndex.get( keyList.get( j ) ) );
}
}
// Seek to the offset recording location;
output.seek( intOffset );
for ( int i = 0; i < offsets.length; i++ )
{
IOUtil.writeLong( dout, offsets[i] );
}
output.close( );
}
catch ( Exception e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
}
private class NumberComparator<T1> implements Comparator<T>
{
public int compare( T o1, T o2 )
{
try
{
return ScriptEvalUtil.compare( o1, o2 );
}
catch ( DataException e )
{
throw new RuntimeException( e );
}
}
}
}
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/index/SerializableDataSetNumberIndex.java | /*******************************************************************************
* Copyright (c) 2004, 2010 Actuate Corporation.
* 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
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.impl.index;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.archive.RAOutputStream;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.script.ScriptEvalUtil;
public class SerializableDataSetNumberIndex<T> implements IIndexSerializer
{
private static int BLOCKNUMBER = 5000;
private Map<T, List<Integer>> numberAndIndex = new HashMap<T, List<Integer>>( );
private RAOutputStream output;
public SerializableDataSetNumberIndex( RAOutputStream stream )
{
this.output = stream;
}
/**
* Put a value into index
*
* @param number
* @param index
* @throws DataException
*/
public Object put( Object number, Object index ) throws DataException
{
if ( this.numberAndIndex.containsKey( number ) )
{
this.numberAndIndex.get( number ).add( (Integer)index );
}
else
{
List<Integer> list = new ArrayList<Integer>( );
list.add( (Integer) index );
this.numberAndIndex.put( (T)number, list );
}
return null;
}
public void close( ) throws DataException
{
try
{
List<T> keyList = new LinkedList<T>( );
keyList.addAll( this.numberAndIndex.keySet( ) );
Collections.sort( keyList, new NumberComparator<T>( ) );
int segs = keyList.size( ) / BLOCKNUMBER + 1;
IOUtil.writeInt( output, segs );
long intOffset = output.getOffset( );
DataOutputStream dout = new DataOutputStream( output );
long[] offsets = new long[segs];
Object[] boundaryValues = new Object[segs];
for ( int i = 0; i < segs; i++ )
{
IOUtil.writeLong( dout, 0 );
boundaryValues[i] = keyList.get( i * BLOCKNUMBER );
}
for ( int i = 0; i < boundaryValues.length; i++ )
{
IOUtil.writeObject( dout, boundaryValues[i] );
}
for ( int i = 0; i < segs; i++ )
{
offsets[i] = output.getOffset( );
IOUtil.writeInt( dout, i == segs - 1? keyList.size( )%BLOCKNUMBER : BLOCKNUMBER );
for ( int j = i * BLOCKNUMBER; j < ( i + 1 ) * BLOCKNUMBER && j < keyList.size( ); j++ )
{
IOUtil.writeObject( dout, keyList.get( j ) );
IOUtil.writeList( dout,
numberAndIndex.get( keyList.get( j ) ) );
}
}
// Seek to the offset recording location;
output.seek( intOffset );
for ( int i = 0; i < offsets.length; i++ )
{
IOUtil.writeLong( dout, offsets[i] );
}
output.close( );
}
catch ( Exception e )
{
throw new DataException( e.getLocalizedMessage( ), e );
}
}
private class NumberComparator<T1> implements Comparator<T>
{
public int compare( T o1, T o2 )
{
try
{
return ScriptEvalUtil.compare( o1, o2 );
}
catch ( DataException e )
{
throw new RuntimeException( e );
}
}
}
}
| CheckIN:Fix a minor issue when serialize DataSetNumberIndex.
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/index/SerializableDataSetNumberIndex.java | CheckIN:Fix a minor issue when serialize DataSetNumberIndex. | <ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/impl/index/SerializableDataSetNumberIndex.java
<ide> {
<ide> List<T> keyList = new LinkedList<T>( );
<ide> keyList.addAll( this.numberAndIndex.keySet( ) );
<add> if ( keyList.size( ) == 0 )
<add> {
<add> output.close( );
<add> return;
<add> }
<add>
<ide> Collections.sort( keyList, new NumberComparator<T>( ) );
<del> int segs = keyList.size( ) / BLOCKNUMBER + 1;
<add> int segs = ( keyList.size( ) - 1 ) / BLOCKNUMBER + 1;
<ide> IOUtil.writeInt( output, segs );
<ide> long intOffset = output.getOffset( );
<ide> DataOutputStream dout = new DataOutputStream( output ); |
|
Java | mit | af713dd1acb3215cd871994932f83e183f645652 | 0 | tim-group/test-driven-detectors4findbugs | /*
* test-driven-detectors4findbugs. Copyright (c) 2011 youDevise, Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.youdevise.fbplugins.tdd4fb;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.Detector2;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.analysis.ClassInfo;
import edu.umd.cs.findbugs.classfile.analysis.MethodInfo;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import static com.youdevise.fbplugins.tdd4fb.TestingBugReporter.tddBugReporter;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DetectorRunnerTest {
private final Detector detector = mock(Detector.class);
private final Detector2 detector2 = mock(Detector2.class);
private final BugReporter bugReporter = tddBugReporter();
@Test public void runDetectorOnClassVisitsDetectorWithClassContextOfSpecifiedClass() throws Exception {
new DetectorRunner().runDetectorOnClass(detector, DetectorRunner.class, bugReporter);
verify(detector).visitClassContext(argThat(isClassContextFor("DetectorRunner")));
}
@Test public void runDetector2OnClassVisitsDetectorWithClassContextOfSpecifiedClass() throws Exception {
new DetectorRunner().runDetectorOnClass(detector2, DetectorRunner.class, bugReporter);
verify(detector2).visitClass(argThat(isClassDescriptorFor("DetectorRunner")));
}
public static ArgumentMatcher<ClassContext> isClassContextFor(final String simpleClassName) {
return new ArgumentMatcher<ClassContext>() {
@Override
public boolean matches(ClassContext argument) {
return argument.getClassDescriptor().getSimpleName().equals(simpleClassName);
}
};
}
private ArgumentMatcher<ClassDescriptor> isClassDescriptorFor(final String simpleClassName) {
return new ArgumentMatcher<ClassDescriptor>() {
@Override public boolean matches(ClassDescriptor argument) {
return argument.getSimpleName().equals(simpleClassName);
}
};
}
@Test
public void canRetrieveXClassInfoForAnApplicationClass() throws Exception {
BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
MyDetector myDetector = new MyDetector();
DetectorAssert.assertNoBugsReported(SomeClassOfMine.class, myDetector, bugReporter);
assertThat(myDetector.xMethod, instanceOf(MethodInfo.class));
assertTrue(myDetector.xMethod.isSynchronized());
}
@Test
public void canRetrieveSuperclassInfoAsXClass() throws Exception {
BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
MyDetector myDetector = new MyDetector();
DetectorAssert.assertNoBugsReported(SomeClassOfMine.class, myDetector, bugReporter);
assertThat(myDetector.xSuperclass, instanceOf(ClassInfo.class));
assertThat(asList(myDetector.xSuperclass.getInterfaceDescriptorList()), hasSize(1));
assertThat(asList(myDetector.xSuperclass.getInterfaceDescriptorList()).get(0), equalTo(DescriptorFactory.createClassDescriptor(MarkerInterface.class)));
}
public static interface MarkerInterface { }
public static class SuperClass implements MarkerInterface {
public void superMethod() {
}
}
public static class SomeClassOfMine extends SuperClass {
public synchronized void aMethod() {}
}
public static final class MyDetector implements Detector {
private XMethod xMethod;
private XClass xSuperclass;
public void report() { }
public void visitClassContext(ClassContext classContext) {
xMethod = XFactory.createXMethod(DescriptorFactory.instance().getMethodDescriptor(
"com/youdevise/fbplugins/tdd4fb/DetectorRunnerTest$SomeClassOfMine",
"aMethod",
"()V",
false));
try {
xSuperclass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classContext.getXClass().getSuperclassDescriptor());
} catch (CheckedAnalysisException e) {
throw new RuntimeException(e);
}
}
}
}
| src/test/java/com/youdevise/fbplugins/tdd4fb/DetectorRunnerTest.java | /*
* test-driven-detectors4findbugs. Copyright (c) 2011 youDevise, Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.youdevise.fbplugins.tdd4fb;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.Detector;
import edu.umd.cs.findbugs.Detector2;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.XClass;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.classfile.CheckedAnalysisException;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.Global;
import edu.umd.cs.findbugs.classfile.analysis.ClassInfo;
import edu.umd.cs.findbugs.classfile.analysis.MethodInfo;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import static com.youdevise.fbplugins.tdd4fb.TestingBugReporter.tddBugReporter;
import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DetectorRunnerTest {
private final Detector detector = mock(Detector.class);
private final Detector2 detector2 = mock(Detector2.class);
private final BugReporter bugReporter = tddBugReporter();
@Test public void runDetectorOnClassVisitsDetectorWithClassContextOfSpecifiedClass() throws Exception {
new DetectorRunner().runDetectorOnClass(detector, DetectorRunner.class, bugReporter);
verify(detector).visitClassContext(argThat(isClassContextFor("DetectorRunner")));
}
@Test public void runDetector2OnClassVisitsDetectorWithClassContextOfSpecifiedClass() throws Exception {
new DetectorRunner().runDetectorOnClass(detector2, DetectorRunner.class, bugReporter);
verify(detector2).visitClass(argThat(isClassDescriptorFor("DetectorRunner")));
}
public static ArgumentMatcher<ClassContext> isClassContextFor(final String simpleClassName) {
return new ArgumentMatcher<ClassContext>() {
@Override public boolean matches(Object argument) {
if (!(argument instanceof ClassContext)) {
return false;
} else {
return ((ClassContext) argument).getClassDescriptor().getSimpleName().equals(simpleClassName);
}
}
};
}
private ArgumentMatcher<ClassDescriptor> isClassDescriptorFor(final String simpleClassName) {
return new ArgumentMatcher<ClassDescriptor>() {
@Override public boolean matches(Object argument) {
if (!(argument instanceof ClassDescriptor)) {
return false;
} else {
return ((ClassDescriptor) argument).getSimpleName().equals(simpleClassName);
}
}
};
}
@Test
public void canRetrieveXClassInfoForAnApplicationClass() throws Exception {
BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
MyDetector myDetector = new MyDetector();
DetectorAssert.assertNoBugsReported(SomeClassOfMine.class, myDetector, bugReporter);
assertThat(myDetector.xMethod, instanceOf(MethodInfo.class));
assertTrue(myDetector.xMethod.isSynchronized());
}
@Test
public void canRetrieveSuperclassInfoAsXClass() throws Exception {
BugReporter bugReporter = DetectorAssert.bugReporterForTesting();
MyDetector myDetector = new MyDetector();
DetectorAssert.assertNoBugsReported(SomeClassOfMine.class, myDetector, bugReporter);
assertThat(myDetector.xSuperclass, instanceOf(ClassInfo.class));
assertThat(asList(myDetector.xSuperclass.getInterfaceDescriptorList()), hasSize(1));
assertThat(asList(myDetector.xSuperclass.getInterfaceDescriptorList()).get(0), equalTo(DescriptorFactory.createClassDescriptor(MarkerInterface.class)));
}
public static interface MarkerInterface { }
public static class SuperClass implements MarkerInterface {
public void superMethod() {
}
}
public static class SomeClassOfMine extends SuperClass {
public synchronized void aMethod() {}
}
public static final class MyDetector implements Detector {
private XMethod xMethod;
private XClass xSuperclass;
public void report() { }
public void visitClassContext(ClassContext classContext) {
xMethod = XFactory.createXMethod(DescriptorFactory.instance().getMethodDescriptor(
"com/youdevise/fbplugins/tdd4fb/DetectorRunnerTest$SomeClassOfMine",
"aMethod",
"()V",
false));
try {
xSuperclass = Global.getAnalysisCache().getClassAnalysis(XClass.class, classContext.getXClass().getSuperclassDescriptor());
} catch (CheckedAnalysisException e) {
throw new RuntimeException(e);
}
}
}
}
| Fix compilation errors
| src/test/java/com/youdevise/fbplugins/tdd4fb/DetectorRunnerTest.java | Fix compilation errors | <ide><path>rc/test/java/com/youdevise/fbplugins/tdd4fb/DetectorRunnerTest.java
<ide>
<ide> public static ArgumentMatcher<ClassContext> isClassContextFor(final String simpleClassName) {
<ide> return new ArgumentMatcher<ClassContext>() {
<del> @Override public boolean matches(Object argument) {
<del> if (!(argument instanceof ClassContext)) {
<del> return false;
<del> } else {
<del> return ((ClassContext) argument).getClassDescriptor().getSimpleName().equals(simpleClassName);
<del> }
<add> @Override
<add> public boolean matches(ClassContext argument) {
<add> return argument.getClassDescriptor().getSimpleName().equals(simpleClassName);
<ide> }
<ide>
<ide> };
<ide>
<ide> private ArgumentMatcher<ClassDescriptor> isClassDescriptorFor(final String simpleClassName) {
<ide> return new ArgumentMatcher<ClassDescriptor>() {
<del> @Override public boolean matches(Object argument) {
<del> if (!(argument instanceof ClassDescriptor)) {
<del> return false;
<del> } else {
<del> return ((ClassDescriptor) argument).getSimpleName().equals(simpleClassName);
<del> }
<add> @Override public boolean matches(ClassDescriptor argument) {
<add> return argument.getSimpleName().equals(simpleClassName);
<ide> }
<ide> };
<ide> } |
|
Java | apache-2.0 | a70d7382242c09b50c8ec20c6d872bd3820c9b5a | 0 | hurzl/dmix,abarisain/dmix,jcnoir/dmix,0359xiaodong/dmix,jcnoir/dmix,joansmith/dmix,hurzl/dmix,abarisain/dmix,0359xiaodong/dmix,joansmith/dmix | /*
* Copyright (C) 2010-2014 The MPDroid Project
*
* 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.namelessdev.mpdroid;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper.ConnectionListener;
import com.namelessdev.mpdroid.helpers.UpdateTrackInfo;
import com.namelessdev.mpdroid.service.MPDroidService;
import com.namelessdev.mpdroid.service.StreamingService;
import com.namelessdev.mpdroid.tools.SettingsHelper;
import org.a0z.mpd.MPD;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager.BadTokenException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static android.util.Log.w;
public class MPDApplication extends Application implements ConnectionListener {
private static final long DISCONNECT_TIMER = 15000L;
private static final int SETTINGS = 5;
private static final String TAG = "MPDApplication";
private static MPDApplication sInstance;
private final Collection<Object> mConnectionLocks = new LinkedList<>();
public MPDAsyncHelper oMPDAsyncHelper = null;
public UpdateTrackInfo updateTrackInfo = null;
private AlertDialog mAlertDialog = null;
private Activity mCurrentActivity = null;
private Timer mDisconnectScheduler = null;
private SettingsHelper mSettingsHelper = null;
private boolean mSettingsShown = false;
private SharedPreferences mSharedPreferences = null;
private boolean mWarningShown = false;
public static MPDApplication getInstance() {
return sInstance;
}
/**
* Checks against a list of running service classes for the needle parameter. This method
* (ab)uses getRunningServices() due to no other clear cut way whether our own services are
* active. We could use static boolean, but this method is more fullproof in the case of
* process instability. Please replace if you know a better way.
*
* @param serviceClass The class to search for.
* @return True if {@code serviceClass} was found, false otherwise.
*/
private static boolean isServiceRunning(final Class<?> serviceClass) {
final int maxServices = 1000;
final ActivityManager activityManager =
(ActivityManager) sInstance.getSystemService(sInstance.ACTIVITY_SERVICE);
final List<ActivityManager.RunningServiceInfo> services =
activityManager.getRunningServices(maxServices);
boolean isServiceRunning = false;
for (final ActivityManager.RunningServiceInfo serviceInfo : services) {
if (serviceClass.getName().equals(serviceInfo.service.getClassName())) {
isServiceRunning = true;
break;
}
}
return isServiceRunning;
}
public final void addConnectionLock(final Object lockOwner) {
mConnectionLocks.add(lockOwner);
checkConnectionNeeded();
cancelDisconnectScheduler();
}
private void cancelDisconnectScheduler() {
mDisconnectScheduler.cancel();
mDisconnectScheduler.purge();
mDisconnectScheduler = new Timer();
}
private void checkConnectionNeeded() {
if (mConnectionLocks.isEmpty()) {
disconnect();
} else {
if (!oMPDAsyncHelper.isMonitorAlive()) {
oMPDAsyncHelper.startMonitor();
}
if (!oMPDAsyncHelper.oMPD.isConnected() && (mCurrentActivity == null
|| !mCurrentActivity.getClass().equals(WifiConnectionSettings.class))) {
connect();
}
}
}
public final void connect() {
if (!mSettingsHelper.updateSettings()) {
// Absolutely no settings defined! Open Settings!
if (mCurrentActivity != null && !mSettingsShown) {
mCurrentActivity.startActivityForResult(new Intent(mCurrentActivity,
WifiConnectionSettings.class), SETTINGS);
mSettingsShown = true;
}
}
if (mCurrentActivity != null && !mSettingsHelper.warningShown() && !mWarningShown) {
mCurrentActivity.startActivity(new Intent(mCurrentActivity, WarningActivity.class));
mWarningShown = true;
}
connectMPD();
}
@Override
public final synchronized void connectionFailed(final String message) {
if (mAlertDialog != null && !(mAlertDialog instanceof ProgressDialog) && mAlertDialog
.isShowing()) {
return;
}
// dismiss possible dialog
dismissAlertDialog();
oMPDAsyncHelper.disconnect();
if (mCurrentActivity != null && !mConnectionLocks.isEmpty()) {
// are we in the settings activity?
if (mCurrentActivity.getClass().equals(SettingsActivity.class)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
builder.setCancelable(false);
builder.setMessage(
getResources().getString(R.string.connectionFailedMessageSetting, message));
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
}
});
mAlertDialog = builder.show();
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
builder.setTitle(R.string.connectionFailed);
builder.setMessage(
getResources().getString(R.string.connectionFailedMessage, message));
builder.setCancelable(false);
final OnClickListener oDialogClickListener = new DialogClickListener();
builder.setNegativeButton(R.string.quit, oDialogClickListener);
builder.setNeutralButton(R.string.settings, oDialogClickListener);
builder.setPositiveButton(R.string.retry, oDialogClickListener);
try {
mAlertDialog = builder.show();
} catch (final BadTokenException ignored) {
// Can't display it. Don't care.
}
}
}
}
@Override
public final synchronized void connectionSucceeded(final String message) {
dismissAlertDialog();
}
private void connectMPD() {
// dismiss possible dialog
dismissAlertDialog();
// show connecting to server dialog
if (mCurrentActivity != null) {
mAlertDialog = new ProgressDialog(mCurrentActivity);
mAlertDialog.setTitle(R.string.connecting);
mAlertDialog.setMessage(getResources().getString(R.string.connectingToServer));
mAlertDialog.setCancelable(false);
mAlertDialog.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(final DialogInterface dialog, final int keyCode,
final KeyEvent event) {
// Handle all keys!
return true;
}
});
try {
mAlertDialog.show();
} catch (final BadTokenException ignored) {
// Can't display it. Don't care.
}
}
cancelDisconnectScheduler();
// really connect
oMPDAsyncHelper.connect();
}
final void disconnect() {
cancelDisconnectScheduler();
startDisconnectScheduler();
}
private void dismissAlertDialog() {
if (mAlertDialog != null) {
if (mAlertDialog.isShowing()) {
try {
mAlertDialog.dismiss();
} catch (final IllegalArgumentException ignored) {
// We don't care, it has already been destroyed
}
}
}
}
void init(final Context context) {
MPD.setApplicationContext(context);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
final StrictMode.VmPolicy vmPolicy = new StrictMode.VmPolicy.Builder().penaltyLog().build();
final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()
.build();
StrictMode.setThreadPolicy(policy);
StrictMode.setVmPolicy(vmPolicy);
// Init the default preferences (meaning we won't have different defaults between code/xml)
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
oMPDAsyncHelper = new MPDAsyncHelper();
oMPDAsyncHelper.addConnectionListener(this);
mSettingsHelper = new SettingsHelper(oMPDAsyncHelper);
mDisconnectScheduler = new Timer();
if (!mSharedPreferences.contains("albumTrackSort")) {
mSharedPreferences.edit().putBoolean("albumTrackSort", true).commit();
}
}
public final boolean isInSimpleMode() {
return mSharedPreferences.getBoolean("simpleMode", false);
}
public final boolean isLightThemeSelected() {
return mSharedPreferences.getBoolean("lightTheme", false);
}
/**
* isLocalAudible()
*
* @return Returns whether it is probable that the local audio
* system will be playing audio controlled by this application.
*/
public final boolean isLocalAudible() {
return isStreamingServiceRunning() ||
"127.0.0.1".equals(oMPDAsyncHelper.getConnectionSettings().sServer);
}
/**
* Checks to see if the MPDroid scheduling service is active.
*
* @return True if MPDroid scheduling service running, false otherwise.
*/
public final boolean isMPDroidServiceRunning() {
return isServiceRunning(MPDroidService.class);
}
/**
* Checks the MPDroid scheduling service and the persistent override to
*/
public final boolean isNotificationPersistent() {
final boolean result;
if (oMPDAsyncHelper.getConnectionSettings().persistentNotification &&
!mSharedPreferences.getBoolean("notificationOverride", false)) {
result = true;
} else {
result = false;
}
return result;
}
/**
* Checks for a running Streaming service.
*
* @return True if streaming service is running, false otherwise.
*/
public final boolean isStreamingServiceRunning() {
return isServiceRunning(StreamingService.class);
}
public final boolean isTabletUiEnabled() {
return getResources().getBoolean(R.bool.isTablet)
&& mSharedPreferences.getBoolean("tabletUI", true);
}
@Override
public final void onCreate() {
super.onCreate();
sInstance = this;
Log.d(TAG, "onCreate Application");
init(this);
}
public final void removeConnectionLock(final Object lockOwner) {
mConnectionLocks.remove(lockOwner);
checkConnectionNeeded();
}
public final void setActivity(final Object activity) {
if (activity instanceof Activity) {
mCurrentActivity = (Activity) activity;
}
addConnectionLock(activity);
}
/**
* Set this to override the persistent notification for the current session.
*
* @param override True to override persistent notification, false otherwise.
*/
public final void setPersistentOverride(final boolean override) {
mSharedPreferences.edit()
.putBoolean("notificationOverride", override)
.apply();
}
private void startDisconnectScheduler() {
mDisconnectScheduler.schedule(new TimerTask() {
@Override
public void run() {
w(TAG, "Disconnecting (" + DISCONNECT_TIMER + " ms timeout)");
oMPDAsyncHelper.stopMonitor();
oMPDAsyncHelper.disconnect();
}
}, DISCONNECT_TIMER);
}
public final void unsetActivity(final Object activity) {
removeConnectionLock(activity);
if (mCurrentActivity != null && mCurrentActivity.equals(activity)) {
mCurrentActivity = null;
}
}
private class DialogClickListener implements OnClickListener {
@Override
public final void onClick(final DialogInterface dialog, final int which) {
switch (which) {
case DialogInterface.BUTTON_NEUTRAL:
final Intent intent =
new Intent(mCurrentActivity, WifiConnectionSettings.class);
// Show Settings
mCurrentActivity.startActivityForResult(intent, SETTINGS);
break;
case DialogInterface.BUTTON_NEGATIVE:
mCurrentActivity.finish();
break;
case DialogInterface.BUTTON_POSITIVE:
connectMPD();
break;
default:
break;
}
}
}
}
| MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java | /*
* Copyright (C) 2010-2014 The MPDroid Project
*
* 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.namelessdev.mpdroid;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper;
import com.namelessdev.mpdroid.helpers.MPDAsyncHelper.ConnectionListener;
import com.namelessdev.mpdroid.helpers.UpdateTrackInfo;
import com.namelessdev.mpdroid.service.MPDroidService;
import com.namelessdev.mpdroid.service.StreamingService;
import com.namelessdev.mpdroid.tools.SettingsHelper;
import org.a0z.mpd.MPD;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager.BadTokenException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static android.util.Log.w;
public class MPDApplication extends Application implements ConnectionListener {
public static final String TAG = "MPDroid";
public static final int SETTINGS = 5;
private static final long DISCONNECT_TIMER = 15000;
private static MPDApplication instance;
public MPDAsyncHelper oMPDAsyncHelper = null;
public UpdateTrackInfo updateTrackInfo = null;
private SharedPreferences mSharedPreferences;
private SettingsHelper settingsHelper = null;
private Collection<Object> connectionLocks = new LinkedList<Object>();
private AlertDialog ad;
private boolean settingsShown = false;
private boolean warningShown = false;
private Activity currentActivity;
private Timer disconnectSheduler;
public static MPDApplication getInstance() {
return instance;
}
/**
* Checks against a list of running service classes for the needle parameter. This method
* (ab)uses getRunningServices() due to no other clear cut way whether our own services are
* active. We could use static boolean, but this method is more fullproof in the case of
* process instability. Please replace if you know a better way.
*
* @param serviceClass The class to search for.
* @return True if {@code serviceClass} was found, false otherwise.
*/
private static boolean isServiceRunning(final Class<?> serviceClass) {
final int maxServices = 1000;
final ActivityManager activityManager =
(ActivityManager) instance.getSystemService(instance.ACTIVITY_SERVICE);
final List<ActivityManager.RunningServiceInfo> services =
activityManager.getRunningServices(maxServices);
boolean isServiceRunning = false;
for (final ActivityManager.RunningServiceInfo serviceInfo : services) {
if (serviceClass.getName().equals(serviceInfo.service.getClassName())) {
isServiceRunning = true;
break;
}
}
return isServiceRunning;
}
public void addConnectionLock(Object lockOwner) {
connectionLocks.add(lockOwner);
checkConnectionNeeded();
cancelDisconnectSheduler();
}
private void cancelDisconnectSheduler() {
disconnectSheduler.cancel();
disconnectSheduler.purge();
disconnectSheduler = new Timer();
}
private void checkConnectionNeeded() {
if (connectionLocks.size() > 0) {
if (!oMPDAsyncHelper.isMonitorAlive()) {
oMPDAsyncHelper.startMonitor();
}
if (!oMPDAsyncHelper.oMPD.isConnected() && (currentActivity == null
|| !currentActivity.getClass().equals(WifiConnectionSettings.class))) {
connect();
}
} else {
disconnect();
}
}
public void connect() {
if (!settingsHelper.updateSettings()) {
// Absolutely no settings defined! Open Settings!
if (currentActivity != null && !settingsShown) {
currentActivity.startActivityForResult(new Intent(currentActivity,
WifiConnectionSettings.class), SETTINGS);
settingsShown = true;
}
}
if (currentActivity != null && !settingsHelper.warningShown() && !warningShown) {
currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class));
warningShown = true;
}
connectMPD();
}
public synchronized void connectionFailed(String message) {
if (ad != null && !(ad instanceof ProgressDialog) && ad.isShowing()) {
return;
}
// dismiss possible dialog
dismissAlertDialog();
oMPDAsyncHelper.disconnect();
if (currentActivity == null) {
return;
}
if (currentActivity != null && connectionLocks.size() > 0) {
// are we in the settings activity?
if (currentActivity.getClass() == SettingsActivity.class) {
AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
builder.setCancelable(false);
builder.setMessage(
getResources().getString(R.string.connectionFailedMessageSetting, message));
builder.setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
ad = builder.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
builder.setTitle(R.string.connectionFailed);
builder.setMessage(
getResources().getString(R.string.connectionFailedMessage, message));
builder.setCancelable(false);
DialogClickListener oDialogClickListener = new DialogClickListener();
builder.setNegativeButton(R.string.quit, oDialogClickListener);
builder.setNeutralButton(R.string.settings, oDialogClickListener);
builder.setPositiveButton(R.string.retry, oDialogClickListener);
try {
ad = builder.show();
} catch (BadTokenException e) {
// Can't display it. Don't care.
}
}
}
}
public synchronized void connectionSucceeded(String message) {
dismissAlertDialog();
// checkMonitorNeeded();
}
private void connectMPD() {
// dismiss possible dialog
dismissAlertDialog();
// show connecting to server dialog
if (currentActivity != null) {
ad = new ProgressDialog(currentActivity);
ad.setTitle(R.string.connecting);
ad.setMessage(getResources().getString(R.string.connectingToServer));
ad.setCancelable(false);
ad.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Handle all keys!
return true;
}
});
try {
ad.show();
} catch (BadTokenException e) {
// Can't display it. Don't care.
}
}
cancelDisconnectSheduler();
// really connect
oMPDAsyncHelper.connect();
}
public void disconnect() {
cancelDisconnectSheduler();
startDisconnectSheduler();
}
private void dismissAlertDialog() {
if (ad != null) {
if (ad.isShowing()) {
try {
ad.dismiss();
} catch (IllegalArgumentException e) {
// We don't care, it has already been destroyed
}
}
}
}
public void init(Context context) {
MPD.setApplicationContext(context);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
StrictMode.VmPolicy vmpolicy = new StrictMode.VmPolicy.Builder().penaltyLog().build();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
StrictMode.setVmPolicy(vmpolicy);
// Init the default preferences (meaning we won't have different defaults between code/xml)
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
oMPDAsyncHelper = new MPDAsyncHelper();
oMPDAsyncHelper.addConnectionListener(this);
settingsHelper = new SettingsHelper(oMPDAsyncHelper);
disconnectSheduler = new Timer();
if (!mSharedPreferences.contains("albumTrackSort")) {
mSharedPreferences.edit().putBoolean("albumTrackSort", true).commit();
}
}
public boolean isInSimpleMode() {
return mSharedPreferences.getBoolean("simpleMode", false);
}
public boolean isLightThemeSelected() {
return mSharedPreferences.getBoolean("lightTheme", false);
}
/**
* isLocalAudible()
*
* @return Returns whether it is probable that the local audio
* system will be playing audio controlled by this application.
*/
public final boolean isLocalAudible() {
return isStreamingServiceRunning() ||
"127.0.0.1".equals(oMPDAsyncHelper.getConnectionSettings().sServer);
}
/**
* Checks to see if the MPDroid scheduling service is active.
*
* @return True if MPDroid scheduling service running, false otherwise.
*/
public final boolean isMPDroidServiceRunning() {
return isServiceRunning(MPDroidService.class);
}
/**
* Checks the MPDroid scheduling service and the persistent override to
*/
public final boolean isNotificationPersistent() {
final boolean result;
if (oMPDAsyncHelper.getConnectionSettings().persistentNotification &&
!mSharedPreferences.getBoolean("notificationOverride", false)) {
result = true;
} else {
result = false;
}
return result;
}
/**
* Checks for a running Streaming service.
*
* @return True if streaming service is running, false otherwise.
*/
public final boolean isStreamingServiceRunning() {
return isServiceRunning(StreamingService.class);
}
public boolean isTabletUiEnabled() {
return getResources().getBoolean(R.bool.isTablet)
&& mSharedPreferences.getBoolean("tabletUI", true);
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
Log.d(MPDApplication.TAG, "onCreate Application");
init(this);
}
public void removeConnectionLock(Object lockOwner) {
connectionLocks.remove(lockOwner);
checkConnectionNeeded();
}
public void setActivity(Object activity) {
if (activity instanceof Activity) {
currentActivity = (Activity) activity;
}
addConnectionLock(activity);
}
/**
* Set this to override the persistent notification for the current session.
*
* @param override True to override persistent notification, false otherwise.
*/
public final void setPersistentOverride(final boolean override) {
mSharedPreferences.edit()
.putBoolean("notificationOverride", override)
.apply();
}
private void startDisconnectSheduler() {
disconnectSheduler.schedule(new TimerTask() {
@Override
public void run() {
w(TAG, "Disconnecting (" + DISCONNECT_TIMER + " ms timeout)");
oMPDAsyncHelper.stopMonitor();
oMPDAsyncHelper.disconnect();
}
}, DISCONNECT_TIMER);
}
public void terminateApplication() {
this.currentActivity.finish();
}
public void unsetActivity(Object activity) {
removeConnectionLock(activity);
if (currentActivity == activity) {
currentActivity = null;
}
}
class DialogClickListener implements OnClickListener {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case AlertDialog.BUTTON_NEUTRAL:
// Show Settings
currentActivity.startActivityForResult(new Intent(currentActivity,
WifiConnectionSettings.class), SETTINGS);
break;
case AlertDialog.BUTTON_NEGATIVE:
currentActivity.finish();
break;
case AlertDialog.BUTTON_POSITIVE:
connectMPD();
break;
}
}
}
}
| MPDApplication: Fix many warnings.
| MPDroid/src/com/namelessdev/mpdroid/MPDApplication.java | MPDApplication: Fix many warnings. | <ide><path>PDroid/src/com/namelessdev/mpdroid/MPDApplication.java
<ide>
<ide> public class MPDApplication extends Application implements ConnectionListener {
<ide>
<del> public static final String TAG = "MPDroid";
<del>
<del> public static final int SETTINGS = 5;
<del>
<del> private static final long DISCONNECT_TIMER = 15000;
<del>
<del> private static MPDApplication instance;
<add> private static final long DISCONNECT_TIMER = 15000L;
<add>
<add> private static final int SETTINGS = 5;
<add>
<add> private static final String TAG = "MPDApplication";
<add>
<add> private static MPDApplication sInstance;
<add>
<add> private final Collection<Object> mConnectionLocks = new LinkedList<>();
<ide>
<ide> public MPDAsyncHelper oMPDAsyncHelper = null;
<ide>
<ide> public UpdateTrackInfo updateTrackInfo = null;
<ide>
<del> private SharedPreferences mSharedPreferences;
<del>
<del> private SettingsHelper settingsHelper = null;
<del>
<del> private Collection<Object> connectionLocks = new LinkedList<Object>();
<del>
<del> private AlertDialog ad;
<del>
<del> private boolean settingsShown = false;
<del>
<del> private boolean warningShown = false;
<del>
<del> private Activity currentActivity;
<del>
<del> private Timer disconnectSheduler;
<add> private AlertDialog mAlertDialog = null;
<add>
<add> private Activity mCurrentActivity = null;
<add>
<add> private Timer mDisconnectScheduler = null;
<add>
<add> private SettingsHelper mSettingsHelper = null;
<add>
<add> private boolean mSettingsShown = false;
<add>
<add> private SharedPreferences mSharedPreferences = null;
<add>
<add> private boolean mWarningShown = false;
<ide>
<ide> public static MPDApplication getInstance() {
<del> return instance;
<add> return sInstance;
<ide> }
<ide>
<ide> /**
<ide> private static boolean isServiceRunning(final Class<?> serviceClass) {
<ide> final int maxServices = 1000;
<ide> final ActivityManager activityManager =
<del> (ActivityManager) instance.getSystemService(instance.ACTIVITY_SERVICE);
<add> (ActivityManager) sInstance.getSystemService(sInstance.ACTIVITY_SERVICE);
<ide> final List<ActivityManager.RunningServiceInfo> services =
<ide> activityManager.getRunningServices(maxServices);
<ide> boolean isServiceRunning = false;
<ide> return isServiceRunning;
<ide> }
<ide>
<del> public void addConnectionLock(Object lockOwner) {
<del> connectionLocks.add(lockOwner);
<add> public final void addConnectionLock(final Object lockOwner) {
<add> mConnectionLocks.add(lockOwner);
<ide> checkConnectionNeeded();
<del> cancelDisconnectSheduler();
<del> }
<del>
<del> private void cancelDisconnectSheduler() {
<del> disconnectSheduler.cancel();
<del> disconnectSheduler.purge();
<del> disconnectSheduler = new Timer();
<add> cancelDisconnectScheduler();
<add> }
<add>
<add> private void cancelDisconnectScheduler() {
<add> mDisconnectScheduler.cancel();
<add> mDisconnectScheduler.purge();
<add> mDisconnectScheduler = new Timer();
<ide> }
<ide>
<ide> private void checkConnectionNeeded() {
<del> if (connectionLocks.size() > 0) {
<add> if (mConnectionLocks.isEmpty()) {
<add> disconnect();
<add> } else {
<ide> if (!oMPDAsyncHelper.isMonitorAlive()) {
<ide> oMPDAsyncHelper.startMonitor();
<ide> }
<del> if (!oMPDAsyncHelper.oMPD.isConnected() && (currentActivity == null
<del> || !currentActivity.getClass().equals(WifiConnectionSettings.class))) {
<add> if (!oMPDAsyncHelper.oMPD.isConnected() && (mCurrentActivity == null
<add> || !mCurrentActivity.getClass().equals(WifiConnectionSettings.class))) {
<ide> connect();
<ide> }
<del> } else {
<del> disconnect();
<del> }
<del> }
<del>
<del> public void connect() {
<del> if (!settingsHelper.updateSettings()) {
<add> }
<add> }
<add>
<add> public final void connect() {
<add> if (!mSettingsHelper.updateSettings()) {
<ide> // Absolutely no settings defined! Open Settings!
<del> if (currentActivity != null && !settingsShown) {
<del> currentActivity.startActivityForResult(new Intent(currentActivity,
<add> if (mCurrentActivity != null && !mSettingsShown) {
<add> mCurrentActivity.startActivityForResult(new Intent(mCurrentActivity,
<ide> WifiConnectionSettings.class), SETTINGS);
<del> settingsShown = true;
<del> }
<del> }
<del>
<del> if (currentActivity != null && !settingsHelper.warningShown() && !warningShown) {
<del> currentActivity.startActivity(new Intent(currentActivity, WarningActivity.class));
<del> warningShown = true;
<add> mSettingsShown = true;
<add> }
<add> }
<add>
<add> if (mCurrentActivity != null && !mSettingsHelper.warningShown() && !mWarningShown) {
<add> mCurrentActivity.startActivity(new Intent(mCurrentActivity, WarningActivity.class));
<add> mWarningShown = true;
<ide> }
<ide> connectMPD();
<ide> }
<ide>
<del> public synchronized void connectionFailed(String message) {
<del>
<del> if (ad != null && !(ad instanceof ProgressDialog) && ad.isShowing()) {
<add> @Override
<add> public final synchronized void connectionFailed(final String message) {
<add>
<add> if (mAlertDialog != null && !(mAlertDialog instanceof ProgressDialog) && mAlertDialog
<add> .isShowing()) {
<ide> return;
<ide> }
<ide>
<ide>
<ide> oMPDAsyncHelper.disconnect();
<ide>
<del> if (currentActivity == null) {
<del> return;
<del> }
<del>
<del> if (currentActivity != null && connectionLocks.size() > 0) {
<add> if (mCurrentActivity != null && !mConnectionLocks.isEmpty()) {
<ide> // are we in the settings activity?
<del> if (currentActivity.getClass() == SettingsActivity.class) {
<del> AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
<add> if (mCurrentActivity.getClass().equals(SettingsActivity.class)) {
<add> final AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
<ide> builder.setCancelable(false);
<ide> builder.setMessage(
<ide> getResources().getString(R.string.connectionFailedMessageSetting, message));
<ide> builder.setPositiveButton("OK", new OnClickListener() {
<del> public void onClick(DialogInterface arg0, int arg1) {
<add> @Override
<add> public void onClick(final DialogInterface dialog, final int which) {
<ide> }
<ide> });
<del> ad = builder.show();
<add> mAlertDialog = builder.show();
<ide> } else {
<del> AlertDialog.Builder builder = new AlertDialog.Builder(currentActivity);
<add> final AlertDialog.Builder builder = new AlertDialog.Builder(mCurrentActivity);
<ide> builder.setTitle(R.string.connectionFailed);
<ide> builder.setMessage(
<ide> getResources().getString(R.string.connectionFailedMessage, message));
<ide> builder.setCancelable(false);
<ide>
<del> DialogClickListener oDialogClickListener = new DialogClickListener();
<add> final OnClickListener oDialogClickListener = new DialogClickListener();
<ide> builder.setNegativeButton(R.string.quit, oDialogClickListener);
<ide> builder.setNeutralButton(R.string.settings, oDialogClickListener);
<ide> builder.setPositiveButton(R.string.retry, oDialogClickListener);
<ide>
<ide> try {
<del> ad = builder.show();
<del> } catch (BadTokenException e) {
<add> mAlertDialog = builder.show();
<add> } catch (final BadTokenException ignored) {
<ide> // Can't display it. Don't care.
<ide> }
<ide> }
<ide> }
<del>
<del> }
<del>
<del> public synchronized void connectionSucceeded(String message) {
<add> }
<add>
<add> @Override
<add> public final synchronized void connectionSucceeded(final String message) {
<ide> dismissAlertDialog();
<del> // checkMonitorNeeded();
<ide> }
<ide>
<ide> private void connectMPD() {
<ide> dismissAlertDialog();
<ide>
<ide> // show connecting to server dialog
<del> if (currentActivity != null) {
<del> ad = new ProgressDialog(currentActivity);
<del> ad.setTitle(R.string.connecting);
<del> ad.setMessage(getResources().getString(R.string.connectingToServer));
<del> ad.setCancelable(false);
<del> ad.setOnKeyListener(new OnKeyListener() {
<del> public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
<add> if (mCurrentActivity != null) {
<add> mAlertDialog = new ProgressDialog(mCurrentActivity);
<add> mAlertDialog.setTitle(R.string.connecting);
<add> mAlertDialog.setMessage(getResources().getString(R.string.connectingToServer));
<add> mAlertDialog.setCancelable(false);
<add> mAlertDialog.setOnKeyListener(new OnKeyListener() {
<add> @Override
<add> public boolean onKey(final DialogInterface dialog, final int keyCode,
<add> final KeyEvent event) {
<ide> // Handle all keys!
<ide> return true;
<ide> }
<ide> });
<ide> try {
<del> ad.show();
<del> } catch (BadTokenException e) {
<add> mAlertDialog.show();
<add> } catch (final BadTokenException ignored) {
<ide> // Can't display it. Don't care.
<ide> }
<ide> }
<ide>
<del> cancelDisconnectSheduler();
<add> cancelDisconnectScheduler();
<ide>
<ide> // really connect
<ide> oMPDAsyncHelper.connect();
<ide> }
<ide>
<del> public void disconnect() {
<del> cancelDisconnectSheduler();
<del> startDisconnectSheduler();
<add> final void disconnect() {
<add> cancelDisconnectScheduler();
<add> startDisconnectScheduler();
<ide> }
<ide>
<ide> private void dismissAlertDialog() {
<del> if (ad != null) {
<del> if (ad.isShowing()) {
<add> if (mAlertDialog != null) {
<add> if (mAlertDialog.isShowing()) {
<ide> try {
<del> ad.dismiss();
<del> } catch (IllegalArgumentException e) {
<add> mAlertDialog.dismiss();
<add> } catch (final IllegalArgumentException ignored) {
<ide> // We don't care, it has already been destroyed
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<del> public void init(Context context) {
<add> void init(final Context context) {
<ide> MPD.setApplicationContext(context);
<ide>
<ide> mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
<ide>
<del> StrictMode.VmPolicy vmpolicy = new StrictMode.VmPolicy.Builder().penaltyLog().build();
<del> StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
<add> final StrictMode.VmPolicy vmPolicy = new StrictMode.VmPolicy.Builder().penaltyLog().build();
<add> final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll()
<add> .build();
<ide> StrictMode.setThreadPolicy(policy);
<del> StrictMode.setVmPolicy(vmpolicy);
<add> StrictMode.setVmPolicy(vmPolicy);
<ide>
<ide> // Init the default preferences (meaning we won't have different defaults between code/xml)
<ide> PreferenceManager.setDefaultValues(this, R.xml.settings, false);
<ide> oMPDAsyncHelper = new MPDAsyncHelper();
<ide> oMPDAsyncHelper.addConnectionListener(this);
<ide>
<del> settingsHelper = new SettingsHelper(oMPDAsyncHelper);
<del>
<del> disconnectSheduler = new Timer();
<add> mSettingsHelper = new SettingsHelper(oMPDAsyncHelper);
<add>
<add> mDisconnectScheduler = new Timer();
<ide>
<ide> if (!mSharedPreferences.contains("albumTrackSort")) {
<ide> mSharedPreferences.edit().putBoolean("albumTrackSort", true).commit();
<ide> }
<ide> }
<ide>
<del> public boolean isInSimpleMode() {
<add> public final boolean isInSimpleMode() {
<ide> return mSharedPreferences.getBoolean("simpleMode", false);
<ide> }
<ide>
<del> public boolean isLightThemeSelected() {
<add> public final boolean isLightThemeSelected() {
<ide> return mSharedPreferences.getBoolean("lightTheme", false);
<ide> }
<ide>
<ide> return isServiceRunning(StreamingService.class);
<ide> }
<ide>
<del> public boolean isTabletUiEnabled() {
<add> public final boolean isTabletUiEnabled() {
<ide> return getResources().getBoolean(R.bool.isTablet)
<ide> && mSharedPreferences.getBoolean("tabletUI", true);
<ide> }
<ide>
<ide> @Override
<del> public void onCreate() {
<add> public final void onCreate() {
<ide> super.onCreate();
<del> instance = this;
<del> Log.d(MPDApplication.TAG, "onCreate Application");
<add> sInstance = this;
<add> Log.d(TAG, "onCreate Application");
<ide> init(this);
<ide> }
<ide>
<del> public void removeConnectionLock(Object lockOwner) {
<del> connectionLocks.remove(lockOwner);
<add> public final void removeConnectionLock(final Object lockOwner) {
<add> mConnectionLocks.remove(lockOwner);
<ide> checkConnectionNeeded();
<ide> }
<ide>
<del> public void setActivity(Object activity) {
<add> public final void setActivity(final Object activity) {
<ide> if (activity instanceof Activity) {
<del> currentActivity = (Activity) activity;
<add> mCurrentActivity = (Activity) activity;
<ide> }
<ide>
<ide> addConnectionLock(activity);
<ide> .apply();
<ide> }
<ide>
<del> private void startDisconnectSheduler() {
<del> disconnectSheduler.schedule(new TimerTask() {
<add> private void startDisconnectScheduler() {
<add> mDisconnectScheduler.schedule(new TimerTask() {
<ide> @Override
<ide> public void run() {
<ide> w(TAG, "Disconnecting (" + DISCONNECT_TIMER + " ms timeout)");
<ide>
<ide> }
<ide>
<del> public void terminateApplication() {
<del> this.currentActivity.finish();
<del> }
<del>
<del> public void unsetActivity(Object activity) {
<add> public final void unsetActivity(final Object activity) {
<ide> removeConnectionLock(activity);
<ide>
<del> if (currentActivity == activity) {
<del> currentActivity = null;
<del> }
<del> }
<del>
<del> class DialogClickListener implements OnClickListener {
<del>
<del> public void onClick(DialogInterface dialog, int which) {
<add> if (mCurrentActivity != null && mCurrentActivity.equals(activity)) {
<add> mCurrentActivity = null;
<add> }
<add> }
<add>
<add> private class DialogClickListener implements OnClickListener {
<add>
<add> @Override
<add> public final void onClick(final DialogInterface dialog, final int which) {
<ide> switch (which) {
<del> case AlertDialog.BUTTON_NEUTRAL:
<add> case DialogInterface.BUTTON_NEUTRAL:
<add> final Intent intent =
<add> new Intent(mCurrentActivity, WifiConnectionSettings.class);
<ide> // Show Settings
<del> currentActivity.startActivityForResult(new Intent(currentActivity,
<del> WifiConnectionSettings.class), SETTINGS);
<add> mCurrentActivity.startActivityForResult(intent, SETTINGS);
<ide> break;
<del> case AlertDialog.BUTTON_NEGATIVE:
<del> currentActivity.finish();
<add> case DialogInterface.BUTTON_NEGATIVE:
<add> mCurrentActivity.finish();
<ide> break;
<del> case AlertDialog.BUTTON_POSITIVE:
<add> case DialogInterface.BUTTON_POSITIVE:
<ide> connectMPD();
<ide> break;
<del>
<add> default:
<add> break;
<ide> }
<ide> }
<ide> } |
|
Java | mit | e7a5706a57596a613b353a58f8c7c7fc3722bf5b | 0 | benjimarshall/anticake,benjimarshall/anticake | package anticake;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class AntiCake {
public static void main(String args[]) {
File homedir = new File("./");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(homedir.list()));
for (int x = 0; x < names.size(); x++) {
if (names.get(x).startsWith("Cake")) {
(new File("./" + names.get(x))).delete();
}
}
}
}
| anticake/AntiCake.java | package anticake;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public class AntiCake {
public static void main(String args[]) {
File homedir = new File("./");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(homedir.list()));
for (int x = 0; x < names.size(); x++) {
if (names.get(x).startsWith("Cake")) {
(new File("./" + names.get(x))).delete();
}
}
}
} | Newline Added | anticake/AntiCake.java | Newline Added | ||
Java | mit | 4fd0bb03daa85ceef8f2be4d555ce8afbe3127d6 | 0 | Randores/Randores2 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 [email protected]
* Copyright (c) 2017 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.gmail.socraticphoenix.randores.mod.component;
import com.gmail.socraticphoenix.randores.translations.Keys;
import net.minecraft.client.resources.I18n;
public enum CraftableType {
AXE(Keys.AXE, false, true, true, false, true, true),
HOE(Keys.HOE, false, true, true, false, true, false),
PICKAXE(Keys.PICKAXE, false, true, true, false, true, true),
SHOVEL(Keys.SHOVEL, false, true, true, false, true, true),
HELMET(Keys.HELMET, false, true, true, true, false, false),
CHESTPLATE(Keys.CHESTPLATE, false, true, true, true, false, false),
LEGGINGS(Keys.LEGGINGS, false, true, true, true, false, false),
BOOTS(Keys.BOOTS, false, true, true, true, false, false),
SWORD(Keys.SWORD, false, true, true, false, true, false),
BATTLEAXE(Keys.BATTLEAXE, false, true, true, false, true, true),
SLEDGEHAMMER(Keys.SLEDGEHAMMER, false, true, true, false, true, false),
BOW(Keys.BOW, false, true, true, false, false, false),
STICK(Keys.STICK, false, false, false, false, false, false),
BRICKS(Keys.BRICKS, true, false, false, false, false, false),
TORCH(Keys.TORCH, true, false, false, false, false, false);
private String name;
private boolean block;
private boolean enchant;
private boolean durable;
private boolean armor;
private boolean damage;
private boolean tool;
CraftableType(String name, boolean block, boolean enchant, boolean durable, boolean armor, boolean damage, boolean tool) {
this.name = name;
this.enchant = enchant;
this.durable = durable;
this.armor = armor;
this.damage = damage;
this.tool = tool;
this.block = block;
}
public boolean isTool() {
return this.tool;
}
public boolean isArmor() {
return this.armor;
}
public boolean isDamage() {
return this.damage;
}
public boolean isEnchant() {
return this.enchant;
}
public boolean isDurable() {
return this.durable;
}
public boolean isBlock() {
return this.block;
}
public String getName() {
return this.name;
}
public String getLocalName() {
return I18n.format(this.getName());
}
} | src/main/java/com/gmail/socraticphoenix/randores/mod/component/CraftableType.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 [email protected]
* Copyright (c) 2017 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.gmail.socraticphoenix.randores.mod.component;
import com.gmail.socraticphoenix.randores.translations.Keys;
import net.minecraft.client.resources.I18n;
public enum CraftableType {
AXE(Keys.AXE, false, true, true, false, true, true),
HOE(Keys.HOE, false, true, true, false, true, false),
PICKAXE(Keys.PICKAXE, false, true, true, false, true, true),
SHOVEL(Keys.SHOVEL, false, true, true, false, true, true),
SWORD(Keys.SWORD, false, true, true, false, true, false),
STICK(Keys.STICK, false, false, false, false, false, false),
BOOTS(Keys.BOOTS, false, true, true, true, false, false),
CHESTPLATE(Keys.CHESTPLATE, false, true, true, true, false, false),
HELMET(Keys.HELMET, false, true, true, true, false, false),
LEGGINGS(Keys.LEGGINGS, false, true, true, true, false, false),
BATTLEAXE(Keys.BATTLEAXE, false, true, true, false, true, true),
SLEDGEHAMMER(Keys.SLEDGEHAMMER, false, true, true, false, true, false),
BOW(Keys.BOW, false, true, true, false, false, false),
BRICKS(Keys.BRICKS, true, false, false, false, false, false),
TORCH(Keys.TORCH, true, false, false, false, false, false);
private String name;
private boolean block;
private boolean enchant;
private boolean durable;
private boolean armor;
private boolean damage;
private boolean tool;
CraftableType(String name, boolean block, boolean enchant, boolean durable, boolean armor, boolean damage, boolean tool) {
this.name = name;
this.enchant = enchant;
this.durable = durable;
this.armor = armor;
this.damage = damage;
this.tool = tool;
this.block = block;
}
public boolean isTool() {
return this.tool;
}
public boolean isArmor() {
return this.armor;
}
public boolean isDamage() {
return this.damage;
}
public boolean isEnchant() {
return this.enchant;
}
public boolean isDurable() {
return this.durable;
}
public boolean isBlock() {
return this.block;
}
public String getName() {
return this.name;
}
public String getLocalName() {
return I18n.format(this.getName());
}
} | re-order craftables
| src/main/java/com/gmail/socraticphoenix/randores/mod/component/CraftableType.java | re-order craftables | <ide><path>rc/main/java/com/gmail/socraticphoenix/randores/mod/component/CraftableType.java
<ide> HOE(Keys.HOE, false, true, true, false, true, false),
<ide> PICKAXE(Keys.PICKAXE, false, true, true, false, true, true),
<ide> SHOVEL(Keys.SHOVEL, false, true, true, false, true, true),
<add> HELMET(Keys.HELMET, false, true, true, true, false, false),
<add> CHESTPLATE(Keys.CHESTPLATE, false, true, true, true, false, false),
<add> LEGGINGS(Keys.LEGGINGS, false, true, true, true, false, false),
<add> BOOTS(Keys.BOOTS, false, true, true, true, false, false),
<ide> SWORD(Keys.SWORD, false, true, true, false, true, false),
<del> STICK(Keys.STICK, false, false, false, false, false, false),
<del> BOOTS(Keys.BOOTS, false, true, true, true, false, false),
<del> CHESTPLATE(Keys.CHESTPLATE, false, true, true, true, false, false),
<del> HELMET(Keys.HELMET, false, true, true, true, false, false),
<del> LEGGINGS(Keys.LEGGINGS, false, true, true, true, false, false),
<ide> BATTLEAXE(Keys.BATTLEAXE, false, true, true, false, true, true),
<ide> SLEDGEHAMMER(Keys.SLEDGEHAMMER, false, true, true, false, true, false),
<ide> BOW(Keys.BOW, false, true, true, false, false, false),
<add> STICK(Keys.STICK, false, false, false, false, false, false),
<ide> BRICKS(Keys.BRICKS, true, false, false, false, false, false),
<ide> TORCH(Keys.TORCH, true, false, false, false, false, false);
<ide> |
|
Java | apache-2.0 | ec816350a31e58ce4f24ff8f604aff1ee8ede822 | 0 | etnetera/jmeter,max3163/jmeter,ra0077/jmeter,ubikloadpack/jmeter,vherilier/jmeter,max3163/jmeter,max3163/jmeter,ubikloadpack/jmeter,vherilier/jmeter,vherilier/jmeter,max3163/jmeter,ra0077/jmeter,ra0077/jmeter,ra0077/jmeter,etnetera/jmeter,ubikloadpack/jmeter,ubikloadpack/jmeter,etnetera/jmeter,etnetera/jmeter,vherilier/jmeter,etnetera/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.visualizers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import org.apache.jmeter.gui.util.FileDialoger;
import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
import org.apache.jmeter.samplers.Clearable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.save.CSVSaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.Calculator;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.visualizers.gui.AbstractVisualizer;
import org.apache.jorphan.gui.NumberRenderer;
import org.apache.jorphan.gui.ObjectTableModel;
import org.apache.jorphan.gui.RateRenderer;
import org.apache.jorphan.gui.RendererUtils;
import org.apache.jorphan.reflect.Functor;
import org.apache.jorphan.util.JOrphanUtils;
/**
* Simpler (lower memory) version of Aggregate Report (StatVisualizer).
* Excludes the Median and 90% columns, which are expensive in memory terms
*/
public class SummaryReport extends AbstractVisualizer implements Clearable, ActionListener {
private static final long serialVersionUID = 240L;
private static final String USE_GROUP_NAME = "useGroupName"; //$NON-NLS-1$
private static final String SAVE_HEADERS = "saveHeaders"; //$NON-NLS-1$
private static final String[] COLUMNS = {
"sampler_label", //$NON-NLS-1$
"aggregate_report_count", //$NON-NLS-1$
"average", //$NON-NLS-1$
"aggregate_report_min", //$NON-NLS-1$
"aggregate_report_max", //$NON-NLS-1$
"aggregate_report_stddev", //$NON-NLS-1$
"aggregate_report_error%", //$NON-NLS-1$
"aggregate_report_rate", //$NON-NLS-1$
"aggregate_report_bandwidth", //$NON-NLS-1$
"aggregate_report_sent_bytes_per_sec", //$NON-NLS-1$
"average_bytes", //$NON-NLS-1$
};
private final String TOTAL_ROW_LABEL
= JMeterUtils.getResString("aggregate_report_total_label"); //$NON-NLS-1$
private JTable myJTable;
private JScrollPane myScrollPane;
private final JButton saveTable =
new JButton(JMeterUtils.getResString("aggregate_graph_save_table")); //$NON-NLS-1$
private final JCheckBox saveHeaders = // should header be saved with the data?
new JCheckBox(JMeterUtils.getResString("aggregate_graph_save_table_header"),true); //$NON-NLS-1$
private final JCheckBox useGroupName =
new JCheckBox(JMeterUtils.getResString("aggregate_graph_use_group_name")); //$NON-NLS-1$
private transient ObjectTableModel model;
/**
* Lock used to protect tableRows update + model update
*/
private final transient Object lock = new Object();
private final Map<String, Calculator> tableRows = new ConcurrentHashMap<>();
// Column renderers
private static final TableCellRenderer[] RENDERERS =
new TableCellRenderer[]{
null, // Label
null, // count
null, // Mean
null, // Min
null, // Max
new NumberRenderer("#0.00"), // Std Dev. //$NON-NLS-1$
new NumberRenderer("#0.00%"), // Error %age //$NON-NLS-1$
new RateRenderer("#.0"), // Throughput //$NON-NLS-1$
new NumberRenderer("#0.00"), // kB/sec //$NON-NLS-1$
new NumberRenderer("#0.00"), // sent kB/sec //$NON-NLS-1$
new NumberRenderer("#.0"), // avg. pageSize //$NON-NLS-1$
};
// Column formats
static final Format[] FORMATS =
new Format[]{
null, // Label
null, // count
null, // Mean
null, // Min
null, // Max
new DecimalFormat("#0.00"), // Std Dev. //$NON-NLS-1$
new DecimalFormat("#0.000%"), // Error %age //$NON-NLS-1$
new DecimalFormat("#.00000"), // Throughput //$NON-NLS-1$
new DecimalFormat("#0.00"), // kB/sec //$NON-NLS-1$
new DecimalFormat("#0.00"), // sent kB/sec //$NON-NLS-1$
new DecimalFormat("#.0"), // avg. pageSize //$NON-NLS-1$
};
public SummaryReport() {
super();
model = new ObjectTableModel(COLUMNS,
Calculator.class,// All rows have this class
new Functor[] {
new Functor("getLabel"), //$NON-NLS-1$
new Functor("getCount"), //$NON-NLS-1$
new Functor("getMeanAsNumber"), //$NON-NLS-1$
new Functor("getMin"), //$NON-NLS-1$
new Functor("getMax"), //$NON-NLS-1$
new Functor("getStandardDeviation"), //$NON-NLS-1$
new Functor("getErrorPercentage"), //$NON-NLS-1$
new Functor("getRate"), //$NON-NLS-1$
new Functor("getKBPerSecond"), //$NON-NLS-1$
new Functor("getSentKBPerSecond"), //$NON-NLS-1$
new Functor("getAvgPageBytes"), //$NON-NLS-1$
},
new Functor[] { null, null, null, null, null, null, null, null , null, null, null },
new Class[] { String.class, Long.class, Long.class, Long.class, Long.class,
String.class, String.class, String.class, String.class, String.class, String.class });
clearData();
init();
}
/**
* @return <code>true</code> if all functors can be found
* @deprecated - only for use in testing
* */
@Deprecated
public static boolean testFunctors(){
SummaryReport instance = new SummaryReport();
return instance.model.checkFunctors(null,instance.getClass());
}
@Override
public String getLabelResource() {
return "summary_report"; //$NON-NLS-1$
}
@Override
public void add(final SampleResult res) {
final String sampleLabel = res.getSampleLabel(useGroupName.isSelected());
JMeterUtils.runSafe(false, new Runnable() {
@Override
public void run() {
Calculator row = null;
synchronized (lock) {
row = tableRows.get(sampleLabel);
if (row == null) {
row = new Calculator(sampleLabel);
tableRows.put(row.getLabel(), row);
model.insertRow(row, model.getRowCount() - 1);
}
}
/*
* Synch is needed because multiple threads can update the counts.
*/
synchronized(row) {
row.addSample(res);
}
Calculator tot = tableRows.get(TOTAL_ROW_LABEL);
synchronized(tot) {
tot.addSample(res);
}
model.fireTableDataChanged();
}
});
}
/**
* Clears this visualizer and its model, and forces a repaint of the table.
*/
@Override
public void clearData() {
//Synch is needed because a clear can occur while add occurs
synchronized (lock) {
model.clearData();
tableRows.clear();
tableRows.put(TOTAL_ROW_LABEL, new Calculator(TOTAL_ROW_LABEL));
model.addRow(tableRows.get(TOTAL_ROW_LABEL));
}
}
/**
* Main visualizer setup.
*/
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
this.setLayout(new BorderLayout());
// MAIN PANEL
JPanel mainPanel = new JPanel();
Border margin = new EmptyBorder(10, 10, 5, 10);
mainPanel.setBorder(margin);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(makeTitlePanel());
myJTable = new JTable(model);
JMeterUtils.applyHiDPI(myJTable);
myJTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
RendererUtils.applyRenderers(myJTable, RENDERERS);
myScrollPane = new JScrollPane(myJTable);
this.add(mainPanel, BorderLayout.NORTH);
this.add(myScrollPane, BorderLayout.CENTER);
saveTable.addActionListener(this);
JPanel opts = new JPanel();
opts.add(useGroupName, BorderLayout.WEST);
opts.add(saveTable, BorderLayout.CENTER);
opts.add(saveHeaders, BorderLayout.EAST);
this.add(opts,BorderLayout.SOUTH);
}
@Override
public void modifyTestElement(TestElement c) {
super.modifyTestElement(c);
c.setProperty(USE_GROUP_NAME, useGroupName.isSelected(), false);
c.setProperty(SAVE_HEADERS, saveHeaders.isSelected(), true);
}
@Override
public void configure(TestElement el) {
super.configure(el);
useGroupName.setSelected(el.getPropertyAsBoolean(USE_GROUP_NAME, false));
saveHeaders.setSelected(el.getPropertyAsBoolean(SAVE_HEADERS, true));
}
@Override
public void actionPerformed(ActionEvent ev) {
if (ev.getSource() == saveTable) {
JFileChooser chooser = FileDialoger.promptToSaveFile("summary.csv");//$NON-NLS-1$
if (chooser == null) {
return;
}
FileWriter writer = null;
try {
writer = new FileWriter(chooser.getSelectedFile());
CSVSaveService.saveCSVStats(StatGraphVisualizer.getAllTableData(model, FORMATS),writer,
saveHeaders.isSelected() ? StatGraphVisualizer.getLabels(COLUMNS) : null);
} catch (IOException e) {
JMeterUtils.reportErrorToUser(e.getMessage(), "Error saving data");
} finally {
JOrphanUtils.closeQuietly(writer);
}
}
}
}
| src/components/org/apache/jmeter/visualizers/SummaryReport.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.visualizers;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import org.apache.jmeter.gui.util.FileDialoger;
import org.apache.jmeter.gui.util.HeaderAsPropertyRenderer;
import org.apache.jmeter.samplers.Clearable;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.save.CSVSaveService;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.Calculator;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.visualizers.gui.AbstractVisualizer;
import org.apache.jorphan.gui.NumberRenderer;
import org.apache.jorphan.gui.ObjectTableModel;
import org.apache.jorphan.gui.RateRenderer;
import org.apache.jorphan.gui.RendererUtils;
import org.apache.jorphan.reflect.Functor;
import org.apache.jorphan.util.JOrphanUtils;
/**
* Simpler (lower memory) version of Aggregate Report (StatVisualizer).
* Excludes the Median and 90% columns, which are expensive in memory terms
*/
public class SummaryReport extends AbstractVisualizer implements Clearable, ActionListener {
private static final long serialVersionUID = 240L;
private static final String USE_GROUP_NAME = "useGroupName"; //$NON-NLS-1$
private static final String SAVE_HEADERS = "saveHeaders"; //$NON-NLS-1$
private static final String[] COLUMNS = {
"sampler_label", //$NON-NLS-1$
"aggregate_report_count", //$NON-NLS-1$
"average", //$NON-NLS-1$
"aggregate_report_min", //$NON-NLS-1$
"aggregate_report_max", //$NON-NLS-1$
"aggregate_report_stddev", //$NON-NLS-1$
"aggregate_report_error%", //$NON-NLS-1$
"aggregate_report_rate", //$NON-NLS-1$
"aggregate_report_bandwidth", //$NON-NLS-1$
"aggregate_report_sent_bytes_per_sec", //$NON-NLS-1$
"average_bytes", //$NON-NLS-1$
};
private final String TOTAL_ROW_LABEL
= JMeterUtils.getResString("aggregate_report_total_label"); //$NON-NLS-1$
private JTable myJTable;
private JScrollPane myScrollPane;
private final JButton saveTable =
new JButton(JMeterUtils.getResString("aggregate_graph_save_table")); //$NON-NLS-1$
private final JCheckBox saveHeaders = // should header be saved with the data?
new JCheckBox(JMeterUtils.getResString("aggregate_graph_save_table_header"),true); //$NON-NLS-1$
private final JCheckBox useGroupName =
new JCheckBox(JMeterUtils.getResString("aggregate_graph_use_group_name")); //$NON-NLS-1$
private transient ObjectTableModel model;
/**
* Lock used to protect tableRows update + model update
*/
private final transient Object lock = new Object();
private final Map<String, Calculator> tableRows = new ConcurrentHashMap<>();
// Column renderers
private static final TableCellRenderer[] RENDERERS =
new TableCellRenderer[]{
null, // Label
null, // count
null, // Mean
null, // Min
null, // Max
new NumberRenderer("#0.00"), // Std Dev. //$NON-NLS-1$
new NumberRenderer("#0.00%"), // Error %age //$NON-NLS-1$
new RateRenderer("#.0"), // Throughput //$NON-NLS-1$
new NumberRenderer("#0.00"), // kB/sec //$NON-NLS-1$
new NumberRenderer("#0.00"), // sent kB/sec //$NON-NLS-1$
new NumberRenderer("#.0"), // avg. pageSize //$NON-NLS-1$
};
// Column formats
static final Format[] FORMATS =
new Format[]{
null, // Label
null, // count
null, // Mean
null, // Min
null, // Max
new DecimalFormat("#0.00"), // Std Dev. //$NON-NLS-1$
new DecimalFormat("#0.000%"), // Error %age //$NON-NLS-1$
new DecimalFormat("#.00000"), // Throughput //$NON-NLS-1$
new DecimalFormat("#0.00"), // kB/sec //$NON-NLS-1$
new DecimalFormat("#0.00"), // sent kB/sec //$NON-NLS-1$
new DecimalFormat("#.0"), // avg. pageSize //$NON-NLS-1$
};
public SummaryReport() {
super();
model = new ObjectTableModel(COLUMNS,
Calculator.class,// All rows have this class
new Functor[] {
new Functor("getLabel"), //$NON-NLS-1$
new Functor("getCount"), //$NON-NLS-1$
new Functor("getMeanAsNumber"), //$NON-NLS-1$
new Functor("getMin"), //$NON-NLS-1$
new Functor("getMax"), //$NON-NLS-1$
new Functor("getStandardDeviation"), //$NON-NLS-1$
new Functor("getErrorPercentage"), //$NON-NLS-1$
new Functor("getRate"), //$NON-NLS-1$
new Functor("getKBPerSecond"), //$NON-NLS-1$
new Functor("getSentKBPerSecond"), //$NON-NLS-1$
new Functor("getAvgPageBytes"), //$NON-NLS-1$
},
new Functor[] { null, null, null, null, null, null, null, null , null, null, null },
new Class[] { String.class, Long.class, Long.class, Long.class, Long.class,
String.class, String.class, String.class, String.class, String.class, String.class });
clearData();
init();
}
/**
* @return <code>true</code> iff all functors can be found
* @deprecated - only for use in testing
* */
@Deprecated
public static boolean testFunctors(){
SummaryReport instance = new SummaryReport();
return instance.model.checkFunctors(null,instance.getClass());
}
@Override
public String getLabelResource() {
return "summary_report"; //$NON-NLS-1$
}
@Override
public void add(final SampleResult res) {
final String sampleLabel = res.getSampleLabel(useGroupName.isSelected());
JMeterUtils.runSafe(false, new Runnable() {
@Override
public void run() {
Calculator row = null;
synchronized (lock) {
row = tableRows.get(sampleLabel);
if (row == null) {
row = new Calculator(sampleLabel);
tableRows.put(row.getLabel(), row);
model.insertRow(row, model.getRowCount() - 1);
}
}
/*
* Synch is needed because multiple threads can update the counts.
*/
synchronized(row) {
row.addSample(res);
}
Calculator tot = tableRows.get(TOTAL_ROW_LABEL);
synchronized(tot) {
tot.addSample(res);
}
model.fireTableDataChanged();
}
});
}
/**
* Clears this visualizer and its model, and forces a repaint of the table.
*/
@Override
public void clearData() {
//Synch is needed because a clear can occur while add occurs
synchronized (lock) {
model.clearData();
tableRows.clear();
tableRows.put(TOTAL_ROW_LABEL, new Calculator(TOTAL_ROW_LABEL));
model.addRow(tableRows.get(TOTAL_ROW_LABEL));
}
}
/**
* Main visualizer setup.
*/
private void init() { // WARNING: called from ctor so must not be overridden (i.e. must be private or final)
this.setLayout(new BorderLayout());
// MAIN PANEL
JPanel mainPanel = new JPanel();
Border margin = new EmptyBorder(10, 10, 5, 10);
mainPanel.setBorder(margin);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(makeTitlePanel());
myJTable = new JTable(model);
JMeterUtils.applyHiDPI(myJTable);
myJTable.getTableHeader().setDefaultRenderer(new HeaderAsPropertyRenderer());
myJTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
RendererUtils.applyRenderers(myJTable, RENDERERS);
myScrollPane = new JScrollPane(myJTable);
this.add(mainPanel, BorderLayout.NORTH);
this.add(myScrollPane, BorderLayout.CENTER);
saveTable.addActionListener(this);
JPanel opts = new JPanel();
opts.add(useGroupName, BorderLayout.WEST);
opts.add(saveTable, BorderLayout.CENTER);
opts.add(saveHeaders, BorderLayout.EAST);
this.add(opts,BorderLayout.SOUTH);
}
@Override
public void modifyTestElement(TestElement c) {
super.modifyTestElement(c);
c.setProperty(USE_GROUP_NAME, useGroupName.isSelected(), false);
c.setProperty(SAVE_HEADERS, saveHeaders.isSelected(), true);
}
@Override
public void configure(TestElement el) {
super.configure(el);
useGroupName.setSelected(el.getPropertyAsBoolean(USE_GROUP_NAME, false));
saveHeaders.setSelected(el.getPropertyAsBoolean(SAVE_HEADERS, true));
}
@Override
public void actionPerformed(ActionEvent ev) {
if (ev.getSource() == saveTable) {
JFileChooser chooser = FileDialoger.promptToSaveFile("summary.csv");//$NON-NLS-1$
if (chooser == null) {
return;
}
FileWriter writer = null;
try {
writer = new FileWriter(chooser.getSelectedFile());
CSVSaveService.saveCSVStats(StatGraphVisualizer.getAllTableData(model, FORMATS),writer,
saveHeaders.isSelected() ? StatGraphVisualizer.getLabels(COLUMNS) : null);
} catch (IOException e) {
JMeterUtils.reportErrorToUser(e.getMessage(), "Error saving data");
} finally {
JOrphanUtils.closeQuietly(writer);
}
}
}
}
| typo
git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1771648 13f79535-47bb-0310-9956-ffa450edef68
| src/components/org/apache/jmeter/visualizers/SummaryReport.java | typo | <ide><path>rc/components/org/apache/jmeter/visualizers/SummaryReport.java
<ide> }
<ide>
<ide> /**
<del> * @return <code>true</code> iff all functors can be found
<add> * @return <code>true</code> if all functors can be found
<ide> * @deprecated - only for use in testing
<ide> * */
<ide> @Deprecated |
|
Java | mit | faca328c2be0628457aeeb0243b3b0645f684a22 | 0 | douggie/XChange | package org.knowm.xchange.bitstamp;
import static java.math.BigDecimal.ZERO;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.knowm.xchange.bitstamp.dto.account.BitstampBalance;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampOrderBook;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampTicker;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampTransaction;
import org.knowm.xchange.bitstamp.dto.trade.BitstampUserTransaction;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.utils.DateUtils;
/**
* Various adapters for converting from Bitstamp DTOs to XChange DTOs
*/
public final class BitstampAdapters {
/**
* private Constructor
*/
private BitstampAdapters() {
}
/**
* Adapts a BitstampBalance to an AccountInfo
*
* @param bitstampBalance The Bitstamp balance
* @param userName The user name
* @return The account info
*/
public static AccountInfo adaptAccountInfo(BitstampBalance bitstampBalance, String userName) {
// Adapt to XChange DTOs
List<Balance> balances = new ArrayList<>();
for (org.knowm.xchange.bitstamp.dto.account.BitstampBalance.Balance b : bitstampBalance.getBalances()) {
Balance xchangeBalance = new Balance(new Currency(b.getCurrency().toUpperCase()), b.getBalance(), b.getAvailable(),
b.getReserved(), ZERO, ZERO, b.getBalance().subtract(b.getAvailable()).subtract(b.getReserved()), ZERO);
balances.add(xchangeBalance);
}
return new AccountInfo(userName, bitstampBalance.getFee(), new Wallet(balances));
}
/**
* Adapts a org.knowm.xchange.bitstamp.api.model.OrderBook to a OrderBook Object
*
* @param currencyPair (e.g. BTC/USD)
* @param timeScale polled order books provide a timestamp in seconds, stream in ms
* @return The XChange OrderBook
*/
public static OrderBook adaptOrderBook(BitstampOrderBook bitstampOrderBook, CurrencyPair currencyPair) {
List<LimitOrder> asks = createOrders(currencyPair, Order.OrderType.ASK, bitstampOrderBook.getAsks());
List<LimitOrder> bids = createOrders(currencyPair, Order.OrderType.BID, bitstampOrderBook.getBids());
return new OrderBook(bitstampOrderBook.getTimestamp(), asks, bids);
}
public static List<LimitOrder> createOrders(CurrencyPair currencyPair, Order.OrderType orderType, List<List<BigDecimal>> orders) {
List<LimitOrder> limitOrders = new ArrayList<>();
for (List<BigDecimal> ask : orders) {
checkArgument(ask.size() == 2, "Expected a pair (price, amount) but got {0} elements.", ask.size());
limitOrders.add(createOrder(currencyPair, ask, orderType));
}
return limitOrders;
}
public static LimitOrder createOrder(CurrencyPair currencyPair, List<BigDecimal> priceAndAmount, Order.OrderType orderType) {
return new LimitOrder(orderType, priceAndAmount.get(1), currencyPair, "", null, priceAndAmount.get(0));
}
public static void checkArgument(boolean argument, String msgPattern, Object... msgArgs) {
if (!argument) {
throw new IllegalArgumentException(MessageFormat.format(msgPattern, msgArgs));
}
}
/**
* Adapts a Transaction[] to a Trades Object
*
* @param transactions The Bitstamp transactions
* @param currencyPair (e.g. BTC/USD)
* @return The XChange Trades
*/
public static Trades adaptTrades(BitstampTransaction[] transactions, CurrencyPair currencyPair) {
List<Trade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitstampTransaction tx : transactions) {
final long tradeId = tx.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
trades.add(adaptTrade(tx, currencyPair, 1000));
}
return new Trades(trades, lastTradeId, TradeSortType.SortByID);
}
/**
* Adapts a Transaction to a Trade Object
*
* @param tx The Bitstamp transaction
* @param currencyPair (e.g. BTC/USD)
* @param timeScale polled order books provide a timestamp in seconds, stream in ms
* @return The XChange Trade
*/
public static Trade adaptTrade(BitstampTransaction tx, CurrencyPair currencyPair, int timeScale) {
OrderType orderType = tx.getType() == 0 ? OrderType.BID : OrderType.ASK;
final String tradeId = String.valueOf(tx.getTid());
Date date = DateUtils.fromMillisUtc(tx.getDate() * timeScale);// polled order books provide a timestamp in seconds, stream in ms
return new Trade(orderType, tx.getAmount(), currencyPair, tx.getPrice(), date, tradeId);
}
/**
* Adapts a BitstampTicker to a Ticker Object
*
* @param bitstampTicker The exchange specific ticker
* @param currencyPair (e.g. BTC/USD)
* @return The ticker
*/
public static Ticker adaptTicker(BitstampTicker bitstampTicker, CurrencyPair currencyPair) {
BigDecimal last = bitstampTicker.getLast();
BigDecimal bid = bitstampTicker.getBid();
BigDecimal ask = bitstampTicker.getAsk();
BigDecimal high = bitstampTicker.getHigh();
BigDecimal low = bitstampTicker.getLow();
BigDecimal vwap = bitstampTicker.getVwap();
BigDecimal volume = bitstampTicker.getVolume();
Date timestamp = new Date(bitstampTicker.getTimestamp() * 1000L);
return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).vwap(vwap).volume(volume)
.timestamp(timestamp).build();
}
/**
* Adapt the user's trades
*
* @param bitstampUserTransactions
* @return
*/
public static UserTrades adaptTradeHistory(BitstampUserTransaction[] bitstampUserTransactions) {
List<UserTrade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitstampUserTransaction t : bitstampUserTransactions) {
if (!t.getType().equals(BitstampUserTransaction.TransactionType.trade)) { // skip account deposits and withdrawals.
continue;
}
final OrderType orderType;
if (t.getCounterAmount().doubleValue() == 0.0){
orderType = t.getBaseAmount().doubleValue() < 0.0 ? OrderType.ASK : OrderType.BID;
} else {
orderType = t.getCounterAmount().doubleValue() > 0.0 ? OrderType.ASK : OrderType.BID;
}
long tradeId = t.getId();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
final CurrencyPair pair = new CurrencyPair(t.getBaseCurrency().toUpperCase(), t.getCounterCurrency().toUpperCase());
UserTrade trade = new UserTrade(orderType, t.getBaseAmount().abs(), pair, t.getPrice().abs(), t.getDatetime()
, Long.toString(tradeId), Long.toString(t.getOrderId()), t.getFee(), new Currency(t.getFeeCurrency().toUpperCase()));
trades.add(trade);
}
return new UserTrades(trades, lastTradeId, TradeSortType.SortByID);
}
}
| xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAdapters.java | package org.knowm.xchange.bitstamp;
import static java.math.BigDecimal.ZERO;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.knowm.xchange.bitstamp.dto.account.BitstampBalance;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampOrderBook;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampTicker;
import org.knowm.xchange.bitstamp.dto.marketdata.BitstampTransaction;
import org.knowm.xchange.bitstamp.dto.trade.BitstampUserTransaction;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.account.AccountInfo;
import org.knowm.xchange.dto.account.Balance;
import org.knowm.xchange.dto.account.Wallet;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.dto.marketdata.Trades;
import org.knowm.xchange.dto.marketdata.Trades.TradeSortType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.utils.DateUtils;
/**
* Various adapters for converting from Bitstamp DTOs to XChange DTOs
*/
public final class BitstampAdapters {
/**
* private Constructor
*/
private BitstampAdapters() {
}
/**
* Adapts a BitstampBalance to an AccountInfo
*
* @param bitstampBalance The Bitstamp balance
* @param userName The user name
* @return The account info
*/
public static AccountInfo adaptAccountInfo(BitstampBalance bitstampBalance, String userName) {
// Adapt to XChange DTOs
List<Balance> balances = new ArrayList<>();
for (org.knowm.xchange.bitstamp.dto.account.BitstampBalance.Balance b : bitstampBalance.getBalances()) {
Balance xchangeBalance = new Balance(new Currency(b.getCurrency().toUpperCase()), b.getBalance(), b.getAvailable(),
b.getReserved(), ZERO, ZERO, b.getBalance().subtract(b.getAvailable()).subtract(b.getReserved()), ZERO);
balances.add(xchangeBalance);
}
return new AccountInfo(userName, bitstampBalance.getFee(), new Wallet(balances));
}
/**
* Adapts a org.knowm.xchange.bitstamp.api.model.OrderBook to a OrderBook Object
*
* @param currencyPair (e.g. BTC/USD)
* @param timeScale polled order books provide a timestamp in seconds, stream in ms
* @return The XChange OrderBook
*/
public static OrderBook adaptOrderBook(BitstampOrderBook bitstampOrderBook, CurrencyPair currencyPair) {
List<LimitOrder> asks = createOrders(currencyPair, Order.OrderType.ASK, bitstampOrderBook.getAsks());
List<LimitOrder> bids = createOrders(currencyPair, Order.OrderType.BID, bitstampOrderBook.getBids());
return new OrderBook(bitstampOrderBook.getTimestamp(), asks, bids);
}
public static List<LimitOrder> createOrders(CurrencyPair currencyPair, Order.OrderType orderType, List<List<BigDecimal>> orders) {
List<LimitOrder> limitOrders = new ArrayList<>();
for (List<BigDecimal> ask : orders) {
checkArgument(ask.size() == 2, "Expected a pair (price, amount) but got {0} elements.", ask.size());
limitOrders.add(createOrder(currencyPair, ask, orderType));
}
return limitOrders;
}
public static LimitOrder createOrder(CurrencyPair currencyPair, List<BigDecimal> priceAndAmount, Order.OrderType orderType) {
return new LimitOrder(orderType, priceAndAmount.get(1), currencyPair, "", null, priceAndAmount.get(0));
}
public static void checkArgument(boolean argument, String msgPattern, Object... msgArgs) {
if (!argument) {
throw new IllegalArgumentException(MessageFormat.format(msgPattern, msgArgs));
}
}
/**
* Adapts a Transaction[] to a Trades Object
*
* @param transactions The Bitstamp transactions
* @param currencyPair (e.g. BTC/USD)
* @return The XChange Trades
*/
public static Trades adaptTrades(BitstampTransaction[] transactions, CurrencyPair currencyPair) {
List<Trade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitstampTransaction tx : transactions) {
final long tradeId = tx.getTid();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
trades.add(adaptTrade(tx, currencyPair, 1000));
}
return new Trades(trades, lastTradeId, TradeSortType.SortByID);
}
/**
* Adapts a Transaction to a Trade Object
*
* @param tx The Bitstamp transaction
* @param currencyPair (e.g. BTC/USD)
* @param timeScale polled order books provide a timestamp in seconds, stream in ms
* @return The XChange Trade
*/
public static Trade adaptTrade(BitstampTransaction tx, CurrencyPair currencyPair, int timeScale) {
OrderType orderType = tx.getType() == 0 ? OrderType.BID : OrderType.ASK;
final String tradeId = String.valueOf(tx.getTid());
Date date = DateUtils.fromMillisUtc(tx.getDate() * timeScale);// polled order books provide a timestamp in seconds, stream in ms
return new Trade(orderType, tx.getAmount(), currencyPair, tx.getPrice(), date, tradeId);
}
/**
* Adapts a BitstampTicker to a Ticker Object
*
* @param bitstampTicker The exchange specific ticker
* @param currencyPair (e.g. BTC/USD)
* @return The ticker
*/
public static Ticker adaptTicker(BitstampTicker bitstampTicker, CurrencyPair currencyPair) {
BigDecimal last = bitstampTicker.getLast();
BigDecimal bid = bitstampTicker.getBid();
BigDecimal ask = bitstampTicker.getAsk();
BigDecimal high = bitstampTicker.getHigh();
BigDecimal low = bitstampTicker.getLow();
BigDecimal vwap = bitstampTicker.getVwap();
BigDecimal volume = bitstampTicker.getVolume();
Date timestamp = new Date(bitstampTicker.getTimestamp() * 1000L);
return new Ticker.Builder().currencyPair(currencyPair).last(last).bid(bid).ask(ask).high(high).low(low).vwap(vwap).volume(volume)
.timestamp(timestamp).build();
}
/**
* Adapt the user's trades
*
* @param bitstampUserTransactions
* @return
*/
public static UserTrades adaptTradeHistory(BitstampUserTransaction[] bitstampUserTransactions) {
List<UserTrade> trades = new ArrayList<>();
long lastTradeId = 0;
for (BitstampUserTransaction t : bitstampUserTransactions) {
if (!t.getType().equals(BitstampUserTransaction.TransactionType.trade)) { // skip account deposits and withdrawals.
continue;
}
OrderType orderType = t.getCounterAmount().doubleValue() > 0.0 ? OrderType.ASK : OrderType.BID;
long tradeId = t.getId();
if (tradeId > lastTradeId) {
lastTradeId = tradeId;
}
final CurrencyPair pair = new CurrencyPair(t.getBaseCurrency().toUpperCase(), t.getCounterCurrency().toUpperCase());
UserTrade trade = new UserTrade(orderType, t.getBaseAmount().abs(), pair, t.getPrice().abs(), t.getDatetime()
, Long.toString(tradeId), Long.toString(t.getOrderId()), t.getFee(), new Currency(t.getFeeCurrency().toUpperCase()));
trades.add(trade);
}
return new UserTrades(trades, lastTradeId, TradeSortType.SortByID);
}
}
| #1512 - [Bitstamp] Order Type is wrong when there is a very small transaction fill.
| xchange-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAdapters.java | #1512 - [Bitstamp] Order Type is wrong when there is a very small transaction fill. | <ide><path>change-bitstamp/src/main/java/org/knowm/xchange/bitstamp/BitstampAdapters.java
<ide> if (!t.getType().equals(BitstampUserTransaction.TransactionType.trade)) { // skip account deposits and withdrawals.
<ide> continue;
<ide> }
<del> OrderType orderType = t.getCounterAmount().doubleValue() > 0.0 ? OrderType.ASK : OrderType.BID;
<add> final OrderType orderType;
<add> if (t.getCounterAmount().doubleValue() == 0.0){
<add> orderType = t.getBaseAmount().doubleValue() < 0.0 ? OrderType.ASK : OrderType.BID;
<add> } else {
<add> orderType = t.getCounterAmount().doubleValue() > 0.0 ? OrderType.ASK : OrderType.BID;
<add> }
<add>
<ide> long tradeId = t.getId();
<ide> if (tradeId > lastTradeId) {
<ide> lastTradeId = tradeId; |
|
Java | apache-2.0 | 4760a5542178173e5d2b031e803da42847da6643 | 0 | cuba-platform/cuba,dimone-kun/cuba,dimone-kun/cuba,cuba-platform/cuba,cuba-platform/cuba,dimone-kun/cuba | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.gui.components;
/**
*/
public interface HtmlBoxLayout extends Component.Container, Component.BelongToFrame {
String NAME = "htmlBox";
/**
* Return filename of the related HTML template
*/
String getTemplateName();
/**
* Set filename of the related HTML template inside theme/layouts directory
*/
void setTemplateName(String templateName);
} | modules/gui/src/com/haulmont/cuba/gui/components/HtmlBoxLayout.java | /*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.haulmont.cuba.gui.components;
/**
*/
public interface HtmlBoxLayout extends Component.Container, Component.BelongToFrame {
String NAME = "htmlBox";
String getTemplateName();
void setTemplateName(String templateName);
} | PL-6943 JavaDoc for HtmlLayout
| modules/gui/src/com/haulmont/cuba/gui/components/HtmlBoxLayout.java | PL-6943 JavaDoc for HtmlLayout | <ide><path>odules/gui/src/com/haulmont/cuba/gui/components/HtmlBoxLayout.java
<ide>
<ide> String NAME = "htmlBox";
<ide>
<add> /**
<add> * Return filename of the related HTML template
<add> */
<ide> String getTemplateName();
<add>
<add> /**
<add> * Set filename of the related HTML template inside theme/layouts directory
<add> */
<ide> void setTemplateName(String templateName);
<ide> } |
|
Java | apache-2.0 | 7eb64d19f2f269341134ad0b57afb231c7ffabe1 | 0 | Syncleus/Ferma,Syncleus/Ferma | /******************************************************************************
* *
* Copyright: (c) Syncleus, Inc. *
* *
* You may redistribute and modify this source code under the terms and *
* conditions of the Open Source Community License - Type C version 1.0 *
* or any later version as published by Syncleus, Inc. at www.syncleus.com. *
* There should be a copy of the license included with this file. If a copy *
* of the license is not included you are granted no right to distribute or *
* otherwise use this file except through a legal and valid license. You *
* should also contact Syncleus, Inc. at the information below if you cannot *
* find a license: *
* *
* Syncleus, Inc. *
* 2604 South 12th Street *
* Philadelphia, PA 19148 *
* *
******************************************************************************/
package com.syncleus.ferma.annotations;
import com.syncleus.ferma.*;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.ClassLoadingStrategy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.instrumentation.FieldAccessor;
import net.bytebuddy.modifier.FieldManifestation;
import net.bytebuddy.modifier.Visibility;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
public class AnnotationFrameFactory implements FrameFactory {
private final Map<Class<? extends Annotation>, MethodHandler> methodHandlers = new HashMap<>();
private final Map<Class, Class> constructedClassCache = new HashMap<>();
private final ReflectionCache reflectionCache;
public AnnotationFrameFactory(final ReflectionCache reflectionCache) {
this.reflectionCache = reflectionCache;
final PropertyMethodHandler propertyHandler = new PropertyMethodHandler();
methodHandlers.put(propertyHandler.getAnnotationType(), propertyHandler);
final InVertexMethodHandler inVertexHandler = new InVertexMethodHandler();
methodHandlers.put(inVertexHandler.getAnnotationType(), inVertexHandler);
final OutVertexMethodHandler outVertexHandler = new OutVertexMethodHandler();
methodHandlers.put(outVertexHandler.getAnnotationType(), outVertexHandler);
final AdjacencyMethodHandler adjacencyHandler = new AdjacencyMethodHandler();
methodHandlers.put(adjacencyHandler.getAnnotationType(), adjacencyHandler);
final IncidenceMethodHandler incidenceHandler = new IncidenceMethodHandler();
methodHandlers.put(incidenceHandler.getAnnotationType(), incidenceHandler);
}
@Override
public <T> T create(final Element element, final Class<T> kind) {
Class<? extends T> resolvedKind = kind;
if( isAbstract(resolvedKind) )
resolvedKind = constructClass(element, kind);
try {
final T object = resolvedKind.newInstance();
if (object instanceof CachesReflection)
((CachesReflection) object).setReflectionCache(this.reflectionCache);
return object;
} catch (final InstantiationException caught) {
throw new IllegalArgumentException("kind could not be instantiated", caught);
} catch (final IllegalAccessException caught) {
throw new IllegalArgumentException("kind could not be instantiated", caught);
}
}
private static boolean isAbstract(final Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
private static boolean isAbstract(final Method method) {
return Modifier.isAbstract(method.getModifiers());
}
private <E> Class<? extends E> constructClass(final Element element, final Class<E> clazz) {
Class constructedClass = constructedClassCache.get(clazz);
if(constructedClass != null )
return constructedClass;
DynamicType.Builder<? extends E> classBuilder;
if( clazz.isInterface() ) {
if( element instanceof Vertex)
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().withImplementing(clazz).subclass(AbstractVertexFrame.class);
else if( element instanceof Edge)
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().withImplementing(clazz).subclass(AbstractEdgeFrame.class);
else
throw new IllegalStateException("class is neither an Edge or a vertex!");
}
else {
if( element instanceof Vertex && ! VertexFrame.class.isAssignableFrom(clazz) )
throw new IllegalStateException(clazz.getName() + " Class is not a type of VertexFrame");
if( element instanceof Edge && ! EdgeFrame.class.isAssignableFrom(clazz) )
throw new IllegalStateException(clazz.getName() + " Class is not a type of EdgeFrame");
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(clazz);
}
classBuilder = classBuilder.defineField("reflectionCache", ReflectionCache.class, Visibility.PRIVATE, FieldManifestation.PLAIN).implement(CachesReflection.class).intercept(FieldAccessor.ofBeanProperty());
//try and construct any abstract methods that are left
for(final Method method : clazz.getMethods() ) {
if( isAbstract(method) ) {
annotation_loop:
for (final Annotation annotation : method.getAnnotations()) {
final MethodHandler handler = methodHandlers.get(annotation.annotationType());
if (handler != null) {
classBuilder = handler.processMethod(classBuilder, method, annotation);
break;
}
}
}
}
constructedClass = classBuilder.make().load(AnnotationFrameFactory.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
this.constructedClassCache.put(clazz, constructedClass);
return constructedClass;
}
}
| src/main/java/com/syncleus/ferma/annotations/AnnotationFrameFactory.java | /******************************************************************************
* *
* Copyright: (c) Syncleus, Inc. *
* *
* You may redistribute and modify this source code under the terms and *
* conditions of the Open Source Community License - Type C version 1.0 *
* or any later version as published by Syncleus, Inc. at www.syncleus.com. *
* There should be a copy of the license included with this file. If a copy *
* of the license is not included you are granted no right to distribute or *
* otherwise use this file except through a legal and valid license. You *
* should also contact Syncleus, Inc. at the information below if you cannot *
* find a license: *
* *
* Syncleus, Inc. *
* 2604 South 12th Street *
* Philadelphia, PA 19148 *
* *
******************************************************************************/
package com.syncleus.ferma.annotations;
import com.syncleus.ferma.*;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Element;
import com.tinkerpop.blueprints.Vertex;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.ClassLoadingStrategy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.instrumentation.FieldAccessor;
import net.bytebuddy.modifier.FieldManifestation;
import net.bytebuddy.modifier.Visibility;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
public class AnnotationFrameFactory implements FrameFactory {
private final Map<Class<? extends Annotation>, MethodHandler> methodHandlers = new HashMap<>();
private final Map<Class, Class> constructedClassCache = new HashMap<>();
private final ReflectionCache reflectionCache;
public AnnotationFrameFactory(final ReflectionCache reflectionCache) {
this.reflectionCache = reflectionCache;
final PropertyMethodHandler propertyHandler = new PropertyMethodHandler();
methodHandlers.put(propertyHandler.getAnnotationType(), propertyHandler);
final InVertexMethodHandler inVertexHandler = new InVertexMethodHandler();
methodHandlers.put(inVertexHandler.getAnnotationType(), inVertexHandler);
final OutVertexMethodHandler outVertexHandler = new OutVertexMethodHandler();
methodHandlers.put(outVertexHandler.getAnnotationType(), outVertexHandler);
final AdjacencyMethodHandler adjacencyHandler = new AdjacencyMethodHandler();
methodHandlers.put(adjacencyHandler.getAnnotationType(), adjacencyHandler);
final IncidenceMethodHandler incidenceHandler = new IncidenceMethodHandler();
methodHandlers.put(incidenceHandler.getAnnotationType(), incidenceHandler);
}
@Override
public <T> T create(final Element element, final Class<T> kind) {
Class<? extends T> resolvedKind = kind;
if( isAbstract(resolvedKind) )
resolvedKind = constructClass(element, kind);
try {
final T object = resolvedKind.newInstance();
if (object instanceof CachesReflection)
((CachesReflection) object).setReflectionCache(this.reflectionCache);
return object;
} catch (final InstantiationException caught) {
throw new IllegalArgumentException("kind could not be instantiated", caught);
} catch (final IllegalAccessException caught) {
throw new IllegalArgumentException("kind could not be instantiated", caught);
}
}
private static boolean isAbstract(final Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
private static boolean isAbstract(final Method method) {
return Modifier.isAbstract(method.getModifiers());
}
private <E> Class<? extends E> constructClass(final Element element, final Class<E> clazz) {
Class constructedClass = constructedClassCache.get(clazz);
if(constructedClass != null )
return constructedClass;
DynamicType.Builder<? extends E> classBuilder;
if( clazz.isInterface() ) {
if( element instanceof Vertex)
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().withImplementing(clazz).subclass(AbstractVertexFrame.class);
else if( element instanceof Edge)
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().withImplementing(clazz).subclass(AbstractEdgeFrame.class);
else
throw new IllegalStateException("class is neither an Edge or a vertex!");
}
else {
if( element instanceof Vertex && ! VertexFrame.class.isAssignableFrom(clazz) )
throw new IllegalStateException(clazz.getName() + " Class is not a type of VertexFrame");
if( element instanceof Edge && ! EdgeFrame.class.isAssignableFrom(clazz) )
throw new IllegalStateException(clazz.getName() + " Class is not a type of EdgeFrame");
classBuilder = (DynamicType.Builder<? extends E>) new ByteBuddy().subclass(clazz);
}
classBuilder = classBuilder.defineField("reflectionCache", ReflectionCache.class, Visibility.PRIVATE, FieldManifestation.PLAIN).implement(CachesReflection.class).intercept(FieldAccessor.ofBeanProperty());
//try and construct any abstract methods that are left
for(final Method method : clazz.getMethods() ) {
if( isAbstract(method) ) {
annotation_loop:
for (final Annotation annotation : method.getAnnotations()) {
final MethodHandler handler = methodHandlers.get(annotation.annotationType());
if (handler != null) {
classBuilder = handler.processMethod(classBuilder, method, annotation);
break annotation_loop;
}
}
}
}
constructedClass = classBuilder.make().load(AnnotationFrameFactory.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
this.constructedClassCache.put(clazz, constructedClass);
return constructedClass;
}
}
| Removed an unnecesary label on the break keyword.
Change-Id: I8657263ee408f03e7f69f7700d2af9316d42fa53
| src/main/java/com/syncleus/ferma/annotations/AnnotationFrameFactory.java | Removed an unnecesary label on the break keyword. | <ide><path>rc/main/java/com/syncleus/ferma/annotations/AnnotationFrameFactory.java
<ide> final MethodHandler handler = methodHandlers.get(annotation.annotationType());
<ide> if (handler != null) {
<ide> classBuilder = handler.processMethod(classBuilder, method, annotation);
<del> break annotation_loop;
<add> break;
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | e4031932edaea00b5ec06f6153aa7e02e8f0e74e | 0 | sreeramjayan/elasticsearch,ZTE-PaaS/elasticsearch,ZTE-PaaS/elasticsearch,ThiagoGarciaAlves/elasticsearch,trangvh/elasticsearch,MisterAndersen/elasticsearch,wenpos/elasticsearch,brandonkearby/elasticsearch,yanjunh/elasticsearch,shreejay/elasticsearch,elasticdog/elasticsearch,liweinan0423/elasticsearch,mohit/elasticsearch,gingerwizard/elasticsearch,lks21c/elasticsearch,jimczi/elasticsearch,strapdata/elassandra5-rc,yanjunh/elasticsearch,trangvh/elasticsearch,sreeramjayan/elasticsearch,clintongormley/elasticsearch,C-Bish/elasticsearch,a2lin/elasticsearch,rlugojr/elasticsearch,nomoa/elasticsearch,nilabhsagar/elasticsearch,pozhidaevak/elasticsearch,awislowski/elasticsearch,gfyoung/elasticsearch,zkidkid/elasticsearch,C-Bish/elasticsearch,pozhidaevak/elasticsearch,coding0011/elasticsearch,Stacey-Gammon/elasticsearch,rlugojr/elasticsearch,nazarewk/elasticsearch,gfyoung/elasticsearch,jprante/elasticsearch,rajanm/elasticsearch,scottsom/elasticsearch,GlenRSmith/elasticsearch,sneivandt/elasticsearch,kalimatas/elasticsearch,fred84/elasticsearch,MisterAndersen/elasticsearch,yynil/elasticsearch,girirajsharma/elasticsearch,nilabhsagar/elasticsearch,Stacey-Gammon/elasticsearch,a2lin/elasticsearch,jprante/elasticsearch,IanvsPoplicola/elasticsearch,nilabhsagar/elasticsearch,vroyer/elasticassandra,ThiagoGarciaAlves/elasticsearch,mortonsykes/elasticsearch,coding0011/elasticsearch,a2lin/elasticsearch,qwerty4030/elasticsearch,sreeramjayan/elasticsearch,masaruh/elasticsearch,nilabhsagar/elasticsearch,nknize/elasticsearch,henakamaMSFT/elasticsearch,dpursehouse/elasticsearch,nezirus/elasticsearch,myelin/elasticsearch,s1monw/elasticsearch,nazarewk/elasticsearch,winstonewert/elasticsearch,wenpos/elasticsearch,robin13/elasticsearch,i-am-Nathan/elasticsearch,maddin2016/elasticsearch,pozhidaevak/elasticsearch,GlenRSmith/elasticsearch,obourgain/elasticsearch,Helen-Zhao/elasticsearch,lks21c/elasticsearch,uschindler/elasticsearch,geidies/elasticsearch,dongjoon-hyun/elasticsearch,fred84/elasticsearch,rajanm/elasticsearch,fred84/elasticsearch,clintongormley/elasticsearch,nazarewk/elasticsearch,fernandozhu/elasticsearch,clintongormley/elasticsearch,yanjunh/elasticsearch,camilojd/elasticsearch,MaineC/elasticsearch,girirajsharma/elasticsearch,wangtuo/elasticsearch,LewayneNaidoo/elasticsearch,mohit/elasticsearch,IanvsPoplicola/elasticsearch,naveenhooda2000/elasticsearch,gingerwizard/elasticsearch,vroyer/elasticassandra,umeshdangat/elasticsearch,clintongormley/elasticsearch,liweinan0423/elasticsearch,njlawton/elasticsearch,nazarewk/elasticsearch,MaineC/elasticsearch,MaineC/elasticsearch,alexshadow007/elasticsearch,kalimatas/elasticsearch,cwurm/elasticsearch,obourgain/elasticsearch,masaruh/elasticsearch,LeoYao/elasticsearch,mikemccand/elasticsearch,LeoYao/elasticsearch,mmaracic/elasticsearch,fernandozhu/elasticsearch,gmarz/elasticsearch,myelin/elasticsearch,s1monw/elasticsearch,jimczi/elasticsearch,geidies/elasticsearch,coding0011/elasticsearch,MaineC/elasticsearch,mikemccand/elasticsearch,glefloch/elasticsearch,Helen-Zhao/elasticsearch,rlugojr/elasticsearch,artnowo/elasticsearch,yynil/elasticsearch,nknize/elasticsearch,zkidkid/elasticsearch,obourgain/elasticsearch,njlawton/elasticsearch,trangvh/elasticsearch,mikemccand/elasticsearch,strapdata/elassandra5-rc,markwalkom/elasticsearch,LeoYao/elasticsearch,mjason3/elasticsearch,alexshadow007/elasticsearch,mmaracic/elasticsearch,palecur/elasticsearch,MaineC/elasticsearch,maddin2016/elasticsearch,sneivandt/elasticsearch,artnowo/elasticsearch,scottsom/elasticsearch,winstonewert/elasticsearch,mjason3/elasticsearch,avikurapati/elasticsearch,camilojd/elasticsearch,Helen-Zhao/elasticsearch,markwalkom/elasticsearch,strapdata/elassandra5-rc,rlugojr/elasticsearch,a2lin/elasticsearch,mapr/elasticsearch,wuranbo/elasticsearch,shreejay/elasticsearch,avikurapati/elasticsearch,umeshdangat/elasticsearch,palecur/elasticsearch,yynil/elasticsearch,gfyoung/elasticsearch,cwurm/elasticsearch,yanjunh/elasticsearch,fforbeck/elasticsearch,brandonkearby/elasticsearch,Stacey-Gammon/elasticsearch,fernandozhu/elasticsearch,fforbeck/elasticsearch,gmarz/elasticsearch,vroyer/elasticassandra,glefloch/elasticsearch,wuranbo/elasticsearch,LeoYao/elasticsearch,wangtuo/elasticsearch,ThiagoGarciaAlves/elasticsearch,strapdata/elassandra,artnowo/elasticsearch,henakamaMSFT/elasticsearch,xuzha/elasticsearch,njlawton/elasticsearch,markwalkom/elasticsearch,uschindler/elasticsearch,girirajsharma/elasticsearch,elasticdog/elasticsearch,nknize/elasticsearch,Shepard1212/elasticsearch,sneivandt/elasticsearch,wenpos/elasticsearch,LewayneNaidoo/elasticsearch,s1monw/elasticsearch,yynil/elasticsearch,mikemccand/elasticsearch,myelin/elasticsearch,dongjoon-hyun/elasticsearch,qwerty4030/elasticsearch,bawse/elasticsearch,xuzha/elasticsearch,gfyoung/elasticsearch,wangtuo/elasticsearch,brandonkearby/elasticsearch,robin13/elasticsearch,JackyMai/elasticsearch,scottsom/elasticsearch,cwurm/elasticsearch,JSCooke/elasticsearch,girirajsharma/elasticsearch,awislowski/elasticsearch,geidies/elasticsearch,fforbeck/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,dongjoon-hyun/elasticsearch,scorpionvicky/elasticsearch,myelin/elasticsearch,gmarz/elasticsearch,maddin2016/elasticsearch,geidies/elasticsearch,spiegela/elasticsearch,scorpionvicky/elasticsearch,trangvh/elasticsearch,Shepard1212/elasticsearch,mjason3/elasticsearch,mikemccand/elasticsearch,obourgain/elasticsearch,s1monw/elasticsearch,LewayneNaidoo/elasticsearch,i-am-Nathan/elasticsearch,ThiagoGarciaAlves/elasticsearch,cwurm/elasticsearch,rajanm/elasticsearch,alexshadow007/elasticsearch,naveenhooda2000/elasticsearch,mjason3/elasticsearch,Stacey-Gammon/elasticsearch,jprante/elasticsearch,nilabhsagar/elasticsearch,JackyMai/elasticsearch,GlenRSmith/elasticsearch,bawse/elasticsearch,dpursehouse/elasticsearch,ricardocerq/elasticsearch,ZTE-PaaS/elasticsearch,lks21c/elasticsearch,i-am-Nathan/elasticsearch,jimczi/elasticsearch,obourgain/elasticsearch,nknize/elasticsearch,StefanGor/elasticsearch,henakamaMSFT/elasticsearch,nezirus/elasticsearch,s1monw/elasticsearch,wuranbo/elasticsearch,alexshadow007/elasticsearch,camilojd/elasticsearch,HonzaKral/elasticsearch,ZTE-PaaS/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,winstonewert/elasticsearch,xuzha/elasticsearch,shreejay/elasticsearch,geidies/elasticsearch,JSCooke/elasticsearch,palecur/elasticsearch,C-Bish/elasticsearch,ThiagoGarciaAlves/elasticsearch,naveenhooda2000/elasticsearch,yynil/elasticsearch,artnowo/elasticsearch,lks21c/elasticsearch,wenpos/elasticsearch,ricardocerq/elasticsearch,qwerty4030/elasticsearch,henakamaMSFT/elasticsearch,dpursehouse/elasticsearch,mohit/elasticsearch,naveenhooda2000/elasticsearch,wuranbo/elasticsearch,umeshdangat/elasticsearch,mohit/elasticsearch,uschindler/elasticsearch,shreejay/elasticsearch,Helen-Zhao/elasticsearch,jprante/elasticsearch,qwerty4030/elasticsearch,LeoYao/elasticsearch,fforbeck/elasticsearch,gingerwizard/elasticsearch,yynil/elasticsearch,JackyMai/elasticsearch,wangtuo/elasticsearch,Shepard1212/elasticsearch,winstonewert/elasticsearch,MisterAndersen/elasticsearch,bawse/elasticsearch,glefloch/elasticsearch,MisterAndersen/elasticsearch,coding0011/elasticsearch,nomoa/elasticsearch,kalimatas/elasticsearch,IanvsPoplicola/elasticsearch,sneivandt/elasticsearch,nomoa/elasticsearch,zkidkid/elasticsearch,masaruh/elasticsearch,winstonewert/elasticsearch,mjason3/elasticsearch,elasticdog/elasticsearch,JackyMai/elasticsearch,nezirus/elasticsearch,vroyer/elassandra,ThiagoGarciaAlves/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,myelin/elasticsearch,GlenRSmith/elasticsearch,njlawton/elasticsearch,clintongormley/elasticsearch,markwalkom/elasticsearch,elasticdog/elasticsearch,jimczi/elasticsearch,brandonkearby/elasticsearch,a2lin/elasticsearch,nknize/elasticsearch,ricardocerq/elasticsearch,rajanm/elasticsearch,camilojd/elasticsearch,gmarz/elasticsearch,mapr/elasticsearch,C-Bish/elasticsearch,nomoa/elasticsearch,nazarewk/elasticsearch,LeoYao/elasticsearch,HonzaKral/elasticsearch,elasticdog/elasticsearch,IanvsPoplicola/elasticsearch,Shepard1212/elasticsearch,umeshdangat/elasticsearch,spiegela/elasticsearch,clintongormley/elasticsearch,camilojd/elasticsearch,brandonkearby/elasticsearch,masaruh/elasticsearch,markwalkom/elasticsearch,sreeramjayan/elasticsearch,markwalkom/elasticsearch,bawse/elasticsearch,StefanGor/elasticsearch,yanjunh/elasticsearch,jprante/elasticsearch,mortonsykes/elasticsearch,jimczi/elasticsearch,sreeramjayan/elasticsearch,fforbeck/elasticsearch,mapr/elasticsearch,wuranbo/elasticsearch,avikurapati/elasticsearch,ricardocerq/elasticsearch,JervyShi/elasticsearch,JervyShi/elasticsearch,rajanm/elasticsearch,robin13/elasticsearch,ricardocerq/elasticsearch,Shepard1212/elasticsearch,trangvh/elasticsearch,LewayneNaidoo/elasticsearch,sneivandt/elasticsearch,dongjoon-hyun/elasticsearch,strapdata/elassandra5-rc,xuzha/elasticsearch,vroyer/elassandra,fred84/elasticsearch,spiegela/elasticsearch,strapdata/elassandra,umeshdangat/elasticsearch,mmaracic/elasticsearch,strapdata/elassandra,gingerwizard/elasticsearch,mmaracic/elasticsearch,lks21c/elasticsearch,rlugojr/elasticsearch,strapdata/elassandra5-rc,HonzaKral/elasticsearch,JSCooke/elasticsearch,masaruh/elasticsearch,i-am-Nathan/elasticsearch,fernandozhu/elasticsearch,henakamaMSFT/elasticsearch,gfyoung/elasticsearch,scorpionvicky/elasticsearch,JervyShi/elasticsearch,nezirus/elasticsearch,njlawton/elasticsearch,mmaracic/elasticsearch,girirajsharma/elasticsearch,xuzha/elasticsearch,Helen-Zhao/elasticsearch,avikurapati/elasticsearch,shreejay/elasticsearch,mortonsykes/elasticsearch,palecur/elasticsearch,pozhidaevak/elasticsearch,mortonsykes/elasticsearch,bawse/elasticsearch,awislowski/elasticsearch,StefanGor/elasticsearch,glefloch/elasticsearch,LeoYao/elasticsearch,JackyMai/elasticsearch,fred84/elasticsearch,coding0011/elasticsearch,rajanm/elasticsearch,nezirus/elasticsearch,gmarz/elasticsearch,mapr/elasticsearch,mapr/elasticsearch,sreeramjayan/elasticsearch,avikurapati/elasticsearch,pozhidaevak/elasticsearch,JervyShi/elasticsearch,JervyShi/elasticsearch,JervyShi/elasticsearch,StefanGor/elasticsearch,HonzaKral/elasticsearch,artnowo/elasticsearch,dongjoon-hyun/elasticsearch,alexshadow007/elasticsearch,fernandozhu/elasticsearch,qwerty4030/elasticsearch,wenpos/elasticsearch,maddin2016/elasticsearch,awislowski/elasticsearch,spiegela/elasticsearch,uschindler/elasticsearch,i-am-Nathan/elasticsearch,mapr/elasticsearch,liweinan0423/elasticsearch,JSCooke/elasticsearch,kalimatas/elasticsearch,robin13/elasticsearch,geidies/elasticsearch,scorpionvicky/elasticsearch,liweinan0423/elasticsearch,gingerwizard/elasticsearch,ZTE-PaaS/elasticsearch,kalimatas/elasticsearch,palecur/elasticsearch,IanvsPoplicola/elasticsearch,xuzha/elasticsearch,MisterAndersen/elasticsearch,spiegela/elasticsearch,LewayneNaidoo/elasticsearch,wangtuo/elasticsearch,cwurm/elasticsearch,camilojd/elasticsearch,Stacey-Gammon/elasticsearch,zkidkid/elasticsearch,scottsom/elasticsearch,awislowski/elasticsearch,naveenhooda2000/elasticsearch,girirajsharma/elasticsearch,dpursehouse/elasticsearch,C-Bish/elasticsearch,mohit/elasticsearch,nomoa/elasticsearch,JSCooke/elasticsearch,vroyer/elassandra,GlenRSmith/elasticsearch,zkidkid/elasticsearch,maddin2016/elasticsearch,StefanGor/elasticsearch,dpursehouse/elasticsearch,scottsom/elasticsearch,glefloch/elasticsearch,mmaracic/elasticsearch,liweinan0423/elasticsearch,strapdata/elassandra,mortonsykes/elasticsearch | /*
* 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.common.settings;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.support.ToXContentToBytes;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.MemorySizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* A setting. Encapsulates typical stuff like default value, parsing, and scope.
* Some (SettingsProperty.Dynamic) can by modified at run time using the API.
* All settings inside elasticsearch or in any of the plugins should use this type-safe and generic settings infrastructure
* together with {@link AbstractScopedSettings}. This class contains several utility methods that makes it straight forward
* to add settings for the majority of the cases. For instance a simple boolean settings can be defined like this:
* <pre>{@code
* public static final Setting<Boolean>; MY_BOOLEAN = Setting.boolSetting("my.bool.setting", true, SettingsProperty.ClusterScope);}
* </pre>
* To retrieve the value of the setting a {@link Settings} object can be passed directly to the {@link Setting#get(Settings)} method.
* <pre>
* final boolean myBooleanValue = MY_BOOLEAN.get(settings);
* </pre>
* It's recommended to use typed settings rather than string based settings. For example adding a setting for an enum type:
* <pre>{@code
* public enum Color {
* RED, GREEN, BLUE;
* }
* public static final Setting<Color> MY_BOOLEAN =
* new Setting<>("my.color.setting", Color.RED.toString(), Color::valueOf, SettingsProperty.ClusterScope);
* }
* </pre>
*/
public class Setting<T> extends ToXContentToBytes {
public enum SettingsProperty {
/**
* should be filtered in some api (mask password/credentials)
*/
Filtered,
/**
* iff this setting can be dynamically updateable
*/
Dynamic,
/**
* mark this setting as deprecated
*/
Deprecated,
/**
* Cluster scope.
* @See IndexScope
* @See NodeScope
*/
ClusterScope,
/**
* Node scope.
* @See ClusterScope
* @See IndexScope
*/
NodeScope,
/**
* Index scope.
* @See ClusterScope
* @See NodeScope
*/
IndexScope;
}
private static final ESLogger logger = Loggers.getLogger(Setting.class);
private static final DeprecationLogger deprecationLogger = new DeprecationLogger(logger);
private final String key;
protected final Function<Settings, String> defaultValue;
private final Function<String, T> parser;
private final EnumSet<SettingsProperty> properties;
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Function<Settings, String> defaultValue, Function<String, T> parser, SettingsProperty... properties) {
assert parser.apply(defaultValue.apply(Settings.EMPTY)) != null || this.isGroupSetting(): "parser returned null";
this.key = key;
this.defaultValue = defaultValue;
this.parser = parser;
if (properties.length == 0) {
this.properties = EnumSet.of(SettingsProperty.NodeScope);
} else {
this.properties = EnumSet.copyOf(Arrays.asList(properties));
}
// We validate scope settings. They are mutually exclusive
int numScopes = 0;
for (SettingsProperty property : properties) {
if (property == SettingsProperty.ClusterScope ||
property == SettingsProperty.IndexScope ||
property == SettingsProperty.NodeScope) {
numScopes++;
}
}
if (numScopes > 1) {
throw new IllegalArgumentException("More than one scope has been added to the setting [" + key + "]");
}
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, String defaultValue, Function<String, T> parser, SettingsProperty... properties) {
this(key, s -> defaultValue, parser, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallBackSetting a setting to fall back to if the current setting is not set.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Setting<T> fallBackSetting, Function<String, T> parser, SettingsProperty... properties) {
this(key, fallBackSetting::getRaw, parser, properties);
}
/**
* Returns the settings key or a prefix if this setting is a group setting.
* <b>Note: this method should not be used to retrieve a value from a {@link Settings} object.
* Use {@link #get(Settings)} instead</b>
*
* @see #isGroupSetting()
*/
public final String getKey() {
return key;
}
/**
* Returns <code>true</code> if this setting is dynamically updateable, otherwise <code>false</code>
*/
public final boolean isDynamic() {
return properties.contains(SettingsProperty.Dynamic);
}
/**
* Returns the setting properties
* @see SettingsProperty
*/
public EnumSet<SettingsProperty> getProperties() {
return properties;
}
/**
* Returns <code>true</code> if this setting must be filtered, otherwise <code>false</code>
*/
public boolean isFiltered() {
return properties.contains(SettingsProperty.Filtered);
}
/**
* Returns <code>true</code> if this setting has a cluster scope, otherwise <code>false</code>
*/
public boolean hasClusterScope() {
return properties.contains(SettingsProperty.ClusterScope);
}
/**
* Returns <code>true</code> if this setting has an index scope, otherwise <code>false</code>
*/
public boolean hasIndexScope() {
return properties.contains(SettingsProperty.IndexScope);
}
/**
* Returns <code>true</code> if this setting has an index scope, otherwise <code>false</code>
*/
public boolean hasNodeScope() {
return properties.contains(SettingsProperty.NodeScope);
}
/**
* Returns <code>true</code> if this setting is deprecated, otherwise <code>false</code>
*/
public boolean isDeprecated() {
return properties.contains(SettingsProperty.Deprecated);
}
/**
* Returns <code>true</code> iff this setting is a group setting. Group settings represent a set of settings
* rather than a single value. The key, see {@link #getKey()}, in contrast to non-group settings is a prefix like <tt>cluster.store.</tt>
* that matches all settings with this prefix.
*/
boolean isGroupSetting() {
return false;
}
boolean hasComplexMatcher() {
return isGroupSetting();
}
/**
* Returns the default value string representation for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public final String getDefaultRaw(Settings settings) {
return defaultValue.apply(settings);
}
/**
* Returns the default value for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public final T getDefault(Settings settings) {
return parser.apply(getDefaultRaw(settings));
}
/**
* Returns <code>true</code> iff this setting is present in the given settings object. Otherwise <code>false</code>
*/
public final boolean exists(Settings settings) {
return settings.get(key) != null;
}
/**
* Returns the settings value. If the setting is not present in the given settings object the default value is returned
* instead.
*/
public T get(Settings settings) {
String value = getRaw(settings);
try {
return parser.apply(value);
} catch (ElasticsearchParseException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Failed to parse value [" + value + "] for setting [" + getKey() + "]", ex);
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception t) {
throw new IllegalArgumentException("Failed to parse value [" + value + "] for setting [" + getKey() + "]", t);
}
}
/**
* Returns the raw (string) settings value. If the setting is not present in the given settings object the default value is returned
* instead. This is useful if the value can't be parsed due to an invalid value to access the actual value.
*/
public String getRaw(Settings settings) {
// They're using the setting, so we need to tell them to stop
if (this.isDeprecated() && this.exists(settings)) {
// It would be convenient to show its replacement key, but replacement is often not so simple
deprecationLogger.deprecated("[{}] setting was deprecated in Elasticsearch and it will be removed in a future release! " +
"See the breaking changes lists in the documentation for details", getKey());
}
return settings.get(key, defaultValue.apply(settings));
}
/**
* Returns <code>true</code> iff the given key matches the settings key or if this setting is a group setting if the
* given key is part of the settings group.
* @see #isGroupSetting()
*/
public boolean match(String toTest) {
return key.equals(toTest);
}
@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("key", key);
builder.field("properties", properties);
builder.field("is_group_setting", isGroupSetting());
builder.field("default", defaultValue.apply(Settings.EMPTY));
builder.endObject();
return builder;
}
/**
* Returns the value for this setting but falls back to the second provided settings object
*/
public final T get(Settings primary, Settings secondary) {
if (exists(primary)) {
return get(primary);
}
return get(secondary);
}
public Setting<T> getConcreteSetting(String key) {
assert key.startsWith(this.getKey()) : "was " + key + " expected: " + getKey(); // we use startsWith here since the key might be foo.bar.0 if it's an array
return this;
}
/**
* Build a new updater with a noop validator.
*/
final AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger) {
return newUpdater(consumer, logger, (s) -> {});
}
/**
* Build the updater responsible for validating new values, logging the new
* value, and eventually setting the value where it belongs.
*/
AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger, Consumer<T> validator) {
if (isDynamic()) {
return new Updater(consumer, logger, validator);
} else {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
}
/**
* this is used for settings that depend on each other... see {@link org.elasticsearch.common.settings.AbstractScopedSettings#addSettingsUpdateConsumer(Setting, Setting, BiConsumer)} and it's
* usage for details.
*/
static <A, B> AbstractScopedSettings.SettingUpdater<Tuple<A, B>> compoundUpdater(final BiConsumer<A,B> consumer, final Setting<A> aSetting, final Setting<B> bSetting, ESLogger logger) {
final AbstractScopedSettings.SettingUpdater<A> aSettingUpdater = aSetting.newUpdater(null, logger);
final AbstractScopedSettings.SettingUpdater<B> bSettingUpdater = bSetting.newUpdater(null, logger);
return new AbstractScopedSettings.SettingUpdater<Tuple<A, B>>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return aSettingUpdater.hasChanged(current, previous) || bSettingUpdater.hasChanged(current, previous);
}
@Override
public Tuple<A, B> getValue(Settings current, Settings previous) {
return new Tuple<>(aSettingUpdater.getValue(current, previous), bSettingUpdater.getValue(current, previous));
}
@Override
public void apply(Tuple<A, B> value, Settings current, Settings previous) {
consumer.accept(value.v1(), value.v2());
}
@Override
public String toString() {
return "CompoundUpdater for: " + aSettingUpdater + " and " + bSettingUpdater;
}
};
}
private final class Updater implements AbstractScopedSettings.SettingUpdater<T> {
private final Consumer<T> consumer;
private final ESLogger logger;
private final Consumer<T> accept;
public Updater(Consumer<T> consumer, ESLogger logger, Consumer<T> accept) {
this.consumer = consumer;
this.logger = logger;
this.accept = accept;
}
@Override
public String toString() {
return "Updater for: " + Setting.this.toString();
}
@Override
public boolean hasChanged(Settings current, Settings previous) {
final String newValue = getRaw(current);
final String value = getRaw(previous);
assert isGroupSetting() == false : "group settings must override this method";
assert value != null : "value was null but can't be unless default is null which is invalid";
return value.equals(newValue) == false;
}
@Override
public T getValue(Settings current, Settings previous) {
final String newValue = getRaw(current);
final String value = getRaw(previous);
T inst = get(current);
try {
accept.accept(inst);
} catch (Exception | AssertionError e) {
throw new IllegalArgumentException("illegal value can't update [" + key + "] from [" + value + "] to [" + newValue + "]", e);
}
return inst;
}
@Override
public final void apply(T value, Settings current, Settings previous) {
logger.info("updating [{}] from [{}] to [{}]", key, getRaw(previous), getRaw(current));
consumer.accept(value);
}
}
public static Setting<Float> floatSetting(String key, float defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Float.toString(defaultValue), Float::parseFloat, properties);
}
public static Setting<Float> floatSetting(String key, float defaultValue, float minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Float.toString(defaultValue), (s) -> {
float value = Float.parseFloat(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return value;
}, properties);
}
public static Setting<Integer> intSetting(String key, int defaultValue, int minValue, int maxValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Integer.toString(defaultValue), (s) -> parseInt(s, minValue, maxValue, key), properties);
}
public static Setting<Integer> intSetting(String key, int defaultValue, int minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Integer.toString(defaultValue), (s) -> parseInt(s, minValue, key), properties);
}
public static Setting<Long> longSetting(String key, long defaultValue, long minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Long.toString(defaultValue), (s) -> parseLong(s, minValue, key), properties);
}
public static Setting<String> simpleString(String key, SettingsProperty... properties) {
return new Setting<>(key, s -> "", Function.identity(), properties);
}
public static int parseInt(String s, int minValue, String key) {
return parseInt(s, minValue, Integer.MAX_VALUE, key);
}
public static int parseInt(String s, int minValue, int maxValue, String key) {
int value = Integer.parseInt(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
if (value > maxValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be =< " + maxValue);
}
return value;
}
public static long parseLong(String s, long minValue, String key) {
long value = Long.parseLong(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return value;
}
public static Setting<Integer> intSetting(String key, int defaultValue, SettingsProperty... properties) {
return intSetting(key, defaultValue, Integer.MIN_VALUE, properties);
}
public static Setting<Boolean> boolSetting(String key, boolean defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Boolean.toString(defaultValue), Booleans::parseBooleanExact, properties);
}
public static Setting<Boolean> boolSetting(String key, Setting<Boolean> fallbackSetting, SettingsProperty... properties) {
return new Setting<>(key, fallbackSetting, Booleans::parseBooleanExact, properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, String percentage, SettingsProperty... properties) {
return new Setting<>(key, (s) -> percentage, (s) -> MemorySizeValue.parseBytesSizeValueOrHeapRatio(s, key), properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, ByteSizeValue value, SettingsProperty... properties) {
return byteSizeSetting(key, (s) -> value.toString(), properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, Setting<ByteSizeValue> fallbackSettings,
SettingsProperty... properties) {
return byteSizeSetting(key, fallbackSettings::getRaw, properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, Function<Settings, String> defaultValue,
SettingsProperty... properties) {
return new Setting<>(key, defaultValue, (s) -> ByteSizeValue.parseBytesSizeValue(s, key), properties);
}
public static Setting<TimeValue> positiveTimeSetting(String key, TimeValue defaultValue, SettingsProperty... properties) {
return timeSetting(key, defaultValue, TimeValue.timeValueMillis(0), properties);
}
public static <T> Setting<List<T>> listSetting(String key, List<String> defaultStringValue, Function<String, T> singleValueParser,
SettingsProperty... properties) {
return listSetting(key, (s) -> defaultStringValue, singleValueParser, properties);
}
public static <T> Setting<List<T>> listSetting(String key, Setting<List<T>> fallbackSetting, Function<String, T> singleValueParser,
SettingsProperty... properties) {
return listSetting(key, (s) -> parseableStringToList(fallbackSetting.getRaw(s)), singleValueParser, properties);
}
public static <T> Setting<List<T>> listSetting(String key, Function<Settings, List<String>> defaultStringValue,
Function<String, T> singleValueParser, SettingsProperty... properties) {
Function<String, List<T>> parser = (s) ->
parseableStringToList(s).stream().map(singleValueParser).collect(Collectors.toList());
return new Setting<List<T>>(key, (s) -> arrayToParsableString(defaultStringValue.apply(s).toArray(Strings.EMPTY_ARRAY)), parser,
properties) {
private final Pattern pattern = Pattern.compile(Pattern.quote(key)+"(\\.\\d+)?");
@Override
public String getRaw(Settings settings) {
String[] array = settings.getAsArray(key, null);
return array == null ? defaultValue.apply(settings) : arrayToParsableString(array);
}
@Override
public boolean match(String toTest) {
return pattern.matcher(toTest).matches();
}
@Override
boolean hasComplexMatcher() {
return true;
}
};
}
private static List<String> parseableStringToList(String parsableString) {
try (XContentParser xContentParser = XContentType.JSON.xContent().createParser(parsableString)) {
XContentParser.Token token = xContentParser.nextToken();
if (token != XContentParser.Token.START_ARRAY) {
throw new IllegalArgumentException("expected START_ARRAY but got " + token);
}
ArrayList<String> list = new ArrayList<>();
while ((token = xContentParser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token != XContentParser.Token.VALUE_STRING) {
throw new IllegalArgumentException("expected VALUE_STRING but got " + token);
}
list.add(xContentParser.text());
}
return list;
} catch (IOException e) {
throw new IllegalArgumentException("failed to parse array", e);
}
}
private static String arrayToParsableString(String[] array) {
try {
XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent());
builder.startArray();
for (String element : array) {
builder.value(element);
}
builder.endArray();
return builder.string();
} catch (IOException ex) {
throw new ElasticsearchException(ex);
}
}
public static Setting<Settings> groupSetting(String key, SettingsProperty... properties) {
if (key.endsWith(".") == false) {
throw new IllegalArgumentException("key must end with a '.'");
}
return new Setting<Settings>(key, "", (s) -> null, properties) {
@Override
public boolean isGroupSetting() {
return true;
}
@Override
public Settings get(Settings settings) {
return settings.getByPrefix(key);
}
@Override
public boolean match(String toTest) {
return Regex.simpleMatch(key + "*", toTest);
}
@Override
public AbstractScopedSettings.SettingUpdater<Settings> newUpdater(Consumer<Settings> consumer, ESLogger logger, Consumer<Settings> validator) {
if (isDynamic() == false) {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
final Setting<?> setting = this;
return new AbstractScopedSettings.SettingUpdater<Settings>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
return currentSettings.equals(previousSettings) == false;
}
@Override
public Settings getValue(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
try {
validator.accept(currentSettings);
} catch (Exception | AssertionError e) {
throw new IllegalArgumentException("illegal value can't update [" + key + "] from [" + previousSettings.getAsMap() + "] to [" + currentSettings.getAsMap() + "]", e);
}
return currentSettings;
}
@Override
public void apply(Settings value, Settings current, Settings previous) {
logger.info("updating [{}] from [{}] to [{}]", key, getRaw(previous), getRaw(current));
consumer.accept(value);
}
@Override
public String toString() {
return "Updater for: " + setting.toString();
}
};
}
};
}
public static Setting<TimeValue> timeSetting(String key, Function<Settings, String> defaultValue, TimeValue minValue,
SettingsProperty... properties) {
return new Setting<>(key, defaultValue, (s) -> {
TimeValue timeValue = TimeValue.parseTimeValue(s, null, key);
if (timeValue.millis() < minValue.millis()) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return timeValue;
}, properties);
}
public static Setting<TimeValue> timeSetting(String key, TimeValue defaultValue, TimeValue minValue, SettingsProperty... properties) {
return timeSetting(key, (s) -> defaultValue.getStringRep(), minValue, properties);
}
public static Setting<TimeValue> timeSetting(String key, TimeValue defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> defaultValue.toString(), (s) -> TimeValue.parseTimeValue(s, key), properties);
}
public static Setting<TimeValue> timeSetting(String key, Setting<TimeValue> fallbackSetting, SettingsProperty... properties) {
return new Setting<>(key, fallbackSetting::getRaw, (s) -> TimeValue.parseTimeValue(s, key), properties);
}
public static Setting<Double> doubleSetting(String key, double defaultValue, double minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Double.toString(defaultValue), (s) -> {
final double d = Double.parseDouble(s);
if (d < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return d;
}, properties);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Setting<?> setting = (Setting<?>) o;
return Objects.equals(key, setting.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
/**
* This setting type allows to validate settings that have the same type and a common prefix. For instance feature.${type}=[true|false]
* can easily be added with this setting. Yet, dynamic key settings don't support updaters out of the box unless {@link #getConcreteSetting(String)}
* is used to pull the updater.
*/
public static <T> Setting<T> dynamicKeySetting(String key, String defaultValue, Function<String, T> parser,
SettingsProperty... properties) {
return new Setting<T>(key, defaultValue, parser, properties) {
@Override
boolean isGroupSetting() {
return true;
}
@Override
public boolean match(String toTest) {
return toTest.startsWith(getKey());
}
@Override
AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger, Consumer<T> validator) {
throw new UnsupportedOperationException("dynamic settings can't be updated use #getConcreteSetting for updating");
}
@Override
public Setting<T> getConcreteSetting(String key) {
if (match(key)) {
return new Setting<>(key, defaultValue, parser, properties);
} else {
throw new IllegalArgumentException("key must match setting but didn't ["+key +"]");
}
}
};
}
}
| core/src/main/java/org/elasticsearch/common/settings/Setting.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.common.settings;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.support.ToXContentToBytes;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.MemorySizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* A setting. Encapsulates typical stuff like default value, parsing, and scope.
* Some (SettingsProperty.Dynamic) can by modified at run time using the API.
* All settings inside elasticsearch or in any of the plugins should use this type-safe and generic settings infrastructure
* together with {@link AbstractScopedSettings}. This class contains several utility methods that makes it straight forward
* to add settings for the majority of the cases. For instance a simple boolean settings can be defined like this:
* <pre>{@code
* public static final Setting<Boolean>; MY_BOOLEAN = Setting.boolSetting("my.bool.setting", true, SettingsProperty.ClusterScope);}
* </pre>
* To retrieve the value of the setting a {@link Settings} object can be passed directly to the {@link Setting#get(Settings)} method.
* <pre>
* final boolean myBooleanValue = MY_BOOLEAN.get(settings);
* </pre>
* It's recommended to use typed settings rather than string based settings. For example adding a setting for an enum type:
* <pre>{@code
* public enum Color {
* RED, GREEN, BLUE;
* }
* public static final Setting<Color> MY_BOOLEAN =
* new Setting<>("my.color.setting", Color.RED.toString(), Color::valueOf, SettingsProperty.ClusterScope);
* }
* </pre>
*/
public class Setting<T> extends ToXContentToBytes {
public enum SettingsProperty {
/**
* should be filtered in some api (mask password/credentials)
*/
Filtered,
/**
* iff this setting can be dynamically updateable
*/
Dynamic,
/**
* mark this setting as deprecated
*/
Deprecated,
/**
* Cluster scope.
* @See IndexScope
* @See NodeScope
*/
ClusterScope,
/**
* Node scope.
* @See ClusterScope
* @See IndexScope
*/
NodeScope,
/**
* Index scope.
* @See ClusterScope
* @See NodeScope
*/
IndexScope;
}
private static final ESLogger logger = Loggers.getLogger(Setting.class);
private final String key;
protected final Function<Settings, String> defaultValue;
private final Function<String, T> parser;
private final EnumSet<SettingsProperty> properties;
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value function that returns the default values string representation.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Function<Settings, String> defaultValue, Function<String, T> parser, SettingsProperty... properties) {
assert parser.apply(defaultValue.apply(Settings.EMPTY)) != null || this.isGroupSetting(): "parser returned null";
this.key = key;
this.defaultValue = defaultValue;
this.parser = parser;
if (properties.length == 0) {
this.properties = EnumSet.of(SettingsProperty.NodeScope);
} else {
this.properties = EnumSet.copyOf(Arrays.asList(properties));
}
// We validate scope settings. They are mutually exclusive
int numScopes = 0;
for (SettingsProperty property : properties) {
if (property == SettingsProperty.ClusterScope ||
property == SettingsProperty.IndexScope ||
property == SettingsProperty.NodeScope) {
numScopes++;
}
}
if (numScopes > 1) {
throw new IllegalArgumentException("More than one scope has been added to the setting [" + key + "]");
}
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param defaultValue a default value.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, String defaultValue, Function<String, T> parser, SettingsProperty... properties) {
this(key, s -> defaultValue, parser, properties);
}
/**
* Creates a new Setting instance
* @param key the settings key for this setting.
* @param fallBackSetting a setting to fall back to if the current setting is not set.
* @param parser a parser that parses the string rep into a complex datatype.
* @param properties properties for this setting like scope, filtering...
*/
public Setting(String key, Setting<T> fallBackSetting, Function<String, T> parser, SettingsProperty... properties) {
this(key, fallBackSetting::getRaw, parser, properties);
}
/**
* Returns the settings key or a prefix if this setting is a group setting.
* <b>Note: this method should not be used to retrieve a value from a {@link Settings} object.
* Use {@link #get(Settings)} instead</b>
*
* @see #isGroupSetting()
*/
public final String getKey() {
return key;
}
/**
* Returns <code>true</code> if this setting is dynamically updateable, otherwise <code>false</code>
*/
public final boolean isDynamic() {
return properties.contains(SettingsProperty.Dynamic);
}
/**
* Returns the setting properties
* @see SettingsProperty
*/
public EnumSet<SettingsProperty> getProperties() {
return properties;
}
/**
* Returns <code>true</code> if this setting must be filtered, otherwise <code>false</code>
*/
public boolean isFiltered() {
return properties.contains(SettingsProperty.Filtered);
}
/**
* Returns <code>true</code> if this setting has a cluster scope, otherwise <code>false</code>
*/
public boolean hasClusterScope() {
return properties.contains(SettingsProperty.ClusterScope);
}
/**
* Returns <code>true</code> if this setting has an index scope, otherwise <code>false</code>
*/
public boolean hasIndexScope() {
return properties.contains(SettingsProperty.IndexScope);
}
/**
* Returns <code>true</code> if this setting has an index scope, otherwise <code>false</code>
*/
public boolean hasNodeScope() {
return properties.contains(SettingsProperty.NodeScope);
}
/**
* Returns <code>true</code> if this setting is deprecated, otherwise <code>false</code>
*/
public boolean isDeprecated() {
return properties.contains(SettingsProperty.Deprecated);
}
/**
* Returns <code>true</code> iff this setting is a group setting. Group settings represent a set of settings
* rather than a single value. The key, see {@link #getKey()}, in contrast to non-group settings is a prefix like <tt>cluster.store.</tt>
* that matches all settings with this prefix.
*/
boolean isGroupSetting() {
return false;
}
boolean hasComplexMatcher() {
return isGroupSetting();
}
/**
* Returns the default value string representation for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public final String getDefaultRaw(Settings settings) {
return defaultValue.apply(settings);
}
/**
* Returns the default value for this setting.
* @param settings a settings object for settings that has a default value depending on another setting if available
*/
public final T getDefault(Settings settings) {
return parser.apply(getDefaultRaw(settings));
}
/**
* Returns <code>true</code> iff this setting is present in the given settings object. Otherwise <code>false</code>
*/
public final boolean exists(Settings settings) {
return settings.get(key) != null;
}
/**
* Returns the settings value. If the setting is not present in the given settings object the default value is returned
* instead.
*/
public T get(Settings settings) {
String value = getRaw(settings);
try {
return parser.apply(value);
} catch (ElasticsearchParseException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Failed to parse value [" + value + "] for setting [" + getKey() + "]", ex);
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception t) {
throw new IllegalArgumentException("Failed to parse value [" + value + "] for setting [" + getKey() + "]", t);
}
}
/**
* Returns the raw (string) settings value. If the setting is not present in the given settings object the default value is returned
* instead. This is useful if the value can't be parsed due to an invalid value to access the actual value.
*/
public String getRaw(Settings settings) {
// They're using the setting, so we need to tell them to stop
if (this.isDeprecated() && this.exists(settings)) {
// It would be convenient to show its replacement key, but replacement is often not so simple
logger.warn("[{}] setting was deprecated in Elasticsearch and it will be removed in a future release! " +
"See the breaking changes lists in the documentation for details", getKey());
}
return settings.get(key, defaultValue.apply(settings));
}
/**
* Returns <code>true</code> iff the given key matches the settings key or if this setting is a group setting if the
* given key is part of the settings group.
* @see #isGroupSetting()
*/
public boolean match(String toTest) {
return key.equals(toTest);
}
@Override
public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("key", key);
builder.field("properties", properties);
builder.field("is_group_setting", isGroupSetting());
builder.field("default", defaultValue.apply(Settings.EMPTY));
builder.endObject();
return builder;
}
/**
* Returns the value for this setting but falls back to the second provided settings object
*/
public final T get(Settings primary, Settings secondary) {
if (exists(primary)) {
return get(primary);
}
return get(secondary);
}
public Setting<T> getConcreteSetting(String key) {
assert key.startsWith(this.getKey()) : "was " + key + " expected: " + getKey(); // we use startsWith here since the key might be foo.bar.0 if it's an array
return this;
}
/**
* Build a new updater with a noop validator.
*/
final AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger) {
return newUpdater(consumer, logger, (s) -> {});
}
/**
* Build the updater responsible for validating new values, logging the new
* value, and eventually setting the value where it belongs.
*/
AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger, Consumer<T> validator) {
if (isDynamic()) {
return new Updater(consumer, logger, validator);
} else {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
}
/**
* this is used for settings that depend on each other... see {@link org.elasticsearch.common.settings.AbstractScopedSettings#addSettingsUpdateConsumer(Setting, Setting, BiConsumer)} and it's
* usage for details.
*/
static <A, B> AbstractScopedSettings.SettingUpdater<Tuple<A, B>> compoundUpdater(final BiConsumer<A,B> consumer, final Setting<A> aSetting, final Setting<B> bSetting, ESLogger logger) {
final AbstractScopedSettings.SettingUpdater<A> aSettingUpdater = aSetting.newUpdater(null, logger);
final AbstractScopedSettings.SettingUpdater<B> bSettingUpdater = bSetting.newUpdater(null, logger);
return new AbstractScopedSettings.SettingUpdater<Tuple<A, B>>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
return aSettingUpdater.hasChanged(current, previous) || bSettingUpdater.hasChanged(current, previous);
}
@Override
public Tuple<A, B> getValue(Settings current, Settings previous) {
return new Tuple<>(aSettingUpdater.getValue(current, previous), bSettingUpdater.getValue(current, previous));
}
@Override
public void apply(Tuple<A, B> value, Settings current, Settings previous) {
consumer.accept(value.v1(), value.v2());
}
@Override
public String toString() {
return "CompoundUpdater for: " + aSettingUpdater + " and " + bSettingUpdater;
}
};
}
private final class Updater implements AbstractScopedSettings.SettingUpdater<T> {
private final Consumer<T> consumer;
private final ESLogger logger;
private final Consumer<T> accept;
public Updater(Consumer<T> consumer, ESLogger logger, Consumer<T> accept) {
this.consumer = consumer;
this.logger = logger;
this.accept = accept;
}
@Override
public String toString() {
return "Updater for: " + Setting.this.toString();
}
@Override
public boolean hasChanged(Settings current, Settings previous) {
final String newValue = getRaw(current);
final String value = getRaw(previous);
assert isGroupSetting() == false : "group settings must override this method";
assert value != null : "value was null but can't be unless default is null which is invalid";
return value.equals(newValue) == false;
}
@Override
public T getValue(Settings current, Settings previous) {
final String newValue = getRaw(current);
final String value = getRaw(previous);
T inst = get(current);
try {
accept.accept(inst);
} catch (Exception | AssertionError e) {
throw new IllegalArgumentException("illegal value can't update [" + key + "] from [" + value + "] to [" + newValue + "]", e);
}
return inst;
}
@Override
public final void apply(T value, Settings current, Settings previous) {
logger.info("updating [{}] from [{}] to [{}]", key, getRaw(previous), getRaw(current));
consumer.accept(value);
}
}
public static Setting<Float> floatSetting(String key, float defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Float.toString(defaultValue), Float::parseFloat, properties);
}
public static Setting<Float> floatSetting(String key, float defaultValue, float minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Float.toString(defaultValue), (s) -> {
float value = Float.parseFloat(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return value;
}, properties);
}
public static Setting<Integer> intSetting(String key, int defaultValue, int minValue, int maxValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Integer.toString(defaultValue), (s) -> parseInt(s, minValue, maxValue, key), properties);
}
public static Setting<Integer> intSetting(String key, int defaultValue, int minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Integer.toString(defaultValue), (s) -> parseInt(s, minValue, key), properties);
}
public static Setting<Long> longSetting(String key, long defaultValue, long minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Long.toString(defaultValue), (s) -> parseLong(s, minValue, key), properties);
}
public static Setting<String> simpleString(String key, SettingsProperty... properties) {
return new Setting<>(key, s -> "", Function.identity(), properties);
}
public static int parseInt(String s, int minValue, String key) {
return parseInt(s, minValue, Integer.MAX_VALUE, key);
}
public static int parseInt(String s, int minValue, int maxValue, String key) {
int value = Integer.parseInt(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
if (value > maxValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be =< " + maxValue);
}
return value;
}
public static long parseLong(String s, long minValue, String key) {
long value = Long.parseLong(s);
if (value < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return value;
}
public static Setting<Integer> intSetting(String key, int defaultValue, SettingsProperty... properties) {
return intSetting(key, defaultValue, Integer.MIN_VALUE, properties);
}
public static Setting<Boolean> boolSetting(String key, boolean defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Boolean.toString(defaultValue), Booleans::parseBooleanExact, properties);
}
public static Setting<Boolean> boolSetting(String key, Setting<Boolean> fallbackSetting, SettingsProperty... properties) {
return new Setting<>(key, fallbackSetting, Booleans::parseBooleanExact, properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, String percentage, SettingsProperty... properties) {
return new Setting<>(key, (s) -> percentage, (s) -> MemorySizeValue.parseBytesSizeValueOrHeapRatio(s, key), properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, ByteSizeValue value, SettingsProperty... properties) {
return byteSizeSetting(key, (s) -> value.toString(), properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, Setting<ByteSizeValue> fallbackSettings,
SettingsProperty... properties) {
return byteSizeSetting(key, fallbackSettings::getRaw, properties);
}
public static Setting<ByteSizeValue> byteSizeSetting(String key, Function<Settings, String> defaultValue,
SettingsProperty... properties) {
return new Setting<>(key, defaultValue, (s) -> ByteSizeValue.parseBytesSizeValue(s, key), properties);
}
public static Setting<TimeValue> positiveTimeSetting(String key, TimeValue defaultValue, SettingsProperty... properties) {
return timeSetting(key, defaultValue, TimeValue.timeValueMillis(0), properties);
}
public static <T> Setting<List<T>> listSetting(String key, List<String> defaultStringValue, Function<String, T> singleValueParser,
SettingsProperty... properties) {
return listSetting(key, (s) -> defaultStringValue, singleValueParser, properties);
}
public static <T> Setting<List<T>> listSetting(String key, Setting<List<T>> fallbackSetting, Function<String, T> singleValueParser,
SettingsProperty... properties) {
return listSetting(key, (s) -> parseableStringToList(fallbackSetting.getRaw(s)), singleValueParser, properties);
}
public static <T> Setting<List<T>> listSetting(String key, Function<Settings, List<String>> defaultStringValue,
Function<String, T> singleValueParser, SettingsProperty... properties) {
Function<String, List<T>> parser = (s) ->
parseableStringToList(s).stream().map(singleValueParser).collect(Collectors.toList());
return new Setting<List<T>>(key, (s) -> arrayToParsableString(defaultStringValue.apply(s).toArray(Strings.EMPTY_ARRAY)), parser,
properties) {
private final Pattern pattern = Pattern.compile(Pattern.quote(key)+"(\\.\\d+)?");
@Override
public String getRaw(Settings settings) {
String[] array = settings.getAsArray(key, null);
return array == null ? defaultValue.apply(settings) : arrayToParsableString(array);
}
@Override
public boolean match(String toTest) {
return pattern.matcher(toTest).matches();
}
@Override
boolean hasComplexMatcher() {
return true;
}
};
}
private static List<String> parseableStringToList(String parsableString) {
try (XContentParser xContentParser = XContentType.JSON.xContent().createParser(parsableString)) {
XContentParser.Token token = xContentParser.nextToken();
if (token != XContentParser.Token.START_ARRAY) {
throw new IllegalArgumentException("expected START_ARRAY but got " + token);
}
ArrayList<String> list = new ArrayList<>();
while ((token = xContentParser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token != XContentParser.Token.VALUE_STRING) {
throw new IllegalArgumentException("expected VALUE_STRING but got " + token);
}
list.add(xContentParser.text());
}
return list;
} catch (IOException e) {
throw new IllegalArgumentException("failed to parse array", e);
}
}
private static String arrayToParsableString(String[] array) {
try {
XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent());
builder.startArray();
for (String element : array) {
builder.value(element);
}
builder.endArray();
return builder.string();
} catch (IOException ex) {
throw new ElasticsearchException(ex);
}
}
public static Setting<Settings> groupSetting(String key, SettingsProperty... properties) {
if (key.endsWith(".") == false) {
throw new IllegalArgumentException("key must end with a '.'");
}
return new Setting<Settings>(key, "", (s) -> null, properties) {
@Override
public boolean isGroupSetting() {
return true;
}
@Override
public Settings get(Settings settings) {
return settings.getByPrefix(key);
}
@Override
public boolean match(String toTest) {
return Regex.simpleMatch(key + "*", toTest);
}
@Override
public AbstractScopedSettings.SettingUpdater<Settings> newUpdater(Consumer<Settings> consumer, ESLogger logger, Consumer<Settings> validator) {
if (isDynamic() == false) {
throw new IllegalStateException("setting [" + getKey() + "] is not dynamic");
}
final Setting<?> setting = this;
return new AbstractScopedSettings.SettingUpdater<Settings>() {
@Override
public boolean hasChanged(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
return currentSettings.equals(previousSettings) == false;
}
@Override
public Settings getValue(Settings current, Settings previous) {
Settings currentSettings = get(current);
Settings previousSettings = get(previous);
try {
validator.accept(currentSettings);
} catch (Exception | AssertionError e) {
throw new IllegalArgumentException("illegal value can't update [" + key + "] from [" + previousSettings.getAsMap() + "] to [" + currentSettings.getAsMap() + "]", e);
}
return currentSettings;
}
@Override
public void apply(Settings value, Settings current, Settings previous) {
logger.info("updating [{}] from [{}] to [{}]", key, getRaw(previous), getRaw(current));
consumer.accept(value);
}
@Override
public String toString() {
return "Updater for: " + setting.toString();
}
};
}
};
}
public static Setting<TimeValue> timeSetting(String key, Function<Settings, String> defaultValue, TimeValue minValue,
SettingsProperty... properties) {
return new Setting<>(key, defaultValue, (s) -> {
TimeValue timeValue = TimeValue.parseTimeValue(s, null, key);
if (timeValue.millis() < minValue.millis()) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return timeValue;
}, properties);
}
public static Setting<TimeValue> timeSetting(String key, TimeValue defaultValue, TimeValue minValue, SettingsProperty... properties) {
return timeSetting(key, (s) -> defaultValue.getStringRep(), minValue, properties);
}
public static Setting<TimeValue> timeSetting(String key, TimeValue defaultValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> defaultValue.toString(), (s) -> TimeValue.parseTimeValue(s, key), properties);
}
public static Setting<TimeValue> timeSetting(String key, Setting<TimeValue> fallbackSetting, SettingsProperty... properties) {
return new Setting<>(key, fallbackSetting::getRaw, (s) -> TimeValue.parseTimeValue(s, key), properties);
}
public static Setting<Double> doubleSetting(String key, double defaultValue, double minValue, SettingsProperty... properties) {
return new Setting<>(key, (s) -> Double.toString(defaultValue), (s) -> {
final double d = Double.parseDouble(s);
if (d < minValue) {
throw new IllegalArgumentException("Failed to parse value [" + s + "] for setting [" + key + "] must be >= " + minValue);
}
return d;
}, properties);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Setting<?> setting = (Setting<?>) o;
return Objects.equals(key, setting.key);
}
@Override
public int hashCode() {
return Objects.hash(key);
}
/**
* This setting type allows to validate settings that have the same type and a common prefix. For instance feature.${type}=[true|false]
* can easily be added with this setting. Yet, dynamic key settings don't support updaters out of the box unless {@link #getConcreteSetting(String)}
* is used to pull the updater.
*/
public static <T> Setting<T> dynamicKeySetting(String key, String defaultValue, Function<String, T> parser,
SettingsProperty... properties) {
return new Setting<T>(key, defaultValue, parser, properties) {
@Override
boolean isGroupSetting() {
return true;
}
@Override
public boolean match(String toTest) {
return toTest.startsWith(getKey());
}
@Override
AbstractScopedSettings.SettingUpdater<T> newUpdater(Consumer<T> consumer, ESLogger logger, Consumer<T> validator) {
throw new UnsupportedOperationException("dynamic settings can't be updated use #getConcreteSetting for updating");
}
@Override
public Setting<T> getConcreteSetting(String key) {
if (match(key)) {
return new Setting<>(key, defaultValue, parser, properties);
} else {
throw new IllegalArgumentException("key must match setting but didn't ["+key +"]");
}
}
};
}
}
| Use deprecation Logger
| core/src/main/java/org/elasticsearch/common/settings/Setting.java | Use deprecation Logger | <ide><path>ore/src/main/java/org/elasticsearch/common/settings/Setting.java
<ide> import org.elasticsearch.common.Booleans;
<ide> import org.elasticsearch.common.Strings;
<ide> import org.elasticsearch.common.collect.Tuple;
<add>import org.elasticsearch.common.logging.DeprecationLogger;
<ide> import org.elasticsearch.common.logging.ESLogger;
<ide> import org.elasticsearch.common.logging.Loggers;
<ide> import org.elasticsearch.common.regex.Regex;
<ide> }
<ide>
<ide> private static final ESLogger logger = Loggers.getLogger(Setting.class);
<add> private static final DeprecationLogger deprecationLogger = new DeprecationLogger(logger);
<add>
<ide> private final String key;
<ide> protected final Function<Settings, String> defaultValue;
<ide> private final Function<String, T> parser;
<ide> // They're using the setting, so we need to tell them to stop
<ide> if (this.isDeprecated() && this.exists(settings)) {
<ide> // It would be convenient to show its replacement key, but replacement is often not so simple
<del> logger.warn("[{}] setting was deprecated in Elasticsearch and it will be removed in a future release! " +
<add> deprecationLogger.deprecated("[{}] setting was deprecated in Elasticsearch and it will be removed in a future release! " +
<ide> "See the breaking changes lists in the documentation for details", getKey());
<ide> }
<ide> return settings.get(key, defaultValue.apply(settings)); |
|
Java | apache-2.0 | e6ee9059319e9ac5bbf1ddb5549a37d3f4c6e480 | 0 | nknize/elasticsearch,gingerwizard/elasticsearch,robin13/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,coding0011/elasticsearch,vroyer/elassandra,scorpionvicky/elasticsearch,vroyer/elassandra,vroyer/elassandra,nknize/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,robin13/elasticsearch,uschindler/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,uschindler/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,HonzaKral/elasticsearch,HonzaKral/elasticsearch,gingerwizard/elasticsearch,gfyoung/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,nknize/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,HonzaKral/elasticsearch,nknize/elasticsearch,gfyoung/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,gfyoung/elasticsearch,robin13/elasticsearch,gfyoung/elasticsearch,uschindler/elasticsearch,strapdata/elassandra,strapdata/elassandra,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,strapdata/elassandra,coding0011/elasticsearch,GlenRSmith/elasticsearch,strapdata/elassandra,robin13/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch | elasticsearch/src/main/java/org/elasticsearch/xpack/watcher/support/SearchRequestEquivalence.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.watcher.support;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import java.util.Arrays;
import static org.elasticsearch.xpack.watcher.support.Exceptions.illegalState;
/**
* The only true way today to compare search request object (outside of core) is to
* serialize it and compare the serialized output. this is heavy obviously, but luckily we
* don't compare search requests in normal runtime... we only do it in the tests. The is here basically
* due to the lack of equals/hashcode support in SearchRequest in core.
*/
public final class SearchRequestEquivalence {
public static final SearchRequestEquivalence INSTANCE = new SearchRequestEquivalence();
private SearchRequestEquivalence() {
}
public boolean equivalent(@Nullable SearchRequest a, @Nullable SearchRequest b) {
return a == b ? true : (a != null && b != null ? this.doEquivalent(a, b) : false);
}
protected boolean doEquivalent(SearchRequest r1, SearchRequest r2) {
try {
BytesStreamOutput output1 = new BytesStreamOutput();
r1.writeTo(output1);
byte[] bytes1 = BytesReference.toBytes(output1.bytes());
output1.reset();
r2.writeTo(output1);
byte[] bytes2 = BytesReference.toBytes(output1.bytes());
return Arrays.equals(bytes1, bytes2);
} catch (Exception e) {
throw illegalState("could not compare search requests", e);
}
}
}
| Watcher: Remove unused class
Original commit: elastic/x-pack-elasticsearch@ecd48b7914ebfc0d496c5c1adf4add199b09b48e
| elasticsearch/src/main/java/org/elasticsearch/xpack/watcher/support/SearchRequestEquivalence.java | Watcher: Remove unused class | <ide><path>lasticsearch/src/main/java/org/elasticsearch/xpack/watcher/support/SearchRequestEquivalence.java
<del>/*
<del> * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
<del> * or more contributor license agreements. Licensed under the Elastic License;
<del> * you may not use this file except in compliance with the Elastic License.
<del> */
<del>package org.elasticsearch.xpack.watcher.support;
<del>
<del>import org.elasticsearch.action.search.SearchRequest;
<del>import org.elasticsearch.common.Nullable;
<del>import org.elasticsearch.common.bytes.BytesArray;
<del>import org.elasticsearch.common.bytes.BytesReference;
<del>import org.elasticsearch.common.io.stream.BytesStreamOutput;
<del>
<del>import java.util.Arrays;
<del>
<del>import static org.elasticsearch.xpack.watcher.support.Exceptions.illegalState;
<del>
<del>
<del>/**
<del> * The only true way today to compare search request object (outside of core) is to
<del> * serialize it and compare the serialized output. this is heavy obviously, but luckily we
<del> * don't compare search requests in normal runtime... we only do it in the tests. The is here basically
<del> * due to the lack of equals/hashcode support in SearchRequest in core.
<del> */
<del>public final class SearchRequestEquivalence {
<del>
<del> public static final SearchRequestEquivalence INSTANCE = new SearchRequestEquivalence();
<del>
<del> private SearchRequestEquivalence() {
<del> }
<del>
<del> public boolean equivalent(@Nullable SearchRequest a, @Nullable SearchRequest b) {
<del> return a == b ? true : (a != null && b != null ? this.doEquivalent(a, b) : false);
<del> }
<del>
<del> protected boolean doEquivalent(SearchRequest r1, SearchRequest r2) {
<del> try {
<del> BytesStreamOutput output1 = new BytesStreamOutput();
<del> r1.writeTo(output1);
<del> byte[] bytes1 = BytesReference.toBytes(output1.bytes());
<del> output1.reset();
<del> r2.writeTo(output1);
<del> byte[] bytes2 = BytesReference.toBytes(output1.bytes());
<del> return Arrays.equals(bytes1, bytes2);
<del> } catch (Exception e) {
<del> throw illegalState("could not compare search requests", e);
<del> }
<del> }
<del>} |
||
Java | apache-2.0 | d658e87c9bd129004008fdb632e4c6bdc25d2860 | 0 | RapidPM/proxybuilder,tfeiner/proxybuilder,ProxyBuilder/proxybuilder,tfeiner/proxybuilder,ProxyBuilder/proxybuilder,ProxyBuilder/proxybuilder,RapidPM/proxybuilder | /*
* 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.rapidpm.proxybuilder.core.annotationprocessor;
import com.google.common.base.Joiner;
import com.squareup.javapoet.*;
import com.squareup.javapoet.TypeSpec.Builder;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Generated;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import static com.squareup.javapoet.MethodSpec.methodBuilder;
import static java.util.stream.Collectors.toList;
public abstract class BasicAnnotationProcessor<T extends Annotation> extends AbstractProcessor {
public static final String METHOD_NAME_FINALIZE = "finalize";
public static final String METHOD_NAME_HASH_CODE = "hashCode";
public static final String METHOD_NAME_EQUALS = "equals";
protected static final String CLASS_NAME = "CLASS_NAME";
protected static final String DELEGATOR_FIELD_NAME = "delegator";
private final Set<MethodIdentifier> executableElementSet = new HashSet<>();
protected Filer filer;
protected Messager messager;
protected Elements elementUtils;
protected Types typeUtils;
protected Builder typeSpecBuilderForTargetClass;
@Override
public Set<String> getSupportedAnnotationTypes() {
final Set<String> annotataions = new LinkedHashSet<>();
annotataions.add(responsibleFor().getCanonicalName());
return annotataions;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
typeUtils = processingEnv.getTypeUtils();
elementUtils = processingEnv.getElementUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
roundEnv
.getElementsAnnotatedWith(responsibleFor())
.stream()
.map(e -> (TypeElement) e)
.forEach(typeElement -> {
final TypeName interface2Implement = TypeName.get(typeElement.asType());
final Builder forTargetClass = createTypeSpecBuilderForTargetClass(typeElement, interface2Implement);
addClassLevelSpecs(typeElement, roundEnv);
System.out.println(" ============================================================ ");
executableElementSet.clear();
defineNewGeneratedMethod(typeElement, forTargetClass);
executableElementSet.clear();
System.out.println(" ============================================================ ");
writeDefinedClass(pkgName(typeElement), forTargetClass);
typeSpecBuilderForTargetClass = null;
});
return true;
}
public abstract Class<T> responsibleFor();
private void defineNewGeneratedMethod(final TypeElement typeElement, final Builder forTargetClass) {
System.out.println("defineNewGeneratedMethod.typeElement = " + typeElement.getQualifiedName().toString());
if (typeElement == null) {
//loggen
} else {
// final Map<Boolean, List<ExecutableElement>> nativeNoneNativeMethodMap = typeElement
typeElement
.getEnclosedElements()
.stream()
.filter(e -> e.getKind() == ElementKind.METHOD)
.map(methodElement -> (ExecutableElement) methodElement) //cast only
.filter(methodElement -> methodElement.getModifiers().contains(Modifier.PUBLIC))
.filter(methodElement -> !methodElement.getModifiers().contains(Modifier.FINAL))
.filter(methodElement -> !methodElement.getSimpleName().toString().equals(METHOD_NAME_FINALIZE))
.filter(methodElement -> !executableElementSet.contains(new MethodIdentifier(methodElement)))
.forEach(
methodElement -> {
executableElementSet.add(new MethodIdentifier(methodElement));
final String methodName2Delegate = methodElement.getSimpleName().toString();
final CodeBlock codeBlock = defineMethodImplementation(methodElement, methodName2Delegate);
final MethodSpec delegatedMethodSpec = defineDelegatorMethod(methodElement, methodName2Delegate, codeBlock);
forTargetClass.addMethod(delegatedMethodSpec);
}
);
// work on Parent class
final TypeMirror superclass = typeElement.getSuperclass();
if (superclass != null && !"none".equals(superclass.toString())) {
final TypeElement typeElement1 = (TypeElement) typeUtils.asElement(superclass);
defineNewGeneratedMethod(typeElement1, forTargetClass);
}
// work on Interfaces
typeElement.getInterfaces()
.stream()
.forEach(t -> defineNewGeneratedMethod((TypeElement) typeUtils.asElement(t), forTargetClass));
}
}
private Builder createTypeSpecBuilderForTargetClass(final TypeElement typeElement, final TypeName type2inherit) {
if (typeSpecBuilderForTargetClass == null) {
if (typeElement.getKind() == ElementKind.INTERFACE) {
typeSpecBuilderForTargetClass = TypeSpec
.classBuilder(targetClassNameSimple(typeElement))
.addSuperinterface(type2inherit);
} else if (typeElement.getKind() == ElementKind.CLASS) {
typeSpecBuilderForTargetClass = TypeSpec
.classBuilder(targetClassNameSimple(typeElement))
.superclass(type2inherit);
// .addModifiers(Modifier.PUBLIC);
} else {
throw new RuntimeException("alles doof");
}
typeElement.getModifiers()
.stream()
.filter(m -> !m.equals(Modifier.ABSTRACT))
.forEach(m -> typeSpecBuilderForTargetClass.addModifiers(m));
}
typeSpecBuilderForTargetClass.addAnnotation(createAnnotationSpecGenerated());
return typeSpecBuilderForTargetClass;
}
protected abstract void addClassLevelSpecs(final TypeElement typeElement, final RoundEnvironment roundEnv);
protected abstract CodeBlock defineMethodImplementation(final ExecutableElement methodElement, final String methodName2Delegate);
protected MethodSpec defineDelegatorMethod(final ExecutableElement methodElement, final String methodName2Delegate, final CodeBlock codeBlock) {
System.out.println("defineDelegatorMethod.methodElement = " + methodElement);
final Set<Modifier> reducedMethodModifiers = EnumSet.copyOf(methodElement.getModifiers());
reducedMethodModifiers.remove(Modifier.ABSTRACT);
reducedMethodModifiers.remove(Modifier.NATIVE);
final MethodSpec.Builder methodBuilder = methodBuilder(methodName2Delegate);
final TypeMirror returnType = methodElement.getReturnType();
final TypeKind returnTypeKind = returnType.getKind();
final boolean primitive = returnTypeKind.isPrimitive();
if (!primitive && !returnType.toString().equals("void")) {
final boolean isDeclaredType = returnType instanceof DeclaredType;
if (!isDeclaredType) { // <T extends List>
System.out.println("defineDelegatorMethod.returnType " + returnType);
final String name = TypeName.get(returnType).toString();
System.out.println("defineDelegatorMethod.name = " + name);
final List<? extends TypeMirror> directSupertypes = typeUtils.directSupertypes(returnType);
if (directSupertypes != null && directSupertypes.size() > 1) { // <T extends List>
System.out.println("defineDelegatorMethod.directSupertypes = " + directSupertypes);
final List<TypeName> typeNames = directSupertypes
.stream()
.filter((typeMirror) -> !typeMirror.toString().equals("java.lang.Object"))
.map(TypeName::get)
.collect(Collectors.toList());
System.out.println("defineDelegatorMethod.typeNames = " + typeNames);
final ElementKind elementKind = typeUtils.asElement(returnType).getKind();
if (!elementKind.equals(ElementKind.CLASS) && !elementKind.equals(ElementKind.INTERFACE)) {
System.out.println("defineDelegatorMethod.kind (no Class no Interface ) = " + returnTypeKind);
final TypeName typeName = TypeVariableName.get(returnType);
methodBuilder.addTypeVariable(
TypeVariableName.get(
typeName.toString(),
typeNames.toArray(new TypeName[typeNames.size()])));
}
} else { // <T>
final TypeName typeName = TypeVariableName.get(returnType);
System.out.println("defineDelegatorMethod.typeName (else) = " + typeName);
methodBuilder.addTypeVariable(TypeVariableName.get(typeName.toString()));
}
}
}
return methodBuilder
.addModifiers(reducedMethodModifiers)
.returns(TypeName.get(returnType))
.addParameters(defineParamsForMethod(methodElement))
.addExceptions(methodElement
.getThrownTypes()
.stream()
.map(TypeName::get)
.collect(toList()))
.addCode(codeBlock)
.build();
}
protected String targetClassNameSimple(final TypeElement typeElement) {
return ClassName.get(pkgName(typeElement), className(typeElement) + classNamePostFix()).simpleName();
}
private String classNamePostFix() {
return responsibleFor().getSimpleName();
}
// protected Optional<TypeSpec> writeFunctionalInterface(final ExecutableElement methodElement, final MethodSpec.Builder methodSpecBuilder) {
protected Optional<TypeSpec> writeFunctionalInterface(final ExecutableElement methodElement) {
final TypeMirror returnType = methodElement.getReturnType();
final List<ParameterSpec> parameterSpecList = defineParamsForMethod(methodElement);
final MethodSpec.Builder methodSpecBuilder =
methodBuilder(methodElement.getSimpleName().toString())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.returns(TypeName.get(returnType));
parameterSpecList.forEach(methodSpecBuilder::addParameter);
final String methodNameRaw = methodElement.getSimpleName().toString();
final String firstCharUpper = (methodNameRaw.charAt(0) + "").toUpperCase();
final String finalMethodName = firstCharUpper + methodNameRaw.substring(1);
final Element typeElement = methodElement.getEnclosingElement();
final Builder functionalInterfaceTypeSpecBuilder = TypeSpec
.interfaceBuilder(typeElement.getSimpleName().toString() + "Method" + finalMethodName)
.addAnnotation(createAnnotationSpecGenerated())
.addAnnotation(FunctionalInterface.class)
.addMethod(methodSpecBuilder.build())
.addModifiers(Modifier.PUBLIC);
final Element enclosingElement = typeElement.getEnclosingElement();
final String packageName = enclosingElement.toString();
return writeDefinedClass(packageName, functionalInterfaceTypeSpecBuilder);
}
protected List<ParameterSpec> defineParamsForMethod(final ExecutableElement methodElement) {
return methodElement
.getParameters()
.stream()
.map(parameter -> {
final Name simpleName = parameter.getSimpleName();
final TypeMirror typeMirror = parameter.asType();
TypeName typeName = TypeName.get(typeMirror);
return ParameterSpec.builder(typeName, simpleName.toString(), Modifier.FINAL).build();
})
.collect(toList());
}
@NotNull
private AnnotationSpec createAnnotationSpecGenerated() {
return AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", this.getClass().getSimpleName())
.addMember("date", "$S", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME))
.addMember("comments", "$S", "www.proxybuilder.org")
.build();
}
protected Optional<TypeSpec> writeDefinedClass(String pkgName, Builder typeSpecBuilder) {
System.out.println("typeSpecBuilder = " + typeSpecBuilder);
final TypeSpec typeSpec = typeSpecBuilder.build();
final JavaFile javaFile = JavaFile.builder(pkgName, typeSpec).skipJavaLangImports(true).build();
final String className = javaFile.packageName + "." + javaFile.typeSpec.name;
try {
JavaFileObject jfo = filer.createSourceFile(className);
Writer writer = jfo.openWriter();
javaFile.writeTo(writer);
writer.flush();
return Optional.of(typeSpec);
} catch (IOException e) {
e.printStackTrace();
if (e instanceof FilerException) {
if (e.getMessage().contains("Attempt to recreate a file for type")) {
return Optional.of(typeSpec);
}
}
System.out.println("e = " + e);
}
return Optional.empty();
}
protected FieldSpec defineSimpleClassNameField(final TypeElement typeElement) {
final ClassName className = ClassName.get(typeElement);
return FieldSpec
.builder(ClassName.get(String.class), CLASS_NAME)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
// .initializer("\"" + className.simpleName() + "\"")
.initializer("\"" + className + "\"")
.build();
}
protected FieldSpec defineDelegatorField(final TypeElement typeElement) {
final ClassName delegatorClassName = ClassName.get(pkgName(typeElement), className(typeElement));
return FieldSpec
.builder(delegatorClassName, DELEGATOR_FIELD_NAME)
.addModifiers(Modifier.PRIVATE)
.build();
}
protected String pkgName(final TypeElement typeElement) {
return elementUtils.getPackageOf(typeElement).getQualifiedName().toString();
}
private String className(final Element typeElement) {
return typeElement.getSimpleName().toString();
}
protected String delegatorStatementWithReturn(final ExecutableElement methodElement, final String methodName2Delegate) {
return "return " + DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate);
}
protected String delegatorMethodCall(final ExecutableElement methodElement, final String methodName2Delegate) {
return methodName2Delegate + "(" +
Joiner.on(", ")
.skipNulls()
.join(defineParamsForMethod(methodElement)
.stream()
.map(v -> v.name)
.collect(toList())) +
")";
}
private static class MethodIdentifier {
private final String name;
private final TypeName[] parameters;
public MethodIdentifier(final String name) {
this.name = name;
parameters = new TypeName[0];
}
public MethodIdentifier(final String name, TypeName... typeNames) {
this.name = name;
parameters = new TypeName[typeNames.length];
System.arraycopy(typeNames, 0, parameters, 0, parameters.length);
}
public MethodIdentifier(final ExecutableElement methodElement) {
final List<? extends VariableElement> p = methodElement.getParameters();
parameters = new TypeName[p.size()];
for (int i = 0; i < parameters.length; i++) {
final VariableElement variableElement = p.get(i);
parameters[i] = TypeName.get(variableElement.asType());
}
name = methodElement.getSimpleName().toString();
}
public int hashCode() {
return name.hashCode();
}
// we can save time by assuming that we only compare against
// other MethodIdentifier objects
public boolean equals(Object o) {
MethodIdentifier mid = (MethodIdentifier) o;
return name.equals(mid.name) &&
Arrays.equals(parameters, mid.parameters);
}
}
}
| modules/core-annotationprocessor/src/main/java/org/rapidpm/proxybuilder/core/annotationprocessor/BasicAnnotationProcessor.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.rapidpm.proxybuilder.core.annotationprocessor;
import com.google.common.base.Joiner;
import com.squareup.javapoet.*;
import com.squareup.javapoet.TypeSpec.Builder;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Generated;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import static com.squareup.javapoet.MethodSpec.methodBuilder;
import static java.util.stream.Collectors.toList;
public abstract class BasicAnnotationProcessor<T extends Annotation> extends AbstractProcessor {
public static final String METHOD_NAME_FINALIZE = "finalize";
public static final String METHOD_NAME_HASH_CODE = "hashCode";
public static final String METHOD_NAME_EQUALS = "equals";
protected static final String CLASS_NAME = "CLASS_NAME";
protected static final String DELEGATOR_FIELD_NAME = "delegator";
private final Set<MethodIdentifier> executableElementSet = new HashSet<>();
protected Filer filer;
protected Messager messager;
protected Elements elementUtils;
protected Types typeUtils;
protected Builder typeSpecBuilderForTargetClass;
@Override
public Set<String> getSupportedAnnotationTypes() {
final Set<String> annotataions = new LinkedHashSet<>();
annotataions.add(responsibleFor().getCanonicalName());
return annotataions;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
typeUtils = processingEnv.getTypeUtils();
elementUtils = processingEnv.getElementUtils();
filer = processingEnv.getFiler();
messager = processingEnv.getMessager();
}
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
roundEnv
.getElementsAnnotatedWith(responsibleFor())
.stream()
.map(e -> (TypeElement) e)
.forEach(typeElement -> {
final TypeName interface2Implement = TypeName.get(typeElement.asType());
final Builder forTargetClass = createTypeSpecBuilderForTargetClass(typeElement, interface2Implement);
addClassLevelSpecs(typeElement, roundEnv);
System.out.println(" ============================================================ ");
executableElementSet.clear();
defineNewGeneratedMethod(typeElement, forTargetClass);
executableElementSet.clear();
System.out.println(" ============================================================ ");
writeDefinedClass(pkgName(typeElement), forTargetClass);
typeSpecBuilderForTargetClass = null;
});
return true;
}
public abstract Class<T> responsibleFor();
private void defineNewGeneratedMethod(final TypeElement typeElement, final Builder forTargetClass) {
System.out.println("defineNewGeneratedMethod.typeElement = " + typeElement.getQualifiedName().toString());
if (typeElement == null) {
//loggen
} else {
// final Map<Boolean, List<ExecutableElement>> nativeNoneNativeMethodMap = typeElement
typeElement
.getEnclosedElements()
.stream()
.filter(e -> e.getKind() == ElementKind.METHOD)
.map(methodElement -> (ExecutableElement) methodElement) //cast only
.filter(methodElement -> methodElement.getModifiers().contains(Modifier.PUBLIC))
.filter(methodElement -> !methodElement.getModifiers().contains(Modifier.FINAL))
.filter(methodElement -> !methodElement.getSimpleName().toString().equals(METHOD_NAME_FINALIZE))
.filter(methodElement -> !executableElementSet.contains(new MethodIdentifier(methodElement)))
.forEach(
methodElement -> {
executableElementSet.add(new MethodIdentifier(methodElement));
final String methodName2Delegate = methodElement.getSimpleName().toString();
final CodeBlock codeBlock = defineMethodImplementation(methodElement, methodName2Delegate);
final MethodSpec delegatedMethodSpec = defineDelegatorMethod(methodElement, methodName2Delegate, codeBlock);
forTargetClass.addMethod(delegatedMethodSpec);
}
);
// work on Parent class
final TypeMirror superclass = typeElement.getSuperclass();
if (superclass != null && !"none".equals(superclass.toString())) {
final TypeElement typeElement1 = (TypeElement) typeUtils.asElement(superclass);
defineNewGeneratedMethod(typeElement1, forTargetClass);
}
// work on Interfaces
typeElement.getInterfaces()
.stream()
.forEach(t -> defineNewGeneratedMethod((TypeElement) typeUtils.asElement(t), forTargetClass));
}
}
private Builder createTypeSpecBuilderForTargetClass(final TypeElement typeElement, final TypeName type2inherit) {
if (typeSpecBuilderForTargetClass == null) {
if (typeElement.getKind() == ElementKind.INTERFACE) {
typeSpecBuilderForTargetClass = TypeSpec
.classBuilder(targetClassNameSimple(typeElement))
.addSuperinterface(type2inherit);
} else if (typeElement.getKind() == ElementKind.CLASS) {
typeSpecBuilderForTargetClass = TypeSpec
.classBuilder(targetClassNameSimple(typeElement))
.superclass(type2inherit);
// .addModifiers(Modifier.PUBLIC);
} else {
throw new RuntimeException("alles doof");
}
typeElement.getModifiers()
.stream()
.filter(m -> !m.equals(Modifier.ABSTRACT))
.forEach(m -> typeSpecBuilderForTargetClass.addModifiers(m));
}
typeSpecBuilderForTargetClass.addAnnotation(createAnnotationSpecGenerated());
return typeSpecBuilderForTargetClass;
}
protected abstract void addClassLevelSpecs(final TypeElement typeElement, final RoundEnvironment roundEnv);
protected abstract CodeBlock defineMethodImplementation(final ExecutableElement methodElement, final String methodName2Delegate);
protected MethodSpec defineDelegatorMethod(final ExecutableElement methodElement, final String methodName2Delegate, final CodeBlock codeBlock) {
System.out.println("defineDelegatorMethod.methodElement = " + methodElement);
final Set<Modifier> reducedMethodModifiers = EnumSet.copyOf(methodElement.getModifiers());
reducedMethodModifiers.remove(Modifier.ABSTRACT);
reducedMethodModifiers.remove(Modifier.NATIVE);
final MethodSpec.Builder methodBuilder = methodBuilder(methodName2Delegate);
final TypeMirror returnType = methodElement.getReturnType();
if (returnType instanceof DeclaredType) { // <T> or <T extends List>
final boolean primitive = returnType.getKind().isPrimitive();
if (!primitive && !returnType.toString().equals("void")) {
System.out.println("defineDelegatorMethod.returnType " + returnType);
final String name = TypeName.get(returnType).toString();
System.out.println("name = " + name);
final List<? extends TypeMirror> directSupertypes = typeUtils.directSupertypes(returnType);
if (directSupertypes != null && directSupertypes.size() > 1) { // <T extends List>
System.out.println("directSupertypes = " + directSupertypes);
final List<TypeName> typeNames = directSupertypes
.stream()
.filter((typeMirror) -> !typeMirror.toString().equals("java.lang.Object"))
.map(TypeName::get)
.collect(Collectors.toList());
System.out.println("typeNames = " + typeNames);
final TypeName typeName = TypeVariableName.get(returnType);
methodBuilder.addTypeVariable(
TypeVariableName.get(
typeName.toString(),
typeNames.toArray(new TypeName[typeNames.size()])));
} else { // <T>
final TypeName typeName = TypeVariableName.get(returnType);
methodBuilder.addTypeVariable(TypeVariableName.get(typeName.toString()));
}
}
}
return methodBuilder
.addModifiers(reducedMethodModifiers)
.returns(TypeName.get(returnType))
.addParameters(defineParamsForMethod(methodElement))
.addExceptions(methodElement
.getThrownTypes()
.stream()
.map(TypeName::get)
.collect(toList()))
.addCode(codeBlock)
.build();
}
protected String targetClassNameSimple(final TypeElement typeElement) {
return ClassName.get(pkgName(typeElement), className(typeElement) + classNamePostFix()).simpleName();
}
private String classNamePostFix() {
return responsibleFor().getSimpleName();
}
// protected Optional<TypeSpec> writeFunctionalInterface(final ExecutableElement methodElement, final MethodSpec.Builder methodSpecBuilder) {
protected Optional<TypeSpec> writeFunctionalInterface(final ExecutableElement methodElement) {
final TypeMirror returnType = methodElement.getReturnType();
final List<ParameterSpec> parameterSpecList = defineParamsForMethod(methodElement);
final MethodSpec.Builder methodSpecBuilder =
methodBuilder(methodElement.getSimpleName().toString())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.returns(TypeName.get(returnType));
parameterSpecList.forEach(methodSpecBuilder::addParameter);
final String methodNameRaw = methodElement.getSimpleName().toString();
final String firstCharUpper = (methodNameRaw.charAt(0) + "").toUpperCase();
final String finalMethodName = firstCharUpper + methodNameRaw.substring(1);
final Element typeElement = methodElement.getEnclosingElement();
final Builder functionalInterfaceTypeSpecBuilder = TypeSpec
.interfaceBuilder(typeElement.getSimpleName().toString() + "Method" + finalMethodName)
.addAnnotation(createAnnotationSpecGenerated())
.addAnnotation(FunctionalInterface.class)
.addMethod(methodSpecBuilder.build())
.addModifiers(Modifier.PUBLIC);
final Element enclosingElement = typeElement.getEnclosingElement();
final String packageName = enclosingElement.toString();
return writeDefinedClass(packageName, functionalInterfaceTypeSpecBuilder);
}
protected List<ParameterSpec> defineParamsForMethod(final ExecutableElement methodElement) {
return methodElement
.getParameters()
.stream()
.map(parameter -> {
final Name simpleName = parameter.getSimpleName();
final TypeMirror typeMirror = parameter.asType();
TypeName typeName = TypeName.get(typeMirror);
return ParameterSpec.builder(typeName, simpleName.toString(), Modifier.FINAL).build();
})
.collect(toList());
}
@NotNull
private AnnotationSpec createAnnotationSpecGenerated() {
return AnnotationSpec.builder(Generated.class)
.addMember("value", "$S", this.getClass().getSimpleName())
.addMember("date", "$S", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME))
.addMember("comments", "$S", "www.proxybuilder.org")
.build();
}
protected Optional<TypeSpec> writeDefinedClass(String pkgName, Builder typeSpecBuilder) {
System.out.println("typeSpecBuilder = " + typeSpecBuilder);
final TypeSpec typeSpec = typeSpecBuilder.build();
final JavaFile javaFile = JavaFile.builder(pkgName, typeSpec).skipJavaLangImports(true).build();
final String className = javaFile.packageName + "." + javaFile.typeSpec.name;
try {
JavaFileObject jfo = filer.createSourceFile(className);
Writer writer = jfo.openWriter();
javaFile.writeTo(writer);
writer.flush();
return Optional.of(typeSpec);
} catch (IOException e) {
e.printStackTrace();
if (e instanceof FilerException) {
if (e.getMessage().contains("Attempt to recreate a file for type")) {
return Optional.of(typeSpec);
}
}
System.out.println("e = " + e);
}
return Optional.empty();
}
protected FieldSpec defineSimpleClassNameField(final TypeElement typeElement) {
final ClassName className = ClassName.get(typeElement);
return FieldSpec
.builder(ClassName.get(String.class), CLASS_NAME)
.addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
// .initializer("\"" + className.simpleName() + "\"")
.initializer("\"" + className + "\"")
.build();
}
protected FieldSpec defineDelegatorField(final TypeElement typeElement) {
final ClassName delegatorClassName = ClassName.get(pkgName(typeElement), className(typeElement));
return FieldSpec
.builder(delegatorClassName, DELEGATOR_FIELD_NAME)
.addModifiers(Modifier.PRIVATE)
.build();
}
protected String pkgName(final TypeElement typeElement) {
return elementUtils.getPackageOf(typeElement).getQualifiedName().toString();
}
private String className(final Element typeElement) {
return typeElement.getSimpleName().toString();
}
protected String delegatorStatementWithReturn(final ExecutableElement methodElement, final String methodName2Delegate) {
return "return " + DELEGATOR_FIELD_NAME + "." + delegatorMethodCall(methodElement, methodName2Delegate);
}
protected String delegatorMethodCall(final ExecutableElement methodElement, final String methodName2Delegate) {
return methodName2Delegate + "(" +
Joiner.on(", ")
.skipNulls()
.join(defineParamsForMethod(methodElement)
.stream()
.map(v -> v.name)
.collect(toList())) +
")";
}
private static class MethodIdentifier {
private final String name;
private final TypeName[] parameters;
public MethodIdentifier(final String name) {
this.name = name;
parameters = new TypeName[0];
}
public MethodIdentifier(final String name, TypeName... typeNames) {
this.name = name;
parameters = new TypeName[typeNames.length];
System.arraycopy(typeNames, 0, parameters, 0, parameters.length);
}
public MethodIdentifier(final ExecutableElement methodElement) {
final List<? extends VariableElement> p = methodElement.getParameters();
parameters = new TypeName[p.size()];
for (int i = 0; i < parameters.length; i++) {
final VariableElement variableElement = p.get(i);
parameters[i] = TypeName.get(variableElement.asType());
}
name = methodElement.getSimpleName().toString();
}
public int hashCode() {
return name.hashCode();
}
// we can save time by assuming that we only compare against
// other MethodIdentifier objects
public boolean equals(Object o) {
MethodIdentifier mid = (MethodIdentifier) o;
return name.equals(mid.name) &&
Arrays.equals(parameters, mid.parameters);
}
}
}
| added support for methods like <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException; <T extends List> T unwrapList(T type);
| modules/core-annotationprocessor/src/main/java/org/rapidpm/proxybuilder/core/annotationprocessor/BasicAnnotationProcessor.java | added support for methods like <T> T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException; <T extends List> T unwrapList(T type); | <ide><path>odules/core-annotationprocessor/src/main/java/org/rapidpm/proxybuilder/core/annotationprocessor/BasicAnnotationProcessor.java
<ide> import javax.lang.model.SourceVersion;
<ide> import javax.lang.model.element.*;
<ide> import javax.lang.model.type.DeclaredType;
<add>import javax.lang.model.type.TypeKind;
<ide> import javax.lang.model.type.TypeMirror;
<ide> import javax.lang.model.util.Elements;
<ide> import javax.lang.model.util.Types;
<ide> final MethodSpec.Builder methodBuilder = methodBuilder(methodName2Delegate);
<ide>
<ide> final TypeMirror returnType = methodElement.getReturnType();
<del> if (returnType instanceof DeclaredType) { // <T> or <T extends List>
<del> final boolean primitive = returnType.getKind().isPrimitive();
<del> if (!primitive && !returnType.toString().equals("void")) {
<add> final TypeKind returnTypeKind = returnType.getKind();
<add> final boolean primitive = returnTypeKind.isPrimitive();
<add>
<add> if (!primitive && !returnType.toString().equals("void")) {
<add> final boolean isDeclaredType = returnType instanceof DeclaredType;
<add> if (!isDeclaredType) { // <T extends List>
<ide> System.out.println("defineDelegatorMethod.returnType " + returnType);
<ide>
<ide> final String name = TypeName.get(returnType).toString();
<del> System.out.println("name = " + name);
<add> System.out.println("defineDelegatorMethod.name = " + name);
<ide>
<ide> final List<? extends TypeMirror> directSupertypes = typeUtils.directSupertypes(returnType);
<ide> if (directSupertypes != null && directSupertypes.size() > 1) { // <T extends List>
<del> System.out.println("directSupertypes = " + directSupertypes);
<add> System.out.println("defineDelegatorMethod.directSupertypes = " + directSupertypes);
<ide>
<ide> final List<TypeName> typeNames = directSupertypes
<ide> .stream()
<ide> .map(TypeName::get)
<ide> .collect(Collectors.toList());
<ide>
<del> System.out.println("typeNames = " + typeNames);
<del> final TypeName typeName = TypeVariableName.get(returnType);
<del> methodBuilder.addTypeVariable(
<del> TypeVariableName.get(
<del> typeName.toString(),
<del> typeNames.toArray(new TypeName[typeNames.size()])));
<add> System.out.println("defineDelegatorMethod.typeNames = " + typeNames);
<add> final ElementKind elementKind = typeUtils.asElement(returnType).getKind();
<add> if (!elementKind.equals(ElementKind.CLASS) && !elementKind.equals(ElementKind.INTERFACE)) {
<add> System.out.println("defineDelegatorMethod.kind (no Class no Interface ) = " + returnTypeKind);
<add> final TypeName typeName = TypeVariableName.get(returnType);
<add> methodBuilder.addTypeVariable(
<add> TypeVariableName.get(
<add> typeName.toString(),
<add> typeNames.toArray(new TypeName[typeNames.size()])));
<add> }
<ide> } else { // <T>
<ide> final TypeName typeName = TypeVariableName.get(returnType);
<add> System.out.println("defineDelegatorMethod.typeName (else) = " + typeName);
<ide> methodBuilder.addTypeVariable(TypeVariableName.get(typeName.toString()));
<ide> }
<ide> } |
|
Java | lgpl-2.1 | a1b33fcba205c57dc815d8fcb5374e35845c3b17 | 0 | golovnin/wildfly,99sono/wildfly,rhusar/wildfly,pferraro/wildfly,xasx/wildfly,tadamski/wildfly,pferraro/wildfly,jstourac/wildfly,iweiss/wildfly,99sono/wildfly,iweiss/wildfly,pferraro/wildfly,wildfly/wildfly,pferraro/wildfly,wildfly/wildfly,wildfly/wildfly,99sono/wildfly,xasx/wildfly,rhusar/wildfly,tadamski/wildfly,golovnin/wildfly,wildfly/wildfly,jstourac/wildfly,xasx/wildfly,rhusar/wildfly,tomazzupan/wildfly,golovnin/wildfly,rhusar/wildfly,jstourac/wildfly,iweiss/wildfly,tomazzupan/wildfly,jstourac/wildfly,iweiss/wildfly,tomazzupan/wildfly,tadamski/wildfly | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.webservices.service;
import static org.jboss.as.webservices.WSLogger.ROOT_LOGGER;
import java.util.List;
import javax.management.JMException;
import javax.management.MBeanServer;
import org.jboss.as.ejb3.security.service.EJBViewMethodSecurityAttributesService;
import org.jboss.as.security.plugins.SecurityDomainContext;
import org.jboss.as.security.service.SecurityDomainService;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.webservices.metadata.model.EJBEndpoint;
import org.jboss.as.webservices.security.EJBMethodSecurityAttributesAdaptor;
import org.jboss.as.webservices.security.SecurityDomainContextAdaptor;
import org.jboss.as.webservices.util.ASHelper;
import org.jboss.as.webservices.util.WSServices;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceBuilder.DependencyType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.security.SecurityConstants;
import org.jboss.security.SecurityUtil;
import org.jboss.ws.api.monitoring.RecordProcessor;
import org.jboss.ws.common.ObjectNameFactory;
import org.jboss.ws.common.management.ManagedEndpoint;
import org.jboss.ws.common.monitoring.ManagedRecordProcessor;
import org.jboss.wsf.spi.deployment.Endpoint;
import org.jboss.wsf.spi.deployment.EndpointType;
import org.jboss.wsf.spi.security.EJBMethodSecurityAttributeProvider;
/**
* WS endpoint service; this is meant for setting the lazy deployment time info into the Endpoint (stuff coming from
* dependencies upon other AS services that are started during the deployment)
*
* @author [email protected]
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author <a href="mailto:[email protected]">Jim Ma</a>
*/
public final class EndpointService implements Service<Endpoint> {
private static final ServiceName MBEAN_SERVER_NAME = ServiceName.JBOSS.append("mbean", "server");
private final Endpoint endpoint;
private final ServiceName name;
private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>();
private final InjectedValue<MBeanServer> mBeanServerValue = new InjectedValue<MBeanServer>();
private final InjectedValue<EJBViewMethodSecurityAttributesService> ejbMethodSecurityAttributeServiceValue = new InjectedValue<EJBViewMethodSecurityAttributesService>();
private EndpointService(final Endpoint endpoint, final ServiceName name) {
this.endpoint = endpoint;
this.name = name;
}
@Override
public Endpoint getValue() {
return endpoint;
}
public static ServiceName getServiceName(final DeploymentUnit unit, final String endpointName) {
if (unit.getParent() != null) {
return WSServices.ENDPOINT_SERVICE.append(unit.getParent().getName()).append(unit.getName()).append(endpointName);
} else {
return WSServices.ENDPOINT_SERVICE.append(unit.getName()).append(endpointName);
}
}
@Override
public void start(final StartContext context) throws StartException {
ROOT_LOGGER.starting(name);
endpoint.setSecurityDomainContext(new SecurityDomainContextAdaptor(securityDomainContextValue.getValue()));
if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) {
final EJBViewMethodSecurityAttributesService ejbMethodSecurityAttributeService = ejbMethodSecurityAttributeServiceValue.getValue();
endpoint.addAttachment(EJBMethodSecurityAttributeProvider.class, new EJBMethodSecurityAttributesAdaptor(ejbMethodSecurityAttributeService));
}
final List<RecordProcessor> processors = endpoint.getRecordProcessors();
for (final RecordProcessor processor : processors) {
registerRecordProcessor(processor, endpoint);
}
registerEndpoint(endpoint);
endpoint.getLifecycleHandler().start(endpoint);
}
@Override
public void stop(final StopContext context) {
ROOT_LOGGER.stopping(name);
endpoint.getLifecycleHandler().stop(endpoint);
endpoint.setSecurityDomainContext(null);
unregisterEndpoint(endpoint);
final List<RecordProcessor> processors = endpoint.getRecordProcessors();
for (final RecordProcessor processor : processors) {
unregisterRecordProcessor(processor, endpoint);
}
}
private void registerEndpoint(final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
ManagedEndpoint jmxEndpoint = new ManagedEndpoint(endpoint, mbeanServer);
mbeanServer.registerMBean(jmxEndpoint, endpoint.getName());
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot register endpoint in JMX server", ex);
ROOT_LOGGER.cannotRegisterEndpoint(endpoint.getShortName());
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(endpoint.getShortName());
}
}
private void unregisterEndpoint(final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.unregisterMBean(endpoint.getName());
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot unregister endpoint from JMX server", ex);
ROOT_LOGGER.cannotUnregisterEndpoint(endpoint.getShortName());
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(endpoint.getShortName());
}
}
private void registerRecordProcessor(final RecordProcessor processor, final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.registerMBean(processor,
ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot register endpoint in JMX server, trying with the default ManagedRecordProcessor", ex);
try {
mbeanServer.registerMBean(new ManagedRecordProcessor(processor),
ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException e) {
ROOT_LOGGER.cannotRegisterRecordProcessor();
}
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(processor);
}
}
private void unregisterRecordProcessor(final RecordProcessor processor, final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.unregisterMBean(ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException e) {
ROOT_LOGGER.cannotUnregisterRecordProcessor();
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(processor);
}
}
public Injector<SecurityDomainContext> getSecurityDomainContextInjector() {
return securityDomainContextValue;
}
public Injector<MBeanServer> getMBeanServerInjector() {
return mBeanServerValue;
}
public Injector<EJBViewMethodSecurityAttributesService> getEJBMethodSecurityAttributeServiceInjector() {
return ejbMethodSecurityAttributeServiceValue;
}
public static void install(final ServiceTarget serviceTarget, final Endpoint endpoint, final DeploymentUnit unit) {
final ServiceName serviceName = getServiceName(unit, endpoint.getShortName());
final String propContext = endpoint.getName().getKeyProperty(Endpoint.SEPID_PROPERTY_CONTEXT);
final String propEndpoint = endpoint.getName().getKeyProperty(Endpoint.SEPID_PROPERTY_ENDPOINT);
final StringBuilder context = new StringBuilder(Endpoint.SEPID_PROPERTY_CONTEXT).append("=").append(propContext);
final EndpointService service = new EndpointService(endpoint, serviceName);
final ServiceBuilder<Endpoint> builder = serviceTarget.addService(serviceName, service);
final ServiceName alias = WSServices.ENDPOINT_SERVICE.append(context.toString()).append(propEndpoint);
builder.addAliases(alias);
builder.addDependency(DependencyType.REQUIRED,
SecurityDomainService.SERVICE_NAME.append(getDeploymentSecurityDomainName(endpoint)),
SecurityDomainContext.class, service.getSecurityDomainContextInjector());
builder.addDependency(DependencyType.REQUIRED, WSServices.CONFIG_SERVICE);
builder.addDependency(DependencyType.OPTIONAL, MBEAN_SERVER_NAME, MBeanServer.class, service.getMBeanServerInjector());
if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) {
builder.addDependency(DependencyType.OPTIONAL, getEJBViewMethodSecurityAttributesServiceName(unit, endpoint),
EJBViewMethodSecurityAttributesService.class, service.getEJBMethodSecurityAttributeServiceInjector());
}
builder.setInitialMode(Mode.ACTIVE);
builder.install();
//add a dependency on the endpoint service to web deployments, so that the
//endpoint servlet is not started before the endpoint is actually available
unit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, serviceName);
}
public static void uninstall(final Endpoint endpoint, final DeploymentUnit unit) {
final ServiceName serviceName = getServiceName(unit, endpoint.getShortName());
final ServiceController<?> endpointService = WSServices.getContainerRegistry().getService(serviceName);
if (endpointService != null) {
endpointService.setMode(Mode.REMOVE);
}
}
private static String getDeploymentSecurityDomainName(final Endpoint ep) {
JBossWebMetaData metadata = ep.getService().getDeployment().getAttachment(JBossWebMetaData.class);
String metaDataSecurityDomain = metadata != null ? metadata.getSecurityDomain() : null;
return metaDataSecurityDomain == null ? SecurityConstants.DEFAULT_APPLICATION_POLICY : SecurityUtil
.unprefixSecurityDomain(metaDataSecurityDomain.trim());
}
private static ServiceName getEJBViewMethodSecurityAttributesServiceName(final DeploymentUnit unit, final Endpoint endpoint) {
for (EJBEndpoint ep : ASHelper.getJaxwsEjbs(unit)) {
if (ep.getClassName().equals(endpoint.getTargetBeanName())) {
return ep.getEJBViewMethodSecurityAttributesService();
}
}
return null;
}
}
| webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.webservices.service;
import static org.jboss.as.webservices.WSLogger.ROOT_LOGGER;
import java.util.List;
import javax.management.JMException;
import javax.management.MBeanServer;
import org.jboss.as.ejb3.security.service.EJBViewMethodSecurityAttributesService;
import org.jboss.as.security.plugins.SecurityDomainContext;
import org.jboss.as.security.service.SecurityDomainService;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.webservices.metadata.model.EJBEndpoint;
import org.jboss.as.webservices.security.EJBMethodSecurityAttributesAdaptor;
import org.jboss.as.webservices.security.SecurityDomainContextAdaptor;
import org.jboss.as.webservices.util.ASHelper;
import org.jboss.as.webservices.util.WSServices;
import org.jboss.metadata.web.jboss.JBossWebMetaData;
import org.jboss.msc.inject.Injector;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceBuilder.DependencyType;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceController.Mode;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.security.SecurityConstants;
import org.jboss.security.SecurityUtil;
import org.jboss.ws.api.monitoring.RecordProcessor;
import org.jboss.ws.common.ObjectNameFactory;
import org.jboss.ws.common.management.ManagedEndpoint;
import org.jboss.ws.common.monitoring.ManagedRecordProcessor;
import org.jboss.wsf.spi.deployment.Endpoint;
import org.jboss.wsf.spi.deployment.EndpointType;
import org.jboss.wsf.spi.security.EJBMethodSecurityAttributeProvider;
/**
* WS endpoint service; this is meant for setting the lazy deployment time info into the Endpoint (stuff coming from
* dependencies upon other AS services that are started during the deployment)
*
* @author [email protected]
* @author <a href="mailto:[email protected]">Richard Opalka</a>
* @author <a href="mailto:[email protected]">Jim Ma</a>
*/
public final class EndpointService implements Service<Endpoint> {
private static final ServiceName MBEAN_SERVER_NAME = ServiceName.JBOSS.append("mbean", "server");
private final Endpoint endpoint;
private final ServiceName name;
private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>();
private final InjectedValue<MBeanServer> mBeanServerValue = new InjectedValue<MBeanServer>();
private final InjectedValue<EJBViewMethodSecurityAttributesService> ejbMethodSecurityAttributeServiceValue = new InjectedValue<EJBViewMethodSecurityAttributesService>();
private EndpointService(final Endpoint endpoint, final ServiceName name) {
this.endpoint = endpoint;
this.name = name;
}
@Override
public Endpoint getValue() {
return endpoint;
}
public static ServiceName getServiceName(final DeploymentUnit unit, final String endpointName) {
if (unit.getParent() != null) {
return WSServices.ENDPOINT_SERVICE.append(unit.getParent().getName()).append(unit.getName()).append(endpointName);
} else {
return WSServices.ENDPOINT_SERVICE.append(unit.getName()).append(endpointName);
}
}
@Override
public void start(final StartContext context) throws StartException {
ROOT_LOGGER.starting(name);
endpoint.setSecurityDomainContext(new SecurityDomainContextAdaptor(securityDomainContextValue.getValue()));
if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) {
final EJBViewMethodSecurityAttributesService ejbMethodSecurityAttributeService = ejbMethodSecurityAttributeServiceValue.getValue();
endpoint.addAttachment(EJBMethodSecurityAttributeProvider.class, new EJBMethodSecurityAttributesAdaptor(ejbMethodSecurityAttributeService));
}
final List<RecordProcessor> processors = endpoint.getRecordProcessors();
for (final RecordProcessor processor : processors) {
registerRecordProcessor(processor, endpoint);
}
registerEndpoint(endpoint);
endpoint.getLifecycleHandler().start(endpoint);
}
@Override
public void stop(final StopContext context) {
ROOT_LOGGER.stopping(name);
endpoint.getLifecycleHandler().stop(endpoint);
endpoint.setSecurityDomainContext(null);
unregisterEndpoint(endpoint);
final List<RecordProcessor> processors = endpoint.getRecordProcessors();
for (final RecordProcessor processor : processors) {
unregisterRecordProcessor(processor, endpoint);
}
}
private void registerEndpoint(final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
ManagedEndpoint jmxEndpoint = new ManagedEndpoint(endpoint, mbeanServer);
mbeanServer.registerMBean(jmxEndpoint, endpoint.getName());
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot register endpoint in JMX server", ex);
ROOT_LOGGER.cannotRegisterEndpoint(endpoint.getShortName());
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(endpoint.getShortName());
}
}
private void unregisterEndpoint(final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.unregisterMBean(endpoint.getName());
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot unregister endpoint from JMX server", ex);
ROOT_LOGGER.cannotUnregisterEndpoint(endpoint.getShortName());
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(endpoint.getShortName());
}
}
private void registerRecordProcessor(final RecordProcessor processor, final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.registerMBean(processor,
ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException ex) {
ROOT_LOGGER.trace("Cannot register endpoint in JMX server, trying with the default ManagedRecordProcessor", ex);
try {
mbeanServer.registerMBean(new ManagedRecordProcessor(processor),
ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException e) {
ROOT_LOGGER.cannotRegisterRecordProcessor();
}
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(processor);
}
}
private void unregisterRecordProcessor(final RecordProcessor processor, final Endpoint ep) {
MBeanServer mbeanServer = mBeanServerValue.getValue();
if (mbeanServer != null) {
try {
mbeanServer.unregisterMBean(ObjectNameFactory.create(ep.getName() + ",recordProcessor=" + processor.getName()));
} catch (final JMException e) {
ROOT_LOGGER.cannotUnregisterRecordProcessor();
}
} else {
ROOT_LOGGER.mBeanServerNotAvailable(processor);
}
}
public Injector<SecurityDomainContext> getSecurityDomainContextInjector() {
return securityDomainContextValue;
}
public Injector<MBeanServer> getMBeanServerInjector() {
return mBeanServerValue;
}
public Injector<EJBViewMethodSecurityAttributesService> getEJBMethodSecurityAttributeServiceInjector() {
return ejbMethodSecurityAttributeServiceValue;
}
public static void install(final ServiceTarget serviceTarget, final Endpoint endpoint, final DeploymentUnit unit) {
final ServiceName serviceName = getServiceName(unit, endpoint.getShortName());
final String propContext = endpoint.getName().getKeyProperty(Endpoint.SEPID_PROPERTY_CONTEXT);
final String propEndpoint = endpoint.getName().getKeyProperty(Endpoint.SEPID_PROPERTY_ENDPOINT);
final StringBuilder context = new StringBuilder(Endpoint.SEPID_PROPERTY_CONTEXT).append("=").append(propContext);
final EndpointService service = new EndpointService(endpoint, serviceName);
final ServiceBuilder<Endpoint> builder = serviceTarget.addService(serviceName, service);
final ServiceName alias = WSServices.ENDPOINT_SERVICE.append(context.toString()).append(propEndpoint);
builder.addAliases(alias);
builder.addDependency(DependencyType.REQUIRED,
SecurityDomainService.SERVICE_NAME.append(getDeploymentSecurityDomainName(endpoint)),
SecurityDomainContext.class, service.getSecurityDomainContextInjector());
builder.addDependency(DependencyType.REQUIRED, WSServices.CONFIG_SERVICE);
builder.addDependency(DependencyType.OPTIONAL, MBEAN_SERVER_NAME, MBeanServer.class, service.getMBeanServerInjector());
if (EndpointType.JAXWS_EJB3.equals(endpoint.getType())) {
builder.addDependency(DependencyType.OPTIONAL, getEJBViewMethodSecurityAttributesServiceName(unit, endpoint),
EJBViewMethodSecurityAttributesService.class, service.getEJBMethodSecurityAttributeServiceInjector());
}
builder.setInitialMode(Mode.ACTIVE);
builder.install();
}
public static void uninstall(final Endpoint endpoint, final DeploymentUnit unit) {
final ServiceName serviceName = getServiceName(unit, endpoint.getShortName());
final ServiceController<?> endpointService = WSServices.getContainerRegistry().getService(serviceName);
if (endpointService != null) {
endpointService.setMode(Mode.REMOVE);
}
}
private static String getDeploymentSecurityDomainName(final Endpoint ep) {
JBossWebMetaData metadata = ep.getService().getDeployment().getAttachment(JBossWebMetaData.class);
String metaDataSecurityDomain = metadata != null ? metadata.getSecurityDomain() : null;
return metaDataSecurityDomain == null ? SecurityConstants.DEFAULT_APPLICATION_POLICY : SecurityUtil
.unprefixSecurityDomain(metaDataSecurityDomain.trim());
}
private static ServiceName getEJBViewMethodSecurityAttributesServiceName(final DeploymentUnit unit, final Endpoint endpoint) {
for (EJBEndpoint ep : ASHelper.getJaxwsEjbs(unit)) {
if (ep.getClassName().equals(endpoint.getTargetBeanName())) {
return ep.getEJBViewMethodSecurityAttributesService();
}
}
return null;
}
}
| [JBWS-3735] Add dependencies on WS endpoint services to the web deployment
| webservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java | [JBWS-3735] Add dependencies on WS endpoint services to the web deployment | <ide><path>ebservices/server-integration/src/main/java/org/jboss/as/webservices/service/EndpointService.java
<ide> import org.jboss.as.ejb3.security.service.EJBViewMethodSecurityAttributesService;
<ide> import org.jboss.as.security.plugins.SecurityDomainContext;
<ide> import org.jboss.as.security.service.SecurityDomainService;
<add>import org.jboss.as.server.deployment.Attachments;
<ide> import org.jboss.as.server.deployment.DeploymentUnit;
<ide> import org.jboss.as.webservices.metadata.model.EJBEndpoint;
<ide> import org.jboss.as.webservices.security.EJBMethodSecurityAttributesAdaptor;
<ide> }
<ide> builder.setInitialMode(Mode.ACTIVE);
<ide> builder.install();
<add> //add a dependency on the endpoint service to web deployments, so that the
<add> //endpoint servlet is not started before the endpoint is actually available
<add> unit.addToAttachmentList(Attachments.WEB_DEPENDENCIES, serviceName);
<ide> }
<ide>
<ide> public static void uninstall(final Endpoint endpoint, final DeploymentUnit unit) { |
|
Java | mit | 71bf0470f100095443130eddc012a39096415621 | 0 | Mararok/EpicWar | /**
* EpicWar
* The MIT License
* Copyright (C) 2015 Mararok <[email protected]>
*/
package com.mararok.epicwar.control.point.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.logging.Level;
import org.bukkit.scheduler.BukkitRunnable;
import com.mararok.epicwar.War;
import com.mararok.epicwar.control.ControlPoint;
import com.mararok.epicwar.control.ControlPointData;
import com.mararok.epicwar.control.ControlPointManager;
public class ControlPointManagerImpl implements ControlPointManager {
private ArrayList<ControlPoint> controlPoints;
private Collection<ControlPointImpl> occupiedControlPoints;
private UpdateTask updateTask;
private ControlPointMapper mapper;
private War war;
public ControlPointManagerImpl(ControlPointMapper mapper, War war) throws Exception {
controlPoints = new ArrayList<ControlPoint>();
this.mapper = mapper;
this.war = war;
loadAll();
}
private void loadAll() throws Exception {
Collection<ControlPointImpl> collection = mapper.findAll();
controlPoints.ensureCapacity(collection.size() + 1);
for (ControlPoint controlPoint : collection) {
controlPoints.set(controlPoint.getId(), controlPoint);
}
if (!war.getSettings().editMode) {
occupiedControlPoints = new LinkedList<ControlPointImpl>();
updateTask = this.new UpdateTask();
updateTask.runTaskTimer(war.getPlugin(), 0, war.getSettings().controlPoint.updateInterval);
}
}
@Override
public ControlPoint findById(int id) {
return (id > 0 && id < controlPoints.size()) ? controlPoints.get(id) : null;
}
@Override
public Collection<ControlPoint> findAll() {
return Collections.unmodifiableCollection(controlPoints);
}
@Override
public ControlPoint create(ControlPointData data) throws Exception {
ControlPointImpl controlPoint = mapper.insert(data);
controlPoints.ensureCapacity(controlPoint.getId() + 1);
controlPoints.set(controlPoint.getId(), controlPoint);
return controlPoint;
}
@Override
public void update(ControlPoint controlPoint) throws Exception {
ControlPointImpl entity = (ControlPointImpl) controlPoint;
mapper.update(entity);
entity.clearChanges();
}
@Override
public War getWar() {
return war;
}
private class UpdateTask extends BukkitRunnable {
@Override
public void run() {
try {
for (ControlPointImpl controlPoint : occupiedControlPoints) {
controlPoint.getOccupation().update();
}
} catch (Exception e) {
war.getPlugin().getLogger().log(Level.SEVERE, "Exception in control point occupation update", e);
}
}
}
public void addOccupied(ControlPointImpl controlPoint) {
if (!occupiedControlPoints.contains(controlPoint)) {
occupiedControlPoints.add(controlPoint);
}
}
public void removeOccupied(ControlPointImpl controlPoint) {
occupiedControlPoints.remove(controlPoint);
}
}
| src/main/com/mararok/epicwar/control/point/internal/ControlPointManagerImpl.java | /**
* EpicWar
* The MIT License
* Copyright (C) 2015 Mararok <[email protected]>
*/
package com.mararok.epicwar.control.point.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.scheduler.BukkitRunnable;
import com.mararok.epicwar.War;
import com.mararok.epicwar.control.ControlPoint;
import com.mararok.epicwar.control.ControlPointData;
import com.mararok.epicwar.control.ControlPointManager;
public class ControlPointManagerImpl implements ControlPointManager {
private List<ControlPoint> controlPoints;
private Collection<ControlPointImpl> occupiedControlPoints;
private ControlPointMapper mapper;
private UpdateTask updateTask;
private War war;
public ControlPointManagerImpl(ControlPointMapper mapper, War war) throws Exception {
this.mapper = mapper;
this.war = war;
controlPoints = new ArrayList<ControlPoint>();
loadAll();
}
private void loadAll() throws Exception {
Collection<ControlPointImpl> collection = mapper.findAll();
for (ControlPoint controlPoint : collection) {
controlPoints.set(controlPoint.getId(), controlPoint);
}
if (!war.getSettings().editMode) {
occupiedControlPoints = new LinkedList<ControlPointImpl>();
updateTask = this.new UpdateTask();
updateTask.runTaskTimer(war.getPlugin(), 0, war.getSettings().controlPoint.updateInterval);
}
}
@Override
public ControlPoint findById(int id) {
if (id > 0 && id < controlPoints.size()) {
return controlPoints.get(id);
}
return null;
}
@Override
public Collection<ControlPoint> findAll() {
return Collections.unmodifiableCollection(controlPoints);
}
@Override
public ControlPoint create(ControlPointData data) throws Exception {
ControlPointImpl controlPoint = mapper.insert(data);
controlPoints.set(controlPoint.getId(), controlPoint);
return controlPoint;
}
@Override
public void update(ControlPoint controlPoint) throws Exception {
ControlPointImpl entity = (ControlPointImpl) controlPoint;
mapper.update(entity);
}
@Override
public void delete(ControlPoint controlPoint) throws Exception {
ControlPointImpl entity = (ControlPointImpl) controlPoint;
mapper.delete(entity);
controlPoints.remove(entity.getId());
}
@Override
public War getWar() {
return war;
}
private class UpdateTask extends BukkitRunnable {
@Override
public void run() {
for (ControlPointImpl controlPoint : occupiedControlPoints) {
controlPoint.getOccupation().update();
}
}
}
}
| Refactored
Removed "delete" method
Fixed update method | src/main/com/mararok/epicwar/control/point/internal/ControlPointManagerImpl.java | Refactored | <ide><path>rc/main/com/mararok/epicwar/control/point/internal/ControlPointManagerImpl.java
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.LinkedList;
<del>import java.util.List;
<add>import java.util.logging.Level;
<ide>
<ide> import org.bukkit.scheduler.BukkitRunnable;
<ide>
<ide> import com.mararok.epicwar.control.ControlPointManager;
<ide>
<ide> public class ControlPointManagerImpl implements ControlPointManager {
<del> private List<ControlPoint> controlPoints;
<add> private ArrayList<ControlPoint> controlPoints;
<add>
<ide> private Collection<ControlPointImpl> occupiedControlPoints;
<add> private UpdateTask updateTask;
<add>
<ide> private ControlPointMapper mapper;
<del> private UpdateTask updateTask;
<ide> private War war;
<ide>
<ide> public ControlPointManagerImpl(ControlPointMapper mapper, War war) throws Exception {
<add> controlPoints = new ArrayList<ControlPoint>();
<ide> this.mapper = mapper;
<ide> this.war = war;
<del>
<del> controlPoints = new ArrayList<ControlPoint>();
<ide> loadAll();
<ide> }
<ide>
<ide> private void loadAll() throws Exception {
<ide> Collection<ControlPointImpl> collection = mapper.findAll();
<add> controlPoints.ensureCapacity(collection.size() + 1);
<ide> for (ControlPoint controlPoint : collection) {
<ide> controlPoints.set(controlPoint.getId(), controlPoint);
<ide> }
<ide>
<ide> @Override
<ide> public ControlPoint findById(int id) {
<del> if (id > 0 && id < controlPoints.size()) {
<del> return controlPoints.get(id);
<del> }
<del> return null;
<add> return (id > 0 && id < controlPoints.size()) ? controlPoints.get(id) : null;
<ide> }
<ide>
<ide> @Override
<ide> @Override
<ide> public ControlPoint create(ControlPointData data) throws Exception {
<ide> ControlPointImpl controlPoint = mapper.insert(data);
<add> controlPoints.ensureCapacity(controlPoint.getId() + 1);
<ide> controlPoints.set(controlPoint.getId(), controlPoint);
<ide> return controlPoint;
<ide> }
<ide> public void update(ControlPoint controlPoint) throws Exception {
<ide> ControlPointImpl entity = (ControlPointImpl) controlPoint;
<ide> mapper.update(entity);
<del> }
<del>
<del> @Override
<del> public void delete(ControlPoint controlPoint) throws Exception {
<del> ControlPointImpl entity = (ControlPointImpl) controlPoint;
<del> mapper.delete(entity);
<del> controlPoints.remove(entity.getId());
<add> entity.clearChanges();
<ide> }
<ide>
<ide> @Override
<ide> private class UpdateTask extends BukkitRunnable {
<ide> @Override
<ide> public void run() {
<del> for (ControlPointImpl controlPoint : occupiedControlPoints) {
<del> controlPoint.getOccupation().update();
<add> try {
<add> for (ControlPointImpl controlPoint : occupiedControlPoints) {
<add> controlPoint.getOccupation().update();
<add> }
<add> } catch (Exception e) {
<add> war.getPlugin().getLogger().log(Level.SEVERE, "Exception in control point occupation update", e);
<ide> }
<ide> }
<ide> }
<ide>
<add> public void addOccupied(ControlPointImpl controlPoint) {
<add> if (!occupiedControlPoints.contains(controlPoint)) {
<add> occupiedControlPoints.add(controlPoint);
<add> }
<add> }
<add>
<add> public void removeOccupied(ControlPointImpl controlPoint) {
<add> occupiedControlPoints.remove(controlPoint);
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | f121b6ac9040ecfe26683eb3a82848792556de5b | 0 | Peter32/spring-security,liuguohua/spring-security,cyratech/spring-security,kazuki43zoo/spring-security,raindev/spring-security,fhanik/spring-security,zgscwjm/spring-security,zshift/spring-security,olezhuravlev/spring-security,caiwenshu/spring-security,zhaoqin102/spring-security,xingguang2013/spring-security,thomasdarimont/spring-security,pwheel/spring-security,chinazhaoht/spring-security,pwheel/spring-security,justinedelson/spring-security,xingguang2013/spring-security,pwheel/spring-security,dsyer/spring-security,pwheel/spring-security,fhanik/spring-security,spring-projects/spring-security,djechelon/spring-security,caiwenshu/spring-security,izeye/spring-security,SanjayUser/SpringSecurityPro,mdeinum/spring-security,jgrandja/spring-security,spring-projects/spring-security,olezhuravlev/spring-security,izeye/spring-security,kazuki43zoo/spring-security,follow99/spring-security,ajdinhedzic/spring-security,adairtaosy/spring-security,jgrandja/spring-security,yinhe402/spring-security,forestqqqq/spring-security,Xcorpio/spring-security,cyratech/spring-security,eddumelendez/spring-security,jgrandja/spring-security,thomasdarimont/spring-security,jgrandja/spring-security,hippostar/spring-security,driftman/spring-security,rwinch/spring-security,spring-projects/spring-security,chinazhaoht/spring-security,hippostar/spring-security,liuguohua/spring-security,likaiwalkman/spring-security,justinedelson/spring-security,kazuki43zoo/spring-security,SanjayUser/SpringSecurityPro,wilkinsona/spring-security,zgscwjm/spring-security,SanjayUser/SpringSecurityPro,mparaz/spring-security,mdeinum/spring-security,zhaoqin102/spring-security,mrkingybc/spring-security,ractive/spring-security,ollie314/spring-security,rwinch/spring-security,spring-projects/spring-security,pwheel/spring-security,yinhe402/spring-security,fhanik/spring-security,ractive/spring-security,tekul/spring-security,mounb/spring-security,spring-projects/spring-security,MatthiasWinzeler/spring-security,olezhuravlev/spring-security,driftman/spring-security,zshift/spring-security,pkdevbox/spring-security,yinhe402/spring-security,eddumelendez/spring-security,vitorgv/spring-security,diegofernandes/spring-security,SanjayUser/SpringSecurityPro,wilkinsona/spring-security,djechelon/spring-security,dsyer/spring-security,rwinch/spring-security,liuguohua/spring-security,rwinch/spring-security,olezhuravlev/spring-security,jmnarloch/spring-security,hippostar/spring-security,djechelon/spring-security,MatthiasWinzeler/spring-security,cyratech/spring-security,adairtaosy/spring-security,spring-projects/spring-security,follow99/spring-security,thomasdarimont/spring-security,caiwenshu/spring-security,kazuki43zoo/spring-security,ractive/spring-security,panchenko/spring-security,pkdevbox/spring-security,spring-projects/spring-security,Peter32/spring-security,vitorgv/spring-security,dsyer/spring-security,djechelon/spring-security,eddumelendez/spring-security,dsyer/spring-security,Xcorpio/spring-security,dsyer/spring-security,hippostar/spring-security,ajdinhedzic/spring-security,driftman/spring-security,mparaz/spring-security,driftman/spring-security,MatthiasWinzeler/spring-security,izeye/spring-security,mparaz/spring-security,ollie314/spring-security,mrkingybc/spring-security,mounb/spring-security,likaiwalkman/spring-security,Krasnyanskiy/spring-security,Peter32/spring-security,chinazhaoht/spring-security,thomasdarimont/spring-security,tekul/spring-security,zgscwjm/spring-security,zhaoqin102/spring-security,eddumelendez/spring-security,ajdinhedzic/spring-security,fhanik/spring-security,diegofernandes/spring-security,rwinch/spring-security,zgscwjm/spring-security,Xcorpio/spring-security,zshift/spring-security,ollie314/spring-security,pkdevbox/spring-security,wkorando/spring-security,eddumelendez/spring-security,justinedelson/spring-security,fhanik/spring-security,tekul/spring-security,jmnarloch/spring-security,diegofernandes/spring-security,wilkinsona/spring-security,zshift/spring-security,izeye/spring-security,diegofernandes/spring-security,djechelon/spring-security,likaiwalkman/spring-security,thomasdarimont/spring-security,mrkingybc/spring-security,mounb/spring-security,mdeinum/spring-security,follow99/spring-security,jmnarloch/spring-security,chinazhaoht/spring-security,wkorando/spring-security,mparaz/spring-security,follow99/spring-security,Krasnyanskiy/spring-security,raindev/spring-security,Xcorpio/spring-security,vitorgv/spring-security,raindev/spring-security,liuguohua/spring-security,forestqqqq/spring-security,mdeinum/spring-security,forestqqqq/spring-security,Peter32/spring-security,jgrandja/spring-security,forestqqqq/spring-security,olezhuravlev/spring-security,zhaoqin102/spring-security,cyratech/spring-security,ollie314/spring-security,xingguang2013/spring-security,Krasnyanskiy/spring-security,mounb/spring-security,panchenko/spring-security,mrkingybc/spring-security,ractive/spring-security,wilkinsona/spring-security,wkorando/spring-security,SanjayUser/SpringSecurityPro,likaiwalkman/spring-security,raindev/spring-security,yinhe402/spring-security,vitorgv/spring-security,ajdinhedzic/spring-security,panchenko/spring-security,Krasnyanskiy/spring-security,jgrandja/spring-security,xingguang2013/spring-security,rwinch/spring-security,pkdevbox/spring-security,jmnarloch/spring-security,tekul/spring-security,caiwenshu/spring-security,wkorando/spring-security,kazuki43zoo/spring-security,MatthiasWinzeler/spring-security,adairtaosy/spring-security,adairtaosy/spring-security,justinedelson/spring-security,fhanik/spring-security,panchenko/spring-security | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.concurrent;
import junit.framework.TestCase;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.mock.web.MockHttpSession;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
/**
* Tests {@link SessionRegistryImpl}.
*
* @author Ben Alex
* @version $Id$
*/
public class SessionRegistryImplTests extends TestCase {
private SessionRegistryImpl sessionRegistry;
//~ Methods ========================================================================================================
protected void setUp() throws Exception {
sessionRegistry = new SessionRegistryImpl();
}
public void testEventPublishing() {
MockHttpSession httpSession = new MockHttpSession();
Object principal = "Some principal object";
String sessionId = httpSession.getId();
assertNotNull(sessionId);
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
// Deregister session via an ApplicationEvent
sessionRegistry.onApplicationEvent(new HttpSessionDestroyedEvent(httpSession));
// Check attempts to retrieve cleared session return null
assertNull(sessionRegistry.getSessionInformation(sessionId));
}
public void testMultiplePrincipals() throws Exception {
Object principal1 = "principal_1";
Object principal2 = "principal_2";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
String sessionId3 = "5432109876";
sessionRegistry.registerNewSession(sessionId1, principal1);
sessionRegistry.registerNewSession(sessionId2, principal1);
sessionRegistry.registerNewSession(sessionId3, principal2);
assertEquals(principal1, sessionRegistry.getAllPrincipals()[0]);
assertEquals(principal2, sessionRegistry.getAllPrincipals()[1]);
}
public void testSessionInformationLifecycle() throws Exception {
Object principal = "Some principal object";
String sessionId = "1234567890";
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
// Retrieve existing session by session ID
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertEquals(principal, sessionRegistry.getSessionInformation(sessionId).getPrincipal());
assertEquals(sessionId, sessionRegistry.getSessionInformation(sessionId).getSessionId());
assertNotNull(sessionRegistry.getSessionInformation(sessionId).getLastRequest());
// Retrieve existing session by principal
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
// Sleep to ensure SessionRegistryImpl will update time
Thread.sleep(1000);
// Update request date/time
sessionRegistry.refreshLastRequest(sessionId);
Date retrieved = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertTrue(retrieved.after(currentDateTime));
// Check it retrieves correctly when looked up via principal
assertEquals(retrieved, sessionRegistry.getAllSessions(principal, false)[0].getLastRequest());
// Clear session information
sessionRegistry.removeSessionInformation(sessionId);
// Check attempts to retrieve cleared session return null
assertNull(sessionRegistry.getSessionInformation(sessionId));
assertNull(sessionRegistry.getAllSessions(principal, false));
}
public void testTwoSessionsOnePrincipalExpiring() throws Exception {
Object principal = "Some principal object";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
sessionRegistry.registerNewSession(sessionId1, principal);
SessionInformation[] sessions = sessionRegistry.getAllSessions(principal, false);
assertEquals(1, sessions.length);
assertTrue(contains(sessionId1, principal));
sessionRegistry.registerNewSession(sessionId2, principal);
sessions = sessionRegistry.getAllSessions(principal, false);
assertEquals(2, sessions.length);
assertTrue(contains(sessionId2, principal));
// Expire one session
SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
session.expireNow();
// Check retrieval still correct
assertTrue(sessionRegistry.getSessionInformation(sessionId2).isExpired());
assertFalse(sessionRegistry.getSessionInformation(sessionId1).isExpired());
}
public void testTwoSessionsOnePrincipalHandling() throws Exception {
Object principal = "Some principal object";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
sessionRegistry.registerNewSession(sessionId1, principal);
SessionInformation[] sessions = sessionRegistry.getAllSessions(principal, false);
assertEquals(1, sessions.length);
assertTrue(contains(sessionId1, principal));
sessionRegistry.registerNewSession(sessionId2, principal);
sessions = sessionRegistry.getAllSessions(principal, false);
assertEquals(2, sessions.length);
assertTrue(contains(sessionId2, principal));
sessionRegistry.removeSessionInformation(sessionId1);
sessions = sessionRegistry.getAllSessions(principal, false);
assertEquals(1, sessions.length);
assertTrue(contains(sessionId2, principal));
sessionRegistry.removeSessionInformation(sessionId2);
assertNull(sessionRegistry.getSessionInformation(sessionId2));
assertNull(sessionRegistry.getAllSessions(principal, false));
}
boolean contains(String sessionId, Object principal) {
SessionInformation[] info = sessionRegistry.getAllSessions(principal, false);
for (int i = 0; i < info.length; i++) {
if (sessionId.equals(info[i].getSessionId())) {
return true;
}
}
return false;
}
}
| core/src/test/java/org/springframework/security/concurrent/SessionRegistryImplTests.java | /* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.concurrent;
import junit.framework.TestCase;
import org.springframework.security.ui.session.HttpSessionDestroyedEvent;
import org.springframework.mock.web.MockHttpSession;
import java.util.Date;
/**
* Tests {@link SessionRegistryImpl}.
*
* @author Ben Alex
* @version $Id$
*/
public class SessionRegistryImplTests extends TestCase {
//~ Methods ========================================================================================================
public void testEventPublishing() {
MockHttpSession httpSession = new MockHttpSession();
Object principal = "Some principal object";
String sessionId = httpSession.getId();
assertNotNull(sessionId);
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
// Deregister session via an ApplicationEvent
sessionRegistry.onApplicationEvent(new HttpSessionDestroyedEvent(httpSession));
// Check attempts to retrieve cleared session return null
assertNull(sessionRegistry.getSessionInformation(sessionId));
}
public void testMultiplePrincipals() throws Exception {
Object principal1 = "principal_1";
Object principal2 = "principal_2";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
String sessionId3 = "5432109876";
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
sessionRegistry.registerNewSession(sessionId1, principal1);
sessionRegistry.registerNewSession(sessionId2, principal1);
sessionRegistry.registerNewSession(sessionId3, principal2);
assertEquals(principal1, sessionRegistry.getAllPrincipals()[0]);
assertEquals(principal2, sessionRegistry.getAllPrincipals()[1]);
}
public void testSessionInformationLifecycle() throws Exception {
Object principal = "Some principal object";
String sessionId = "1234567890";
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
// Register new Session
sessionRegistry.registerNewSession(sessionId, principal);
// Retrieve existing session by session ID
Date currentDateTime = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertEquals(principal, sessionRegistry.getSessionInformation(sessionId).getPrincipal());
assertEquals(sessionId, sessionRegistry.getSessionInformation(sessionId).getSessionId());
assertNotNull(sessionRegistry.getSessionInformation(sessionId).getLastRequest());
// Retrieve existing session by principal
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
// Sleep to ensure SessionRegistryImpl will update time
Thread.sleep(1000);
// Update request date/time
sessionRegistry.refreshLastRequest(sessionId);
Date retrieved = sessionRegistry.getSessionInformation(sessionId).getLastRequest();
assertTrue(retrieved.after(currentDateTime));
// Check it retrieves correctly when looked up via principal
assertEquals(retrieved, sessionRegistry.getAllSessions(principal, false)[0].getLastRequest());
// Clear session information
sessionRegistry.removeSessionInformation(sessionId);
// Check attempts to retrieve cleared session return null
assertNull(sessionRegistry.getSessionInformation(sessionId));
assertNull(sessionRegistry.getAllSessions(principal, false));
}
public void testTwoSessionsOnePrincipalExpiring() throws Exception {
Object principal = "Some principal object";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
// Register new Session
sessionRegistry.registerNewSession(sessionId1, principal);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Register new Session
sessionRegistry.registerNewSession(sessionId2, principal);
assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
// Expire one session
SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
session.expireNow();
// Check retrieval still correct
assertTrue(sessionRegistry.getSessionInformation(sessionId2).isExpired());
assertFalse(sessionRegistry.getSessionInformation(sessionId1).isExpired());
}
public void testTwoSessionsOnePrincipalHandling() throws Exception {
Object principal = "Some principal object";
String sessionId1 = "1234567890";
String sessionId2 = "9876543210";
SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
// Register new Session
sessionRegistry.registerNewSession(sessionId1, principal);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Register new Session
sessionRegistry.registerNewSession(sessionId2, principal);
assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
// Clear session information
sessionRegistry.removeSessionInformation(sessionId1);
assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
// Clear final session
sessionRegistry.removeSessionInformation(sessionId2);
assertNull(sessionRegistry.getSessionInformation(sessionId2));
assertNull(sessionRegistry.getAllSessions(principal, false));
}
}
| Fixed tests which were making assumptions about ordering within sets.
| core/src/test/java/org/springframework/security/concurrent/SessionRegistryImplTests.java | Fixed tests which were making assumptions about ordering within sets. | <ide><path>ore/src/test/java/org/springframework/security/concurrent/SessionRegistryImplTests.java
<ide> import org.springframework.mock.web.MockHttpSession;
<ide>
<ide> import java.util.Date;
<add>import java.util.Set;
<add>import java.util.HashSet;
<add>import java.util.Arrays;
<ide>
<ide>
<ide> /**
<ide> * @version $Id$
<ide> */
<ide> public class SessionRegistryImplTests extends TestCase {
<add> private SessionRegistryImpl sessionRegistry;
<add>
<ide> //~ Methods ========================================================================================================
<add>
<add> protected void setUp() throws Exception {
<add> sessionRegistry = new SessionRegistryImpl();
<add> }
<ide>
<ide> public void testEventPublishing() {
<ide> MockHttpSession httpSession = new MockHttpSession();
<ide> Object principal = "Some principal object";
<ide> String sessionId = httpSession.getId();
<ide> assertNotNull(sessionId);
<del>
<del> SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
<ide>
<ide> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId, principal);
<ide> String sessionId2 = "9876543210";
<ide> String sessionId3 = "5432109876";
<ide>
<del> SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
<del>
<ide> sessionRegistry.registerNewSession(sessionId1, principal1);
<ide> sessionRegistry.registerNewSession(sessionId2, principal1);
<ide> sessionRegistry.registerNewSession(sessionId3, principal2);
<ide> public void testSessionInformationLifecycle() throws Exception {
<ide> Object principal = "Some principal object";
<ide> String sessionId = "1234567890";
<del> SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
<del>
<ide> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId, principal);
<ide>
<ide> Object principal = "Some principal object";
<ide> String sessionId1 = "1234567890";
<ide> String sessionId2 = "9876543210";
<del> SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
<ide>
<del> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId1, principal);
<del> assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
<del> assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
<add> SessionInformation[] sessions = sessionRegistry.getAllSessions(principal, false);
<add> assertEquals(1, sessions.length);
<add> assertTrue(contains(sessionId1, principal));
<ide>
<del> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId2, principal);
<del> assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
<del> assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
<add> sessions = sessionRegistry.getAllSessions(principal, false);
<add> assertEquals(2, sessions.length);
<add> assertTrue(contains(sessionId2, principal));
<ide>
<ide> // Expire one session
<ide> SessionInformation session = sessionRegistry.getSessionInformation(sessionId2);
<ide> Object principal = "Some principal object";
<ide> String sessionId1 = "1234567890";
<ide> String sessionId2 = "9876543210";
<del> SessionRegistryImpl sessionRegistry = new SessionRegistryImpl();
<ide>
<del> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId1, principal);
<del> assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
<del> assertEquals(sessionId1, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
<add> SessionInformation[] sessions = sessionRegistry.getAllSessions(principal, false);
<add> assertEquals(1, sessions.length);
<add> assertTrue(contains(sessionId1, principal));
<ide>
<del> // Register new Session
<ide> sessionRegistry.registerNewSession(sessionId2, principal);
<del> assertEquals(2, sessionRegistry.getAllSessions(principal, false).length);
<del> assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[1].getSessionId());
<add> sessions = sessionRegistry.getAllSessions(principal, false);
<add> assertEquals(2, sessions.length);
<add> assertTrue(contains(sessionId2, principal));
<ide>
<del> // Clear session information
<ide> sessionRegistry.removeSessionInformation(sessionId1);
<del> assertEquals(1, sessionRegistry.getAllSessions(principal, false).length);
<del> assertEquals(sessionId2, sessionRegistry.getAllSessions(principal, false)[0].getSessionId());
<add> sessions = sessionRegistry.getAllSessions(principal, false);
<add> assertEquals(1, sessions.length);
<add> assertTrue(contains(sessionId2, principal));
<ide>
<del> // Clear final session
<ide> sessionRegistry.removeSessionInformation(sessionId2);
<ide> assertNull(sessionRegistry.getSessionInformation(sessionId2));
<ide> assertNull(sessionRegistry.getAllSessions(principal, false));
<ide> }
<add>
<add> boolean contains(String sessionId, Object principal) {
<add> SessionInformation[] info = sessionRegistry.getAllSessions(principal, false);
<add>
<add> for (int i = 0; i < info.length; i++) {
<add> if (sessionId.equals(info[i].getSessionId())) {
<add> return true;
<add> }
<add> }
<add>
<add> return false;
<add> }
<ide> } |
|
Java | apache-2.0 | 732a94a574fa22f6bb2b8ad6195128375c03fa94 | 0 | boldtrn/graphhopper,graphhopper/graphhopper,don-philipe/graphhopper,devemux86/graphhopper,komoot/graphhopper,devemux86/graphhopper,ratrun/graphhopper,routexl/graphhopper,routexl/graphhopper,routexl/graphhopper,devemux86/graphhopper,boldtrn/graphhopper,prembasumatary/graphhopper,fbonzon/graphhopper,fbonzon/graphhopper,boldtrn/graphhopper,routexl/graphhopper,ammagamma/graphhopper,don-philipe/graphhopper,prembasumatary/graphhopper,graphhopper/graphhopper,hguerrero/graphhopper,don-philipe/graphhopper,fbonzon/graphhopper,boldtrn/graphhopper,ammagamma/graphhopper,komoot/graphhopper,devemux86/graphhopper,hguerrero/graphhopper,ratrun/graphhopper,hguerrero/graphhopper,graphhopper/graphhopper,komoot/graphhopper,ammagamma/graphhopper,komoot/graphhopper,graphhopper/graphhopper,hguerrero/graphhopper,fbonzon/graphhopper,prembasumatary/graphhopper,ammagamma/graphhopper,prembasumatary/graphhopper,ratrun/graphhopper,don-philipe/graphhopper,ratrun/graphhopper | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.lm;
import com.carrotsearch.hppc.IntArrayList;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.predicates.IntObjectPredicate;
import com.carrotsearch.hppc.procedures.IntObjectProcedure;
import com.graphhopper.coll.MapEntry;
import com.graphhopper.routing.DijkstraBidirectionRef;
import com.graphhopper.routing.subnetwork.SubnetworkStorage;
import com.graphhopper.routing.subnetwork.TarjansSCCAlgorithm;
import com.graphhopper.routing.util.*;
import com.graphhopper.routing.util.spatialrules.SpatialRule;
import com.graphhopper.routing.util.spatialrules.SpatialRuleLookup;
import com.graphhopper.routing.weighting.AbstractWeighting;
import com.graphhopper.routing.weighting.ShortestWeighting;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.*;
import com.graphhopper.util.*;
import com.graphhopper.util.exceptions.ConnectionNotFoundException;
import com.graphhopper.util.shapes.BBox;
import com.graphhopper.util.shapes.GHPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class stores the landmark nodes and the weights from and to all other nodes in every
* subnetwork. This data is created to apply a speed-up for path calculation but at the same times
* stays flexible to per-request changes. The class is safe for usage from multiple reading threads
* across algorithms.
*
* @author Peter Karich
*/
public class LandmarkStorage implements Storable<LandmarkStorage> {
private static final Logger LOGGER = LoggerFactory.getLogger(LandmarkStorage.class);
// This value is used to identify nodes where no subnetwork is associated
private static final int UNSET_SUBNETWORK = -1;
// This value should only be used if subnetwork is too small to be explicitely stored
private static final int UNCLEAR_SUBNETWORK = 0;
// one node has an associated landmark information ('one landmark row'): the forward and backward weight
private long LM_ROW_LENGTH;
private int landmarks;
private final int FROM_OFFSET;
private final int TO_OFFSET;
private final DataAccess landmarkWeightDA;
/* every subnetwork has its own landmark mapping but the count of landmarks is always the same */
private final List<int[]> landmarkIDs;
private double factor = -1;
private final static double DOUBLE_MLTPL = 1e6;
private final GraphHopperStorage graph;
private final FlagEncoder encoder;
private final Weighting weighting;
private Weighting lmSelectionWeighting;
private final TraversalMode traversalMode;
private boolean initialized;
private int minimumNodes = 500_000;
private final SubnetworkStorage subnetworkStorage;
private List<LandmarkSuggestion> landmarkSuggestions = Collections.emptyList();
private SpatialRuleLookup ruleLookup;
/**
* 'to' and 'from' fit into 32 bit => 16 bit for each of them => 65536
*/
static final long PRECISION = 1 << 16;
public LandmarkStorage(GraphHopperStorage graph, Directory dir, int landmarks, final Weighting weighting, TraversalMode traversalMode) {
this.graph = graph;
this.minimumNodes = Math.min(graph.getNodes() / 2, 500_000);
this.encoder = weighting.getFlagEncoder();
this.weighting = weighting;
// allowing arbitrary weighting is too dangerous
this.lmSelectionWeighting = new ShortestWeighting(encoder) {
@Override
public double calcWeight(EdgeIteratorState edge, boolean reverse, int prevOrNextEdgeId) {
// make accessibility of shortest identical to the provided weighting to avoid problems like shown in testWeightingConsistence
double res = weighting.calcWeight(edge, reverse, prevOrNextEdgeId);
if (res >= Double.MAX_VALUE)
return Double.POSITIVE_INFINITY;
// returning the time or distance leads to strange landmark positions (ferries -> slow&very long) and BFS is more what we want
return 1;
}
@Override
public String toString() {
return "LM_BFS|" + encoder;
}
};
// later make edge base working! Not really necessary as when adding turn costs while routing we can still
// use the node based traversal as this is a smaller weight approximation
this.traversalMode = TraversalMode.NODE_BASED;
final String name = AbstractWeighting.weightingToFileName(weighting);
this.landmarkWeightDA = dir.find("landmarks_" + name);
this.landmarks = landmarks;
// one short per landmark and two directions => 2*2 byte
this.LM_ROW_LENGTH = landmarks * 4;
this.FROM_OFFSET = 0;
this.TO_OFFSET = 2;
this.landmarkIDs = new ArrayList<>();
this.subnetworkStorage = new SubnetworkStorage(dir, "landmarks_" + name);
}
/**
* Specify the maximum possible value for your used area. With this maximum weight value you can influence the storage
* precision for your weights that help A* finding its way to the goal. The same value is used for all subnetworks.
* Note, if you pick this value too big then too similar weights are stored
* (some bits of the storage capability will be left unused) which could lead to suboptimal routes.
* If too low then far away values will have the same maximum value associated ("maxed out") leading to bad performance.
*
* @param maxWeight use a negative value to automatically determine this value.
*/
public LandmarkStorage setMaximumWeight(double maxWeight) {
if (maxWeight > 0) {
this.factor = maxWeight / PRECISION;
if (Double.isInfinite(factor) || Double.isNaN(factor))
throw new IllegalStateException("Illegal factor " + factor + " calculated from maximum weight " + maxWeight);
}
return this;
}
/**
* This method forces the landmark preparation to skip the landmark search and uses the specified landmark list instead.
* Useful for manual tuning of larger areas to safe import time or improve quality.
*/
public LandmarkStorage setLandmarkSuggestions(List<LandmarkSuggestion> landmarkSuggestions) {
if (landmarkSuggestions == null)
throw new IllegalArgumentException("landmark suggestions cannot be null");
this.landmarkSuggestions = landmarkSuggestions;
return this;
}
/**
* This method sets the required number of nodes of a subnetwork for which landmarks should be calculated. Every
* subnetwork below this count will be ignored.
*/
public void setMinimumNodes(int minimumNodes) {
this.minimumNodes = minimumNodes;
}
/**
* @see #setMinimumNodes(int)
*/
public int getMinimumNodes() {
return minimumNodes;
}
SubnetworkStorage getSubnetworkStorage() {
return subnetworkStorage;
}
/**
* This weighting is used for the selection heuristic and is per default not the weighting specified in the contructor.
* The special weighting leads to a much better distribution of the landmarks and results in better response times.
*/
public void setLMSelectionWeighting(Weighting lmSelectionWeighting) {
this.lmSelectionWeighting = lmSelectionWeighting;
}
public Weighting getLmSelectionWeighting() {
return lmSelectionWeighting;
}
/**
* This method returns the weighting for which the landmarks are originally created
*/
public Weighting getWeighting() {
return weighting;
}
boolean isInitialized() {
return initialized;
}
/**
* This method calculates the landmarks and initial weightings to & from them.
*/
public void createLandmarks() {
if (isInitialized())
throw new IllegalStateException("Initialize the landmark storage only once!");
// fill 'from' and 'to' weights with maximum value
long maxBytes = (long) graph.getNodes() * LM_ROW_LENGTH;
this.landmarkWeightDA.create(2000);
this.landmarkWeightDA.ensureCapacity(maxBytes);
for (long pointer = 0; pointer < maxBytes; pointer += 2) {
landmarkWeightDA.setShort(pointer, (short) SHORT_INFINITY);
}
String additionalInfo = "";
// guess the factor
if (factor <= 0) {
// A 'factor' is necessary to store the weight in just a short value but without loosing too much precision.
// This factor is rather delicate to pick, we estimate it through the graph boundaries its maximum distance.
// For small areas we use max_bounds_dist*X and otherwise we use a big fixed value for this distance.
// If we would pick the distance too big for small areas this could lead to (slightly) suboptimal routes as there
// will be too big rounding errors. But picking it too small is dangerous regarding performance
// e.g. for Germany at least 1500km is very important otherwise speed is at least twice as slow e.g. for just 1000km
BBox bounds = graph.getBounds();
double distanceInMeter = Helper.DIST_EARTH.calcDist(bounds.maxLat, bounds.maxLon, bounds.minLat, bounds.minLon) * 7;
if (distanceInMeter > 50_000 * 7 || /* for tests and convenience we do for now: */ !bounds.isValid())
distanceInMeter = 30_000_000;
double maxWeight = weighting.getMinWeight(distanceInMeter);
setMaximumWeight(maxWeight);
additionalInfo = ", maxWeight:" + maxWeight + ", from max distance:" + distanceInMeter / 1000f + "km";
}
LOGGER.info("init landmarks for subnetworks with node count greater than " + minimumNodes + " with factor:" + factor + additionalInfo);
int[] empty = new int[landmarks];
Arrays.fill(empty, UNSET_SUBNETWORK);
landmarkIDs.add(empty);
byte[] subnetworks = new byte[graph.getNodes()];
Arrays.fill(subnetworks, (byte) UNSET_SUBNETWORK);
EdgeFilter tarjanFilter = new DefaultEdgeFilter(encoder, false, true);
IntHashSet blockedEdges = new IntHashSet();
// the ruleLookup splits certain areas from each other but avoids making this a permanent change so that other algorithms still can route through these regions.
if (ruleLookup != null && ruleLookup.size() > 0) {
StopWatch sw = new StopWatch().start();
blockedEdges = findBorderEdgeIds(ruleLookup);
tarjanFilter = new BlockedEdgesFilter(encoder, false, true, blockedEdges);
LOGGER.info("Made " + blockedEdges.size() + " edges inaccessible. Calculated country cut in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
}
StopWatch sw = new StopWatch().start();
// we cannot reuse the components calculated in PrepareRoutingSubnetworks as the edgeIds changed in between (called graph.optimize)
// also calculating subnetworks from scratch makes bigger problems when working with many oneways
TarjansSCCAlgorithm tarjanAlgo = new TarjansSCCAlgorithm(graph, tarjanFilter, true);
List<IntArrayList> graphComponents = tarjanAlgo.findComponents();
LOGGER.info("Calculated tarjan subnetworks in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
EdgeExplorer tmpExplorer = graph.createEdgeExplorer(new RequireBothDirectionsEdgeFilter(encoder));
int nodes = 0;
for (IntArrayList subnetworkIds : graphComponents) {
nodes += subnetworkIds.size();
if (subnetworkIds.size() < minimumNodes)
continue;
int index = subnetworkIds.size() - 1;
// ensure start node is reachable from both sides and no subnetwork is associated
for (; index >= 0; index--) {
int nextStartNode = subnetworkIds.get(index);
if (subnetworks[nextStartNode] == UNSET_SUBNETWORK
&& GHUtility.count(tmpExplorer.setBaseNode(nextStartNode)) > 0) {
GHPoint p = createPoint(graph, nextStartNode);
LOGGER.info("start node: " + nextStartNode + " (" + p + ") subnetwork size: " + subnetworkIds.size()
+ ", " + Helper.getMemInfo() + ((ruleLookup == null) ? "" : " area:" + ruleLookup.lookupRule(p).getId()));
if (createLandmarksForSubnetwork(nextStartNode, subnetworks, blockedEdges))
break;
}
}
if (index < 0)
LOGGER.warn("next start node not found in big enough network of size " + subnetworkIds.size() + ", first element is " + subnetworkIds.get(0) + ", " + createPoint(graph, subnetworkIds.get(0)));
}
int subnetworkCount = landmarkIDs.size();
// store all landmark node IDs and one int for the factor itself.
this.landmarkWeightDA.ensureCapacity(maxBytes /* landmark weights */ + subnetworkCount * landmarks /* landmark mapping per subnetwork */);
// calculate offset to point into landmark mapping
long bytePos = maxBytes;
for (int[] landmarks : landmarkIDs) {
for (int lmNodeId : landmarks) {
landmarkWeightDA.setInt(bytePos, lmNodeId);
bytePos += 4L;
}
}
landmarkWeightDA.setHeader(0 * 4, graph.getNodes());
landmarkWeightDA.setHeader(1 * 4, landmarks);
landmarkWeightDA.setHeader(2 * 4, subnetworkCount);
if (factor * DOUBLE_MLTPL > Integer.MAX_VALUE)
throw new UnsupportedOperationException("landmark weight factor cannot be bigger than Integer.MAX_VALUE " + factor * DOUBLE_MLTPL);
landmarkWeightDA.setHeader(3 * 4, (int) Math.round(factor * DOUBLE_MLTPL));
// serialize fast byte[] into DataAccess
subnetworkStorage.create(graph.getNodes());
for (int nodeId = 0; nodeId < subnetworks.length; nodeId++) {
subnetworkStorage.setSubnetwork(nodeId, subnetworks[nodeId]);
}
LOGGER.info("Finished landmark creation. Subnetwork node count sum " + nodes + " vs. nodes " + graph.getNodes());
initialized = true;
}
/**
* This method creates landmarks for the specified subnetwork (integer list)
*
* @return landmark mapping
*/
private boolean createLandmarksForSubnetwork(final int startNode, final byte[] subnetworks, IntHashSet blockedEdges) {
final int subnetworkId = landmarkIDs.size();
boolean random = false;
int[] tmpLandmarkNodeIds = new int[landmarks];
int logOffset = Math.max(1, tmpLandmarkNodeIds.length / 2);
boolean pickedPrecalculatedLandmarks = false;
if (!landmarkSuggestions.isEmpty()) {
NodeAccess na = graph.getNodeAccess();
double lat = na.getLatitude(startNode), lon = na.getLongitude(startNode);
LandmarkSuggestion selectedSuggestion = null;
for (LandmarkSuggestion lmsugg : landmarkSuggestions) {
if (lmsugg.getBox().contains(lat, lon)) {
selectedSuggestion = lmsugg;
break;
}
}
if (selectedSuggestion != null) {
if (selectedSuggestion.getNodeIds().size() < tmpLandmarkNodeIds.length)
throw new IllegalArgumentException("landmark suggestions are too few " + selectedSuggestion.getNodeIds().size() + " for requested landmarks " + landmarks);
pickedPrecalculatedLandmarks = true;
for (int i = 0; i < tmpLandmarkNodeIds.length; i++) {
int lmNodeId = selectedSuggestion.getNodeIds().get(i);
tmpLandmarkNodeIds[i] = lmNodeId;
}
}
// Random randomInst = new Random();
// for (int i = 0; i < tmpLandmarkNodeIds.length; i++) {
// int index = randomInst.nextInt(subnetworkIds.size());
// tmpLandmarkNodeIds[i] = subnetworkIds.get(index);
// }
}
if (pickedPrecalculatedLandmarks) {
LOGGER.info("Picked " + tmpLandmarkNodeIds.length + " landmark suggestions, skipped expensive landmark determination");
} else {
// 1a) pick landmarks via special weighting for a better geographical spreading
Weighting initWeighting = lmSelectionWeighting;
LandmarkExplorer explorer = new LandmarkExplorer(graph, this, initWeighting, traversalMode);
explorer.initFrom(startNode, 0);
explorer.setFilter(blockedEdges, true, true);
explorer.runAlgo(true);
if (explorer.getFromCount() < minimumNodes) {
// too small subnetworks are initialized with special id==0
explorer.setSubnetworks(subnetworks, UNCLEAR_SUBNETWORK);
return false;
}
// 1b) we have one landmark, now determine the other landmarks
tmpLandmarkNodeIds[0] = explorer.getLastNode();
for (int lmIdx = 0; lmIdx < tmpLandmarkNodeIds.length - 1; lmIdx++) {
if(Thread.currentThread().isInterrupted()){
throw new RuntimeException("Thread was interrupted");
}
explorer = new LandmarkExplorer(graph, this, initWeighting, traversalMode);
explorer.setFilter(blockedEdges, true, true);
// set all current landmarks as start so that the next getLastNode is hopefully a "far away" node
for (int j = 0; j < lmIdx + 1; j++) {
explorer.initFrom(tmpLandmarkNodeIds[j], 0);
}
explorer.runAlgo(true);
tmpLandmarkNodeIds[lmIdx + 1] = explorer.getLastNode();
if (lmIdx % logOffset == 0)
LOGGER.info("Finding landmarks [" + weighting + "] in network [" + explorer.getVisitedNodes() + "]. "
+ "Progress " + (int) (100.0 * lmIdx / tmpLandmarkNodeIds.length) + "%, " + Helper.getMemInfo());
}
LOGGER.info("Finished searching landmarks for subnetwork " + subnetworkId + " of size " + explorer.getVisitedNodes());
}
// 2) calculate weights for all landmarks -> 'from' and 'to' weight
for (int lmIdx = 0; lmIdx < tmpLandmarkNodeIds.length; lmIdx++) {
if(Thread.currentThread().isInterrupted()){
throw new RuntimeException("Thread was interrupted");
}
int lmNodeId = tmpLandmarkNodeIds[lmIdx];
LandmarkExplorer explorer = new LandmarkExplorer(graph, this, weighting, traversalMode);
explorer.initFrom(lmNodeId, 0);
explorer.setFilter(blockedEdges, false, true);
explorer.runAlgo(true);
explorer.initLandmarkWeights(lmIdx, lmNodeId, LM_ROW_LENGTH, FROM_OFFSET);
// set subnetwork id to all explored nodes, but do this only for the first landmark
if (lmIdx == 0) {
if (explorer.setSubnetworks(subnetworks, subnetworkId))
return false;
}
explorer = new LandmarkExplorer(graph, this, weighting, traversalMode);
explorer.initTo(lmNodeId, 0);
explorer.setFilter(blockedEdges, true, false);
explorer.runAlgo(false);
explorer.initLandmarkWeights(lmIdx, lmNodeId, LM_ROW_LENGTH, TO_OFFSET);
if (lmIdx == 0) {
if (explorer.setSubnetworks(subnetworks, subnetworkId))
return false;
}
if (lmIdx % logOffset == 0)
LOGGER.info("Set landmarks weights [" + weighting + "]. "
+ "Progress " + (int) (100.0 * lmIdx / tmpLandmarkNodeIds.length) + "%");
}
// TODO set weight to SHORT_MAX if entry has either no 'from' or no 'to' entry
landmarkIDs.add(tmpLandmarkNodeIds);
return true;
}
/**
* This method specifies the polygons which should be used to split the world wide area to improve performance and
* quality in this scenario.
*/
public void setSpatialRuleLookup(SpatialRuleLookup ruleLookup) {
this.ruleLookup = ruleLookup;
}
/**
* This method makes edges crossing the specified border inaccessible to split a bigger area into smaller subnetworks.
* This is important for the world wide use case to limit the maximum distance and also to detect unreasonable routes faster.
*/
protected IntHashSet findBorderEdgeIds(SpatialRuleLookup ruleLookup) {
AllEdgesIterator allEdgesIterator = graph.getAllEdges();
NodeAccess nodeAccess = graph.getNodeAccess();
IntHashSet inaccessible = new IntHashSet();
while (allEdgesIterator.next()) {
int adjNode = allEdgesIterator.getAdjNode();
SpatialRule ruleAdj = ruleLookup.lookupRule(nodeAccess.getLatitude(adjNode), nodeAccess.getLongitude(adjNode));
int baseNode = allEdgesIterator.getBaseNode();
SpatialRule ruleBase = ruleLookup.lookupRule(nodeAccess.getLatitude(baseNode), nodeAccess.getLongitude(baseNode));
if (ruleAdj != ruleBase)
inaccessible.add(allEdgesIterator.getEdge());
}
return inaccessible;
}
/**
* The factor is used to convert double values into more compact int values.
*/
double getFactor() {
return factor;
}
/**
* @return the weight from the landmark to the specified node. Where the landmark integer is not
* a node ID but the internal index of the landmark array.
*/
int getFromWeight(int landmarkIndex, int node) {
int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + FROM_OFFSET)
& 0x0000FFFF;
assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node;
if (res == SHORT_INFINITY)
// TODO can happen if endstanding oneway
// we should set a 'from' value to SHORT_MAX if the 'to' value was already set to find real bugs
// and what to return? Integer.MAX_VALUE i.e. convert to Double.pos_infinity upstream?
return SHORT_MAX;
// throw new IllegalStateException("Do not call getFromWeight for wrong landmark[" + landmarkIndex + "]=" + landmarkIDs[landmarkIndex] + " and node " + node);
// TODO if(res == MAX) fallback to beeline approximation!?
return res;
}
/**
* @return the weight from the specified node to the landmark (specified *as index*)
*/
int getToWeight(int landmarkIndex, int node) {
int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + TO_OFFSET)
& 0x0000FFFF;
assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node;
if (res == SHORT_INFINITY)
return SHORT_MAX;
// throw new IllegalStateException("Do not call getToWeight for wrong landmark[" + landmarkIndex + "]=" + landmarkIDs[landmarkIndex] + " and node " + node);
return res;
}
// Short.MAX_VALUE = 2^15-1 but we have unsigned short so we need 2^16-1
private static final int SHORT_INFINITY = Short.MAX_VALUE * 2 + 1;
// We have large values that do not fit into a short, use a specific maximum value
private static final int SHORT_MAX = SHORT_INFINITY - 1;
/**
* @return false if the value capacity was reached and instead of the real value the SHORT_MAX was stored.
*/
final boolean setWeight(long pointer, double value) {
double tmpVal = value / factor;
if (tmpVal > Integer.MAX_VALUE)
throw new UnsupportedOperationException("Cannot store infinity explicitely, pointer=" + pointer + ", value: " + value);
if (tmpVal >= SHORT_MAX) {
landmarkWeightDA.setShort(pointer, (short) SHORT_MAX);
return false;
} else {
landmarkWeightDA.setShort(pointer, (short) tmpVal);
return true;
}
}
boolean isInfinity(long pointer) {
return ((int) landmarkWeightDA.getShort(pointer) & 0x0000FFFF) == SHORT_INFINITY;
}
int calcWeight(EdgeIteratorState edge, boolean reverse) {
return (int) (weighting.calcWeight(edge, reverse, EdgeIterator.NO_EDGE) / factor);
}
// From all available landmarks pick just a few active ones
boolean initActiveLandmarks(int fromNode, int toNode, int[] activeLandmarkIndices,
int[] activeFroms, int[] activeTos, boolean reverse) {
if (fromNode < 0 || toNode < 0)
throw new IllegalStateException("from " + fromNode + " and to "
+ toNode + " nodes have to be 0 or positive to init landmarks");
int subnetworkFrom = subnetworkStorage.getSubnetwork(fromNode);
int subnetworkTo = subnetworkStorage.getSubnetwork(toNode);
if (subnetworkFrom <= UNCLEAR_SUBNETWORK || subnetworkTo <= UNCLEAR_SUBNETWORK)
return false;
if (subnetworkFrom != subnetworkTo) {
throw new ConnectionNotFoundException("Connection between locations not found. Different subnetworks " + subnetworkFrom + " vs. " + subnetworkTo, new HashMap<String, Object>());
}
int[] tmpIDs = landmarkIDs.get(subnetworkFrom);
// kind of code duplication to approximate
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(tmpIDs.length);
for (int lmIndex = 0; lmIndex < tmpIDs.length; lmIndex++) {
int fromWeight = getFromWeight(lmIndex, toNode) - getFromWeight(lmIndex, fromNode);
int toWeight = getToWeight(lmIndex, fromNode) - getToWeight(lmIndex, toNode);
list.add(new MapEntry<>(reverse
? Math.max(-fromWeight, -toWeight)
: Math.max(fromWeight, toWeight), lmIndex));
}
Collections.sort(list, SORT_BY_WEIGHT);
if (activeLandmarkIndices[0] >= 0) {
IntHashSet set = new IntHashSet(activeLandmarkIndices.length);
set.addAll(activeLandmarkIndices);
int existingLandmarkCounter = 0;
final int COUNT = Math.min(activeLandmarkIndices.length - 2, 2);
for (int i = 0; i < activeLandmarkIndices.length; i++) {
if (i >= activeLandmarkIndices.length - COUNT + existingLandmarkCounter) {
// keep at least two of the previous landmarks (pick the best)
break;
} else {
activeLandmarkIndices[i] = list.get(i).getValue();
if (set.contains(activeLandmarkIndices[i]))
existingLandmarkCounter++;
}
}
} else {
for (int i = 0; i < activeLandmarkIndices.length; i++) {
activeLandmarkIndices[i] = list.get(i).getValue();
}
}
// store weight values of active landmarks in 'cache' arrays
for (int i = 0; i < activeLandmarkIndices.length; i++) {
int lmIndex = activeLandmarkIndices[i];
activeFroms[i] = getFromWeight(lmIndex, toNode);
activeTos[i] = getToWeight(lmIndex, toNode);
}
return true;
}
public int getLandmarkCount() {
return landmarks;
}
public int[] getLandmarks(int subnetwork) {
return landmarkIDs.get(subnetwork);
}
/**
* @return the number of subnetworks that have landmarks
*/
public int getSubnetworksWithLandmarks() {
return landmarkIDs.size();
}
public boolean isEmpty() {
return landmarkIDs.size() < 2;
}
@Override
public String toString() {
String str = "";
for (int[] ints : landmarkIDs) {
if (!str.isEmpty())
str += ", ";
str += Arrays.toString(ints);
}
return str;
}
/**
* @return the calculated landmarks as GeoJSON string.
*/
String getLandmarksAsGeoJSON() {
NodeAccess na = graph.getNodeAccess();
String str = "";
for (int subnetwork = 1; subnetwork < landmarkIDs.size(); subnetwork++) {
int[] lmArray = landmarkIDs.get(subnetwork);
for (int lmIdx = 0; lmIdx < lmArray.length; lmIdx++) {
int index = lmArray[lmIdx];
if (!str.isEmpty())
str += ",";
str += "{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": ["
+ na.getLon(index) + ", " + na.getLat(index) + "]},";
str += " \"properties\":{\"node_index\":" + index + ","
+ "\"subnetwork\":" + subnetwork + ","
+ "\"lm_index\":" + lmIdx + "}"
+ "}";
}
}
return "{ \"type\": \"FeatureCollection\", \"features\": [" + str + "]}";
}
@Override
public boolean loadExisting() {
if (isInitialized())
throw new IllegalStateException("Cannot call PrepareLandmarks.loadExisting if already initialized");
if (landmarkWeightDA.loadExisting()) {
if (!subnetworkStorage.loadExisting())
throw new IllegalStateException("landmark weights loaded but not the subnetworks!?");
int nodes = landmarkWeightDA.getHeader(0 * 4);
if (nodes != graph.getNodes())
throw new IllegalArgumentException("Cannot load landmark data as written for different graph storage with " + nodes + " nodes, not " + graph.getNodes());
landmarks = landmarkWeightDA.getHeader(1 * 4);
int subnetworks = landmarkWeightDA.getHeader(2 * 4);
factor = landmarkWeightDA.getHeader(3 * 4) / DOUBLE_MLTPL;
LM_ROW_LENGTH = landmarks * 4;
long maxBytes = LM_ROW_LENGTH * nodes;
long bytePos = maxBytes;
// in the first subnetwork 0 there are no landmark IDs stored
for (int j = 0; j < subnetworks; j++) {
int[] tmpLandmarks = new int[landmarks];
for (int i = 0; i < tmpLandmarks.length; i++) {
tmpLandmarks[i] = landmarkWeightDA.getInt(bytePos);
bytePos += 4;
}
landmarkIDs.add(tmpLandmarks);
}
initialized = true;
return true;
}
return false;
}
@Override
public LandmarkStorage create(long byteCount) {
throw new IllegalStateException("Do not call LandmarkStore.create directly");
}
@Override
public void flush() {
landmarkWeightDA.flush();
subnetworkStorage.flush();
}
@Override
public void close() {
landmarkWeightDA.close();
subnetworkStorage.close();
}
@Override
public boolean isClosed() {
return landmarkWeightDA.isClosed();
}
@Override
public long getCapacity() {
return landmarkWeightDA.getCapacity() + subnetworkStorage.getCapacity();
}
/**
* This class is used to calculate landmark location (equally distributed).
*/
private static class LandmarkExplorer extends DijkstraBidirectionRef {
private int lastNode;
private boolean from;
private final LandmarkStorage lms;
public LandmarkExplorer(Graph g, LandmarkStorage lms, Weighting weighting, TraversalMode tMode) {
super(g, weighting, tMode);
this.lms = lms;
}
public void setFilter(IntHashSet set, boolean bwd, boolean fwd) {
EdgeFilter ef = new BlockedEdgesFilter(flagEncoder, bwd, fwd, set);
outEdgeExplorer = graph.createEdgeExplorer(ef);
inEdgeExplorer = graph.createEdgeExplorer(ef);
}
int getFromCount() {
return bestWeightMapFrom.size();
}
int getToCount() {
return bestWeightMapTo.size();
}
public int getLastNode() {
return lastNode;
}
public void runAlgo(boolean from) {
// no path should be calculated
setUpdateBestPath(false);
// set one of the bi directions as already finished
if (from)
finishedTo = true;
else
finishedFrom = true;
this.from = from;
super.runAlgo();
}
@Override
public boolean finished() {
if (from) {
lastNode = currFrom.adjNode;
return finishedFrom;
} else {
lastNode = currTo.adjNode;
return finishedTo;
}
}
public boolean setSubnetworks(final byte[] subnetworks, final int subnetworkId) {
if (subnetworkId > 127)
throw new IllegalStateException("Too many subnetworks " + subnetworkId);
final AtomicBoolean failed = new AtomicBoolean(false);
IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo;
map.forEach(new IntObjectPredicate<SPTEntry>() {
@Override
public boolean apply(int nodeId, SPTEntry value) {
int sn = subnetworks[nodeId];
if (sn != subnetworkId) {
if (sn != UNSET_SUBNETWORK && sn != UNCLEAR_SUBNETWORK) {
// this is ugly but can happen in real world, see testWithOnewaySubnetworks
LOGGER.error("subnetworkId for node " + nodeId
+ " (" + createPoint(graph, nodeId) + ") already set (" + sn + "). " + "Cannot change to " + subnetworkId);
failed.set(true);
return false;
}
subnetworks[nodeId] = (byte) subnetworkId;
}
return true;
}
});
return failed.get();
}
public void initLandmarkWeights(final int lmIdx, int lmNodeId, final long rowSize, final int offset) {
IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo;
final AtomicInteger maxedout = new AtomicInteger(0);
final Map.Entry<Double, Double> finalMaxWeight = new MapEntry<>(0d, 0d);
map.forEach(new IntObjectProcedure<SPTEntry>() {
@Override
public void apply(int nodeId, SPTEntry b) {
if (!lms.setWeight(nodeId * rowSize + lmIdx * 4 + offset, b.weight)) {
maxedout.incrementAndGet();
finalMaxWeight.setValue(Math.max(b.weight, finalMaxWeight.getValue()));
}
}
});
if ((double) maxedout.get() / map.size() > 0.1) {
LOGGER.warn("landmark " + lmIdx + " (" + nodeAccess.getLatitude(lmNodeId) + "," + nodeAccess.getLongitude(lmNodeId) + "): " +
"too many weights were maxed out (" + maxedout.get() + "/" + map.size() + "). Use a bigger factor than " + lms.factor
+ ". For example use the following in the config.properties: weighting=" + weighting.getName() + "|maximum=" + finalMaxWeight.getValue() * 1.2);
}
}
}
/**
* Sort landmark by weight and let maximum weight come first, to pick best active landmarks.
*/
final static Comparator<Map.Entry<Integer, Integer>> SORT_BY_WEIGHT = new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return Integer.compare(o2.getKey(), o1.getKey());
}
};
static GHPoint createPoint(Graph graph, int nodeId) {
return new GHPoint(graph.getNodeAccess().getLatitude(nodeId), graph.getNodeAccess().getLongitude(nodeId));
}
final static class RequireBothDirectionsEdgeFilter implements EdgeFilter {
private FlagEncoder flagEncoder;
public RequireBothDirectionsEdgeFilter(FlagEncoder flagEncoder) {
this.flagEncoder = flagEncoder;
}
@Override
public boolean accept(EdgeIteratorState edgeState) {
return flagEncoder.isForward(edgeState.getFlags()) && flagEncoder.isBackward(edgeState.getFlags());
}
}
private static class BlockedEdgesFilter implements EdgeFilter {
private final IntHashSet blockedEdges;
private final FlagEncoder encoder;
private final boolean fwd;
private final boolean bwd;
public BlockedEdgesFilter(FlagEncoder encoder, boolean bwd, boolean fwd, IntHashSet blockedEdges) {
this.encoder = encoder;
this.bwd = bwd;
this.fwd = fwd;
this.blockedEdges = blockedEdges;
}
@Override
public final boolean accept(EdgeIteratorState iter) {
boolean blocked = blockedEdges.contains(iter.getEdge());
return fwd && iter.isForward(encoder) && !blocked || bwd && iter.isBackward(encoder) && !blocked;
}
public boolean acceptsBackward() {
return bwd;
}
public boolean acceptsForward() {
return fwd;
}
@Override
public String toString() {
return encoder.toString() + ", bwd:" + bwd + ", fwd:" + fwd;
}
}
}
| core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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.graphhopper.routing.lm;
import com.carrotsearch.hppc.IntArrayList;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.predicates.IntObjectPredicate;
import com.carrotsearch.hppc.procedures.IntObjectProcedure;
import com.graphhopper.coll.MapEntry;
import com.graphhopper.routing.DijkstraBidirectionRef;
import com.graphhopper.routing.subnetwork.SubnetworkStorage;
import com.graphhopper.routing.subnetwork.TarjansSCCAlgorithm;
import com.graphhopper.routing.util.*;
import com.graphhopper.routing.util.spatialrules.SpatialRule;
import com.graphhopper.routing.util.spatialrules.SpatialRuleLookup;
import com.graphhopper.routing.weighting.AbstractWeighting;
import com.graphhopper.routing.weighting.ShortestWeighting;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.*;
import com.graphhopper.util.*;
import com.graphhopper.util.exceptions.ConnectionNotFoundException;
import com.graphhopper.util.shapes.BBox;
import com.graphhopper.util.shapes.GHPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class stores the landmark nodes and the weights from and to all other nodes in every
* subnetwork. This data is created to apply a speed-up for path calculation but at the same times
* stays flexible to per-request changes. The class is safe for usage from multiple reading threads
* across algorithms.
*
* @author Peter Karich
*/
public class LandmarkStorage implements Storable<LandmarkStorage> {
private static final Logger LOGGER = LoggerFactory.getLogger(LandmarkStorage.class);
// This value is used to identify nodes where no subnetwork is associated
private static final int UNSET_SUBNETWORK = -1;
// This value should only be used if subnetwork is too small to be explicitely stored
private static final int UNCLEAR_SUBNETWORK = 0;
// one node has an associated landmark information ('one landmark row'): the forward and backward weight
private long LM_ROW_LENGTH;
private int landmarks;
private final int FROM_OFFSET;
private final int TO_OFFSET;
private final DataAccess landmarkWeightDA;
/* every subnetwork has its own landmark mapping but the count of landmarks is always the same */
private final List<int[]> landmarkIDs;
private double factor = -1;
private final static double DOUBLE_MLTPL = 1e6;
private final GraphHopperStorage graph;
private final FlagEncoder encoder;
private final Weighting weighting;
private Weighting lmSelectionWeighting;
private final TraversalMode traversalMode;
private boolean initialized;
private int minimumNodes = 500_000;
private final SubnetworkStorage subnetworkStorage;
private List<LandmarkSuggestion> landmarkSuggestions = Collections.emptyList();
private SpatialRuleLookup ruleLookup;
/**
* 'to' and 'from' fit into 32 bit => 16 bit for each of them => 65536
*/
static final long PRECISION = 1 << 16;
public LandmarkStorage(GraphHopperStorage graph, Directory dir, int landmarks, final Weighting weighting, TraversalMode traversalMode) {
this.graph = graph;
this.minimumNodes = Math.min(graph.getNodes() / 2, 500_000);
this.encoder = weighting.getFlagEncoder();
this.weighting = weighting;
// allowing arbitrary weighting is too dangerous
this.lmSelectionWeighting = new ShortestWeighting(encoder) {
@Override
public double calcWeight(EdgeIteratorState edge, boolean reverse, int prevOrNextEdgeId) {
// make accessibility of shortest identical to the provided weighting to avoid problems like shown in testWeightingConsistence
double res = weighting.calcWeight(edge, reverse, prevOrNextEdgeId);
if (res >= Double.MAX_VALUE)
return Double.POSITIVE_INFINITY;
// returning the time or distance leads to strange landmark positions (ferries -> slow&very long) and BFS is more what we want
return 1;
}
@Override
public String toString() {
return "LM_BFS|" + encoder;
}
};
// later make edge base working! Not really necessary as when adding turn costs while routing we can still
// use the node based traversal as this is a smaller weight approximation
this.traversalMode = TraversalMode.NODE_BASED;
final String name = AbstractWeighting.weightingToFileName(weighting);
this.landmarkWeightDA = dir.find("landmarks_" + name);
this.landmarks = landmarks;
// one short per landmark and two directions => 2*2 byte
this.LM_ROW_LENGTH = landmarks * 4;
this.FROM_OFFSET = 0;
this.TO_OFFSET = 2;
this.landmarkIDs = new ArrayList<>();
this.subnetworkStorage = new SubnetworkStorage(dir, "landmarks_" + name);
}
/**
* Specify the maximum possible value for your used area. With this maximum weight value you can influence the storage
* precision for your weights that help A* finding its way to the goal. The same value is used for all subnetworks.
* Note, if you pick this value too big then too similar weights are stored
* (some bits of the storage capability will be left unused) which could lead to suboptimal routes.
* If too low then far away values will have the same maximum value associated ("maxed out") leading to bad performance.
*
* @param maxWeight use a negative value to automatically determine this value.
*/
public LandmarkStorage setMaximumWeight(double maxWeight) {
if (maxWeight > 0) {
this.factor = maxWeight / PRECISION;
if (Double.isInfinite(factor) || Double.isNaN(factor))
throw new IllegalStateException("Illegal factor " + factor + " calculated from maximum weight " + maxWeight);
}
return this;
}
/**
* This method forces the landmark preparation to skip the landmark search and uses the specified landmark list instead.
* Useful for manual tuning of larger areas to safe import time or improve quality.
*/
public LandmarkStorage setLandmarkSuggestions(List<LandmarkSuggestion> landmarkSuggestions) {
if (landmarkSuggestions == null)
throw new IllegalArgumentException("landmark suggestions cannot be null");
this.landmarkSuggestions = landmarkSuggestions;
return this;
}
/**
* This method sets the required number of nodes of a subnetwork for which landmarks should be calculated. Every
* subnetwork below this count will be ignored.
*/
public void setMinimumNodes(int minimumNodes) {
this.minimumNodes = minimumNodes;
}
/**
* @see #setMinimumNodes(int)
*/
public int getMinimumNodes() {
return minimumNodes;
}
SubnetworkStorage getSubnetworkStorage() {
return subnetworkStorage;
}
/**
* This weighting is used for the selection heuristic and is per default not the weighting specified in the contructor.
* The special weighting leads to a much better distribution of the landmarks and results in better response times.
*/
public void setLMSelectionWeighting(Weighting lmSelectionWeighting) {
this.lmSelectionWeighting = lmSelectionWeighting;
}
public Weighting getLmSelectionWeighting() {
return lmSelectionWeighting;
}
/**
* This method returns the weighting for which the landmarks are originally created
*/
public Weighting getWeighting() {
return weighting;
}
boolean isInitialized() {
return initialized;
}
/**
* This method calculates the landmarks and initial weightings to & from them.
*/
public void createLandmarks() {
if (isInitialized())
throw new IllegalStateException("Initialize the landmark storage only once!");
// fill 'from' and 'to' weights with maximum value
long maxBytes = (long) graph.getNodes() * LM_ROW_LENGTH;
this.landmarkWeightDA.create(2000);
this.landmarkWeightDA.ensureCapacity(maxBytes);
for (long pointer = 0; pointer < maxBytes; pointer += 2) {
landmarkWeightDA.setShort(pointer, (short) SHORT_INFINITY);
}
String additionalInfo = "";
// guess the factor
if (factor <= 0) {
// A 'factor' is necessary to store the weight in just a short value but without loosing too much precision.
// This factor is rather delicate to pick, we estimate it through the graph boundaries its maximum distance.
// For small areas we use max_bounds_dist*X and otherwise we use a big fixed value for this distance.
// If we would pick the distance too big for small areas this could lead to (slightly) suboptimal routes as there
// will be too big rounding errors. But picking it too small is dangerous regarding performance
// e.g. for Germany at least 1500km is very important otherwise speed is at least twice as slow e.g. for just 1000km
BBox bounds = graph.getBounds();
double distanceInMeter = Helper.DIST_EARTH.calcDist(bounds.maxLat, bounds.maxLon, bounds.minLat, bounds.minLon) * 7;
if (distanceInMeter > 50_000 * 7 || /* for tests and convenience we do for now: */ !bounds.isValid())
distanceInMeter = 30_000_000;
double maxWeight = weighting.getMinWeight(distanceInMeter);
setMaximumWeight(maxWeight);
additionalInfo = ", maxWeight:" + maxWeight + ", from max distance:" + distanceInMeter / 1000f + "km";
}
LOGGER.info("init landmarks for subnetworks with node count greater than " + minimumNodes + " with factor:" + factor + additionalInfo);
int[] empty = new int[landmarks];
Arrays.fill(empty, UNSET_SUBNETWORK);
landmarkIDs.add(empty);
byte[] subnetworks = new byte[graph.getNodes()];
Arrays.fill(subnetworks, (byte) UNSET_SUBNETWORK);
EdgeFilter tarjanFilter = new DefaultEdgeFilter(encoder, false, true);
IntHashSet blockedEdges = new IntHashSet();
// the ruleLookup splits certain areas from each other but avoids making this a permanent change so that other algorithms still can route through these regions.
if (ruleLookup != null && ruleLookup.size() > 0) {
StopWatch sw = new StopWatch().start();
blockedEdges = findBorderEdgeIds(ruleLookup);
tarjanFilter = new BlockedEdgesFilter(encoder, false, true, blockedEdges);
LOGGER.info("Made " + blockedEdges.size() + " edges inaccessible. Calculated country cut in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
}
StopWatch sw = new StopWatch().start();
// we cannot reuse the components calculated in PrepareRoutingSubnetworks as the edgeIds changed in between (called graph.optimize)
// also calculating subnetworks from scratch makes bigger problems when working with many oneways
TarjansSCCAlgorithm tarjanAlgo = new TarjansSCCAlgorithm(graph, tarjanFilter, true);
List<IntArrayList> graphComponents = tarjanAlgo.findComponents();
LOGGER.info("Calculated tarjan subnetworks in " + sw.stop().getSeconds() + "s, " + Helper.getMemInfo());
EdgeExplorer tmpExplorer = graph.createEdgeExplorer(new RequireBothDirectionsEdgeFilter(encoder));
int nodes = 0;
for (IntArrayList subnetworkIds : graphComponents) {
nodes += subnetworkIds.size();
if (subnetworkIds.size() < minimumNodes)
continue;
int index = subnetworkIds.size() - 1;
// ensure start node is reachable from both sides and no subnetwork is associated
for (; index >= 0; index--) {
int nextStartNode = subnetworkIds.get(index);
if (subnetworks[nextStartNode] == UNSET_SUBNETWORK
&& GHUtility.count(tmpExplorer.setBaseNode(nextStartNode)) > 0) {
GHPoint p = createPoint(graph, nextStartNode);
LOGGER.info("start node: " + nextStartNode + " (" + p + ") subnetwork size: " + subnetworkIds.size()
+ ", " + Helper.getMemInfo() + ((ruleLookup == null) ? "" : " area:" + ruleLookup.lookupRule(p).getId()));
if (createLandmarksForSubnetwork(nextStartNode, subnetworks, blockedEdges))
break;
}
}
if (index < 0)
LOGGER.warn("next start node not found in big enough network of size " + subnetworkIds.size() + ", first element is " + subnetworkIds.get(0) + ", " + createPoint(graph, subnetworkIds.get(0)));
}
int subnetworkCount = landmarkIDs.size();
// store all landmark node IDs and one int for the factor itself.
this.landmarkWeightDA.ensureCapacity(maxBytes /* landmark weights */ + subnetworkCount * landmarks /* landmark mapping per subnetwork */);
// calculate offset to point into landmark mapping
long bytePos = maxBytes;
for (int[] landmarks : landmarkIDs) {
for (int lmNodeId : landmarks) {
landmarkWeightDA.setInt(bytePos, lmNodeId);
bytePos += 4L;
}
}
landmarkWeightDA.setHeader(0 * 4, graph.getNodes());
landmarkWeightDA.setHeader(1 * 4, landmarks);
landmarkWeightDA.setHeader(2 * 4, subnetworkCount);
if (factor * DOUBLE_MLTPL > Integer.MAX_VALUE)
throw new UnsupportedOperationException("landmark weight factor cannot be bigger than Integer.MAX_VALUE " + factor * DOUBLE_MLTPL);
landmarkWeightDA.setHeader(3 * 4, (int) Math.round(factor * DOUBLE_MLTPL));
// serialize fast byte[] into DataAccess
subnetworkStorage.create(graph.getNodes());
for (int nodeId = 0; nodeId < subnetworks.length; nodeId++) {
subnetworkStorage.setSubnetwork(nodeId, subnetworks[nodeId]);
}
LOGGER.info("Finished landmark creation. Subnetwork node count sum " + nodes + " vs. nodes " + graph.getNodes());
initialized = true;
}
/**
* This method creates landmarks for the specified subnetwork (integer list)
*
* @return landmark mapping
*/
private boolean createLandmarksForSubnetwork(final int startNode, final byte[] subnetworks, IntHashSet blockedEdges) {
final int subnetworkId = landmarkIDs.size();
boolean random = false;
int[] tmpLandmarkNodeIds = new int[landmarks];
int logOffset = Math.max(1, tmpLandmarkNodeIds.length / 2);
boolean pickedPrecalculatedLandmarks = false;
if (!landmarkSuggestions.isEmpty()) {
NodeAccess na = graph.getNodeAccess();
double lat = na.getLatitude(startNode), lon = na.getLongitude(startNode);
LandmarkSuggestion selectedSuggestion = null;
for (LandmarkSuggestion lmsugg : landmarkSuggestions) {
if (lmsugg.getBox().contains(lat, lon)) {
selectedSuggestion = lmsugg;
break;
}
}
if (selectedSuggestion != null) {
if (selectedSuggestion.getNodeIds().size() < tmpLandmarkNodeIds.length)
throw new IllegalArgumentException("landmark suggestions are too few " + selectedSuggestion.getNodeIds().size() + " for requested landmarks " + landmarks);
pickedPrecalculatedLandmarks = true;
for (int i = 0; i < tmpLandmarkNodeIds.length; i++) {
int lmNodeId = selectedSuggestion.getNodeIds().get(i);
tmpLandmarkNodeIds[i] = lmNodeId;
}
}
// Random randomInst = new Random();
// for (int i = 0; i < tmpLandmarkNodeIds.length; i++) {
// int index = randomInst.nextInt(subnetworkIds.size());
// tmpLandmarkNodeIds[i] = subnetworkIds.get(index);
// }
}
if (pickedPrecalculatedLandmarks) {
LOGGER.info("Picked " + tmpLandmarkNodeIds.length + " landmark suggestions, skipped expensive landmark determination");
} else {
// 1a) pick landmarks via special weighting for a better geographical spreading
Weighting initWeighting = lmSelectionWeighting;
LandmarkExplorer explorer = new LandmarkExplorer(graph, this, initWeighting, traversalMode);
explorer.initFrom(startNode, 0);
explorer.setFilter(blockedEdges, true, true);
explorer.runAlgo(true);
if (explorer.getFromCount() < minimumNodes) {
// too small subnetworks are initialized with special id==0
explorer.setSubnetworks(subnetworks, UNCLEAR_SUBNETWORK);
return false;
}
// 1b) we have one landmark, now determine the other landmarks
tmpLandmarkNodeIds[0] = explorer.getLastNode();
for (int lmIdx = 0; lmIdx < tmpLandmarkNodeIds.length - 1; lmIdx++) {
if(Thread.currentThread().isInterrupted()){
throw new RuntimeException("Thread was interrupted");
}
explorer = new LandmarkExplorer(graph, this, initWeighting, traversalMode);
explorer.setFilter(blockedEdges, true, true);
// set all current landmarks as start so that the next getLastNode is hopefully a "far away" node
for (int j = 0; j < lmIdx + 1; j++) {
explorer.initFrom(tmpLandmarkNodeIds[j], 0);
}
explorer.runAlgo(true);
tmpLandmarkNodeIds[lmIdx + 1] = explorer.getLastNode();
if (lmIdx % logOffset == 0)
LOGGER.info("Finding landmarks [" + weighting + "] in network [" + explorer.getVisitedNodes() + "]. "
+ "Progress " + (int) (100.0 * lmIdx / tmpLandmarkNodeIds.length) + "%, " + Helper.getMemInfo());
}
LOGGER.info("Finished searching landmarks for subnetwork " + subnetworkId + " of size " + explorer.getVisitedNodes());
}
// 2) calculate weights for all landmarks -> 'from' and 'to' weight
for (int lmIdx = 0; lmIdx < tmpLandmarkNodeIds.length; lmIdx++) {
if(Thread.currentThread().isInterrupted()){
throw new RuntimeException("Thread was interrupted");
}
int lmNodeId = tmpLandmarkNodeIds[lmIdx];
LandmarkExplorer explorer = new LandmarkExplorer(graph, this, weighting, traversalMode);
explorer.initFrom(lmNodeId, 0);
explorer.setFilter(blockedEdges, false, true);
explorer.runAlgo(true);
explorer.initLandmarkWeights(lmIdx, lmNodeId, LM_ROW_LENGTH, FROM_OFFSET);
// set subnetwork id to all explored nodes, but do this only for the first landmark
if (lmIdx == 0) {
if (explorer.setSubnetworks(subnetworks, subnetworkId))
return false;
}
explorer = new LandmarkExplorer(graph, this, weighting, traversalMode);
explorer.initTo(lmNodeId, 0);
explorer.setFilter(blockedEdges, true, false);
explorer.runAlgo(false);
explorer.initLandmarkWeights(lmIdx, lmNodeId, LM_ROW_LENGTH, TO_OFFSET);
if (lmIdx == 0) {
if (explorer.setSubnetworks(subnetworks, subnetworkId))
return false;
}
if (lmIdx % logOffset == 0)
LOGGER.info("Set landmarks weights [" + weighting + "]. "
+ "Progress " + (int) (100.0 * lmIdx / tmpLandmarkNodeIds.length) + "%");
}
// TODO set weight to SHORT_MAX if entry has either no 'from' or no 'to' entry
landmarkIDs.add(tmpLandmarkNodeIds);
return true;
}
/**
* This method specifies the polygons which should be used to split the world wide area to improve performance and
* quality in this scenario.
*/
public void setSpatialRuleLookup(SpatialRuleLookup ruleLookup) {
this.ruleLookup = ruleLookup;
}
/**
* This method makes edges crossing the specified border inaccessible to split a bigger area into smaller subnetworks.
* This is important for the world wide use case to limit the maximum distance and also to detect unreasonable routes faster.
*/
protected IntHashSet findBorderEdgeIds(SpatialRuleLookup ruleLookup) {
AllEdgesIterator allEdgesIterator = graph.getAllEdges();
NodeAccess nodeAccess = graph.getNodeAccess();
IntHashSet inaccessible = new IntHashSet();
while (allEdgesIterator.next()) {
int adjNode = allEdgesIterator.getAdjNode();
SpatialRule ruleAdj = ruleLookup.lookupRule(nodeAccess.getLatitude(adjNode), nodeAccess.getLongitude(adjNode));
int baseNode = allEdgesIterator.getBaseNode();
SpatialRule ruleBase = ruleLookup.lookupRule(nodeAccess.getLatitude(baseNode), nodeAccess.getLongitude(baseNode));
if (ruleAdj != ruleBase)
inaccessible.add(allEdgesIterator.getEdge());
}
return inaccessible;
}
/**
* The factor is used to convert double values into more compact int values.
*/
double getFactor() {
return factor;
}
/**
* @return the weight from the landmark to the specified node. Where the landmark integer is not
* a node ID but the internal index of the landmark array.
*/
public int getFromWeight(int landmarkIndex, int node) {
int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + FROM_OFFSET)
& 0x0000FFFF;
assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node;
if (res == SHORT_INFINITY)
// TODO can happen if endstanding oneway
// we should set a 'from' value to SHORT_MAX if the 'to' value was already set to find real bugs
// and what to return? Integer.MAX_VALUE i.e. convert to Double.pos_infinity upstream?
return SHORT_MAX;
// throw new IllegalStateException("Do not call getFromWeight for wrong landmark[" + landmarkIndex + "]=" + landmarkIDs[landmarkIndex] + " and node " + node);
// TODO if(res == MAX) fallback to beeline approximation!?
return res;
}
/**
* @return the weight from the specified node to the landmark (*as index*)
*/
public int getToWeight(int landmarkIndex, int node) {
int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + TO_OFFSET)
& 0x0000FFFF;
assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node;
if (res == SHORT_INFINITY)
return SHORT_MAX;
// throw new IllegalStateException("Do not call getToWeight for wrong landmark[" + landmarkIndex + "]=" + landmarkIDs[landmarkIndex] + " and node " + node);
return res;
}
// Short.MAX_VALUE = 2^15-1 but we have unsigned short so we need 2^16-1
private static final int SHORT_INFINITY = Short.MAX_VALUE * 2 + 1;
// We have large values that do not fit into a short, use a specific maximum value
private static final int SHORT_MAX = SHORT_INFINITY - 1;
/**
* @return false if the value capacity was reached and instead of the real value the SHORT_MAX was stored.
*/
final boolean setWeight(long pointer, double value) {
double tmpVal = value / factor;
if (tmpVal > Integer.MAX_VALUE)
throw new UnsupportedOperationException("Cannot store infinity explicitely, pointer=" + pointer + ", value: " + value);
if (tmpVal >= SHORT_MAX) {
landmarkWeightDA.setShort(pointer, (short) SHORT_MAX);
return false;
} else {
landmarkWeightDA.setShort(pointer, (short) tmpVal);
return true;
}
}
boolean isInfinity(long pointer) {
return ((int) landmarkWeightDA.getShort(pointer) & 0x0000FFFF) == SHORT_INFINITY;
}
int calcWeight(EdgeIteratorState edge, boolean reverse) {
return (int) (weighting.calcWeight(edge, reverse, EdgeIterator.NO_EDGE) / factor);
}
// From all available landmarks pick just a few active ones
boolean initActiveLandmarks(int fromNode, int toNode, int[] activeLandmarkIndices,
int[] activeFroms, int[] activeTos, boolean reverse) {
if (fromNode < 0 || toNode < 0)
throw new IllegalStateException("from " + fromNode + " and to "
+ toNode + " nodes have to be 0 or positive to init landmarks");
int subnetworkFrom = subnetworkStorage.getSubnetwork(fromNode);
int subnetworkTo = subnetworkStorage.getSubnetwork(toNode);
if (subnetworkFrom <= UNCLEAR_SUBNETWORK || subnetworkTo <= UNCLEAR_SUBNETWORK)
return false;
if (subnetworkFrom != subnetworkTo) {
throw new ConnectionNotFoundException("Connection between locations not found. Different subnetworks " + subnetworkFrom + " vs. " + subnetworkTo, new HashMap<String, Object>());
}
int[] tmpIDs = landmarkIDs.get(subnetworkFrom);
// kind of code duplication to approximate
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(tmpIDs.length);
for (int lmIndex = 0; lmIndex < tmpIDs.length; lmIndex++) {
int fromWeight = getFromWeight(lmIndex, toNode) - getFromWeight(lmIndex, fromNode);
int toWeight = getToWeight(lmIndex, fromNode) - getToWeight(lmIndex, toNode);
list.add(new MapEntry<>(reverse
? Math.max(-fromWeight, -toWeight)
: Math.max(fromWeight, toWeight), lmIndex));
}
Collections.sort(list, SORT_BY_WEIGHT);
if (activeLandmarkIndices[0] >= 0) {
IntHashSet set = new IntHashSet(activeLandmarkIndices.length);
set.addAll(activeLandmarkIndices);
int existingLandmarkCounter = 0;
final int COUNT = Math.min(activeLandmarkIndices.length - 2, 2);
for (int i = 0; i < activeLandmarkIndices.length; i++) {
if (i >= activeLandmarkIndices.length - COUNT + existingLandmarkCounter) {
// keep at least two of the previous landmarks (pick the best)
break;
} else {
activeLandmarkIndices[i] = list.get(i).getValue();
if (set.contains(activeLandmarkIndices[i]))
existingLandmarkCounter++;
}
}
} else {
for (int i = 0; i < activeLandmarkIndices.length; i++) {
activeLandmarkIndices[i] = list.get(i).getValue();
}
}
// store weight values of active landmarks in 'cache' arrays
for (int i = 0; i < activeLandmarkIndices.length; i++) {
int lmIndex = activeLandmarkIndices[i];
activeFroms[i] = getFromWeight(lmIndex, toNode);
activeTos[i] = getToWeight(lmIndex, toNode);
}
return true;
}
public int getLandmarkCount() {
return landmarks;
}
public int[] getLandmarks(int subnetwork) {
return landmarkIDs.get(subnetwork);
}
/**
* @return the number of subnetworks that have landmarks
*/
public int getSubnetworksWithLandmarks() {
return landmarkIDs.size();
}
public boolean isEmpty() {
return landmarkIDs.size() < 2;
}
@Override
public String toString() {
String str = "";
for (int[] ints : landmarkIDs) {
if (!str.isEmpty())
str += ", ";
str += Arrays.toString(ints);
}
return str;
}
/**
* @return the calculated landmarks as GeoJSON string.
*/
String getLandmarksAsGeoJSON() {
NodeAccess na = graph.getNodeAccess();
String str = "";
for (int subnetwork = 1; subnetwork < landmarkIDs.size(); subnetwork++) {
int[] lmArray = landmarkIDs.get(subnetwork);
for (int lmIdx = 0; lmIdx < lmArray.length; lmIdx++) {
int index = lmArray[lmIdx];
if (!str.isEmpty())
str += ",";
str += "{ \"type\": \"Feature\", \"geometry\": {\"type\": \"Point\", \"coordinates\": ["
+ na.getLon(index) + ", " + na.getLat(index) + "]},";
str += " \"properties\":{\"node_index\":" + index + ","
+ "\"subnetwork\":" + subnetwork + ","
+ "\"lm_index\":" + lmIdx + "}"
+ "}";
}
}
return "{ \"type\": \"FeatureCollection\", \"features\": [" + str + "]}";
}
@Override
public boolean loadExisting() {
if (isInitialized())
throw new IllegalStateException("Cannot call PrepareLandmarks.loadExisting if already initialized");
if (landmarkWeightDA.loadExisting()) {
if (!subnetworkStorage.loadExisting())
throw new IllegalStateException("landmark weights loaded but not the subnetworks!?");
int nodes = landmarkWeightDA.getHeader(0 * 4);
if (nodes != graph.getNodes())
throw new IllegalArgumentException("Cannot load landmark data as written for different graph storage with " + nodes + " nodes, not " + graph.getNodes());
landmarks = landmarkWeightDA.getHeader(1 * 4);
int subnetworks = landmarkWeightDA.getHeader(2 * 4);
factor = landmarkWeightDA.getHeader(3 * 4) / DOUBLE_MLTPL;
LM_ROW_LENGTH = landmarks * 4;
long maxBytes = LM_ROW_LENGTH * nodes;
long bytePos = maxBytes;
// in the first subnetwork 0 there are no landmark IDs stored
for (int j = 0; j < subnetworks; j++) {
int[] tmpLandmarks = new int[landmarks];
for (int i = 0; i < tmpLandmarks.length; i++) {
tmpLandmarks[i] = landmarkWeightDA.getInt(bytePos);
bytePos += 4;
}
landmarkIDs.add(tmpLandmarks);
}
initialized = true;
return true;
}
return false;
}
@Override
public LandmarkStorage create(long byteCount) {
throw new IllegalStateException("Do not call LandmarkStore.create directly");
}
@Override
public void flush() {
landmarkWeightDA.flush();
subnetworkStorage.flush();
}
@Override
public void close() {
landmarkWeightDA.close();
subnetworkStorage.close();
}
@Override
public boolean isClosed() {
return landmarkWeightDA.isClosed();
}
@Override
public long getCapacity() {
return landmarkWeightDA.getCapacity() + subnetworkStorage.getCapacity();
}
/**
* This class is used to calculate landmark location (equally distributed).
*/
private static class LandmarkExplorer extends DijkstraBidirectionRef {
private int lastNode;
private boolean from;
private final LandmarkStorage lms;
public LandmarkExplorer(Graph g, LandmarkStorage lms, Weighting weighting, TraversalMode tMode) {
super(g, weighting, tMode);
this.lms = lms;
}
public void setFilter(IntHashSet set, boolean bwd, boolean fwd) {
EdgeFilter ef = new BlockedEdgesFilter(flagEncoder, bwd, fwd, set);
outEdgeExplorer = graph.createEdgeExplorer(ef);
inEdgeExplorer = graph.createEdgeExplorer(ef);
}
int getFromCount() {
return bestWeightMapFrom.size();
}
int getToCount() {
return bestWeightMapTo.size();
}
public int getLastNode() {
return lastNode;
}
public void runAlgo(boolean from) {
// no path should be calculated
setUpdateBestPath(false);
// set one of the bi directions as already finished
if (from)
finishedTo = true;
else
finishedFrom = true;
this.from = from;
super.runAlgo();
}
@Override
public boolean finished() {
if (from) {
lastNode = currFrom.adjNode;
return finishedFrom;
} else {
lastNode = currTo.adjNode;
return finishedTo;
}
}
public boolean setSubnetworks(final byte[] subnetworks, final int subnetworkId) {
if (subnetworkId > 127)
throw new IllegalStateException("Too many subnetworks " + subnetworkId);
final AtomicBoolean failed = new AtomicBoolean(false);
IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo;
map.forEach(new IntObjectPredicate<SPTEntry>() {
@Override
public boolean apply(int nodeId, SPTEntry value) {
int sn = subnetworks[nodeId];
if (sn != subnetworkId) {
if (sn != UNSET_SUBNETWORK && sn != UNCLEAR_SUBNETWORK) {
// this is ugly but can happen in real world, see testWithOnewaySubnetworks
LOGGER.error("subnetworkId for node " + nodeId
+ " (" + createPoint(graph, nodeId) + ") already set (" + sn + "). " + "Cannot change to " + subnetworkId);
failed.set(true);
return false;
}
subnetworks[nodeId] = (byte) subnetworkId;
}
return true;
}
});
return failed.get();
}
public void initLandmarkWeights(final int lmIdx, int lmNodeId, final long rowSize, final int offset) {
IntObjectMap<SPTEntry> map = from ? bestWeightMapFrom : bestWeightMapTo;
final AtomicInteger maxedout = new AtomicInteger(0);
final Map.Entry<Double, Double> finalMaxWeight = new MapEntry<>(0d, 0d);
map.forEach(new IntObjectProcedure<SPTEntry>() {
@Override
public void apply(int nodeId, SPTEntry b) {
if (!lms.setWeight(nodeId * rowSize + lmIdx * 4 + offset, b.weight)) {
maxedout.incrementAndGet();
finalMaxWeight.setValue(Math.max(b.weight, finalMaxWeight.getValue()));
}
}
});
if ((double) maxedout.get() / map.size() > 0.1) {
LOGGER.warn("landmark " + lmIdx + " (" + nodeAccess.getLatitude(lmNodeId) + "," + nodeAccess.getLongitude(lmNodeId) + "): " +
"too many weights were maxed out (" + maxedout.get() + "/" + map.size() + "). Use a bigger factor than " + lms.factor
+ ". For example use the following in the config.properties: weighting=" + weighting.getName() + "|maximum=" + finalMaxWeight.getValue() * 1.2);
}
}
}
/**
* Sort landmark by weight and let maximum weight come first, to pick best active landmarks.
*/
final static Comparator<Map.Entry<Integer, Integer>> SORT_BY_WEIGHT = new Comparator<Map.Entry<Integer, Integer>>() {
@Override
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return Integer.compare(o2.getKey(), o1.getKey());
}
};
static GHPoint createPoint(Graph graph, int nodeId) {
return new GHPoint(graph.getNodeAccess().getLatitude(nodeId), graph.getNodeAccess().getLongitude(nodeId));
}
final static class RequireBothDirectionsEdgeFilter implements EdgeFilter {
private FlagEncoder flagEncoder;
public RequireBothDirectionsEdgeFilter(FlagEncoder flagEncoder) {
this.flagEncoder = flagEncoder;
}
@Override
public boolean accept(EdgeIteratorState edgeState) {
return flagEncoder.isForward(edgeState.getFlags()) && flagEncoder.isBackward(edgeState.getFlags());
}
}
private static class BlockedEdgesFilter implements EdgeFilter {
private final IntHashSet blockedEdges;
private final FlagEncoder encoder;
private final boolean fwd;
private final boolean bwd;
public BlockedEdgesFilter(FlagEncoder encoder, boolean bwd, boolean fwd, IntHashSet blockedEdges) {
this.encoder = encoder;
this.bwd = bwd;
this.fwd = fwd;
this.blockedEdges = blockedEdges;
}
@Override
public final boolean accept(EdgeIteratorState iter) {
boolean blocked = blockedEdges.contains(iter.getEdge());
return fwd && iter.isForward(encoder) && !blocked || bwd && iter.isBackward(encoder) && !blocked;
}
public boolean acceptsBackward() {
return bwd;
}
public boolean acceptsForward() {
return fwd;
}
@Override
public String toString() {
return encoder.toString() + ", bwd:" + bwd + ", fwd:" + fwd;
}
}
}
| avoid exposing performance critical method to the public
| core/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java | avoid exposing performance critical method to the public | <ide><path>ore/src/main/java/com/graphhopper/routing/lm/LandmarkStorage.java
<ide> * @return the weight from the landmark to the specified node. Where the landmark integer is not
<ide> * a node ID but the internal index of the landmark array.
<ide> */
<del> public int getFromWeight(int landmarkIndex, int node) {
<add> int getFromWeight(int landmarkIndex, int node) {
<ide> int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + FROM_OFFSET)
<ide> & 0x0000FFFF;
<ide> assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node;
<ide> }
<ide>
<ide> /**
<del> * @return the weight from the specified node to the landmark (*as index*)
<del> */
<del> public int getToWeight(int landmarkIndex, int node) {
<add> * @return the weight from the specified node to the landmark (specified *as index*)
<add> */
<add> int getToWeight(int landmarkIndex, int node) {
<ide> int res = (int) landmarkWeightDA.getShort((long) node * LM_ROW_LENGTH + landmarkIndex * 4 + TO_OFFSET)
<ide> & 0x0000FFFF;
<ide> assert res >= 0 : "Negative to weight " + res + ", landmark index:" + landmarkIndex + ", node:" + node; |
|
JavaScript | mit | 466b7c91ef211cdd2c2ca20f9206c397ca46efcf | 0 | leagueofwashu/leagueofwashu.github.io,leagueofwashu/leagueofwashu.github.io |
var smallNav = false;
$(document).ready(function() {
console.log('hello');
$('.navbar').css('min-height', '36px');
$('body').css('padding-top', '40px');
$('.dd-content').css('display', 'none');
$('.signup-hide').css('display', 'none');
if ($(window).scrollTop() > 30 && $('.navbar-toggle').css('display') === 'none'){
shrinkNav();
}
});
$(window).scroll(function() {
if ( $(window).scrollTop() > 30 && $('.navbar-toggle').css('display') === 'none' && !smallNav) {
shrinkNav();
} else if (smallNav){
expandNav();
}
});
function shrinkNav(){
$('.navbar-wrapper').css('opacity', '0.8');
$('.navbar-brand').css('height', 'auto');
$('.navbar-brand').css('padding-top', '8px');
$('.navbar-brand').css('padding-bottom', '8px');
$('.navbar-nav>li>a').css('padding-top', '8px');
$('.navbar-nav>li>a').css('padding-bottom', '8px');
smallNav = true;
}
function expandNav(){
$('.navbar-wrapper').css('opacity', '1');
$('.navbar-brand').css('height', '40px');
$('.navbar-brand').css('padding-top', '15px');
$('.navbar-brand').css('padding-bottom', '15px');
$('.navbar-nav>li>a').css('padding-top', '15px');
$('.navbar-nav>li>a').css('padding-bottom', '15px');
smallNav = false;
}
$('.signup-link').on('click', function() {
$('#form-' + $(this).attr('id')).toggle();
return false;
});
$('.dd-header').on('click', function() {
$(this).toggleClass('dd-active');
if ( $(this).hasClass('dd-active')) {
$(this).parent().find('.dd-content').slideDown(175);
} else {
$(this).parent().find('.dd-content').slideUp(175);
}
});
| public/js/custom.js |
var smallNav = false;
$(document).ready(function() {
console.log('hello');
$('.navbar').css('min-height', '36px');
$('body').css('padding-top', '40px');
$('.dd-content').css('display', 'none');
$('.signup-hide').css('display', 'none');
if ($(window).scrollTop() > 30){
smallNav = true;
}
});
$(window).scroll(function() {
if ( $(window).scrollTop() > 30 && $('.navbar-toggle').css('display') === 'none' && !smallNav) {
$('.navbar-wrapper').css('opacity', '0.8');
$('.navbar-brand').css('height', 'auto');
$('.navbar-brand').css('padding-top', '8px');
$('.navbar-brand').css('padding-bottom', '8px');
$('.navbar-nav>li>a').css('padding-top', '8px');
$('.navbar-nav>li>a').css('padding-bottom', '8px');
smallNav = true;
} else if (smallNav){
$('.navbar-wrapper').css('opacity', '1');
$('.navbar-brand').css('height', '40px');
$('.navbar-brand').css('padding-top', '15px');
$('.navbar-brand').css('padding-bottom', '15px');
$('.navbar-nav>li>a').css('padding-top', '15px');
$('.navbar-nav>li>a').css('padding-bottom', '15px');
smallNav = false;
}
});
$('.signup-link').on('click', function() {
$('#form-' + $(this).attr('id')).toggle();
return false;
});
$('.dd-header').on('click', function() {
$(this).toggleClass('dd-active');
if ( $(this).hasClass('dd-active')) {
$(this).parent().find('.dd-content').slideDown(175);
} else {
$(this).parent().find('.dd-content').slideUp(175);
}
});
| dsjfiosdfj
| public/js/custom.js | dsjfiosdfj | <ide><path>ublic/js/custom.js
<ide> $('.dd-content').css('display', 'none');
<ide> $('.signup-hide').css('display', 'none');
<ide>
<del> if ($(window).scrollTop() > 30){
<del> smallNav = true;
<add> if ($(window).scrollTop() > 30 && $('.navbar-toggle').css('display') === 'none'){
<add> shrinkNav();
<ide> }
<ide> });
<ide>
<ide> $(window).scroll(function() {
<ide> if ( $(window).scrollTop() > 30 && $('.navbar-toggle').css('display') === 'none' && !smallNav) {
<del> $('.navbar-wrapper').css('opacity', '0.8');
<del> $('.navbar-brand').css('height', 'auto');
<del> $('.navbar-brand').css('padding-top', '8px');
<del> $('.navbar-brand').css('padding-bottom', '8px');
<del> $('.navbar-nav>li>a').css('padding-top', '8px');
<del> $('.navbar-nav>li>a').css('padding-bottom', '8px');
<del> smallNav = true;
<add> shrinkNav();
<ide> } else if (smallNav){
<del> $('.navbar-wrapper').css('opacity', '1');
<del> $('.navbar-brand').css('height', '40px');
<del> $('.navbar-brand').css('padding-top', '15px');
<del> $('.navbar-brand').css('padding-bottom', '15px');
<del> $('.navbar-nav>li>a').css('padding-top', '15px');
<del> $('.navbar-nav>li>a').css('padding-bottom', '15px');
<del>
<del> smallNav = false;
<add> expandNav();
<ide> }
<ide> });
<add>
<add>function shrinkNav(){
<add> $('.navbar-wrapper').css('opacity', '0.8');
<add> $('.navbar-brand').css('height', 'auto');
<add> $('.navbar-brand').css('padding-top', '8px');
<add> $('.navbar-brand').css('padding-bottom', '8px');
<add> $('.navbar-nav>li>a').css('padding-top', '8px');
<add> $('.navbar-nav>li>a').css('padding-bottom', '8px');
<add> smallNav = true;
<add>}
<add>
<add>function expandNav(){
<add> $('.navbar-wrapper').css('opacity', '1');
<add> $('.navbar-brand').css('height', '40px');
<add> $('.navbar-brand').css('padding-top', '15px');
<add> $('.navbar-brand').css('padding-bottom', '15px');
<add> $('.navbar-nav>li>a').css('padding-top', '15px');
<add> $('.navbar-nav>li>a').css('padding-bottom', '15px');
<add> smallNav = false;
<add>}
<ide>
<ide> $('.signup-link').on('click', function() {
<ide> |
|
Java | mit | 5768a8b97db8f09145b3ffc9173d74f61c94168c | 0 | JCThePants/NucleusFramework,JCThePants/NucleusFramework | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.utils.items.loremeta;
import com.jcwhatever.nucleus.collections.wrap.MapWrapper;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.items.ItemStackUtils;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A collection of {@link LoreMetaItem}.
*/
public class LoreMetaMap extends MapWrapper<String, LoreMetaItem> {
private final Map<String, LoreMetaItem> _map;
/**
* Constructor.
*/
public LoreMetaMap() {
_map = new LinkedHashMap<>(7);
}
/**
* Constructor.
*
* @param items The collection of meta items to initialize with.
*/
public LoreMetaMap(Collection<? extends LoreMetaItem> items) {
PreCon.notNull(items);
_map = new HashMap<>(items.size() + (int)(items.size() * 0.25D));
for (LoreMetaItem item : items)
_map.put(item.getName(), item);
}
/**
* Constructor.
*
* @param itemStack The item stack to parse meta from.
*/
public LoreMetaMap(ItemStack itemStack) {
this(itemStack, LoreMetaParser.get());
}
/**
* Constructor.
*
* @param itemStack The item stack to parse meta from.
* @param parser The parser to use.
*/
public LoreMetaMap(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
PreCon.notNull(parser);
List<String> lore = ItemStackUtils.getLore(itemStack);
_map = new HashMap<>(lore.size() + 10);
for (String loreLine : lore) {
LoreMetaItem item = parser.parseLoreMeta(loreLine);
if (item != null)
_map.put(item.getName(), item);
}
}
/**
* Add a new meta item to the collection.
*
* <p>Replaces existing value.</p>
*
* @param name The name of the meta.
* @param value The meta value.
*
* @return The newly created {@link LoreMetaItem} instance.
*/
public LoreMetaItem put(String name, String value) {
PreCon.notNullOrEmpty(name);
PreCon.notNull(value);
LoreMetaItem item = new LoreMetaItem(name, value);
_map.put(name, item);
return item;
}
/**
* Add a new meta item to the collection.
*
* <p>Replaces existing value.</p>
*
* @param item The item to put.
*
* @return The previously stored {@link LoreMetaItem} instance.
*/
@Nullable
public LoreMetaItem put(LoreMetaItem item) {
PreCon.notNull(item);
return _map.put(item.getName(), item);
}
/**
* Set the value of a meta item.
*
* <p>Replaces existing value. Adds new value if not found.</p>
*
* @param name The name of the meta.
* @param value The meta value.
*
* @return Self for chaining.
*/
public LoreMetaMap set(String name, String value) {
put(name, value);
return this;
}
/**
* Remove a meta value by name.
*
* @param name The name of the meta.
*
* @return The removed meta item or null if not found.
*/
@Nullable
public LoreMetaItem remove(String name) {
PreCon.notNull(name);
return _map.remove(name);
}
/**
* Get a meta item by name.
*
* @param name The name of the meta.
*
* @return The meta item or null if not found.
*/
@Nullable
public LoreMetaItem get(String name) {
PreCon.notNull(name);
return _map.get(name);
}
/**
* Append meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
*/
public void appendTo(ItemStack itemStack) {
appendTo(itemStack, LoreMetaParser.get());
}
/**
* Append meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
* @param parser The parser to use.
*/
public void appendTo(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
LoreMeta.append(itemStack, parser, this.values());
}
/**
* Prepend meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
*/
public void prependTo(ItemStack itemStack) {
prependTo(itemStack, LoreMetaParser.get());
}
/**
* Prepend meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
* @param parser The parser to use.
*/
public void prependTo(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
LoreMeta.prepend(itemStack, parser, this.values());
}
@Override
protected Map<String, LoreMetaItem> map() {
return _map;
}
}
| src/com/jcwhatever/nucleus/utils/items/loremeta/LoreMetaMap.java | /*
* This file is part of NucleusFramework for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.jcwhatever.nucleus.utils.items.loremeta;
import com.jcwhatever.nucleus.collections.wrap.MapWrapper;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.items.ItemStackUtils;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A collection of {@link LoreMetaItem}.
*/
public class LoreMetaMap extends MapWrapper<String, LoreMetaItem> {
private final Map<String, LoreMetaItem> _map;
/**
* Constructor.
*/
public LoreMetaMap() {
_map = new HashMap<>(7);
}
/**
* Constructor.
*
* @param items The collection of meta items to initialize with.
*/
public LoreMetaMap(Collection<? extends LoreMetaItem> items) {
PreCon.notNull(items);
_map = new HashMap<>(items.size() + (int)(items.size() * 0.25D));
for (LoreMetaItem item : items)
_map.put(item.getName(), item);
}
/**
* Constructor.
*
* @param itemStack The item stack to parse meta from.
*/
public LoreMetaMap(ItemStack itemStack) {
this(itemStack, LoreMetaParser.get());
}
/**
* Constructor.
*
* @param itemStack The item stack to parse meta from.
* @param parser The parser to use.
*/
public LoreMetaMap(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
PreCon.notNull(parser);
List<String> lore = ItemStackUtils.getLore(itemStack);
_map = new HashMap<>(lore.size() + 10);
for (String loreLine : lore) {
LoreMetaItem item = parser.parseLoreMeta(loreLine);
if (item != null)
_map.put(item.getName(), item);
}
}
/**
* Add a new meta item to the collection.
*
* <p>Replaces existing value.</p>
*
* @param name The name of the meta.
* @param value The meta value.
*
* @return The newly created {@link LoreMetaItem} instance.
*/
public LoreMetaItem put(String name, String value) {
PreCon.notNullOrEmpty(name);
PreCon.notNull(value);
LoreMetaItem item = new LoreMetaItem(name, value);
_map.put(name, item);
return item;
}
/**
* Add a new meta item to the collection.
*
* <p>Replaces existing value.</p>
*
* @param item The item to put.
*
* @return The previously stored {@link LoreMetaItem} instance.
*/
@Nullable
public LoreMetaItem put(LoreMetaItem item) {
PreCon.notNull(item);
return _map.put(item.getName(), item);
}
/**
* Set the value of a meta item.
*
* <p>Replaces existing value. Adds new value if not found.</p>
*
* @param name The name of the meta.
* @param value The meta value.
*
* @return Self for chaining.
*/
public LoreMetaMap set(String name, String value) {
put(name, value);
return this;
}
/**
* Remove a meta value by name.
*
* @param name The name of the meta.
*
* @return The removed meta item or null if not found.
*/
@Nullable
public LoreMetaItem remove(String name) {
PreCon.notNull(name);
return _map.remove(name);
}
/**
* Get a meta item by name.
*
* @param name The name of the meta.
*
* @return The meta item or null if not found.
*/
@Nullable
public LoreMetaItem get(String name) {
PreCon.notNull(name);
return _map.get(name);
}
/**
* Append meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
*/
public void appendTo(ItemStack itemStack) {
appendTo(itemStack, LoreMetaParser.get());
}
/**
* Append meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
* @param parser The parser to use.
*/
public void appendTo(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
LoreMeta.append(itemStack, parser, this.values());
}
/**
* Prepend meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
*/
public void prependTo(ItemStack itemStack) {
prependTo(itemStack, LoreMetaParser.get());
}
/**
* Prepend meta in the collection to an item stacks lore text.
*
* @param itemStack The item stack.
* @param parser The parser to use.
*/
public void prependTo(ItemStack itemStack, ILoreMetaParser parser) {
PreCon.notNull(itemStack);
LoreMeta.prepend(itemStack, parser, this.values());
}
@Override
protected Map<String, LoreMetaItem> map() {
return _map;
}
}
| use LinkedHashMap to maintain meta order
| src/com/jcwhatever/nucleus/utils/items/loremeta/LoreMetaMap.java | use LinkedHashMap to maintain meta order | <ide><path>rc/com/jcwhatever/nucleus/utils/items/loremeta/LoreMetaMap.java
<ide> import javax.annotation.Nullable;
<ide> import java.util.Collection;
<ide> import java.util.HashMap;
<add>import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> * Constructor.
<ide> */
<ide> public LoreMetaMap() {
<del> _map = new HashMap<>(7);
<add> _map = new LinkedHashMap<>(7);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 9ff81ac41c4b2be003d5c58c3c44f8a2928f0d84 | 0 | deepnarsay/JGroups,vjuranek/JGroups,deepnarsay/JGroups,rhusar/JGroups,kedzie/JGroups,pruivo/JGroups,rhusar/JGroups,rpelisse/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,rvansa/JGroups,dimbleby/JGroups,Sanne/JGroups,ibrahimshbat/JGroups,danberindei/JGroups,belaban/JGroups,rpelisse/JGroups,pruivo/JGroups,tristantarrant/JGroups,slaskawi/JGroups,TarantulaTechnology/JGroups,vjuranek/JGroups,vjuranek/JGroups,ligzy/JGroups,ligzy/JGroups,slaskawi/JGroups,kedzie/JGroups,pferraro/JGroups,ibrahimshbat/JGroups,pferraro/JGroups,Sanne/JGroups,rvansa/JGroups,belaban/JGroups,belaban/JGroups,rpelisse/JGroups,TarantulaTechnology/JGroups,rhusar/JGroups,TarantulaTechnology/JGroups,danberindei/JGroups,ibrahimshbat/JGroups,tristantarrant/JGroups,slaskawi/JGroups,ligzy/JGroups,pferraro/JGroups,deepnarsay/JGroups,dimbleby/JGroups,pruivo/JGroups,danberindei/JGroups,kedzie/JGroups,dimbleby/JGroups | package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Range;
import org.jgroups.util.Util;
import java.util.*;
/**
* Fragmentation layer. Fragments messages larger than frag_size into smaller packets.
* Reassembles fragmented packets into bigger ones. The fragmentation number is prepended
* to the messages as a header (and removed at the receiving side).<p>
* Each fragment is identified by (a) the sender (part of the message to which the header is appended),
* (b) the fragmentation ID (which is unique per FRAG2 layer (monotonically increasing) and (c) the
* fragement ID which ranges from 0 to number_of_fragments-1.<p>
* Requirement: lossless delivery (e.g. NAK, ACK). No requirement on ordering. Works for both unicast and
* multicast messages.<br/>
* Compared to FRAG, this protocol does <em>not</em> need to serialize the message in order to break it into
* smaller fragments: it looks only at the message's buffer, which is a byte[] array anyway. We assume that the
* size addition for headers and src and dest address is minimal when the transport finally has to serialize the
* message, so we add a constant (200 bytes).
* @author Bela Ban
* @version $Id: FRAG2.java,v 1.25 2006/08/23 07:20:12 belaban Exp $
*/
public class FRAG2 extends Protocol {
/** The max number of bytes in a message. If a message's buffer is bigger, it will be fragmented */
int frag_size=1500;
/** Number of bytes that we think the headers plus src and dest will take up when
message is serialized by transport. This will be subtracted from frag_size */
int overhead=200;
/*the fragmentation list contains a fragmentation table per sender
*this way it becomes easier to clean up if a sender (member) leaves or crashes
*/
private final FragmentationList fragment_list=new FragmentationList();
private int curr_id=1;
private final Vector members=new Vector(11);
private static final String name="FRAG2";
long num_sent_msgs=0;
long num_sent_frags=0;
long num_received_msgs=0;
long num_received_frags=0;
public final String getName() {
return name;
}
public int getFragSize() {return frag_size;}
public void setFragSize(int s) {frag_size=s;}
public int getOverhead() {return overhead;}
public void setOverhead(int o) {overhead=o;}
public long getNumberOfSentMessages() {return num_sent_msgs;}
public long getNumberOfSentFragments() {return num_sent_frags;}
public long getNumberOfReceivedMessages() {return num_received_msgs;}
public long getNumberOfReceivedFragments() {return num_received_frags;}
synchronized int getNextId() {
return curr_id++;
}
/** Setup the Protocol instance acording to the configuration string */
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("frag_size");
if(str != null) {
frag_size=Integer.parseInt(str);
props.remove("frag_size");
}
str=props.getProperty("overhead");
if(str != null) {
overhead=Integer.parseInt(str);
props.remove("overhead");
}
int old_frag_size=frag_size;
frag_size-=overhead;
if(frag_size <=0) {
log.error("frag_size=" + old_frag_size + ", overhead=" + overhead +
", new frag_size=" + frag_size + ": new frag_size is invalid");
return false;
}
if(log.isInfoEnabled())
log.info("frag_size=" + old_frag_size + ", overhead=" + overhead + ", new frag_size=" + frag_size);
if(props.size() > 0) {
log.error("FRAG2.setProperties(): the following properties are not recognized: " + props);
return false;
}
return true;
}
public void resetStats() {
super.resetStats();
num_sent_msgs=num_sent_frags=num_received_msgs=num_received_frags=0;
}
/**
* Fragment a packet if larger than frag_size (add a header). Otherwise just pass down. Only
* add a header if framentation is needed !
*/
public void down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
long size=msg.getLength();
synchronized(this) {
num_sent_msgs++;
}
if(size > frag_size) {
if(trace) {
StringBuffer sb=new StringBuffer("message's buffer size is ");
sb.append(size).append(", will fragment ").append("(frag_size=");
sb.append(frag_size).append(')');
log.trace(sb.toString());
}
fragment(msg); // Fragment and pass down
return;
}
break;
case Event.VIEW_CHANGE:
//don't do anything if this dude is sending out the view change
//we are receiving a view change,
//in here we check for the
View view=(View)evt.getArg();
Vector new_mbrs=view.getMembers(), left_mbrs;
Address mbr;
left_mbrs=Util.determineLeftMembers(members, new_mbrs);
members.clear();
members.addAll(new_mbrs);
for(int i=0; i < left_mbrs.size(); i++) {
mbr=(Address)left_mbrs.elementAt(i);
//the new view doesn't contain the sender, he must have left,
//hence we will clear all his fragmentation tables
fragment_list.remove(mbr);
if(trace) log.trace("[VIEW_CHANGE] removed " + mbr + " from fragmentation table");
}
break;
case Event.CONFIG:
passDown(evt);
if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passDown(evt); // Pass on to the layer below us
}
/**
* If event is a message, if it is fragmented, re-assemble fragments into big message and pass up
* the stack.
*/
public void up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Object obj=msg.getHeader(name);
if(obj != null && obj instanceof FragHeader) { // needs to be defragmented
unfragment(msg); // Unfragment and possibly pass up
return;
}
else {
num_received_msgs++;
}
break;
case Event.CONFIG:
passUp(evt);
if(log.isInfoEnabled()) log.info("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passUp(evt); // Pass up to the layer above us by default
}
/** Send all fragments as separate messages (with same ID !).
Example:
<pre>
Given the generated ID is 2344, number of fragments=3, message {dst,src,buf}
would be fragmented into:
[2344,3,0]{dst,src,buf1},
[2344,3,1]{dst,src,buf2} and
[2344,3,2]{dst,src,buf3}
</pre>
*/
void fragment(Message msg) {
byte[] buffer;
List fragments;
Event evt;
FragHeader hdr;
Message frag_msg;
Address dest=msg.getDest();
long id=getNextId(); // used as seqnos
int num_frags;
StringBuffer sb;
Range r;
try {
buffer=msg.getBuffer();
fragments=Util.computeFragOffsets(buffer, frag_size);
num_frags=fragments.size();
synchronized(this) {
num_sent_frags+=num_frags;
}
if(trace) {
sb=new StringBuffer("fragmenting packet to ");
sb.append((dest != null ? dest.toString() : "<all members>")).append(" (size=").append(buffer.length);
sb.append(") into ").append(num_frags).append(" fragment(s) [frag_size=").append(frag_size).append(']');
log.trace(sb.toString());
}
for(int i=0; i < fragments.size(); i++) {
r=(Range)fragments.get(i);
// Copy the original msg (needed because we need to copy the headers too)
frag_msg=msg.copy(false); // don't copy the buffer, only src, dest and headers
frag_msg.setBuffer(buffer, (int)r.low, (int)r.high);
hdr=new FragHeader(id, i, num_frags);
frag_msg.putHeader(name, hdr);
evt=new Event(Event.MSG, frag_msg);
passDown(evt);
}
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("fragmentation failure", e);
}
}
/**
1. Get all the fragment buffers
2. When all are received -> Assemble them into one big buffer
3. Read headers and byte buffer from big buffer
4. Set headers and buffer in msg
5. Pass msg up the stack
*/
void unfragment(Message msg) {
FragmentationTable frag_table;
Address sender=msg.getSrc();
Message assembled_msg;
FragHeader hdr=(FragHeader)msg.removeHeader(name);
frag_table=fragment_list.get(sender);
if(frag_table == null) {
frag_table=new FragmentationTable(sender);
try {
fragment_list.add(sender, frag_table);
}
catch(IllegalArgumentException x) { // the entry has already been added, probably in parallel from another thread
frag_table=fragment_list.get(sender);
}
}
num_received_frags++;
assembled_msg=frag_table.add(hdr.id, hdr.frag_id, hdr.num_frags, msg);
if(assembled_msg != null) {
try {
if(trace) log.trace("assembled_msg is " + assembled_msg);
assembled_msg.setSrc(sender); // needed ? YES, because fragments have a null src !!
num_received_msgs++;
passUp(new Event(Event.MSG, assembled_msg));
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("unfragmentation failed", e);
}
}
}
void handleConfigEvent(HashMap map) {
if(map == null) return;
if(map.containsKey("frag_size")) {
frag_size=((Integer)map.get("frag_size")).intValue();
if(log.isDebugEnabled()) log.debug("setting frag_size=" + frag_size);
}
}
/**
* A fragmentation list keeps a list of fragmentation tables
* sorted by an Address ( the sender ).
* This way, if the sender disappears or leaves the group half way
* sending the content, we can simply remove this members fragmentation
* table and clean up the memory of the receiver.
* We do not have to do the same for the sender, since the sender doesn't keep a fragmentation table
*/
static class FragmentationList {
/* * HashMap<Address,FragmentationTable>, initialize the hashtable to hold all the fragmentation
* tables (11 is the best growth capacity to start with)
*/
private final HashMap frag_tables=new HashMap(11);
/**
* Adds a fragmentation table for this particular sender
* If this sender already has a fragmentation table, an IllegalArgumentException
* will be thrown.
* @param sender - the address of the sender, cannot be null
* @param table - the fragmentation table of this sender, cannot be null
* @exception IllegalArgumentException if an entry for this sender already exist
*/
public void add(Address sender, FragmentationTable table) throws IllegalArgumentException {
FragmentationTable healthCheck;
synchronized(frag_tables) {
healthCheck=(FragmentationTable)frag_tables.get(sender);
if(healthCheck == null) {
frag_tables.put(sender, table);
}
else {
throw new IllegalArgumentException("Sender <" + sender + "> already exists in the fragementation list.");
}
}
}
/**
* returns a fragmentation table for this sender
* returns null if the sender doesn't have a fragmentation table
* @return the fragmentation table for this sender, or null if no table exist
*/
public FragmentationTable get(Address sender) {
synchronized(frag_tables) {
return (FragmentationTable)frag_tables.get(sender);
}
}
/**
* returns true if this sender already holds a
* fragmentation for this sender, false otherwise
* @param sender - the sender, cannot be null
* @return true if this sender already has a fragmentation table
*/
public boolean containsSender(Address sender) {
synchronized(frag_tables) {
return frag_tables.containsKey(sender);
}
}
/**
* removes the fragmentation table from the list.
* after this operation, the fragementation list will no longer
* hold a reference to this sender's fragmentation table
* @param sender - the sender who's fragmentation table you wish to remove, cannot be null
* @return true if the table was removed, false if the sender doesn't have an entry
*/
public boolean remove(Address sender) {
synchronized(frag_tables) {
boolean result=containsSender(sender);
frag_tables.remove(sender);
return result;
}
}
/**
* returns a list of all the senders that have fragmentation tables
* opened.
* @return an array of all the senders in the fragmentation list
*/
public Address[] getSenders() {
Address[] result;
int index=0;
synchronized(frag_tables) {
result=new Address[frag_tables.size()];
for(Iterator it=frag_tables.keySet().iterator(); it.hasNext();) {
result[index++]=(Address)it.next();
}
}
return result;
}
public String toString() {
Map.Entry entry;
StringBuffer buf=new StringBuffer("Fragmentation list contains ");
synchronized(frag_tables) {
buf.append(frag_tables.size()).append(" tables\n");
for(Iterator it=frag_tables.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
buf.append(entry.getKey()).append(": " ).append(entry.getValue()).append("\n");
}
}
return buf.toString();
}
}
/**
* Keeps track of the fragments that are received.
* Reassembles fragements into entire messages when all fragments have been received.
* The fragmentation holds a an array of byte arrays for a unique sender
* The first dimension of the array is the order of the fragmentation, in case the arrive out of order
*/
static class FragmentationTable {
private final Address sender;
/* the hashtable that holds the fragmentation entries for this sender*/
private final Hashtable h=new Hashtable(11); // keys: frag_ids, vals: Entrys
FragmentationTable(Address sender) {
this.sender=sender;
}
/**
* inner class represents an entry for a message
* each entry holds an array of byte arrays sorted
* once all the byte buffer entries have been filled
* the fragmentation is considered complete.
*/
static class Entry {
//the total number of fragment in this message
int tot_frags=0;
// each fragment is a byte buffer
Message fragments[]=null;
//the number of fragments we have received
int number_of_frags_recvd=0;
// the message ID
long msg_id=-1;
/**
* Creates a new entry
* @param tot_frags the number of fragments to expect for this message
*/
Entry(long msg_id, int tot_frags) {
this.msg_id=msg_id;
this.tot_frags=tot_frags;
fragments=new Message[tot_frags];
for(int i=0; i < tot_frags; i++)
fragments[i]=null;
}
/**
* adds on fragmentation buffer to the message
* @param frag_id the number of the fragment being added 0..(tot_num_of_frags - 1)
* @param frag the byte buffer containing the data for this fragmentation, should not be null
*/
public void set(int frag_id, Message frag) {
// don't count an already received fragment (should not happen though because the
// reliable transmission protocol(s) below should weed out duplicates
if(fragments[frag_id] == null) {
fragments[frag_id]=frag;
number_of_frags_recvd++;
}
}
/** returns true if this fragmentation is complete
* ie, all fragmentations have been received for this buffer
*
*/
public boolean isComplete() {
/*first make the simple check*/
if(number_of_frags_recvd < tot_frags) {
return false;
}
/*then double check just in case*/
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null)
return false;
}
/*all fragmentations have been received*/
return true;
}
/**
* Assembles all the fragments into one buffer. Takes all Messages, and combines their buffers into one
* buffer.
* This method does not check if the fragmentation is complete (use {@link #isComplete()} to verify
* before calling this method)
* @return the complete message in one buffer
*
*/
public Message assembleMessage() {
Message retval;
byte[] combined_buffer, tmp;
int combined_length=0, length, offset;
Message fragment;
int index=0;
for(int i=0; i < fragments.length; i++) {
fragment=fragments[i];
combined_length+=fragment.getLength();
}
combined_buffer=new byte[combined_length];
for(int i=0; i < fragments.length; i++) {
fragment=fragments[i];
tmp=fragment.getRawBuffer();
length=fragment.getLength();
offset=fragment.getOffset();
System.arraycopy(tmp, offset, combined_buffer, index, length);
index+=length;
}
retval=fragments[0].copy(false);
retval.setBuffer(combined_buffer);
return retval;
}
/**
* debug only
*/
public String toString() {
StringBuffer ret=new StringBuffer();
ret.append("[tot_frags=").append(tot_frags).append(", number_of_frags_recvd=").append(number_of_frags_recvd).append(']');
return ret.toString();
}
public int hashCode() {
return super.hashCode();
}
}
/**
* Creates a new entry if not yet present. Adds the fragment.
* If all fragements for a given message have been received,
* an entire message is reassembled and returned.
* Otherwise null is returned.
* @param id - the message ID, unique for a sender
* @param frag_id the index of this fragmentation (0..tot_frags-1)
* @param tot_frags the total number of fragmentations expected
* @param fragment - the byte buffer for this fragment
*/
public synchronized Message add(long id, int frag_id, int tot_frags, Message fragment) {
Message retval=null;
Entry e=(Entry)h.get(new Long(id));
if(e == null) { // Create new entry if not yet present
e=new Entry(id, tot_frags);
h.put(new Long(id), e);
}
e.set(frag_id, fragment);
if(e.isComplete()) {
retval=e.assembleMessage();
h.remove(new Long(id));
}
return retval;
}
public void reset() {
}
public String toString() {
StringBuffer buf=new StringBuffer("Fragmentation Table Sender:").append(sender).append("\n\t");
java.util.Enumeration e=this.h.elements();
while(e.hasMoreElements()) {
Entry entry=(Entry)e.nextElement();
int count=0;
for(int i=0; i < entry.fragments.length; i++) {
if(entry.fragments[i] != null) {
count++;
}
}
buf.append("Message ID:").append(entry.msg_id).append("\n\t");
buf.append("Total Frags:").append(entry.tot_frags).append("\n\t");
buf.append("Frags Received:").append(count).append("\n\n");
}
return buf.toString();
}
}
}
| src/org/jgroups/protocols/FRAG2.java | package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.View;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Range;
import org.jgroups.util.Util;
import java.util.*;
/**
* Fragmentation layer. Fragments messages larger than frag_size into smaller packets.
* Reassembles fragmented packets into bigger ones. The fragmentation number is prepended
* to the messages as a header (and removed at the receiving side).<p>
* Each fragment is identified by (a) the sender (part of the message to which the header is appended),
* (b) the fragmentation ID (which is unique per FRAG2 layer (monotonically increasing) and (c) the
* fragement ID which ranges from 0 to number_of_fragments-1.<p>
* Requirement: lossless delivery (e.g. NAK, ACK). No requirement on ordering. Works for both unicast and
* multicast messages.<br/>
* Compared to FRAG, this protocol does <em>not</em> need to serialize the message in order to break it into
* smaller fragments: it looks only at the message's buffer, which is a byte[] array anyway. We assume that the
* size addition for headers and src and dest address is minimal when the transport finally has to serialize the
* message, so we add a constant (1000 bytes).
* @author Bela Ban
* @version $Id: FRAG2.java,v 1.24 2006/05/16 04:03:58 belaban Exp $
*/
public class FRAG2 extends Protocol {
/** The max number of bytes in a message. If a message's buffer is bigger, it will be fragmented */
int frag_size=1500;
/** Number of bytes that we think the headers plus src and dest will take up when
message is serialized by transport. This will be subtracted from frag_size */
int overhead=200;
/*the fragmentation list contains a fragmentation table per sender
*this way it becomes easier to clean up if a sender (member) leaves or crashes
*/
private final FragmentationList fragment_list=new FragmentationList();
private int curr_id=1;
private final Vector members=new Vector(11);
private static final String name="FRAG2";
long num_sent_msgs=0;
long num_sent_frags=0;
long num_received_msgs=0;
long num_received_frags=0;
public final String getName() {
return name;
}
public int getFragSize() {return frag_size;}
public void setFragSize(int s) {frag_size=s;}
public int getOverhead() {return overhead;}
public void setOverhead(int o) {overhead=o;}
public long getNumberOfSentMessages() {return num_sent_msgs;}
public long getNumberOfSentFragments() {return num_sent_frags;}
public long getNumberOfReceivedMessages() {return num_received_msgs;}
public long getNumberOfReceivedFragments() {return num_received_frags;}
synchronized int getNextId() {
return curr_id++;
}
/** Setup the Protocol instance acording to the configuration string */
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("frag_size");
if(str != null) {
frag_size=Integer.parseInt(str);
props.remove("frag_size");
}
str=props.getProperty("overhead");
if(str != null) {
overhead=Integer.parseInt(str);
props.remove("overhead");
}
int old_frag_size=frag_size;
frag_size-=overhead;
if(frag_size <=0) {
log.error("frag_size=" + old_frag_size + ", overhead=" + overhead +
", new frag_size=" + frag_size + ": new frag_size is invalid");
return false;
}
if(log.isInfoEnabled())
log.info("frag_size=" + old_frag_size + ", overhead=" + overhead + ", new frag_size=" + frag_size);
if(props.size() > 0) {
log.error("FRAG2.setProperties(): the following properties are not recognized: " + props);
return false;
}
return true;
}
public void resetStats() {
super.resetStats();
num_sent_msgs=num_sent_frags=num_received_msgs=num_received_frags=0;
}
/**
* Fragment a packet if larger than frag_size (add a header). Otherwise just pass down. Only
* add a header if framentation is needed !
*/
public void down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
long size=msg.getLength();
synchronized(this) {
num_sent_msgs++;
}
if(size > frag_size) {
if(trace) {
StringBuffer sb=new StringBuffer("message's buffer size is ");
sb.append(size).append(", will fragment ").append("(frag_size=");
sb.append(frag_size).append(')');
log.trace(sb.toString());
}
fragment(msg); // Fragment and pass down
return;
}
break;
case Event.VIEW_CHANGE:
//don't do anything if this dude is sending out the view change
//we are receiving a view change,
//in here we check for the
View view=(View)evt.getArg();
Vector new_mbrs=view.getMembers(), left_mbrs;
Address mbr;
left_mbrs=Util.determineLeftMembers(members, new_mbrs);
members.clear();
members.addAll(new_mbrs);
for(int i=0; i < left_mbrs.size(); i++) {
mbr=(Address)left_mbrs.elementAt(i);
//the new view doesn't contain the sender, he must have left,
//hence we will clear all his fragmentation tables
fragment_list.remove(mbr);
if(trace) log.trace("[VIEW_CHANGE] removed " + mbr + " from fragmentation table");
}
break;
case Event.CONFIG:
passDown(evt);
if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passDown(evt); // Pass on to the layer below us
}
/**
* If event is a message, if it is fragmented, re-assemble fragments into big message and pass up
* the stack.
*/
public void up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
Object obj=msg.getHeader(name);
if(obj != null && obj instanceof FragHeader) { // needs to be defragmented
unfragment(msg); // Unfragment and possibly pass up
return;
}
else {
num_received_msgs++;
}
break;
case Event.CONFIG:
passUp(evt);
if(log.isInfoEnabled()) log.info("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passUp(evt); // Pass up to the layer above us by default
}
/** Send all fragments as separate messages (with same ID !).
Example:
<pre>
Given the generated ID is 2344, number of fragments=3, message {dst,src,buf}
would be fragmented into:
[2344,3,0]{dst,src,buf1},
[2344,3,1]{dst,src,buf2} and
[2344,3,2]{dst,src,buf3}
</pre>
*/
void fragment(Message msg) {
byte[] buffer;
List fragments;
Event evt;
FragHeader hdr;
Message frag_msg;
Address dest=msg.getDest();
long id=getNextId(); // used as seqnos
int num_frags;
StringBuffer sb;
Range r;
try {
buffer=msg.getBuffer();
fragments=Util.computeFragOffsets(buffer, frag_size);
num_frags=fragments.size();
synchronized(this) {
num_sent_frags+=num_frags;
}
if(trace) {
sb=new StringBuffer("fragmenting packet to ");
sb.append((dest != null ? dest.toString() : "<all members>")).append(" (size=").append(buffer.length);
sb.append(") into ").append(num_frags).append(" fragment(s) [frag_size=").append(frag_size).append(']');
log.trace(sb.toString());
}
for(int i=0; i < fragments.size(); i++) {
r=(Range)fragments.get(i);
// Copy the original msg (needed because we need to copy the headers too)
frag_msg=msg.copy(false); // don't copy the buffer, only src, dest and headers
frag_msg.setBuffer(buffer, (int)r.low, (int)r.high);
hdr=new FragHeader(id, i, num_frags);
frag_msg.putHeader(name, hdr);
evt=new Event(Event.MSG, frag_msg);
passDown(evt);
}
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("fragmentation failure", e);
}
}
/**
1. Get all the fragment buffers
2. When all are received -> Assemble them into one big buffer
3. Read headers and byte buffer from big buffer
4. Set headers and buffer in msg
5. Pass msg up the stack
*/
void unfragment(Message msg) {
FragmentationTable frag_table;
Address sender=msg.getSrc();
Message assembled_msg;
FragHeader hdr=(FragHeader)msg.removeHeader(name);
frag_table=fragment_list.get(sender);
if(frag_table == null) {
frag_table=new FragmentationTable(sender);
try {
fragment_list.add(sender, frag_table);
}
catch(IllegalArgumentException x) { // the entry has already been added, probably in parallel from another thread
frag_table=fragment_list.get(sender);
}
}
num_received_frags++;
assembled_msg=frag_table.add(hdr.id, hdr.frag_id, hdr.num_frags, msg);
if(assembled_msg != null) {
try {
if(trace) log.trace("assembled_msg is " + assembled_msg);
assembled_msg.setSrc(sender); // needed ? YES, because fragments have a null src !!
num_received_msgs++;
passUp(new Event(Event.MSG, assembled_msg));
}
catch(Exception e) {
if(log.isErrorEnabled()) log.error("unfragmentation failed", e);
}
}
}
void handleConfigEvent(HashMap map) {
if(map == null) return;
if(map.containsKey("frag_size")) {
frag_size=((Integer)map.get("frag_size")).intValue();
if(log.isDebugEnabled()) log.debug("setting frag_size=" + frag_size);
}
}
/**
* A fragmentation list keeps a list of fragmentation tables
* sorted by an Address ( the sender ).
* This way, if the sender disappears or leaves the group half way
* sending the content, we can simply remove this members fragmentation
* table and clean up the memory of the receiver.
* We do not have to do the same for the sender, since the sender doesn't keep a fragmentation table
*/
static class FragmentationList {
/* * HashMap<Address,FragmentationTable>, initialize the hashtable to hold all the fragmentation
* tables (11 is the best growth capacity to start with)
*/
private final HashMap frag_tables=new HashMap(11);
/**
* Adds a fragmentation table for this particular sender
* If this sender already has a fragmentation table, an IllegalArgumentException
* will be thrown.
* @param sender - the address of the sender, cannot be null
* @param table - the fragmentation table of this sender, cannot be null
* @exception IllegalArgumentException if an entry for this sender already exist
*/
public void add(Address sender, FragmentationTable table) throws IllegalArgumentException {
FragmentationTable healthCheck;
synchronized(frag_tables) {
healthCheck=(FragmentationTable)frag_tables.get(sender);
if(healthCheck == null) {
frag_tables.put(sender, table);
}
else {
throw new IllegalArgumentException("Sender <" + sender + "> already exists in the fragementation list.");
}
}
}
/**
* returns a fragmentation table for this sender
* returns null if the sender doesn't have a fragmentation table
* @return the fragmentation table for this sender, or null if no table exist
*/
public FragmentationTable get(Address sender) {
synchronized(frag_tables) {
return (FragmentationTable)frag_tables.get(sender);
}
}
/**
* returns true if this sender already holds a
* fragmentation for this sender, false otherwise
* @param sender - the sender, cannot be null
* @return true if this sender already has a fragmentation table
*/
public boolean containsSender(Address sender) {
synchronized(frag_tables) {
return frag_tables.containsKey(sender);
}
}
/**
* removes the fragmentation table from the list.
* after this operation, the fragementation list will no longer
* hold a reference to this sender's fragmentation table
* @param sender - the sender who's fragmentation table you wish to remove, cannot be null
* @return true if the table was removed, false if the sender doesn't have an entry
*/
public boolean remove(Address sender) {
synchronized(frag_tables) {
boolean result=containsSender(sender);
frag_tables.remove(sender);
return result;
}
}
/**
* returns a list of all the senders that have fragmentation tables
* opened.
* @return an array of all the senders in the fragmentation list
*/
public Address[] getSenders() {
Address[] result;
int index=0;
synchronized(frag_tables) {
result=new Address[frag_tables.size()];
for(Iterator it=frag_tables.keySet().iterator(); it.hasNext();) {
result[index++]=(Address)it.next();
}
}
return result;
}
public String toString() {
Map.Entry entry;
StringBuffer buf=new StringBuffer("Fragmentation list contains ");
synchronized(frag_tables) {
buf.append(frag_tables.size()).append(" tables\n");
for(Iterator it=frag_tables.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
buf.append(entry.getKey()).append(": " ).append(entry.getValue()).append("\n");
}
}
return buf.toString();
}
}
/**
* Keeps track of the fragments that are received.
* Reassembles fragements into entire messages when all fragments have been received.
* The fragmentation holds a an array of byte arrays for a unique sender
* The first dimension of the array is the order of the fragmentation, in case the arrive out of order
*/
static class FragmentationTable {
private final Address sender;
/* the hashtable that holds the fragmentation entries for this sender*/
private final Hashtable h=new Hashtable(11); // keys: frag_ids, vals: Entrys
FragmentationTable(Address sender) {
this.sender=sender;
}
/**
* inner class represents an entry for a message
* each entry holds an array of byte arrays sorted
* once all the byte buffer entries have been filled
* the fragmentation is considered complete.
*/
static class Entry {
//the total number of fragment in this message
int tot_frags=0;
// each fragment is a byte buffer
Message fragments[]=null;
//the number of fragments we have received
int number_of_frags_recvd=0;
// the message ID
long msg_id=-1;
/**
* Creates a new entry
* @param tot_frags the number of fragments to expect for this message
*/
Entry(long msg_id, int tot_frags) {
this.msg_id=msg_id;
this.tot_frags=tot_frags;
fragments=new Message[tot_frags];
for(int i=0; i < tot_frags; i++)
fragments[i]=null;
}
/**
* adds on fragmentation buffer to the message
* @param frag_id the number of the fragment being added 0..(tot_num_of_frags - 1)
* @param frag the byte buffer containing the data for this fragmentation, should not be null
*/
public void set(int frag_id, Message frag) {
// don't count an already received fragment (should not happen though because the
// reliable transmission protocol(s) below should weed out duplicates
if(fragments[frag_id] == null) {
fragments[frag_id]=frag;
number_of_frags_recvd++;
}
}
/** returns true if this fragmentation is complete
* ie, all fragmentations have been received for this buffer
*
*/
public boolean isComplete() {
/*first make the simple check*/
if(number_of_frags_recvd < tot_frags) {
return false;
}
/*then double check just in case*/
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null)
return false;
}
/*all fragmentations have been received*/
return true;
}
/**
* Assembles all the fragments into one buffer. Takes all Messages, and combines their buffers into one
* buffer.
* This method does not check if the fragmentation is complete (use {@link #isComplete()} to verify
* before calling this method)
* @return the complete message in one buffer
*
*/
public Message assembleMessage() {
Message retval;
byte[] combined_buffer, tmp;
int combined_length=0, length, offset;
Message fragment;
int index=0;
for(int i=0; i < fragments.length; i++) {
fragment=fragments[i];
combined_length+=fragment.getLength();
}
combined_buffer=new byte[combined_length];
for(int i=0; i < fragments.length; i++) {
fragment=fragments[i];
tmp=fragment.getRawBuffer();
length=fragment.getLength();
offset=fragment.getOffset();
System.arraycopy(tmp, offset, combined_buffer, index, length);
index+=length;
}
retval=fragments[0].copy(false);
retval.setBuffer(combined_buffer);
return retval;
}
/**
* debug only
*/
public String toString() {
StringBuffer ret=new StringBuffer();
ret.append("[tot_frags=").append(tot_frags).append(", number_of_frags_recvd=").append(number_of_frags_recvd).append(']');
return ret.toString();
}
public int hashCode() {
return super.hashCode();
}
}
/**
* Creates a new entry if not yet present. Adds the fragment.
* If all fragements for a given message have been received,
* an entire message is reassembled and returned.
* Otherwise null is returned.
* @param id - the message ID, unique for a sender
* @param frag_id the index of this fragmentation (0..tot_frags-1)
* @param tot_frags the total number of fragmentations expected
* @param fragment - the byte buffer for this fragment
*/
public synchronized Message add(long id, int frag_id, int tot_frags, Message fragment) {
Message retval=null;
Entry e=(Entry)h.get(new Long(id));
if(e == null) { // Create new entry if not yet present
e=new Entry(id, tot_frags);
h.put(new Long(id), e);
}
e.set(frag_id, fragment);
if(e.isComplete()) {
retval=e.assembleMessage();
h.remove(new Long(id));
}
return retval;
}
public void reset() {
}
public String toString() {
StringBuffer buf=new StringBuffer("Fragmentation Table Sender:").append(sender).append("\n\t");
java.util.Enumeration e=this.h.elements();
while(e.hasMoreElements()) {
Entry entry=(Entry)e.nextElement();
int count=0;
for(int i=0; i < entry.fragments.length; i++) {
if(entry.fragments[i] != null) {
count++;
}
}
buf.append("Message ID:").append(entry.msg_id).append("\n\t");
buf.append("Total Frags:").append(entry.tot_frags).append("\n\t");
buf.append("Frags Received:").append(count).append("\n\n");
}
return buf.toString();
}
}
}
| javadoc change
| src/org/jgroups/protocols/FRAG2.java | javadoc change | <ide><path>rc/org/jgroups/protocols/FRAG2.java
<ide> * Compared to FRAG, this protocol does <em>not</em> need to serialize the message in order to break it into
<ide> * smaller fragments: it looks only at the message's buffer, which is a byte[] array anyway. We assume that the
<ide> * size addition for headers and src and dest address is minimal when the transport finally has to serialize the
<del> * message, so we add a constant (1000 bytes).
<add> * message, so we add a constant (200 bytes).
<ide> * @author Bela Ban
<del> * @version $Id: FRAG2.java,v 1.24 2006/05/16 04:03:58 belaban Exp $
<add> * @version $Id: FRAG2.java,v 1.25 2006/08/23 07:20:12 belaban Exp $
<ide> */
<ide> public class FRAG2 extends Protocol {
<ide> |
|
Java | apache-2.0 | 04d19da7e42935d84cf2c05c2877a77eaaf63ced | 0 | xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,da1z/intellij-community,allotria/intellij-community,xfournet/intellij-community,da1z/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,da1z/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community | // Copyright 2000-2017 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.openapi.roots.ui.configuration;
import com.intellij.core.JavaCoreBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.util.BrowseFilesListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.CompilerProjectExtension;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.impl.LanguageLevelProjectExtensionImpl;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectStructureElementConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureDaemonAnalyzer;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement;
import com.intellij.openapi.ui.DetailsComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.project.ProjectKt;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.FieldPanel;
import com.intellij.ui.InsertPathAction;
import com.intellij.ui.components.fields.ExtendableTextField;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
/**
* @author Eugene Zhuravlev
* Date: Dec 15, 2003
*/
public class ProjectConfigurable extends ProjectStructureElementConfigurable<Project> implements DetailsComponent.Facade {
private final Project myProject;
private LanguageLevelCombo myLanguageLevelCombo;
private ProjectJdkConfigurable myProjectJdkConfigurable;
private FieldPanel myProjectCompilerOutput;
private JTextField myProjectName;
private JPanel myPanel;
private final StructureConfigurableContext myContext;
private final ModulesConfigurator myModulesConfigurator;
private JPanel myWholePanel;
private boolean myFreeze = false;
private DetailsComponent myDetailsComponent;
private final GeneralProjectSettingsElement mySettingsElement;
public ProjectConfigurable(Project project,
final StructureConfigurableContext context,
ModulesConfigurator configurator,
ProjectSdksModel model) {
myProject = project;
myContext = context;
myModulesConfigurator = configurator;
mySettingsElement = new GeneralProjectSettingsElement(context);
final ProjectStructureDaemonAnalyzer daemonAnalyzer = context.getDaemonAnalyzer();
myModulesConfigurator.addAllModuleChangeListener(new ModuleEditor.ChangeListener() {
@Override
public void moduleStateChanged(ModifiableRootModel moduleRootModel) {
daemonAnalyzer.queueUpdate(mySettingsElement);
}
});
init(model);
}
@Override
public ProjectStructureElement getProjectStructureElement() {
return mySettingsElement;
}
@Override
public DetailsComponent getDetailsComponent() {
return myDetailsComponent;
}
@Override
public JComponent createOptionsPanel() {
myDetailsComponent = new DetailsComponent(false, false);
myDetailsComponent.setContent(myPanel);
myDetailsComponent.setText(getBannerSlogan());
myProjectJdkConfigurable.createComponent(); //reload changed jdks
return myDetailsComponent.getComponent();
}
private void init(final ProjectSdksModel model) {
myPanel = new JPanel(new GridBagLayout());
myPanel.setPreferredSize(JBUI.size(700, 500));
if (ProjectKt.isDirectoryBased(myProject)) {
final JPanel namePanel = new JPanel(new BorderLayout());
final JLabel label =
new JLabel("<html><body><b>Project name:</b></body></html>", SwingConstants.LEFT);
namePanel.add(label, BorderLayout.NORTH);
myProjectName = new JTextField();
myProjectName.setColumns(40);
final JPanel nameFieldPanel = new JPanel();
nameFieldPanel.setLayout(new BoxLayout(nameFieldPanel, BoxLayout.X_AXIS));
nameFieldPanel.add(Box.createHorizontalStrut(4));
nameFieldPanel.add(myProjectName);
namePanel.add(nameFieldPanel, BorderLayout.CENTER);
final JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
wrapper.add(namePanel);
wrapper.setAlignmentX(0);
myPanel.add(wrapper, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBUI.insets(4, 0, 10, 0), 0, 0));
}
myProjectJdkConfigurable = new ProjectJdkConfigurable(myProject, model);
myPanel.add(myProjectJdkConfigurable.createComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBUI.insetsTop(4), 0, 0));
myPanel.add(myWholePanel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, JBUI.insetsTop(4), 0, 0));
myPanel.setBorder(new EmptyBorder(0, 10, 0, 10));
myProjectCompilerOutput.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
if (myFreeze) return;
myModulesConfigurator.processModuleCompilerOutputChanged(getCompilerOutputUrl());
}
});
myProjectJdkConfigurable.addChangeListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myLanguageLevelCombo.sdkUpdated(myProjectJdkConfigurable.getSelectedProjectJdk(), myProject.isDefault());
LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).setCurrentLevel(myLanguageLevelCombo.getSelectedLevel());
}
});
myLanguageLevelCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).setCurrentLevel(myLanguageLevelCombo.getSelectedLevel());
}
});
}
@Override
public void disposeUIResources() {
if (myProjectJdkConfigurable != null) {
myProjectJdkConfigurable.disposeUIResources();
}
}
@Override
public void reset() {
myFreeze = true;
try {
myProjectJdkConfigurable.reset();
final String compilerOutput = getOriginalCompilerOutputUrl();
if (compilerOutput != null) {
myProjectCompilerOutput.setText(FileUtil.toSystemDependentName(VfsUtilCore.urlToPath(compilerOutput)));
}
myLanguageLevelCombo.reset(myProject);
if (myProjectName != null) {
myProjectName.setText(myProject.getName());
}
}
finally {
myFreeze = false;
}
myContext.getDaemonAnalyzer().queueUpdate(mySettingsElement);
}
@Override
public void apply() throws ConfigurationException {
final CompilerProjectExtension compilerProjectExtension = CompilerProjectExtension.getInstance(myProject);
assert compilerProjectExtension != null : myProject;
if (myProjectName != null && StringUtil.isEmptyOrSpaces(myProjectName.getText())) {
throw new ConfigurationException("Please, specify project name!");
}
ApplicationManager.getApplication().runWriteAction(() -> {
// set the output path first so that handlers of RootsChanged event sent after JDK is set
// would see the updated path
String canonicalPath = myProjectCompilerOutput.getText();
if (canonicalPath != null && canonicalPath.length() > 0) {
try {
canonicalPath = FileUtil.resolveShortWindowsName(canonicalPath);
}
catch (IOException e) {
//file doesn't exist yet
}
canonicalPath = FileUtil.toSystemIndependentName(canonicalPath);
compilerProjectExtension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath));
}
else {
compilerProjectExtension.setCompilerOutputPointer(null);
}
LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject);
LanguageLevel level = myLanguageLevelCombo.getSelectedLevel();
if (level != null) {
extension.setLanguageLevel(level);
}
extension.setDefault(myLanguageLevelCombo.isDefault());
myProjectJdkConfigurable.apply();
if (myProjectName != null) {
((ProjectEx)myProject).setProjectName(getProjectName());
if (myDetailsComponent != null) myDetailsComponent.setText(getBannerSlogan());
}
});
}
@Override
public void setDisplayName(final String name) {
//do nothing
}
@Override
public Project getEditableObject() {
return myProject;
}
@Override
public String getBannerSlogan() {
return ProjectBundle.message("project.roots.project.banner.text", myProject.getName());
}
@Override
public String getDisplayName() {
return ProjectBundle.message("project.roots.project.display.name");
}
@Override
public Icon getIcon(boolean open) {
return AllIcons.Nodes.Project;
}
@Override
@Nullable
@NonNls
public String getHelpTopic() {
return "reference.settingsdialog.project.structure.general";
}
@Override
@SuppressWarnings({"SimplifiableIfStatement"})
public boolean isModified() {
LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject);
if (extension.isDefault() != myLanguageLevelCombo.isDefault() ||
!extension.isDefault() && !extension.getLanguageLevel().equals(myLanguageLevelCombo.getSelectedLevel())) {
return true;
}
final String compilerOutput = getOriginalCompilerOutputUrl();
if (!Comparing.strEqual(FileUtil.toSystemIndependentName(VfsUtilCore.urlToPath(compilerOutput)),
FileUtil.toSystemIndependentName(myProjectCompilerOutput.getText()))) return true;
if (myProjectJdkConfigurable.isModified()) return true;
if (!getProjectName().equals(myProject.getName())) return true;
return false;
}
@NotNull
public String getProjectName() {
return myProjectName != null ? myProjectName.getText().trim() : myProject.getName();
}
@Nullable
private String getOriginalCompilerOutputUrl() {
final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(myProject);
return extension != null ? extension.getCompilerOutputUrl() : null;
}
private void createUIComponents() {
myLanguageLevelCombo = new LanguageLevelCombo(JavaCoreBundle.message("default.language.level.description")) {
@Override
protected LanguageLevel getDefaultLevel() {
Sdk sdk = myProjectJdkConfigurable.getSelectedProjectJdk();
if (sdk == null) return null;
JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version == null ? null : version.getMaxLanguageLevel();
}
};
final JTextField textField = new ExtendableTextField();
final FileChooserDescriptor outputPathsChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
InsertPathAction.addTo(textField, outputPathsChooserDescriptor);
outputPathsChooserDescriptor.setHideIgnored(false);
BrowseFilesListener listener = new BrowseFilesListener(textField, "", ProjectBundle.message("project.compiler.output"), outputPathsChooserDescriptor);
myProjectCompilerOutput = new FieldPanel(textField, null, null, listener, EmptyRunnable.getInstance());
FileChooserFactory.getInstance().installFileCompletion(myProjectCompilerOutput.getTextField(), outputPathsChooserDescriptor, true, null);
}
public String getCompilerOutputUrl() {
return VfsUtilCore.pathToUrl(myProjectCompilerOutput.getText().trim());
}
}
| java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.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.openapi.roots.ui.configuration;
import com.intellij.core.JavaCoreBundle;
import com.intellij.icons.AllIcons;
import com.intellij.ide.util.BrowseFilesListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.CompilerProjectExtension;
import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.impl.LanguageLevelProjectExtensionImpl;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel;
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectStructureElementConfigurable;
import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureDaemonAnalyzer;
import com.intellij.openapi.roots.ui.configuration.projectRoot.daemon.ProjectStructureElement;
import com.intellij.openapi.ui.DetailsComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.project.ProjectKt;
import com.intellij.ui.DocumentAdapter;
import com.intellij.ui.FieldPanel;
import com.intellij.ui.InsertPathAction;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
/**
* @author Eugene Zhuravlev
* Date: Dec 15, 2003
*/
public class ProjectConfigurable extends ProjectStructureElementConfigurable<Project> implements DetailsComponent.Facade {
private final Project myProject;
private LanguageLevelCombo myLanguageLevelCombo;
private ProjectJdkConfigurable myProjectJdkConfigurable;
private FieldPanel myProjectCompilerOutput;
private JTextField myProjectName;
private JPanel myPanel;
private final StructureConfigurableContext myContext;
private final ModulesConfigurator myModulesConfigurator;
private JPanel myWholePanel;
private boolean myFreeze = false;
private DetailsComponent myDetailsComponent;
private final GeneralProjectSettingsElement mySettingsElement;
public ProjectConfigurable(Project project,
final StructureConfigurableContext context,
ModulesConfigurator configurator,
ProjectSdksModel model) {
myProject = project;
myContext = context;
myModulesConfigurator = configurator;
mySettingsElement = new GeneralProjectSettingsElement(context);
final ProjectStructureDaemonAnalyzer daemonAnalyzer = context.getDaemonAnalyzer();
myModulesConfigurator.addAllModuleChangeListener(new ModuleEditor.ChangeListener() {
@Override
public void moduleStateChanged(ModifiableRootModel moduleRootModel) {
daemonAnalyzer.queueUpdate(mySettingsElement);
}
});
init(model);
}
@Override
public ProjectStructureElement getProjectStructureElement() {
return mySettingsElement;
}
@Override
public DetailsComponent getDetailsComponent() {
return myDetailsComponent;
}
@Override
public JComponent createOptionsPanel() {
myDetailsComponent = new DetailsComponent(false, false);
myDetailsComponent.setContent(myPanel);
myDetailsComponent.setText(getBannerSlogan());
myProjectJdkConfigurable.createComponent(); //reload changed jdks
return myDetailsComponent.getComponent();
}
private void init(final ProjectSdksModel model) {
myPanel = new JPanel(new GridBagLayout());
myPanel.setPreferredSize(JBUI.size(700, 500));
if (ProjectKt.isDirectoryBased(myProject)) {
final JPanel namePanel = new JPanel(new BorderLayout());
final JLabel label =
new JLabel("<html><body><b>Project name:</b></body></html>", SwingConstants.LEFT);
namePanel.add(label, BorderLayout.NORTH);
myProjectName = new JTextField();
myProjectName.setColumns(40);
final JPanel nameFieldPanel = new JPanel();
nameFieldPanel.setLayout(new BoxLayout(nameFieldPanel, BoxLayout.X_AXIS));
nameFieldPanel.add(Box.createHorizontalStrut(4));
nameFieldPanel.add(myProjectName);
namePanel.add(nameFieldPanel, BorderLayout.CENTER);
final JPanel wrapper = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
wrapper.add(namePanel);
wrapper.setAlignmentX(0);
myPanel.add(wrapper, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBUI.insets(4, 0, 10, 0), 0, 0));
}
myProjectJdkConfigurable = new ProjectJdkConfigurable(myProject, model);
myPanel.add(myProjectJdkConfigurable.createComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
JBUI.insetsTop(4), 0, 0));
myPanel.add(myWholePanel, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, JBUI.insetsTop(4), 0, 0));
myPanel.setBorder(new EmptyBorder(0, 10, 0, 10));
myProjectCompilerOutput.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(DocumentEvent e) {
if (myFreeze) return;
myModulesConfigurator.processModuleCompilerOutputChanged(getCompilerOutputUrl());
}
});
myProjectJdkConfigurable.addChangeListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myLanguageLevelCombo.sdkUpdated(myProjectJdkConfigurable.getSelectedProjectJdk(), myProject.isDefault());
LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).setCurrentLevel(myLanguageLevelCombo.getSelectedLevel());
}
});
myLanguageLevelCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LanguageLevelProjectExtensionImpl.getInstanceImpl(myProject).setCurrentLevel(myLanguageLevelCombo.getSelectedLevel());
}
});
}
@Override
public void disposeUIResources() {
if (myProjectJdkConfigurable != null) {
myProjectJdkConfigurable.disposeUIResources();
}
}
@Override
public void reset() {
myFreeze = true;
try {
myProjectJdkConfigurable.reset();
final String compilerOutput = getOriginalCompilerOutputUrl();
if (compilerOutput != null) {
myProjectCompilerOutput.setText(FileUtil.toSystemDependentName(VfsUtilCore.urlToPath(compilerOutput)));
}
myLanguageLevelCombo.reset(myProject);
if (myProjectName != null) {
myProjectName.setText(myProject.getName());
}
}
finally {
myFreeze = false;
}
myContext.getDaemonAnalyzer().queueUpdate(mySettingsElement);
}
@Override
public void apply() throws ConfigurationException {
final CompilerProjectExtension compilerProjectExtension = CompilerProjectExtension.getInstance(myProject);
assert compilerProjectExtension != null : myProject;
if (myProjectName != null && StringUtil.isEmptyOrSpaces(myProjectName.getText())) {
throw new ConfigurationException("Please, specify project name!");
}
ApplicationManager.getApplication().runWriteAction(() -> {
// set the output path first so that handlers of RootsChanged event sent after JDK is set
// would see the updated path
String canonicalPath = myProjectCompilerOutput.getText();
if (canonicalPath != null && canonicalPath.length() > 0) {
try {
canonicalPath = FileUtil.resolveShortWindowsName(canonicalPath);
}
catch (IOException e) {
//file doesn't exist yet
}
canonicalPath = FileUtil.toSystemIndependentName(canonicalPath);
compilerProjectExtension.setCompilerOutputUrl(VfsUtilCore.pathToUrl(canonicalPath));
}
else {
compilerProjectExtension.setCompilerOutputPointer(null);
}
LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject);
LanguageLevel level = myLanguageLevelCombo.getSelectedLevel();
if (level != null) {
extension.setLanguageLevel(level);
}
extension.setDefault(myLanguageLevelCombo.isDefault());
myProjectJdkConfigurable.apply();
if (myProjectName != null) {
((ProjectEx)myProject).setProjectName(getProjectName());
if (myDetailsComponent != null) myDetailsComponent.setText(getBannerSlogan());
}
});
}
@Override
public void setDisplayName(final String name) {
//do nothing
}
@Override
public Project getEditableObject() {
return myProject;
}
@Override
public String getBannerSlogan() {
return ProjectBundle.message("project.roots.project.banner.text", myProject.getName());
}
@Override
public String getDisplayName() {
return ProjectBundle.message("project.roots.project.display.name");
}
@Override
public Icon getIcon(boolean open) {
return AllIcons.Nodes.Project;
}
@Override
@Nullable
@NonNls
public String getHelpTopic() {
return "reference.settingsdialog.project.structure.general";
}
@Override
@SuppressWarnings({"SimplifiableIfStatement"})
public boolean isModified() {
LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(myProject);
if (extension.isDefault() != myLanguageLevelCombo.isDefault() ||
!extension.isDefault() && !extension.getLanguageLevel().equals(myLanguageLevelCombo.getSelectedLevel())) {
return true;
}
final String compilerOutput = getOriginalCompilerOutputUrl();
if (!Comparing.strEqual(FileUtil.toSystemIndependentName(VfsUtilCore.urlToPath(compilerOutput)),
FileUtil.toSystemIndependentName(myProjectCompilerOutput.getText()))) return true;
if (myProjectJdkConfigurable.isModified()) return true;
if (!getProjectName().equals(myProject.getName())) return true;
return false;
}
@NotNull
public String getProjectName() {
return myProjectName != null ? myProjectName.getText().trim() : myProject.getName();
}
@Nullable
private String getOriginalCompilerOutputUrl() {
final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(myProject);
return extension != null ? extension.getCompilerOutputUrl() : null;
}
private void createUIComponents() {
myLanguageLevelCombo = new LanguageLevelCombo(JavaCoreBundle.message("default.language.level.description")) {
@Override
protected LanguageLevel getDefaultLevel() {
Sdk sdk = myProjectJdkConfigurable.getSelectedProjectJdk();
if (sdk == null) return null;
JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
return version == null ? null : version.getMaxLanguageLevel();
}
};
final JTextField textField = new JTextField();
final FileChooserDescriptor outputPathsChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
InsertPathAction.addTo(textField, outputPathsChooserDescriptor);
outputPathsChooserDescriptor.setHideIgnored(false);
BrowseFilesListener listener = new BrowseFilesListener(textField, "", ProjectBundle.message("project.compiler.output"), outputPathsChooserDescriptor);
myProjectCompilerOutput = new FieldPanel(textField, null, null, listener, EmptyRunnable.getInstance());
FileChooserFactory.getInstance().installFileCompletion(myProjectCompilerOutput.getTextField(), outputPathsChooserDescriptor, true, null);
}
public String getCompilerOutputUrl() {
return VfsUtilCore.pathToUrl(myProjectCompilerOutput.getText().trim());
}
}
| use ExtendableTextField to merge browse button
| java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java | use ExtendableTextField to merge browse button | <ide><path>ava/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ProjectConfigurable.java
<del>/*
<del> * Copyright 2000-2016 JetBrains s.r.o.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<add>// Copyright 2000-2017 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.
<ide>
<ide> package com.intellij.openapi.roots.ui.configuration;
<ide>
<ide> import com.intellij.ui.DocumentAdapter;
<ide> import com.intellij.ui.FieldPanel;
<ide> import com.intellij.ui.InsertPathAction;
<add>import com.intellij.ui.components.fields.ExtendableTextField;
<ide> import com.intellij.util.ui.JBUI;
<ide> import org.jetbrains.annotations.NonNls;
<ide> import org.jetbrains.annotations.NotNull;
<ide> return version == null ? null : version.getMaxLanguageLevel();
<ide> }
<ide> };
<del> final JTextField textField = new JTextField();
<add> final JTextField textField = new ExtendableTextField();
<ide> final FileChooserDescriptor outputPathsChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
<ide> InsertPathAction.addTo(textField, outputPathsChooserDescriptor);
<ide> outputPathsChooserDescriptor.setHideIgnored(false); |
|
Java | apache-2.0 | f16fc122e9b0a5ce46ac9b121884088f8ec75505 | 0 | AspiroTV/Connect-SDK-Android-Core,ConnectSDK/Connect-SDK-Android-Core | /*
* MediaControl
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 19 Jan 2014
*
* 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.connectsdk.service.capability;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.ServiceSubscription;
public interface MediaControl extends CapabilityMethods {
public final static String Any = "MediaControl.Any";
public final static String Play = "MediaControl.Play";
public final static String Pause = "MediaControl.Pause";
public final static String Stop = "MediaControl.Stop";
public final static String Rewind = "MediaControl.Rewind";
public final static String FastForward = "MediaControl.FastForward";
public final static String Seek = "MediaControl.Seek";
public final static String Previous = "MediaControl.Previous";
public final static String Next = "MediaControl.Next";
public final static String Duration = "MediaControl.Duration";
public final static String PlayState = "MediaControl.PlayState";
public final static String PlayState_Subscribe = "MediaControl.PlayState.Subscribe";
public final static String Position = "MediaControl.Position";
public static final int PLAYER_STATE_UNKNOWN = 0;
public static final int PLAYER_STATE_IDLE = 1;
public static final int PLAYER_STATE_PLAYING = 2;
public static final int PLAYER_STATE_PAUSED = 3;
public static final int PLAYER_STATE_BUFFERING = 4;
public final static String[] Capabilities = {
Play,
Pause,
Stop,
Rewind,
FastForward,
Seek,
Previous,
Next,
Duration,
PlayState,
PlayState_Subscribe,
Position,
};
public enum PlayStateStatus {
Unknown,
Idle,
Playing,
Paused,
Buffering,
Finished;
public static PlayStateStatus convertPlayerStateToPlayStateStatus(int playerState) {
PlayStateStatus status = PlayStateStatus.Unknown;
switch (playerState) {
case PLAYER_STATE_BUFFERING:
status = PlayStateStatus.Buffering;
break;
case PLAYER_STATE_IDLE:
status = PlayStateStatus.Finished;
break;
case PLAYER_STATE_PAUSED:
status = PlayStateStatus.Paused;
break;
case PLAYER_STATE_PLAYING:
status = PlayStateStatus.Playing;
break;
case PLAYER_STATE_UNKNOWN:
default:
status = PlayStateStatus.Unknown;
break;
}
return status;
}
public static PlayStateStatus convertTransportStateToPlayStateStatus(String transportState) {
PlayStateStatus status = PlayStateStatus.Unknown;
if (transportState.equals("STOPPED")) {
status = PlayStateStatus.Finished;
}
else if (transportState.equals("PLAYING")) {
status = PlayStateStatus.Playing;
}
else if (transportState.equals("TRANSITIONING")) {
status = PlayStateStatus.Buffering;
}
else if (transportState.equals("PAUSED_PLAYBACK")) {
status = PlayStateStatus.Paused;
}
else if (transportState.equals("PAUSED_RECORDING")) {
}
else if (transportState.equals("RECORDING")) {
}
else if (transportState.equals("NO_MEDIA_PRESENT")) {
}
return status;
}
};
public MediaControl getMediaControl();
public CapabilityPriorityLevel getMediaControlCapabilityLevel();
public void play(ResponseListener<Object> listener);
public void pause(ResponseListener<Object> listener);
public void stop(ResponseListener<Object> listener);
public void rewind(ResponseListener<Object> listener);
public void fastForward(ResponseListener<Object> listener);
public void previous(ResponseListener<Object> listener);
public void next(ResponseListener<Object> listener);
public void seek(long position, ResponseListener<Object> listener);
public void getDuration(DurationListener listener);
public void getPosition(PositionListener listener);
public void getPlayState(PlayStateListener listener);
public ServiceSubscription<PlayStateListener> subscribePlayState(PlayStateListener listener);
/**
* Success block that is called upon any change in a media file's play state.
*
* Passes a PlayStateStatus enum of the current media file
*/
public static interface PlayStateListener extends ResponseListener<PlayStateStatus> { }
/**
* Success block that is called upon successfully getting the media file's current playhead position.
*
* Passes the position of the current playhead position of the current media file, in seconds
*/
public static interface PositionListener extends ResponseListener<Long> { }
/**
* Success block that is called upon successfully getting the media file's duration.
*
* Passes the duration of the current media file, in seconds
*/
public static interface DurationListener extends ResponseListener<Long> { }
}
| src/com/connectsdk/service/capability/MediaControl.java | /*
* MediaControl
* Connect SDK
*
* Copyright (c) 2014 LG Electronics.
* Created by Hyun Kook Khang on 19 Jan 2014
*
* 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.connectsdk.service.capability;
import com.connectsdk.service.capability.listeners.ResponseListener;
import com.connectsdk.service.command.ServiceSubscription;
import com.google.android.gms.cast.MediaStatus;
public interface MediaControl extends CapabilityMethods {
public final static String Any = "MediaControl.Any";
public final static String Play = "MediaControl.Play";
public final static String Pause = "MediaControl.Pause";
public final static String Stop = "MediaControl.Stop";
public final static String Rewind = "MediaControl.Rewind";
public final static String FastForward = "MediaControl.FastForward";
public final static String Seek = "MediaControl.Seek";
public final static String Previous = "MediaControl.Previous";
public final static String Next = "MediaControl.Next";
public final static String Duration = "MediaControl.Duration";
public final static String PlayState = "MediaControl.PlayState";
public final static String PlayState_Subscribe = "MediaControl.PlayState.Subscribe";
public final static String Position = "MediaControl.Position";
public final static String[] Capabilities = {
Play,
Pause,
Stop,
Rewind,
FastForward,
Seek,
Previous,
Next,
Duration,
PlayState,
PlayState_Subscribe,
Position,
};
public enum PlayStateStatus {
Unknown,
Idle,
Playing,
Paused,
Buffering,
Finished;
public static PlayStateStatus convertPlayerStateToPlayStateStatus(int playerState) {
PlayStateStatus status = PlayStateStatus.Unknown;
switch (playerState) {
case MediaStatus.PLAYER_STATE_BUFFERING:
status = PlayStateStatus.Buffering;
break;
case MediaStatus.PLAYER_STATE_IDLE:
status = PlayStateStatus.Finished;
break;
case MediaStatus.PLAYER_STATE_PAUSED:
status = PlayStateStatus.Paused;
break;
case MediaStatus.PLAYER_STATE_PLAYING:
status = PlayStateStatus.Playing;
break;
case MediaStatus.PLAYER_STATE_UNKNOWN:
default:
status = PlayStateStatus.Unknown;
break;
}
return status;
}
public static PlayStateStatus convertTransportStateToPlayStateStatus(String transportState) {
PlayStateStatus status = PlayStateStatus.Unknown;
if (transportState.equals("STOPPED")) {
status = PlayStateStatus.Finished;
}
else if (transportState.equals("PLAYING")) {
status = PlayStateStatus.Playing;
}
else if (transportState.equals("TRANSITIONING")) {
status = PlayStateStatus.Buffering;
}
else if (transportState.equals("PAUSED_PLAYBACK")) {
status = PlayStateStatus.Paused;
}
else if (transportState.equals("PAUSED_RECORDING")) {
}
else if (transportState.equals("RECORDING")) {
}
else if (transportState.equals("NO_MEDIA_PRESENT")) {
}
return status;
}
};
public MediaControl getMediaControl();
public CapabilityPriorityLevel getMediaControlCapabilityLevel();
public void play(ResponseListener<Object> listener);
public void pause(ResponseListener<Object> listener);
public void stop(ResponseListener<Object> listener);
public void rewind(ResponseListener<Object> listener);
public void fastForward(ResponseListener<Object> listener);
public void previous(ResponseListener<Object> listener);
public void next(ResponseListener<Object> listener);
public void seek(long position, ResponseListener<Object> listener);
public void getDuration(DurationListener listener);
public void getPosition(PositionListener listener);
public void getPlayState(PlayStateListener listener);
public ServiceSubscription<PlayStateListener> subscribePlayState(PlayStateListener listener);
/**
* Success block that is called upon any change in a media file's play state.
*
* Passes a PlayStateStatus enum of the current media file
*/
public static interface PlayStateListener extends ResponseListener<PlayStateStatus> { }
/**
* Success block that is called upon successfully getting the media file's current playhead position.
*
* Passes the position of the current playhead position of the current media file, in seconds
*/
public static interface PositionListener extends ResponseListener<Long> { }
/**
* Success block that is called upon successfully getting the media file's duration.
*
* Passes the duration of the current media file, in seconds
*/
public static interface DurationListener extends ResponseListener<Long> { }
}
| Removed reference to Google Cast SDK
| src/com/connectsdk/service/capability/MediaControl.java | Removed reference to Google Cast SDK | <ide><path>rc/com/connectsdk/service/capability/MediaControl.java
<ide>
<ide> import com.connectsdk.service.capability.listeners.ResponseListener;
<ide> import com.connectsdk.service.command.ServiceSubscription;
<del>import com.google.android.gms.cast.MediaStatus;
<ide>
<ide> public interface MediaControl extends CapabilityMethods {
<ide> public final static String Any = "MediaControl.Any";
<ide> public final static String PlayState = "MediaControl.PlayState";
<ide> public final static String PlayState_Subscribe = "MediaControl.PlayState.Subscribe";
<ide> public final static String Position = "MediaControl.Position";
<add>
<add> public static final int PLAYER_STATE_UNKNOWN = 0;
<add> public static final int PLAYER_STATE_IDLE = 1;
<add> public static final int PLAYER_STATE_PLAYING = 2;
<add> public static final int PLAYER_STATE_PAUSED = 3;
<add> public static final int PLAYER_STATE_BUFFERING = 4;
<add>
<ide>
<ide> public final static String[] Capabilities = {
<ide> Play,
<ide> PlayStateStatus status = PlayStateStatus.Unknown;
<ide>
<ide> switch (playerState) {
<del> case MediaStatus.PLAYER_STATE_BUFFERING:
<add> case PLAYER_STATE_BUFFERING:
<ide> status = PlayStateStatus.Buffering;
<ide> break;
<del> case MediaStatus.PLAYER_STATE_IDLE:
<add> case PLAYER_STATE_IDLE:
<ide> status = PlayStateStatus.Finished;
<ide> break;
<del> case MediaStatus.PLAYER_STATE_PAUSED:
<add> case PLAYER_STATE_PAUSED:
<ide> status = PlayStateStatus.Paused;
<ide> break;
<del> case MediaStatus.PLAYER_STATE_PLAYING:
<add> case PLAYER_STATE_PLAYING:
<ide> status = PlayStateStatus.Playing;
<ide> break;
<del> case MediaStatus.PLAYER_STATE_UNKNOWN:
<add> case PLAYER_STATE_UNKNOWN:
<ide> default:
<ide> status = PlayStateStatus.Unknown;
<ide> break; |
|
Java | apache-2.0 | 4892d049f95f9c19b8068a37422ed87706472ef4 | 0 | bogovicj/jitk-tps,bogovicj/jitk-tps,saalfeldlab/jitk-tps | package jitk.spline;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;
import org.junit.Test;
public class ThinPlateR2LogRSplineKernelTransformTest
{
public static double tol = 0.0001;
public static Random rand = new Random( 31415926536l );
double[][] srcPts;
double[][] tgtPts;
float[][] srcPtsF;
float[][] tgtPtsF;
int ndims;
int N;
public Logger logger = LogManager
.getLogger( ThinPlateR2LogRSplineKernelTransformTest.class.getName() );
public void genPtListSimple2d()
{
ndims = 2;
srcPts = new double[][]{
{ -1.0, 0.0, 1.0, 0.0 }, // x
{ 0.0, -1.0, 0.0, 1.0 } }; // y
tgtPts = new double[][]{
{ -2.0, 0.0, 2.0, 0.0 }, // x
{ 0.0, -2.0, 0.0, 2.0 } }; // y
}
public void genPtListNoAffine1()
{
genPtListNoAffine1( 50, 10 );
}
public void genPtListNoAffine1( int N, int D )
{
ndims = 3;
srcPts = new double[ 3 ][ 2 * N ];
tgtPts = new double[ 3 ][ 2 * N ];
int k = 0;
for ( int i = 0; i < N; i++ )
{
final double[] off = new double[]
{ rand.nextDouble(), rand.nextDouble(), rand.nextDouble() };
srcPts[ 0 ][ k ] = D * rand.nextDouble();
srcPts[ 1 ][ k ] = D * rand.nextDouble();
srcPts[ 2 ][ k ] = D * rand.nextDouble();
tgtPts[ 0 ][ k ] = srcPts[ 0 ][ k ] + off[ 0 ];
tgtPts[ 1 ][ k ] = srcPts[ 1 ][ k ] + off[ 1 ];
tgtPts[ 2 ][ k ] = srcPts[ 2 ][ k ] + off[ 2 ];
k++;
srcPts[ 0 ][ k ] = -srcPts[ 0 ][ k - 1 ];
srcPts[ 1 ][ k ] = -srcPts[ 1 ][ k - 1 ];
srcPts[ 2 ][ k ] = -srcPts[ 2 ][ k - 1 ];
tgtPts[ 0 ][ k ] = srcPts[ 0 ][ k ] - off[ 0 ];
tgtPts[ 1 ][ k ] = srcPts[ 1 ][ k ] - off[ 1 ];
tgtPts[ 2 ][ k ] = srcPts[ 2 ][ k ] - off[ 2 ];
k++;
}
}
@Test
public void testTPSInverseConvenience()
{
final double[] target = new double[]{ 0.5, 0.5 };
final double tolerance = 0.01;
final int maxIters = 9999;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, true );
double[] invResult = new double[ 2 ];
double finalError = tps.inverse( target, invResult, tolerance, maxIters );
double[] invResultXfm = tps.apply( invResult );
logger.debug( "final error : " + finalError );
logger.debug( "final guess : " + XfmUtils.printArray( invResult ) );
logger.debug( "final guessXfm: " + XfmUtils.printArray( invResultXfm ) );
assertTrue( "tolerance met", ( finalError < tolerance ));
}
@Test
public void testTPSInverse2()
{
double[] target = new double[]{ 0.5, 0.5 };
// double[] guessBase = new double[] { 5.0, 5.0 };
// double[] guess = new double[ 2 ];
double[] guess = new double[]{ 5.0, 5.0 };
double[][] mtx;
double error = 9999;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
double finalError= tps.inverseTol( target, guess, 0.5, 1000 );
double[] guessXfm = tps.apply( guess );
logger.debug( "final error : " + finalError );
logger.debug( "final guess : " + XfmUtils.printArray( guess ) );
logger.debug( "final guessXfm: " + XfmUtils.printArray( guessXfm ) );
assertEquals( "within tolerance 0.5 x", 0.5, guessXfm[ 0 ], 0.5 );
assertEquals( "within tolerance 0.5 y", 0.5, guessXfm[ 1 ], 0.5 );
tps.inverseTol( target, guess, 0.25, 2000 );
logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
assertEquals( "within tolerance 0.25 x", 0.5, guess[ 0 ], 0.25 );
assertEquals( "within tolerance 0.25 y", 0.5, guess[ 1 ], 0.25 );
// try for a few different initial guesses
double[] guessBase = new double[] { 0.0, 0.0 };
for (double xm = -2.5; xm <= 2.5; xm += 0.5)
for (double ym = -2.5; ym <= 2.5; ym += 0.5)
{
System.arraycopy(guessBase, 0, guess, 0, ndims);
guess[0] *= xm;
guess[1] *= ym;
tps.inverseTol(target, guess, 0.5, 2000);
logger.debug("final guess: " + XfmUtils.printArray(guess));
assertEquals("within tolerance 0.5 x", 0.5, guess[0], 0.5);
assertEquals("within tolerance 0.5 y", 0.5, guess[1], 0.5);
tps.inverseTol(target, guess, 0.25, 2000);
logger.debug("final guess: " + XfmUtils.printArray(guess));
assertEquals("within tolerance 0.25 x", 0.5, guess[0], 0.25);
assertEquals("within tolerance 0.25 y", 0.5, guess[1], 0.25);
}
}
@Test
public void testStepSize()
{
double[] target = new double[]{ 0.5, 0.5 };
double[] guessBase = new double[]{ 2.0, 2.0 };
double[] guess = new double[ 2 ];
double[] guessXfm = new double[ 2 ];
double[][] mtx;
double error = 9999;
double tolerance = 0.5;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
int xm = 1;
int ym = 1;
System.arraycopy( guessBase, 0, guess, 0, ndims );
guess[ 0 ] *= xm;
guess[ 1 ] *= ym;
tps.apply( guess, guessXfm );
mtx = tps.jacobian( guess );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( guessXfm );
inv.setJacobian( mtx );
inv.setEps( 0.001 * tolerance );
double c = 0.5;
double beta = 0.75;
int k = 0;
mtx = tps.jacobian( guess );
inv.setJacobian( mtx );
// inv.oneIteration( false );
inv.computeDirection();
// is the Armijo condition satisfied
boolean isArmijo = inv.armijoCondition( c, 1.0 );
System.out.println( "isArmijo: " + isArmijo );
}
@Test
public void testTPSInverse()
{
double[] target = new double[]{ 0.0, 0.0 };
double[] guessBase = new double[]{ 5.0, 5.0 };
double[] guess = new double[ 2 ];
double[][] mtx;
double error = 9999;
int maxIters = 2000;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
// try for a few different initial guesses
int xm = 1;
int ym = 1;
System.arraycopy( guessBase, 0, guess, 0, ndims );
guess[ 0 ] *= xm;
guess[ 1 ] *= ym;
double tolerance = 0.5;
double[] guessXfm = new double[ ndims ];
tps.apply( guess, guessXfm );
mtx = tps.jacobian( guess );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( guessXfm );
inv.setJacobian( mtx );
inv.setEps( 0.001 * tolerance );
double c = 0.5;
double beta = 0.75;
int k = 0;
while ( error >= tolerance && k < maxIters )
{
mtx = tps.jacobian( guess );
inv.setJacobian( mtx );
inv.oneIteration( false );
inv.computeDirection();
double t = inv.backtrackingLineSearch( c, beta, 100, 1.0 );
inv.updateEstimate( t );
inv.updateError();
TransformInverseGradientDescent
.copyVectorIntoArray( inv.getEstimate(), guess );
tps.apply( guess, guessXfm );
inv.setEstimateXfm( guessXfm );
error = inv.getError();
// System.out.println( "error: " + error );
k++;
}
System.out.println( "error: " + error );
}
@Test
public void testGradientDescentLinear()
{
double[] target = new double[]{ 10.0, 10.0 };
double[] guess = new double[]{ 1.0, 1.0 };
double[][] mtx = new double[][]{
{ -1.0, 0.0 },
{ 0.0, -1.0 } };
double error = 999;
// error = testGradientDescent( mtx, target, guess );
// assertTrue( "is error small", ( error < 1 ) );
mtx = new double[][]{
{ -2.0, 0.0 },
{ 0.0, -2.0 }};
error = testGradientDescent( mtx, target, guess );
// assertTrue( "is error small 2", ( error < 1 ) );
}
private double testGradientDescent( double[][] mtx, double[] target, double[] guess )
{
int ndims = target.length;
DenseMatrix64F mat = new DenseMatrix64F( mtx );
DenseMatrix64F guessVec = new DenseMatrix64F( ndims, 1 );
guessVec.setData( guess );
DenseMatrix64F xfmVec = new DenseMatrix64F( ndims, 1 );
CommonOps.mult( mat, guessVec, xfmVec );
logger.info( "xfmVec:\n" + xfmVec );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setJacobian( mtx );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( xfmVec.data );
inv.setStepSize( 1.0 );
double error = inv.getError();
int k = 0;
while ( error > 1 && k < 100 )
{
inv.computeDirection();
inv.updateEstimate( 1.0 );
CommonOps.mult( mat, guessVec, xfmVec );
inv.setEstimateXfm( xfmVec.data );
CommonOps.mult( mat, inv.getEstimate(), xfmVec );
inv.setEstimateXfm( xfmVec.data );
error = inv.getError();
double sqerr = inv.squaredError( xfmVec.data );
System.out.println( "estimate ( " + k + " ) : "
+ XfmUtils.printArray( inv.getEstimate().data ) );
System.out.println( "estimate xfm ( " + k + " ) : "
+ XfmUtils.printArray( xfmVec.data ) );
System.out.println( "error ( " + k + " ) : " + sqerr );
k++;
}
return error;
}
@Test
public void testAffineOnly()
{
ndims = 3;
srcPts = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final double[][] aff = new double[][]
{
{ 0, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 0 }
};
N = srcPts[ 0 ].length;
tgtPts = XfmUtils.genPtListAffine( srcPts, aff );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < N; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = srcPts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "pure affine transformation", tgtPts[ i ][ n ], outPt[ i ],
tol );
}
}
}
@Test
public void testIdentitySmall2d()
{
final int ndims = 2;
final double[][] pts = new double[][]
{
{ -1, 0, 0 }, // x
{ -1, 0, 1 } // y
};
final int nL = pts[ 0 ].length;
final double[][] tpts = XfmUtils.genPtListScale( pts, new double[]{ 1, 1 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, tpts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
System.out.println( outPt.length );
System.out.println( tpts.length + " x " + tpts[ 0 ].length );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tpts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testIdentitySmall3d()
{
final int ndims = 3;
final double[][] pts = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1 } // z
};
final int nL = pts[ 0 ].length;
final double[][] tpts = XfmUtils.genPtListScale( pts, new double[]
{ 2, 3, 0.5 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, tpts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tpts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testIdentity()
{
final int ndims = 3;
final double[][] pts = new double[][]
{
{ -1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ -1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final int nL = pts[ 0 ].length;
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, pts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", pts[ i ][ n ], outPt[ i ], tol );
}
}
final ThinPlateR2LogRSplineKernelTransform tpsNA = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, pts, false );
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tpsNA.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", pts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testScale3d()
{
final int ndims = 3;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final double[][] tgtPtList = XfmUtils.genPtListScale( src_simple, new double[]{ 2, 0.5, 4 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgtPtList );
double[] srcPt = new double[]{ 0.0f, 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "scale x1", 0, ptXfm[ 0 ], tol );
assertEquals( "scale y1", 0, ptXfm[ 1 ], tol );
assertEquals( "scale z1", 0, ptXfm[ 2 ], tol );
srcPt = new double[]{ 0.5f, 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x2", 1.00, ptXfm[ 0 ], tol );
assertEquals( "scale y2", 0.25, ptXfm[ 1 ], tol );
assertEquals( "scale z2", 2.00, ptXfm[ 2 ], tol );
srcPt = new double[]{ 1.0f, 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x3", 2.0, ptXfm[ 0 ], tol );
assertEquals( "scale y3", 0.5, ptXfm[ 1 ], tol );
assertEquals( "scale z3", 4.0, ptXfm[ 2 ], tol );
}
@Test
public void testAffineReasonable()
{
genPtListNoAffine1();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts );
// tps.setDoAffine(false);
final double[][] a = tps.getAffine();
final double[] t = tps.getTranslation();
System.out.println( "a: " + XfmUtils.printArray( a ) + "\n" );
System.out.println( "t: " + XfmUtils.printArray( t ) );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < 2 * N; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = srcPts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tgtPts[ i ][ n ], outPt[ i ],
tol );
}
}
}
@Test
public void testAffineSanity()
{
final int ndims = 2;
final double[][] src = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
final double[][] tgt = new double[ src.length ][ src[ 0 ].length ];
for ( int i = 0; i < src.length; i++ )
for ( int j = 0; j < src[ 0 ].length; j++ )
{
tgt[ i ][ j ] = src[ i ][ j ] + Math.random() * 0.1;
}
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src, tgt, false );
// System.out.println(" aMatrix: (Expect all zeros)\n" +
// printArray(tps.aMatrix) + "\n");
assertTrue( "aMatrix should be null", tps.aMatrix == null );
// System.out.println(" bVector: (Expect all zeros)\n" +
// printArray(tps.bVector) + "\n");
assertTrue( "bVector should be null", tps.bVector == null );
// System.out.println(" dMatrix: (Expect non-zero)\n" + tps.dMatrix +
// "\n");
boolean isNonZeroMtxElem = false;
for ( int i = 0; i < tps.dMatrix.getNumElements(); i++ )
{
isNonZeroMtxElem = isNonZeroMtxElem || (tps.dMatrix.get( i ) != 0);
}
assertTrue( " dMatrix has non-zero element", isNonZeroMtxElem );
}
// @Test
// public void testTransXfmAffineTps(){
//
// // int ndims = 2;
// // float[][] src_simple = new float[][]
// // {
// // {-1,-1,-1,1,1,1,2,2,2}, // x
// // {-1,1,2,-1,1,2,0,1,2}, // y
// // };
// //
// // // target points
// // float[][] tgt= new float[][]
// // {
// // { -0.5f, -0.5f, -0.5f, 1.5f, 1.5f, 1.5f, 2.0f, 2.0f, 2.0f}, // x
// // { -0.5f, 1.5f, 2.0f, -0.5f, 1.5f, 2.0f, -0.5f, 1.5f, 2.0f } // y
// // };
//
// int ndims = 2;
// srcPtsF = new float[][]
// {
// {-1,-1,-1,1,1,1,2,2,2}, // x
// {-1,1,2,-1,1,2,-1,1,2}, // y
// };
//
// // target points
// tgtPtsF= new float[][]
// {
// { 0,0,0, 2,2,2, 3,3,3}, // x
// { 1,3,4, 1,3,4, 1,3,5 } // y
// };
//
// ThinPlateR2LogRSplineKernelTransformFloatSep tps
// = new ThinPlateR2LogRSplineKernelTransformFloatSep( ndims, srcPtsF,
// tgtPtsF);
//
// tps.fit();
//
// N = srcPtsF[0].length;
// float[] testPt = new float[ndims];
// for( int n=0; n<N; n++) {
//
// for( int d=0; d<ndims; d++) {
// testPt[d] = srcPtsF[d][n];
// }
//
// float[] outPt = tps.transform(testPt);
// logger.debug("point: " + XfmUtils.printArray(testPt) + " -> " +
// XfmUtils.printArray(outPt));
// for( int d=0; d<ndims; d++) {
// assertEquals("translation, use affine", tgtPtsF[d][n], outPt[d], tol);
// }
// }
//
// }
@Test
public void testScale()
{
final int ndims = 2;
srcPts = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
tgtPts = XfmUtils.genPtListScale( srcPts, new double[]
{ 2, 0.5 } );
logger.debug( "srcPts:\n" + XfmUtils.printArray( srcPts ) );
logger.debug( "\ntgtPts:\n" + XfmUtils.printArray( tgtPts ) );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts );
double[] srcPt = new double[]
{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "scale x1", 0, ptXfm[ 0 ], tol );
assertEquals( "scale y1", 0, ptXfm[ 1 ], tol );
srcPt = new double[]
{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x2", 1.00, ptXfm[ 0 ], tol );
assertEquals( "scale y2", 0.25, ptXfm[ 1 ], tol );
srcPt = new double[]
{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x3", 2.0, ptXfm[ 0 ], tol );
assertEquals( "scale y3", 0.5, ptXfm[ 1 ], tol );
N = srcPts[ 0 ].length;
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < N; n++ )
{
for ( int d = 0; d < ndims; d++ )
{
testPt[ d ] = srcPts[ d ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int d = 0; d < ndims; d++ )
{
assertEquals( "Identity transformation", tgtPts[ d ][ n ], outPt[ d ],
tol );
}
}
}
@Test
public void testWarp()
{
final int ndims = 2;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
// target points
final double[][] tgt = new double[][]
{
{ -0.5, -0.5, -0.5, 1.5, 1.5, 1.5, 2.0, 2.0, 2.0 }, // x
{ -0.5, 1.5, 2.0, -0.5, 1.5, 2.0, -0.5, 1.5, 2.0 } // y
};
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgt );
// tps.printLandmarks();
/* **** PT 2 **** */
double[] srcPt = new double[]{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "warp x1", -0.5, ptXfm[ 0 ], tol );
assertEquals( "warp y1", -0.5, ptXfm[ 1 ], tol );
// check double
final double[] srcPtF = srcPt.clone();
final double[] ptXfmF = tps.apply( srcPtF );
assertEquals( "warp x1 float", -0.5f, ptXfmF[ 0 ], tol );
assertEquals( "warp y1 float", -0.5f, ptXfmF[ 1 ], tol );
// double in place
tps.applyInPlace( srcPt );
assertEquals( "warp x1 in place", -0.5, srcPt[ 0 ], tol );
assertEquals( "warp y1 in place", -0.5, srcPt[ 1 ], tol );
/* **** PT 2 **** */
srcPt = new double[]{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
// the values below are what matlab returns for
// tpaps( p, q, 1 );
// where p and q are the source and target points, respectively
assertEquals( "warp x2", 0.6241617, ptXfm[ 0 ], tol );
assertEquals( "warp y2", 0.6241617, ptXfm[ 1 ], tol );
// double in place 2
tps.applyInPlace( srcPt );
assertEquals( "warp x2 in place", 0.6241617, srcPt[ 0 ], tol );
assertEquals( "warp y2 in place", 0.6241617, srcPt[ 1 ], tol );
/* **** PT 3 **** */
srcPt = new double[]{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "warp x3", 1.5, ptXfm[ 0 ], tol );
assertEquals( "warp y3", 1.5, ptXfm[ 1 ], tol );
tps.applyInPlace( srcPt );
assertEquals( "warp x3 in place", 1.5, srcPt[ 0 ], tol );
assertEquals( "warp y3 in place", 1.5, srcPt[ 1 ], tol );
}
@Test
public void testWeights()
{
final int ndims = 2;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
// target points
final double[][] tgt = new double[][]
{
{ -0.5, -0.5, -0.5, 1.5, 1.5, 1.5, 2.0, 2.0, 2.0 }, // x
{ -0.5, 1.5, 2.0, -0.5, 1.5, 2.0, -0.5, 1.5, 2.0 } // y
};
// double[] weights = new double[]
// { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
final double[] weights = new double[]
{ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 1.0 };
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgt, weights );
// tps.printLandmarks();
double[] srcPt = new double[]{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "warp x1", -0.5, ptXfm[ 0 ], tol );
assertEquals( "warp y1", -0.5, ptXfm[ 1 ], tol );
srcPt = new double[]{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
// the values below are what matlab returns for
// tpaps( p, q, 1 );
// where p and q are the source and target points, respectively
assertEquals( "warp x2", 0.6241617, ptXfm[ 0 ], tol );
assertEquals( "warp y2", 0.6241617, ptXfm[ 1 ], tol );
srcPt = new double[]{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "warp x3", 1.5, ptXfm[ 0 ], tol );
assertEquals( "warp y3", 1.5, ptXfm[ 1 ], tol );
}
}
| src/test/java/jitk/spline/ThinPlateR2LogRSplineKernelTransformTest.java | package jitk.spline;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.ejml.data.DenseMatrix64F;
import org.ejml.ops.CommonOps;
import org.junit.Test;
public class ThinPlateR2LogRSplineKernelTransformTest
{
public static double tol = 0.0001;
public static Random rand = new Random( 31415926536l );
double[][] srcPts;
double[][] tgtPts;
float[][] srcPtsF;
float[][] tgtPtsF;
int ndims;
int N;
public Logger logger = LogManager
.getLogger( ThinPlateR2LogRSplineKernelTransformTest.class.getName() );
public void genPtListSimple2d()
{
ndims = 2;
srcPts = new double[][]{
{ -1.0, 0.0, 1.0, 0.0 }, // x
{ 0.0, -1.0, 0.0, 1.0 } }; // y
tgtPts = new double[][]{
{ -2.0, 0.0, 2.0, 0.0 }, // x
{ 0.0, -2.0, 0.0, 2.0 } }; // y
}
public void genPtListNoAffine1()
{
genPtListNoAffine1( 50, 10 );
}
public void genPtListNoAffine1( int N, int D )
{
ndims = 3;
srcPts = new double[ 3 ][ 2 * N ];
tgtPts = new double[ 3 ][ 2 * N ];
int k = 0;
for ( int i = 0; i < N; i++ )
{
final double[] off = new double[]
{ rand.nextDouble(), rand.nextDouble(), rand.nextDouble() };
srcPts[ 0 ][ k ] = D * rand.nextDouble();
srcPts[ 1 ][ k ] = D * rand.nextDouble();
srcPts[ 2 ][ k ] = D * rand.nextDouble();
tgtPts[ 0 ][ k ] = srcPts[ 0 ][ k ] + off[ 0 ];
tgtPts[ 1 ][ k ] = srcPts[ 1 ][ k ] + off[ 1 ];
tgtPts[ 2 ][ k ] = srcPts[ 2 ][ k ] + off[ 2 ];
k++;
srcPts[ 0 ][ k ] = -srcPts[ 0 ][ k - 1 ];
srcPts[ 1 ][ k ] = -srcPts[ 1 ][ k - 1 ];
srcPts[ 2 ][ k ] = -srcPts[ 2 ][ k - 1 ];
tgtPts[ 0 ][ k ] = srcPts[ 0 ][ k ] - off[ 0 ];
tgtPts[ 1 ][ k ] = srcPts[ 1 ][ k ] - off[ 1 ];
tgtPts[ 2 ][ k ] = srcPts[ 2 ][ k ] - off[ 2 ];
k++;
}
}
@Test
public void testTPSInverseConvenience()
{
final double[] target = new double[]{ 0.5, 0.5 };
final double tolerance = 0.01;
final int maxIters = 9999;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, true );
double[] invResult = new double[ 2 ];
double finalError = tps.inverse( target, invResult, tolerance, maxIters );
double[] invResultXfm = tps.apply( invResult );
logger.debug( "final error : " + finalError );
logger.debug( "final guess : " + XfmUtils.printArray( invResult ) );
logger.debug( "final guessXfm: " + XfmUtils.printArray( invResultXfm ) );
assertTrue( "tolerance met", ( finalError < tolerance ));
}
@Test
public void testTPSInverse2()
{
double[] target = new double[]{ 0.5, 0.5 };
// double[] guessBase = new double[] { 5.0, 5.0 };
// double[] guess = new double[ 2 ];
double[] guess = new double[]{ 5.0, 5.0 };
double[][] mtx;
double error = 9999;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
double finalError= tps.inverseTol( target, guess, 0.5, 2000 );
double[] guessXfm = tps.apply( guess );
logger.debug( "final error : " + finalError );
logger.debug( "final guess : " + XfmUtils.printArray( guess ) );
logger.debug( "final guessXfm: " + XfmUtils.printArray( guessXfm ) );
assertEquals( "within tolerance 0.5 x", 0.5, guessXfm[ 0 ], 0.5 );
assertEquals( "within tolerance 0.5 y", 0.5, guessXfm[ 1 ], 0.5 );
// tps.inverseTol( target, guess, 0.1, 200 );
// logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
//
// assertEquals( "within tolerance 0.1 x", 0.5, guess[ 0 ], 0.1 );
// assertEquals( "within tolerance 0.1 y", 0.5, guess[ 1 ], 0.1 );
//
// // try for a few different initial guesses
// for ( int xm = -1; xm <= 1; xm++ )
// for ( int ym = -1; ym <= 1; ym++ )
// {
// System.arraycopy( guessBase, 0, guess, 0, ndims );
// guess[ 0 ] *= xm;
// guess[ 1 ] *= ym;
//
// tps.inverseTol( target, guess, 0.5, 200 );
// logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
//
// assertEquals( "within tolerance 0.5 x", 0.5, guess[ 0 ], 0.5 );
// assertEquals( "within tolerance 0.5 y", 0.5, guess[ 1 ], 0.5 );
//
// tps.inverseTol( target, guess, 0.1, 2000 );
// logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
//
// assertEquals( "within tolerance 0.1 x", 0.5, guess[ 0 ], 0.1 );
// assertEquals( "within tolerance 0.1 y", 0.5, guess[ 1 ], 0.1 );
// }
}
@Test
public void testStepSize()
{
double[] target = new double[]{ 0.5, 0.5 };
double[] guessBase = new double[]{ 2.0, 2.0 };
double[] guess = new double[ 2 ];
double[] guessXfm = new double[ 2 ];
double[][] mtx;
double error = 9999;
double tolerance = 0.5;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
int xm = 1;
int ym = 1;
System.arraycopy( guessBase, 0, guess, 0, ndims );
guess[ 0 ] *= xm;
guess[ 1 ] *= ym;
tps.apply( guess, guessXfm );
mtx = tps.jacobian( guess );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( guessXfm );
inv.setJacobian( mtx );
inv.setEps( 0.001 * tolerance );
double c = 0.5;
double beta = 0.75;
int k = 0;
mtx = tps.jacobian( guess );
inv.setJacobian( mtx );
// inv.oneIteration( false );
inv.computeDirection();
// is the Armijo condition satisfied
boolean isArmijo = inv.armijoCondition( c, 1.0 );
System.out.println( "isArmijo: " + isArmijo );
}
@Test
public void testTPSInverse()
{
double[] target = new double[]{ 0.0, 0.0 };
double[] guessBase = new double[]{ 5.0, 5.0 };
double[] guess = new double[ 2 ];
double[][] mtx;
double error = 9999;
int maxIters = 2000;
genPtListSimple2d();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
// try for a few different initial guesses
int xm = 1;
int ym = 1;
System.arraycopy( guessBase, 0, guess, 0, ndims );
guess[ 0 ] *= xm;
guess[ 1 ] *= ym;
double tolerance = 0.5;
double[] guessXfm = new double[ ndims ];
tps.apply( guess, guessXfm );
mtx = tps.jacobian( guess );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( guessXfm );
inv.setJacobian( mtx );
inv.setEps( 0.001 * tolerance );
double c = 0.5;
double beta = 0.75;
int k = 0;
while ( error >= tolerance && k < maxIters )
{
mtx = tps.jacobian( guess );
inv.setJacobian( mtx );
inv.oneIteration( false );
inv.computeDirection();
double t = inv.backtrackingLineSearch( c, beta, 100, 1.0 );
inv.updateEstimate( t );
inv.updateError();
TransformInverseGradientDescent
.copyVectorIntoArray( inv.getEstimate(), guess );
tps.apply( guess, guessXfm );
inv.setEstimateXfm( guessXfm );
error = inv.getError();
// System.out.println( "error: " + error );
k++;
}
System.out.println( "error: " + error );
}
@Test
public void testGradientDescentLinear()
{
double[] target = new double[]{ 10.0, 10.0 };
double[] guess = new double[]{ 1.0, 1.0 };
double[][] mtx = new double[][]{
{ -1.0, 0.0 },
{ 0.0, -1.0 } };
double error = 999;
// error = testGradientDescent( mtx, target, guess );
// assertTrue( "is error small", ( error < 1 ) );
mtx = new double[][]{
{ -2.0, 0.0 },
{ 0.0, -2.0 }};
error = testGradientDescent( mtx, target, guess );
// assertTrue( "is error small 2", ( error < 1 ) );
}
private double testGradientDescent( double[][] mtx, double[] target, double[] guess )
{
int ndims = target.length;
DenseMatrix64F mat = new DenseMatrix64F( mtx );
DenseMatrix64F guessVec = new DenseMatrix64F( ndims, 1 );
guessVec.setData( guess );
DenseMatrix64F xfmVec = new DenseMatrix64F( ndims, 1 );
CommonOps.mult( mat, guessVec, xfmVec );
logger.info( "xfmVec:\n" + xfmVec );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims );
TransformInverseGradientDescent inv = new TransformInverseGradientDescent( ndims,
tps );
inv.setJacobian( mtx );
inv.setTarget( target );
inv.setEstimate( guess );
inv.setEstimateXfm( xfmVec.data );
inv.setStepSize( 1.0 );
double error = inv.getError();
int k = 0;
while ( error > 1 && k < 100 )
{
inv.computeDirection();
inv.updateEstimate( 1.0 );
CommonOps.mult( mat, guessVec, xfmVec );
inv.setEstimateXfm( xfmVec.data );
CommonOps.mult( mat, inv.getEstimate(), xfmVec );
inv.setEstimateXfm( xfmVec.data );
error = inv.getError();
double sqerr = inv.squaredError( xfmVec.data );
System.out.println( "estimate ( " + k + " ) : "
+ XfmUtils.printArray( inv.getEstimate().data ) );
System.out.println( "estimate xfm ( " + k + " ) : "
+ XfmUtils.printArray( xfmVec.data ) );
System.out.println( "error ( " + k + " ) : " + sqerr );
k++;
}
return error;
}
@Test
public void testAffineOnly()
{
ndims = 3;
srcPts = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final double[][] aff = new double[][]
{
{ 0, 1, 0 },
{ 0, 0, 1 },
{ 1, 0, 0 }
};
N = srcPts[ 0 ].length;
tgtPts = XfmUtils.genPtListAffine( srcPts, aff );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts, false );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < N; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = srcPts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "pure affine transformation", tgtPts[ i ][ n ], outPt[ i ],
tol );
}
}
}
@Test
public void testIdentitySmall2d()
{
final int ndims = 2;
final double[][] pts = new double[][]
{
{ -1, 0, 0 }, // x
{ -1, 0, 1 } // y
};
final int nL = pts[ 0 ].length;
final double[][] tpts = XfmUtils.genPtListScale( pts, new double[]{ 1, 1 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, tpts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
System.out.println( outPt.length );
System.out.println( tpts.length + " x " + tpts[ 0 ].length );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tpts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testIdentitySmall3d()
{
final int ndims = 3;
final double[][] pts = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1 } // z
};
final int nL = pts[ 0 ].length;
final double[][] tpts = XfmUtils.genPtListScale( pts, new double[]
{ 2, 3, 0.5 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, tpts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tpts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testIdentity()
{
final int ndims = 3;
final double[][] pts = new double[][]
{
{ -1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ -1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ -1, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final int nL = pts[ 0 ].length;
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, pts );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", pts[ i ][ n ], outPt[ i ], tol );
}
}
final ThinPlateR2LogRSplineKernelTransform tpsNA = new ThinPlateR2LogRSplineKernelTransform(
ndims, pts, pts, false );
for ( int n = 0; n < nL; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = pts[ i ][ n ];
}
final double[] outPt = tpsNA.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", pts[ i ][ n ], outPt[ i ], tol );
}
}
}
@Test
public void testScale3d()
{
final int ndims = 3;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2 }, // x
{ 0, 0, 0, 1, 1, 1, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // y
{ 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // z
};
final double[][] tgtPtList = XfmUtils.genPtListScale( src_simple, new double[]{ 2, 0.5, 4 } );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgtPtList );
double[] srcPt = new double[]{ 0.0f, 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "scale x1", 0, ptXfm[ 0 ], tol );
assertEquals( "scale y1", 0, ptXfm[ 1 ], tol );
assertEquals( "scale z1", 0, ptXfm[ 2 ], tol );
srcPt = new double[]{ 0.5f, 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x2", 1.00, ptXfm[ 0 ], tol );
assertEquals( "scale y2", 0.25, ptXfm[ 1 ], tol );
assertEquals( "scale z2", 2.00, ptXfm[ 2 ], tol );
srcPt = new double[]{ 1.0f, 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x3", 2.0, ptXfm[ 0 ], tol );
assertEquals( "scale y3", 0.5, ptXfm[ 1 ], tol );
assertEquals( "scale z3", 4.0, ptXfm[ 2 ], tol );
}
@Test
public void testAffineReasonable()
{
genPtListNoAffine1();
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts );
// tps.setDoAffine(false);
final double[][] a = tps.getAffine();
final double[] t = tps.getTranslation();
System.out.println( "a: " + XfmUtils.printArray( a ) + "\n" );
System.out.println( "t: " + XfmUtils.printArray( t ) );
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < 2 * N; n++ )
{
for ( int i = 0; i < ndims; i++ )
{
testPt[ i ] = srcPts[ i ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int i = 0; i < ndims; i++ )
{
assertEquals( "Identity transformation", tgtPts[ i ][ n ], outPt[ i ],
tol );
}
}
}
@Test
public void testAffineSanity()
{
final int ndims = 2;
final double[][] src = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
final double[][] tgt = new double[ src.length ][ src[ 0 ].length ];
for ( int i = 0; i < src.length; i++ )
for ( int j = 0; j < src[ 0 ].length; j++ )
{
tgt[ i ][ j ] = src[ i ][ j ] + Math.random() * 0.1;
}
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src, tgt, false );
// System.out.println(" aMatrix: (Expect all zeros)\n" +
// printArray(tps.aMatrix) + "\n");
assertTrue( "aMatrix should be null", tps.aMatrix == null );
// System.out.println(" bVector: (Expect all zeros)\n" +
// printArray(tps.bVector) + "\n");
assertTrue( "bVector should be null", tps.bVector == null );
// System.out.println(" dMatrix: (Expect non-zero)\n" + tps.dMatrix +
// "\n");
boolean isNonZeroMtxElem = false;
for ( int i = 0; i < tps.dMatrix.getNumElements(); i++ )
{
isNonZeroMtxElem = isNonZeroMtxElem || (tps.dMatrix.get( i ) != 0);
}
assertTrue( " dMatrix has non-zero element", isNonZeroMtxElem );
}
// @Test
// public void testTransXfmAffineTps(){
//
// // int ndims = 2;
// // float[][] src_simple = new float[][]
// // {
// // {-1,-1,-1,1,1,1,2,2,2}, // x
// // {-1,1,2,-1,1,2,0,1,2}, // y
// // };
// //
// // // target points
// // float[][] tgt= new float[][]
// // {
// // { -0.5f, -0.5f, -0.5f, 1.5f, 1.5f, 1.5f, 2.0f, 2.0f, 2.0f}, // x
// // { -0.5f, 1.5f, 2.0f, -0.5f, 1.5f, 2.0f, -0.5f, 1.5f, 2.0f } // y
// // };
//
// int ndims = 2;
// srcPtsF = new float[][]
// {
// {-1,-1,-1,1,1,1,2,2,2}, // x
// {-1,1,2,-1,1,2,-1,1,2}, // y
// };
//
// // target points
// tgtPtsF= new float[][]
// {
// { 0,0,0, 2,2,2, 3,3,3}, // x
// { 1,3,4, 1,3,4, 1,3,5 } // y
// };
//
// ThinPlateR2LogRSplineKernelTransformFloatSep tps
// = new ThinPlateR2LogRSplineKernelTransformFloatSep( ndims, srcPtsF,
// tgtPtsF);
//
// tps.fit();
//
// N = srcPtsF[0].length;
// float[] testPt = new float[ndims];
// for( int n=0; n<N; n++) {
//
// for( int d=0; d<ndims; d++) {
// testPt[d] = srcPtsF[d][n];
// }
//
// float[] outPt = tps.transform(testPt);
// logger.debug("point: " + XfmUtils.printArray(testPt) + " -> " +
// XfmUtils.printArray(outPt));
// for( int d=0; d<ndims; d++) {
// assertEquals("translation, use affine", tgtPtsF[d][n], outPt[d], tol);
// }
// }
//
// }
@Test
public void testScale()
{
final int ndims = 2;
srcPts = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
tgtPts = XfmUtils.genPtListScale( srcPts, new double[]
{ 2, 0.5 } );
logger.debug( "srcPts:\n" + XfmUtils.printArray( srcPts ) );
logger.debug( "\ntgtPts:\n" + XfmUtils.printArray( tgtPts ) );
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, srcPts, tgtPts );
double[] srcPt = new double[]
{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "scale x1", 0, ptXfm[ 0 ], tol );
assertEquals( "scale y1", 0, ptXfm[ 1 ], tol );
srcPt = new double[]
{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x2", 1.00, ptXfm[ 0 ], tol );
assertEquals( "scale y2", 0.25, ptXfm[ 1 ], tol );
srcPt = new double[]
{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "scale x3", 2.0, ptXfm[ 0 ], tol );
assertEquals( "scale y3", 0.5, ptXfm[ 1 ], tol );
N = srcPts[ 0 ].length;
final double[] testPt = new double[ ndims ];
for ( int n = 0; n < N; n++ )
{
for ( int d = 0; d < ndims; d++ )
{
testPt[ d ] = srcPts[ d ][ n ];
}
final double[] outPt = tps.apply( testPt );
for ( int d = 0; d < ndims; d++ )
{
assertEquals( "Identity transformation", tgtPts[ d ][ n ], outPt[ d ],
tol );
}
}
}
@Test
public void testWarp()
{
final int ndims = 2;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
// target points
final double[][] tgt = new double[][]
{
{ -0.5, -0.5, -0.5, 1.5, 1.5, 1.5, 2.0, 2.0, 2.0 }, // x
{ -0.5, 1.5, 2.0, -0.5, 1.5, 2.0, -0.5, 1.5, 2.0 } // y
};
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgt );
// tps.printLandmarks();
/* **** PT 2 **** */
double[] srcPt = new double[]{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "warp x1", -0.5, ptXfm[ 0 ], tol );
assertEquals( "warp y1", -0.5, ptXfm[ 1 ], tol );
// check double
final double[] srcPtF = srcPt.clone();
final double[] ptXfmF = tps.apply( srcPtF );
assertEquals( "warp x1 float", -0.5f, ptXfmF[ 0 ], tol );
assertEquals( "warp y1 float", -0.5f, ptXfmF[ 1 ], tol );
// double in place
tps.applyInPlace( srcPt );
assertEquals( "warp x1 in place", -0.5, srcPt[ 0 ], tol );
assertEquals( "warp y1 in place", -0.5, srcPt[ 1 ], tol );
/* **** PT 2 **** */
srcPt = new double[]{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
// the values below are what matlab returns for
// tpaps( p, q, 1 );
// where p and q are the source and target points, respectively
assertEquals( "warp x2", 0.6241617, ptXfm[ 0 ], tol );
assertEquals( "warp y2", 0.6241617, ptXfm[ 1 ], tol );
// double in place 2
tps.applyInPlace( srcPt );
assertEquals( "warp x2 in place", 0.6241617, srcPt[ 0 ], tol );
assertEquals( "warp y2 in place", 0.6241617, srcPt[ 1 ], tol );
/* **** PT 3 **** */
srcPt = new double[]{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "warp x3", 1.5, ptXfm[ 0 ], tol );
assertEquals( "warp y3", 1.5, ptXfm[ 1 ], tol );
tps.applyInPlace( srcPt );
assertEquals( "warp x3 in place", 1.5, srcPt[ 0 ], tol );
assertEquals( "warp y3 in place", 1.5, srcPt[ 1 ], tol );
}
@Test
public void testWeights()
{
final int ndims = 2;
final double[][] src_simple = new double[][]
{
{ 0, 0, 0, 1, 1, 1, 2, 2, 2 }, // x
{ 0, 1, 2, 0, 1, 2, 0, 1, 2 }, // y
};
// target points
final double[][] tgt = new double[][]
{
{ -0.5, -0.5, -0.5, 1.5, 1.5, 1.5, 2.0, 2.0, 2.0 }, // x
{ -0.5, 1.5, 2.0, -0.5, 1.5, 2.0, -0.5, 1.5, 2.0 } // y
};
// double[] weights = new double[]
// { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
final double[] weights = new double[]
{ 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 1.0 };
final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
ndims, src_simple, tgt, weights );
// tps.printLandmarks();
double[] srcPt = new double[]{ 0.0f, 0.0f };
double[] ptXfm = tps.apply( srcPt );
assertEquals( "warp x1", -0.5, ptXfm[ 0 ], tol );
assertEquals( "warp y1", -0.5, ptXfm[ 1 ], tol );
srcPt = new double[]{ 0.5f, 0.5f };
ptXfm = tps.apply( srcPt );
// the values below are what matlab returns for
// tpaps( p, q, 1 );
// where p and q are the source and target points, respectively
assertEquals( "warp x2", 0.6241617, ptXfm[ 0 ], tol );
assertEquals( "warp y2", 0.6241617, ptXfm[ 1 ], tol );
srcPt = new double[]{ 1.0f, 1.0f };
ptXfm = tps.apply( srcPt );
assertEquals( "warp x3", 1.5, ptXfm[ 0 ], tol );
assertEquals( "warp y3", 1.5, ptXfm[ 1 ], tol );
}
}
| stricter test for tps-inverse
| src/test/java/jitk/spline/ThinPlateR2LogRSplineKernelTransformTest.java | stricter test for tps-inverse | <ide><path>rc/test/java/jitk/spline/ThinPlateR2LogRSplineKernelTransformTest.java
<ide> final ThinPlateR2LogRSplineKernelTransform tps = new ThinPlateR2LogRSplineKernelTransform(
<ide> ndims, srcPts, tgtPts, false );
<ide>
<del> double finalError= tps.inverseTol( target, guess, 0.5, 2000 );
<add> double finalError= tps.inverseTol( target, guess, 0.5, 1000 );
<ide>
<ide> double[] guessXfm = tps.apply( guess );
<ide> logger.debug( "final error : " + finalError );
<ide> assertEquals( "within tolerance 0.5 x", 0.5, guessXfm[ 0 ], 0.5 );
<ide> assertEquals( "within tolerance 0.5 y", 0.5, guessXfm[ 1 ], 0.5 );
<ide>
<del> // tps.inverseTol( target, guess, 0.1, 200 );
<del> // logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
<del> //
<del> // assertEquals( "within tolerance 0.1 x", 0.5, guess[ 0 ], 0.1 );
<del> // assertEquals( "within tolerance 0.1 y", 0.5, guess[ 1 ], 0.1 );
<del> //
<del> // // try for a few different initial guesses
<del> // for ( int xm = -1; xm <= 1; xm++ )
<del> // for ( int ym = -1; ym <= 1; ym++ )
<del> // {
<del> // System.arraycopy( guessBase, 0, guess, 0, ndims );
<del> // guess[ 0 ] *= xm;
<del> // guess[ 1 ] *= ym;
<del> //
<del> // tps.inverseTol( target, guess, 0.5, 200 );
<del> // logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
<del> //
<del> // assertEquals( "within tolerance 0.5 x", 0.5, guess[ 0 ], 0.5 );
<del> // assertEquals( "within tolerance 0.5 y", 0.5, guess[ 1 ], 0.5 );
<del> //
<del> // tps.inverseTol( target, guess, 0.1, 2000 );
<del> // logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
<del> //
<del> // assertEquals( "within tolerance 0.1 x", 0.5, guess[ 0 ], 0.1 );
<del> // assertEquals( "within tolerance 0.1 y", 0.5, guess[ 1 ], 0.1 );
<del> // }
<add> tps.inverseTol( target, guess, 0.25, 2000 );
<add> logger.debug( "final guess: " + XfmUtils.printArray( guess ) );
<add>
<add> assertEquals( "within tolerance 0.25 x", 0.5, guess[ 0 ], 0.25 );
<add> assertEquals( "within tolerance 0.25 y", 0.5, guess[ 1 ], 0.25 );
<add>
<add> // try for a few different initial guesses
<add> double[] guessBase = new double[] { 0.0, 0.0 };
<add> for (double xm = -2.5; xm <= 2.5; xm += 0.5)
<add> for (double ym = -2.5; ym <= 2.5; ym += 0.5)
<add> {
<add> System.arraycopy(guessBase, 0, guess, 0, ndims);
<add> guess[0] *= xm;
<add> guess[1] *= ym;
<add>
<add> tps.inverseTol(target, guess, 0.5, 2000);
<add> logger.debug("final guess: " + XfmUtils.printArray(guess));
<add>
<add> assertEquals("within tolerance 0.5 x", 0.5, guess[0], 0.5);
<add> assertEquals("within tolerance 0.5 y", 0.5, guess[1], 0.5);
<add>
<add> tps.inverseTol(target, guess, 0.25, 2000);
<add> logger.debug("final guess: " + XfmUtils.printArray(guess));
<add>
<add> assertEquals("within tolerance 0.25 x", 0.5, guess[0], 0.25);
<add> assertEquals("within tolerance 0.25 y", 0.5, guess[1], 0.25);
<add> }
<ide> }
<ide>
<ide> @Test |
|
Java | apache-2.0 | 3dbeccdf8c7c3572d22ea5a5bca3b01b3287097c | 0 | kelemen/JTrim,kelemen/JTrim | package org.jtrim.image.transform;
import org.jtrim.concurrent.async.DataConverter;
/**
* Defines an image transformation from {@link ImageTransformerData} to
* {@link TransformedImage}.
* <P>
* When applying a transformation on the input, the conversion must specify
* the coordinate transformation which transforms the coordinates of the source
* image to the coordinates of the resulting image. That is, where a pixel of
* the original image can be found on the resulting image. The coordinate
* transformation must support coordinates laying outside the bounds of the
* image.
*
* <h3>Thread safety</h3>
* Implementations of this interface are required to be safe to be used by
* multiple threads concurrently.
*
* <h4>Synchronization transparency</h4>
* Implementations of this interface are not required to be
* <I>synchronization transparent</I>.
*
* @see ImageTransformerLink
* @see ImageTransfromerQuery
* @see org.jtrim.swing.component.AsyncImageDisplay
*
* @author Kelemen Attila
*/
public interface ImageTransformer
extends
DataConverter<ImageTransformerData, TransformedImage> {
}
| jtrim-gui/src/main/java/org/jtrim/image/transform/ImageTransformer.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jtrim.image.transform;
import org.jtrim.concurrent.async.DataConverter;
/**
*
* @author Kelemen Attila
*/
public interface ImageTransformer
extends
DataConverter<ImageTransformerData, TransformedImage> {
}
| Documented ImageTransformer | jtrim-gui/src/main/java/org/jtrim/image/transform/ImageTransformer.java | Documented ImageTransformer | <ide><path>trim-gui/src/main/java/org/jtrim/image/transform/ImageTransformer.java
<del>/*
<del> * To change this template, choose Tools | Templates
<del> * and open the template in the editor.
<del> */
<del>
<ide> package org.jtrim.image.transform;
<ide>
<ide> import org.jtrim.concurrent.async.DataConverter;
<ide>
<ide> /**
<add> * Defines an image transformation from {@link ImageTransformerData} to
<add> * {@link TransformedImage}.
<add> * <P>
<add> * When applying a transformation on the input, the conversion must specify
<add> * the coordinate transformation which transforms the coordinates of the source
<add> * image to the coordinates of the resulting image. That is, where a pixel of
<add> * the original image can be found on the resulting image. The coordinate
<add> * transformation must support coordinates laying outside the bounds of the
<add> * image.
<add> *
<add> * <h3>Thread safety</h3>
<add> * Implementations of this interface are required to be safe to be used by
<add> * multiple threads concurrently.
<add> *
<add> * <h4>Synchronization transparency</h4>
<add> * Implementations of this interface are not required to be
<add> * <I>synchronization transparent</I>.
<add> *
<add> * @see ImageTransformerLink
<add> * @see ImageTransfromerQuery
<add> * @see org.jtrim.swing.component.AsyncImageDisplay
<ide> *
<ide> * @author Kelemen Attila
<ide> */ |
|
JavaScript | mit | bc733bfbfb014ad0e09bc5a065afe1d133c8f1f0 | 0 | dhuertas/mat.js,dhuertas/mat.js | /*
* @author dhuertas
* @email [email protected]
*/
var MAT = (function() {
/*
* Arithmetical operations
*/
var OP = {
sum : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0] + b[0], a[1] + b[1]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0] + b, a[1]];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a + b[0], b[1]];
} else {
return a + b;
}
},
subtract : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0] - b[0], a[1] - b[1]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0] - b, a[1]];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a - b[0], b[1]];
} else {
return a - b;
}
},
product : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0]*b[0] - a[1]*b[1], a[0]*b[1] + a[1]*b[0]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0]*b, a[1]*b];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a*b[0], a*b[1]];
} else {
return a*b;
}
},
division : function(a, b) {
if (a instanceof Array && b instanceof Array) {
if (b[0] === 0 && b[1] === 0) {
throw ("division by 0");
}
return [
( a[0]*b[0] + a[1]*b[1] ) / ( b[0]*b[0] + b[1]*b[1] ),
( a[1]*b[0] - a[0]*b[1] ) / ( b[0]*b[0] + b[1]*b[1] )];
} else if (a instanceof Array && ! b instanceof Array) {
if (b === 0) {
throw ("division by 0");
}
return [a[0]/b, a[1]/b];
} else if ( ! a instanceof Array && b instanceof Array) {
if (b[0] === 0 && b[1] === 0) {
throw ("division by 0");
}
return [
a*b[0] / ( b[0]*b[0]+b[1]*b[1] ),
-a*b[1] / ( b[0]*b[0]+b[1]*b[1] )];
} else {
if (b === 0) {
throw ("division by 0");
}
return a/b;
}
},
conjugate : function(a) {
if (a instanceof Array) {
return [a[0], -a[1]];
}
return a;
},
modulus : function(a) {
if (a instanceof Array) {
return Math.sqrt(a[0]*a[0]+a[1]*a[1]);
}
return Math.abs(a);
}
};
var ATTRIBUTES = ['rows', 'columns', 'values', 'error', 'maxrounds', 'overwrite'],
DEFAULTS = {maxrounds : 1000, error : 0.000001, overwrite : false};
/*
* helper functions
*/
function inArray(needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (needle == haystack[i]) return true;
}
return false;
}
/*
* MAT object constructor
* @param {integer} r (rows)
* @param {integer} c (columns)
* @param {array} v (values)
*/
function construct(r, c, v) {
for (var elem in DEFAULTS) {
this[elem] = DEFAULTS[elem];
}
if (arguments[0] instanceof Object) {
for (var elem in arguments[0]) {
if (inArray(elem, ATTRIBUTES)) {
this[elem] = arguments[0][elem];
}
}
} else {
this.rows = r;
this.columns = c;
this.values = v;
}
}
construct.prototype = {
/*
* fromArray
* @param {array} a (e.g. [[0,1,2],[3,4,5],[6,7,8]])
* @return {object} matrix
*/
fromArray : function(a) {
var values = [];
if ( ! a instanceof Array) {
throw ("fromArray: argument must be an array");
} else {
this.setRows(a.length);
this.setColumns(a[0].length);
this.values = Array(this.rows*this.columns);
for (var i = 0; i < this.rows; i++) {
for (var j = 0, len = a[i].length; j < len; j++) {
this.setValue(i, j, a[i][j]);
}
}
}
return this;
},
/*
* toArray
* @return {array}
*/
toArray : function () {
return this.values.slice(0);
},
/*
* toString
* @return {string}
*/
toString : function() {
return this.values.toString();
},
/*
* getColumn
* @param {integer} j (e.g. j-th column)
* @return {object} matrix (column vector)
*/
getColumn : function(j) {
var res = [];
if (this.columns > j && j >= 0) {
for (var i = 0; i < this.rows; i++) {
res.push(this.values[this.columns*i+j]);
}
} else {
for (var i = 0; i < this.rows; i++) {
res.push(0);
}
}
return (new MAT(this.rows, 1, res));
},
/*
* getColumns
* @return {integer} (the number of columns)
*/
getColumns : function() {
return this.columns;
},
/*
* getLength
* @return {integer} (the number of elements)
*/
getLength : function() {
return this.values.length;
},
/*
* getRow
* @param {integer} i (the i-th column)
* @return {object} (row vector)
*/
getRow : function(i) {
var res = [];
if (this.rows > i && i >= 0) {
for (var j = 0; j < this.columns; j++) {
res.push(this.values[this.columns*i+j]);
}
} else {
for (var j = 0; j < this.columns; j++) {
res.push(0);
}
}
return (new MAT(1, this.columns, res));
},
/*
* getRows
* @return {integer} (the number of rows)
*/
getRows : function() {
return this.rows;
},
/*
* getShape
* @return {array}
*/
getShape : function() {
return [this.rows, this.columns];
},
/*
* getValue
* @param {integer} a (i-th row)
* @param {integer} b (j-th column)
* @return {float|array}
*/
getValue : function(i, j) {
return this.values[i*this.columns + j];
},
/*
* getValues
* @return {array} (a copy of|the matrix values)
*/
getValues : function() {
return this.values.slice(0);
},
/*
* setRows
* @param {integer} a
* @return {object}
*/
setRows : function(a) {
this.rows = a;
return this;
},
/*
* setColumns
* @param {integer} a
* @return {object}
*/
setColumns : function(a) {
this.columns = a;
return this;
},
/*
* setValue
* @param {integer} a
* @param {integer} b
* @param {float|array} c
* @return {object}
*/
setValue : function(a, b, c) {
this.values[a*this.columns + b] = c;
return this;
},
/*
* isSquare
* @return {boolean}
*/
isSquare : function() {
return (this.columns === this.rows);
},
/*
* isColumnVector
* @return {boolean}
*/
isColumnVector : function() {
return (this.columns === 1 && this.rows > 1);
},
/*
* isRowVector
* @return {boolean}
*/
isRowVector : function() {
return (this.columns > 1 && this.rows === 1);
},
/*
* isVector
* @return {boolean}
*/
isVector : function() {
return (this.isColumnVector() || this.isRowVector());
},
/*
* isSameSize
* @param {object} a {matrix}
* @return boolean
*/
isSameSize : function(a) {
return (a.getColumns() === this.columns && a.getRows() === this.rows);
},
/*
* add
* @param {object} matrix
* @return {object} matrix (X+A)
*/
add : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.sum(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.sum(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("add: matrices must be same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* subtract
* @param {object} matrix
* @return {object} matrix (X-A)
*/
subtract : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j,
OP.subtract(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.subtract(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("sub: matrices must be same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* product
* @param {object} matrix
* @return {object} matrix (X*A)
*/
product : function(a) {
var temp = 0,
cols = a.getColumns(),
values = [];
if (a.getRows() === this.columns) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < cols; j++) {
temp = 0;
for (var k = 0; k < this.columns; k++) {
temp = OP.sum(temp, OP.product(
this.values[this.columns*i + k],
a.getValue(k, j)));
}
values.push(temp);
}
}
if (this.overwrite) {
this.splice(0, this.values.length, values);
}
} else {
throw ("product: matrix size does not match");
}
return this.overwrite ? this : new MAT(this.rows, a.getColumns(), values);
},
/*
* hadamardProduct
* @param {object} matrix
* @return {object} matrix
*/
hadamardProduct : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.product(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.product(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("hadamardProduct: matrices must be the same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* scalarProduct
* @param {float}
* @return {object} matrix (a*X)
*/
scalarProduct : function(a) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.product(this.getValue(i, j), a));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.product(this.getValue(i, j), a));
}
}
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* transpose
* @return {object} matrix
*/
transpose : function() {
var values = [];
for (var i = 0; i < this.columns; i++) {
for (var j = 0; j < this.rows; j++) {
values.push(this.values[this.columns*j + i]);
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* hermitian
* @return {object} matrix
*/
hermitian : function() {
var values = [];
for (var i = 0; i < this.columns; i++) {
for (var j = 0; j < this.rows; j++) {
values.push(OP.conjugate(this.values[this.columns*j + i]));
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.columns, this.rows, values);
},
/*
* trace
* @return {float}
*/
trace : function() {
var result = 0;
if (this.isSquare()) {
for (var i = 0; i < this.columns; i++) {
result = OP.sum(result, this.getValue(i, i));
}
} else {
throw ("trace: matrix must be square");
}
return result;
},
/*
* upperTrace
* @param {integer} a (a-th upper diagonal)
* @return {float|array} result
*/
upperTrace : function(a) {
var result = 0;
if ( ! this.isSquare()) {
throw ("upperTrace: matrix must be square");
} else if (a > this.columns - 1) {
throw ("upperTrace: diagonal out of range");
} else {
for (var i = 0; i < this.columns - a; i++) {
result = OP.sum(result, this.getValue(i, i + a));
}
}
return result;
},
/*
* lowerTrace
* @param {integer} a (a-th lower trace)
* @return {float|array} result
*/
lowerTrace : function(a) {
var result = 0;
if ( ! this.isSquare()) {
throw ("lowerTrace: matrix must be square");
} else if (a > this.columns - 1) {
throw ("lowerTrace: diagonal out of range");
} else {
for (var i = 0; i < this.columns - a; i++) {
result = OP.sum(result, this.getValue(i + a, i));
}
}
return result;
},
/*
* minor
* @param {integer} row
* @param {integer} column
* @return {object} matrix (a minor (n-1)*(n-1) matrix)
*/
minor : function(r, c) {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (i !== r && j !== c) {
values.push(this.getValue(i, j));
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.rows-1, this.columns-1, values);
},
/*
* determinant
* @return {float|array}
*/
determinant : function() {
var res = 0,
t = 0,
u = 0;
if ( ! this.isSquare()) {
throw ("determinant: matrix must be square");
} else if (this.columns === 1) {
res = this.values[0];
} else if (this.columns === 2) {
res = OP.subtract(
OP.product(this.values[0], this.values[3]),
OP.product(this.values[1], this.values[2]));
} else {
for (var j = 0; j < this.columns; j++) {
t = OP.product((j%2 === 0 ? 1: -1), this.getValue(0, j));
u = this.minor(0, j).determinant();
res = OP.sum(res, OP.product(t, u));
}
}
return res;
},
/*
* Alias for determinant
* @return {float|array}
*/
det : function() { return this.determinant(); },
/*
* gaussElimination
* Naive Gauss Elimination method
* @return {object} matrix
*/
gaussElimination : function() {
var n = this.columns,
l = new Array(n),
R = new MAT(n, n, this.getValues()),
v = 0;
l[0] = 1;
for (var j = 0; j < n-1; j++) {
for (var i = j+1; i < n; i++) {
l[i] = OP.division(R.getValue(i, j), R.getValue(j, j));
}
for (i = j+1; i < n; i++) {
R.setValue(i, j, 0);
for (var k = j + 1; k < n; k++) {
v = OP.subtract(R.getValue(i, k), OP.product(l[i], R.getValue(j, k)));
R.setValue(i, k, v);
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, R.getValues());
}
return this.overwrite ? this : R;
},
/*
* solve
* @param {array} a (constants)
* @return {object} matrix
*/
solve : function(a) {
var m = this.rows,
n = this.columns,
l = new Array(n),
r = new Array(n),
R = new MAT(n, n, this.getValues());
if (a.length !== this.rows || ! this.isSquare()) {
for (var i = 0; i < m; i++) {
r.push(0);
}
} else {
/* Forward Elimination */
for (var j = 0; j < n-1; j++) {
for (var i = j+1; i < n; i++) {
l[i] = OP.division(R.getValue(i, j), R.getValue(j, j));
}
for (i = j+1; i < n; i++) {
R.setValue(i, j, 0);
for (var k = j+1; k < n; k++) {
R.setValue(i, k, OP.subtract(
R.getValue(i, k),
OP.product(l[i], R.getValue(j, k))));
}
a[i] = OP.subtract(a[i], OP.product(l[i], a[j]));
}
}
/* Backward solving */
for (i = n-1; i >= 0; i--) {
r[i] = a[i];
for (j = n-1; j > i; j--) {
r[i] = OP.subtract(r[i], OP.product(R.getValue(i, j), r[j]));
}
r[i] = this.d(r[i], R.getValue(i, i));
}
}
return new MAT(m, 1, r);
},
/*
* gramSchmidt
* The Gram-Schmidt process
* @return {object} matrix
*/
gramSchmidt : function() {
var m = this.rows,
n = this.columns,
e = [],
p, q = [], u, v;
/* Gram-Schmidt */
for (var i = 0; i < n; i++) {
u = this.getColumn(i);
for (var j = 0; j < i; j++) {
v = OP.division(
e[j].hermitian().product(this.getColumn(i)).getValue(0,0),
e[j].norm());
p = e[j].scalarProduct(v); // j-th projection
u = u.subtract(p);
}
e.push(u.scalarProduct(OP.division(1, u.norm())));
q = q.concat(e[i].toArray());
}
if (this.overwrite) {
this.rows = n;
this.columns = m;
this.values.splice(0, this.values.length, q);
}
return (this.overwrite ? this : new MAT(n, m, q)).transpose();
},
/*
* qrDecomposition
* QR decomposition
* @return {array} [Q,R]
*/
qrDecomposition : function() {
var Q, R;
Q = this.gramSchmidt();
R = Q.transpose().product(this);
return [Q, R];
},
/*
* Alias for the qrDecomposition function
*/
qr : function() {
return this.qrDecomposition();
},
/*
* luDecomposition
* LU decomposition
* @return {array} [L,U]
*/
luDecomposition : function() {
var l = [],
L = this.identity(this.columns),
U = new MAT(this.rows, this.columns, this.getValues());
for (var j = 0; j < this.columns - 1; j++) {
for (var i = j+1; i < this.columns; i++) {
l[i] = OP.division(U.getValue(i, j), U.getValue(j, j));
L.setValue(i, j, l[i]);
}
for (i = j+1; i < this.columns; i++) {
U.setValue(i, j, 0);
for (var k = j+1; k < this.columns; k++) {
U.setValue(i, k, OP.subtract(
U.getValue(i, k),
OP.product(l[i], U.getValue(j, k))));
}
}
}
return [L, U];
},
/*
* Alias for the luDecomposition
*/
lu : function() {
return this.luDecomposition();
},
/*
* eigenValues
* Eigenvalues using the QR iteration process
* @return {object} matrix
*/
eigenValues : function() {
var tmp = new MAT(this.rows, this.columns, this.getValues()),
l = Math.min(this.rows, this.columns),
QR,
values = [];
if ( ! this.isSquare()) {
throw ("eigenValues: matrix must be square");
} else {
for (var i = 0; i < this.maxrounds; i++) {
QR = tmp.qrDecomposition();
tmp = QR[1].product(QR[0]);
/*
* Stop the process when the values
* below the main diagonal are sufficiently small
*/
if (tmp.lowerTrace(1) < this.error) {
break;
}
}
for (var j = 0; j < l; j++) {
values.push(tmp.getValue(j, j));
}
}
return new MAT(l, 1, values);
},
/*
* eigenVectors
* @return {object} matrix
*/
eigenVectors : function() {
var tmp = new MAT(this.rows, this.columns, this.getValues()),
l = Math.min(this.rows, this.columns),
QR;
for (var i = 0; i < this.maxrounds; i++) {
QR = tmp.qrDecomposition();
tmp = QR[1].product(QR[0]);
/*
* Stop the process when the values
* below the main diagonal are sufficiently small
*/
if (tmp.lowerTrace(1) < this.error) {
break;
}
}
return QR[0];
},
/*
* identity
* @param {integer} size of the resulting matrix n*n
* @return {object} matrix
*/
identity : function(a) {
var values = [];
if (typeof a !== undefined && a > 0) {
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
values.push(i === j ? 1 : 0);
}
}
}
return new MAT(a, a, values);
},
/*
* diagonal
* @param {integer} a size
* @param {float|array} b (e.g. complex value [real,imag])
* @return {object} matrix
*/
diagonal : function(a, b) {
var values = [],
res;
if (typeof a === "undefined" || a <= 0) {
throw ("diagonal: first argument must be an integer greater than 0");
} else {
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
values.push(i === j ? b : 0);
}
}
res = new MAT(a, a, values);
}
return res;
},
/*
* pNorm
* @param {integer} a
* @return {float}
*/
pNorm : function(a) {
var res = 0,
tmp = 1;
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
tmp = 1;
for (var k = 0; k < a; k++) {
tmp = OP.product(tmp, OP.modulus(this.values[this.columns*i + j]));
}
res = OP.sum(res, tmp);
}
}
res = Math.pow(Math.E, OP.division(Math.log(res), a));
return res;
},
/*
* norm
* Euclidean norm (p = 2)
* @return {float}
*/
norm : function() {
return this.pNorm(2);
},
/*
* toToeplitz
* @param {integer} a
* @return {object} matrix
*/
toToeplitz : function(a) {
var res = [],
row = [],
l = 0,
m = this.values.length;
for (var i = 0; i < a; i++) {
row.push(0);
}
l = m+a-1;
/* column vector */
for (var i = 0; i < l; i++) {
if (i < m) {
if (this.isColumnVector()) {
/* column vector */
row.unshift(OP.conjugate(this.values[i]));
} else if (this.isRowVector()) {
row.unshift(this.values[i]);
} else {
/* do some stuff here */
}
} else {
row.unshift(0);
}
row.pop();
res = res.concat(row);
}
return new MAT(l, a, res);
},
/*
* inverse
* Matrix inverse
* @return {object} matrix
*/
inverse : function() {
var values = [],
det = this.determinant(),
sign = 1;
if (det === 0) {
throw ("inverse: unable to invert matrix, determinant is 0");
} else if ( ! this.isSquare()) {
throw ("inverse: matrix must be square");
} else {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
sign = (i+j)% 2 === 0 ? 1 : -1;
values.push(OP.product(sign,
OP.division(this.minor(i, j).det(), det)));
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return (this.overwrite ? this : new MAT(this.rows, this.columns, values)).hermitian();
},
/*
* pseudoInverse
* The Moore-Penrose Pseudoinverse
* @return {object} matrix
*/
pseudoInverse : function() {
var M = this.hermitian().product(this);
if (M.det() === 0) {
/* right inverse */
M = this.product(this.hermitian());
if (M.det() === 0) {
throw ("pseudoInverse: unable to invert matrix");
} else {
M = this.hermitian().product(M.inverse());
}
} else {
/* left inverse */
M = M.inverse().product(this.hermitian());
}
return M;
},
/*
* toVandermonde
* @param {integer} n (number of columns)
* @return {object} matrix
*/
toVandermonde : function(n) {
var values = [],
k = 0,
a = this.getValues(),
len = a.length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < n; j++) {
if (j === 0) {
values.push(1);
} else if (j === 1) {
values.push(a[i]);
} else {
values.push(OP.product(a[i], values[k-1]));
}
k++;
}
}
if (this.overwrite) {
this.rows = len;
this.columns = n;
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(len, n, values);
},
/*
* zero
* @return {object} a matrix filled with zeros
*/
zero : function() {
var values = [];
for (var i = 0, len = this.columns*this.rows; i < len; i++) {
values.push(0);
}
return new MAT(this.rows, this.columns, values);
},
}
return construct;
})();
| mat.js | /*
* @author dhuertas
* @email [email protected]
*/
var MAT = (function() {
/*
* Arithmetical operations
*/
var OP = {
sum : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0] + b[0], a[1] + b[1]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0] + b, a[1]];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a + b[0], b[1]];
} else {
return a + b;
}
},
subtract : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0] - b[0], a[1] - b[1]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0] - b, a[1]];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a - b[0], b[1]];
} else {
return a - b;
}
},
product : function(a, b) {
if (a instanceof Array && b instanceof Array) {
return [a[0]*b[0] - a[1]*b[1], a[0]*b[1] + a[1]*b[0]];
} else if (a instanceof Array && ! b instanceof Array) {
return [a[0]*b, a[1]*b];
} else if ( ! a instanceof Array && b instanceof Array) {
return [a*b[0], a*b[1]];
} else {
return a*b;
}
},
division : function(a, b) {
if (a instanceof Array && b instanceof Array) {
if (b[0] === 0 && b[1] === 0) {
throw ("division by 0");
}
return [
( a[0]*b[0] + a[1]*b[1] ) / ( b[0]*b[0] + b[1]*b[1] ),
( a[1]*b[0] - a[0]*b[1] ) / ( b[0]*b[0] + b[1]*b[1] )];
} else if (a instanceof Array && ! b instanceof Array) {
if (b === 0) {
throw ("division by 0");
}
return [a[0]/b, a[1]/b];
} else if ( ! a instanceof Array && b instanceof Array) {
if (b[0] === 0 && b[1] === 0) {
throw ("division by 0");
}
return [
a*b[0] / ( b[0]*b[0]+b[1]*b[1] ),
-a*b[1] / ( b[0]*b[0]+b[1]*b[1] )];
} else {
if (b === 0) {
throw ("division by 0");
}
return a/b;
}
},
conjugate : function(a) {
if (a instanceof Array) {
return [a[0], -a[1]];
}
return a;
},
modulus : function(a) {
if (a instanceof Array) {
return Math.sqrt(a[0]*a[0]+a[1]*a[1]);
}
return Math.abs(a);
}
};
var ATTRIBUTES = ['rows', 'columns', 'values', 'error', 'maxrounds', 'overwrite'],
DEFAULTS = {maxrounds : 1000, error : 0.000001, overwrite : false};
/*
* helper functions
*/
function inArray(needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (needle == haystack[i]) return true;
}
return false;
}
/*
* MAT object constructor
* @param {integer} r (rows)
* @param {integer} c (columns)
* @param {array} v (values)
*/
function construct(r, c, v) {
for (var elem in DEFAULTS) {
this[elem] = DEFAULTS[elem];
}
if (arguments[0] instanceof Object) {
for (var elem in arguments[0]) {
if (inArray(elem, ATTRIBUTES)) {
this[elem] = arguments[0][elem];
}
}
} else {
this.rows = r;
this.columns = c;
this.values = v;
}
}
construct.prototype = {
/*
* fromArray
* @param {array} a (e.g. [[0,1,2],[3,4,5],[6,7,8]])
* @return {object} matrix
*/
fromArray : function(a) {
var values = [];
if ( ! a instanceof Array) {
throw ("fromArray: argument must be an array");
} else {
this.setRows(a.length);
this.setColumns(a[0].length);
this.values = Array(this.rows*this.columns);
for (var i = 0; i < this.rows; i++) {
for (var j = 0, len = a[i].length; j < len; j++) {
this.setValue(i, j, a[i][j]);
}
}
}
return this;
},
/*
* toArray
* @return {array}
*/
toArray : function () {
var res = [], n = this.values.length;
for (var i = 0; i < n; i++) {
res.push(this.values[i]);
}
return res;
},
/*
* toString
* @return {string}
*/
toString : function() {
return this.values.toString();
},
/*
* getColumn
* @param {integer} j (e.g. j-th column)
* @return {object} matrix (column vector)
*/
getColumn : function(j) {
var res = [];
if (this.columns > j && j >= 0) {
for (var i = 0; i < this.rows; i++) {
res.push(this.values[this.columns*i+j]);
}
} else {
for (var i = 0; i < this.rows; i++) {
res.push(0);
}
}
return (new MAT(this.rows, 1, res));
},
/*
* getColumns
* @return {integer} (the number of columns)
*/
getColumns : function() {
return this.columns;
},
/*
* getLength
* @return {integer} (the number of elements)
*/
getLength : function() {
return this.values.length;
},
/*
* getRow
* @param {integer} i (the i-th column)
* @return {object} (row vector)
*/
getRow : function(i) {
var res = [];
if (this.rows > i && i >= 0) {
for (var j = 0; j < this.columns; j++) {
res.push(this.values[this.columns*i+j]);
}
} else {
for (var j = 0; j < this.columns; j++) {
res.push(0);
}
}
return (new MAT(1, this.columns, res));
},
/*
* getRows
* @return {integer} (the number of rows)
*/
getRows : function() {
return this.rows;
},
/*
* getShape
* @return {array}
*/
getShape : function() {
return [this.rows, this.columns];
},
/*
* getValue
* @param {integer} a (i-th row)
* @param {integer} b (j-th column)
* @return {float|array}
*/
getValue : function(i, j) {
return this.values[i*this.columns + j];
},
/*
* getValues
* @return {array} (a copy of|the matrix values)
*/
getValues : function() {
return this.values.slice(0);
},
/*
* setRows
* @param {integer} a
* @return {object}
*/
setRows : function(a) {
this.rows = a;
return this;
},
/*
* setColumns
* @param {integer} a
* @return {object}
*/
setColumns : function(a) {
this.columns = a;
return this;
},
/*
* setValue
* @param {integer} a
* @param {integer} b
* @param {float|array} c
* @return {object}
*/
setValue : function(a, b, c) {
this.values[a*this.columns + b] = c;
return this;
},
/*
* isSquare
* @return {boolean}
*/
isSquare : function() {
return (this.columns === this.rows);
},
/*
* isColumnVector
* @return {boolean}
*/
isColumnVector : function() {
return (this.columns === 1 && this.rows > 1);
},
/*
* isRowVector
* @return {boolean}
*/
isRowVector : function() {
return (this.columns > 1 && this.rows === 1);
},
/*
* isVector
* @return {boolean}
*/
isVector : function() {
return (this.isColumnVector() || this.isRowVector());
},
/*
* isSameSize
* @param {object} a {matrix}
* @return boolean
*/
isSameSize : function(a) {
return (a.getColumns() === this.columns && a.getRows() === this.rows);
},
/*
* add
* @param {object} matrix
* @return {object} matrix (X+A)
*/
add : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.sum(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.sum(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("add: matrices must be same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* subtract
* @param {object} matrix
* @return {object} matrix (X-A)
*/
subtract : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j,
OP.subtract(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.subtract(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("sub: matrices must be same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* product
* @param {object} matrix
* @return {object} matrix (X*A)
*/
product : function(a) {
var temp = 0,
cols = a.getColumns(),
values = [];
if (a.getRows() === this.columns) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < cols; j++) {
temp = 0;
for (var k = 0; k < this.columns; k++) {
temp = OP.sum(temp, OP.product(
this.values[this.columns*i + k],
a.getValue(k, j)));
}
values.push(temp);
}
}
if (this.overwrite) {
this.splice(0, this.values.length, values);
}
} else {
throw ("product: matrix size does not match");
}
return this.overwrite ? this : new MAT(this.rows, a.getColumns(), values);
},
/*
* hadamardProduct
* @param {object} matrix
* @return {object} matrix
*/
hadamardProduct : function(a) {
if (this.isSameSize(a)) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.product(this.getValue(i, j), a.getValue(i, j)));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.product(this.getValue(i, j), a.getValue(i, j)));
}
}
}
} else {
throw ("hadamardProduct: matrices must be the same size");
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* scalarProduct
* @param {float}
* @return {object} matrix (a*X)
*/
scalarProduct : function(a) {
if (this.overwrite) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
this.setValue(i, j, OP.product(this.getValue(i, j), a));
}
}
} else {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
values.push(OP.product(this.getValue(i, j), a));
}
}
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* transpose
* @return {object} matrix
*/
transpose : function() {
var values = [];
for (var i = 0; i < this.columns; i++) {
for (var j = 0; j < this.rows; j++) {
values.push(this.values[this.columns*j + i]);
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.rows, this.columns, values);
},
/*
* hermitian
* @return {object} matrix
*/
hermitian : function() {
var values = [];
for (var i = 0; i < this.columns; i++) {
for (var j = 0; j < this.rows; j++) {
values.push(OP.conjugate(this.values[this.columns*j + i]));
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.columns, this.rows, values);
},
/*
* trace
* @return {float}
*/
trace : function() {
var result = 0;
if (this.isSquare()) {
for (var i = 0; i < this.columns; i++) {
result = OP.sum(result, this.getValue(i, i));
}
} else {
throw ("trace: matrix must be square");
}
return result;
},
/*
* upperTrace
* @param {integer} a (a-th upper diagonal)
* @return {float|array} result
*/
upperTrace : function(a) {
var result = 0;
if ( ! this.isSquare()) {
throw ("upperTrace: matrix must be square");
} else if (a > this.columns - 1) {
throw ("upperTrace: diagonal out of range");
} else {
for (var i = 0; i < this.columns - a; i++) {
result = OP.sum(result, this.getValue(i, i + a));
}
}
return result;
},
/*
* lowerTrace
* @param {integer} a (a-th lower trace)
* @return {float|array} result
*/
lowerTrace : function(a) {
var result = 0;
if ( ! this.isSquare()) {
throw ("lowerTrace: matrix must be square");
} else if (a > this.columns - 1) {
throw ("lowerTrace: diagonal out of range");
} else {
for (var i = 0; i < this.columns - a; i++) {
result = OP.sum(result, this.getValue(i + a, i));
}
}
return result;
},
/*
* minor
* @param {integer} row
* @param {integer} column
* @return {object} matrix (a minor (n-1)*(n-1) matrix)
*/
minor : function(r, c) {
var values = [];
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
if (i !== r && j !== c) {
values.push(this.getValue(i, j));
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(this.rows-1, this.columns-1, values);
},
/*
* determinant
* @return {float|array}
*/
determinant : function() {
var res = 0,
t = 0,
u = 0;
if ( ! this.isSquare()) {
throw ("determinant: matrix must be square");
} else if (this.columns === 1) {
res = this.values[0];
} else if (this.columns === 2) {
res = OP.subtract(
OP.product(this.values[0], this.values[3]),
OP.product(this.values[1], this.values[2]));
} else {
for (var j = 0; j < this.columns; j++) {
t = OP.product((j%2 === 0 ? 1: -1), this.getValue(0, j));
u = this.minor(0, j).determinant();
res = OP.sum(res, OP.product(t, u));
}
}
return res;
},
/*
* Alias for determinant
* @return {float|array}
*/
det : function() { return this.determinant(); },
/*
* gaussElimination
* Naive Gauss Elimination method
* @return {object} matrix
*/
gaussElimination : function() {
var n = this.columns,
l = new Array(n),
R = new MAT(n, n, this.getValues()),
v = 0;
l[0] = 1;
for (var j = 0; j < n-1; j++) {
for (var i = j+1; i < n; i++) {
l[i] = OP.division(R.getValue(i, j), R.getValue(j, j));
}
for (i = j+1; i < n; i++) {
R.setValue(i, j, 0);
for (var k = j + 1; k < n; k++) {
v = OP.subtract(R.getValue(i, k), OP.product(l[i], R.getValue(j, k)));
R.setValue(i, k, v);
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, R.getValues());
}
return this.overwrite ? this : R;
},
/*
* solve
* @param {array} a (constants)
* @return {object} matrix
*/
solve : function(a) {
var m = this.rows,
n = this.columns,
l = new Array(n),
r = new Array(n),
R = new MAT(n, n, this.getValues());
if (a.length !== this.rows || ! this.isSquare()) {
for (var i = 0; i < m; i++) {
r.push(0);
}
} else {
/* Forward Elimination */
for (var j = 0; j < n-1; j++) {
for (var i = j+1; i < n; i++) {
l[i] = OP.division(R.getValue(i, j), R.getValue(j, j));
}
for (i = j+1; i < n; i++) {
R.setValue(i, j, 0);
for (var k = j+1; k < n; k++) {
R.setValue(i, k, OP.subtract(
R.getValue(i, k),
OP.product(l[i], R.getValue(j, k))));
}
a[i] = OP.subtract(a[i], OP.product(l[i], a[j]));
}
}
/* Backward solving */
for (i = n-1; i >= 0; i--) {
r[i] = a[i];
for (j = n-1; j > i; j--) {
r[i] = OP.subtract(r[i], OP.product(R.getValue(i, j), r[j]));
}
r[i] = this.d(r[i], R.getValue(i, i));
}
}
return new MAT(m, 1, r);
},
/*
* gramSchmidt
* The Gram-Schmidt process
* @return {object} matrix
*/
gramSchmidt : function() {
var m = this.rows,
n = this.columns,
e = [],
p, q = [], u, v;
/* Gram-Schmidt */
for (var i = 0; i < n; i++) {
u = this.getColumn(i);
for (var j = 0; j < i; j++) {
v = OP.division(
e[j].hermitian().product(this.getColumn(i)).getValue(0,0),
e[j].norm());
p = e[j].scalarProduct(v); // j-th projection
u = u.subtract(p);
}
e.push(u.scalarProduct(OP.division(1, u.norm())));
q = q.concat(e[i].toArray());
}
if (this.overwrite) {
this.rows = n;
this.columns = m;
this.values.splice(0, this.values.length, q);
}
return (this.overwrite ? this : new MAT(n, m, q)).transpose();
},
/*
* qrDecomposition
* QR decomposition
* @return {array} [Q,R]
*/
qrDecomposition : function() {
var Q, R;
Q = this.gramSchmidt();
R = Q.transpose().product(this);
return [Q, R];
},
/*
* Alias for the qrDecomposition function
*/
qr : function() {
return this.qrDecomposition();
},
/*
* luDecomposition
* LU decomposition
* @return {array} [L,U]
*/
luDecomposition : function() {
var l = [],
L = this.identity(this.columns),
U = new MAT(this.rows, this.columns, this.getValues());
for (var j = 0; j < this.columns - 1; j++) {
for (var i = j+1; i < this.columns; i++) {
l[i] = OP.division(U.getValue(i, j), U.getValue(j, j));
L.setValue(i, j, l[i]);
}
for (i = j+1; i < this.columns; i++) {
U.setValue(i, j, 0);
for (var k = j+1; k < this.columns; k++) {
U.setValue(i, k, OP.subtract(
U.getValue(i, k),
OP.product(l[i], U.getValue(j, k))));
}
}
}
return [L, U];
},
/*
* Alias for the luDecomposition
*/
lu : function() {
return this.luDecomposition();
},
/*
* eigenValues
* Eigenvalues using the QR iteration process
* @return {object} matrix
*/
eigenValues : function() {
var tmp = new MAT(this.rows, this.columns, this.getValues()),
l = Math.min(this.rows, this.columns),
QR,
values = [];
if ( ! this.isSquare()) {
throw ("eigenValues: matrix must be square");
} else {
for (var i = 0; i < this.maxrounds; i++) {
QR = tmp.qrDecomposition();
tmp = QR[1].product(QR[0]);
/*
* Stop the process when the values
* below the main diagonal are sufficiently small
*/
if (tmp.lowerTrace(1) < this.error) {
break;
}
}
for (var j = 0; j < l; j++) {
values.push(tmp.getValue(j, j));
}
}
return new MAT(l, 1, values);
},
/*
* eigenVectors
* @return {object} matrix
*/
eigenVectors : function() {
var tmp = new MAT(this.rows, this.columns, this.getValues()),
l = Math.min(this.rows, this.columns),
QR;
for (var i = 0; i < this.maxrounds; i++) {
QR = tmp.qrDecomposition();
tmp = QR[1].product(QR[0]);
/*
* Stop the process when the values
* below the main diagonal are sufficiently small
*/
if (tmp.lowerTrace(1) < this.error) {
break;
}
}
return QR[0];
},
/*
* identity
* @param {integer} size of the resulting matrix n*n
* @return {object} matrix
*/
identity : function(a) {
var values = [];
if (typeof a !== undefined && a > 0) {
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
values.push(i === j ? 1 : 0);
}
}
}
return new MAT(a, a, values);
},
/*
* diagonal
* @param {integer} a size
* @param {float|array} b (e.g. complex value [real,imag])
* @return {object} matrix
*/
diagonal : function(a, b) {
var values = [],
res;
if (typeof a === "undefined" || a <= 0) {
throw ("diagonal: first argument must be an integer greater than 0");
} else {
for (var i = 0; i < a; i++) {
for (var j = 0; j < a; j++) {
values.push(i === j ? b : 0);
}
}
res = new MAT(a, a, values);
}
return res;
},
/*
* pNorm
* @param {integer} a
* @return {float}
*/
pNorm : function(a) {
var res = 0,
tmp = 1;
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
tmp = 1;
for (var k = 0; k < a; k++) {
tmp = OP.product(tmp, OP.modulus(this.values[this.columns*i + j]));
}
res = OP.sum(res, tmp);
}
}
res = Math.pow(Math.E, OP.division(Math.log(res), a));
return res;
},
/*
* norm
* Euclidean norm (p = 2)
* @return {float}
*/
norm : function() {
return this.pNorm(2);
},
/*
* toToeplitz
* @param {integer} a
* @return {object} matrix
*/
toToeplitz : function(a) {
var res = [],
row = [],
l = 0,
m = this.values.length;
for (var i = 0; i < a; i++) {
row.push(0);
}
l = m+a-1;
/* column vector */
for (var i = 0; i < l; i++) {
if (i < m) {
if (this.isColumnVector()) {
/* column vector */
row.unshift(OP.conjugate(this.values[i]));
} else if (this.isRowVector()) {
row.unshift(this.values[i]);
} else {
/* do some stuff here */
}
} else {
row.unshift(0);
}
row.pop();
res = res.concat(row);
}
return new MAT(l, a, res);
},
/*
* inverse
* Matrix inverse
* @return {object} matrix
*/
inverse : function() {
var values = [],
det = this.determinant(),
sign = 1;
if (det === 0) {
throw ("inverse: unable to invert matrix, determinant is 0");
} else if ( ! this.isSquare()) {
throw ("inverse: matrix must be square");
} else {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.columns; j++) {
sign = (i+j)% 2 === 0 ? 1 : -1;
values.push(OP.product(sign,
OP.division(this.minor(i, j).det(), det)));
}
}
}
if (this.overwrite) {
this.values.splice(0, this.values.length, values);
}
return (this.overwrite ? this : new MAT(this.rows, this.columns, values)).hermitian();
},
/*
* pseudoInverse
* The Moore-Penrose Pseudoinverse
* @return {object} matrix
*/
pseudoInverse : function() {
var M = this.hermitian().product(this);
if (M.det() === 0) {
/* right inverse */
M = this.product(this.hermitian());
if (M.det() === 0) {
throw ("pseudoInverse: unable to invert matrix");
} else {
M = this.hermitian().product(M.inverse());
}
} else {
/* left inverse */
M = M.inverse().product(this.hermitian());
}
return M;
},
/*
* toVandermonde
* @param {integer} n (number of columns)
* @return {object} matrix
*/
toVandermonde : function(n) {
var values = [],
k = 0,
a = this.getValues(),
len = a.length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < n; j++) {
if (j === 0) {
values.push(1);
} else if (j === 1) {
values.push(a[i]);
} else {
values.push(OP.product(a[i], values[k-1]));
}
k++;
}
}
if (this.overwrite) {
this.rows = len;
this.columns = n;
this.values.splice(0, this.values.length, values);
}
return this.overwrite ? this : new MAT(len, n, values);
},
/*
* zero
* @return {object} a matrix filled with zeros
*/
zero : function() {
var values = [];
for (var i = 0, len = this.columns*this.rows; i < len; i++) {
values.push(0);
}
return new MAT(this.rows, this.columns, values);
},
}
return construct;
})();
| toArray now uses the slice method of the javascript Array object
| mat.js | toArray now uses the slice method of the javascript Array object | <ide><path>at.js
<ide> */
<ide> toArray : function () {
<ide>
<del> var res = [], n = this.values.length;
<del>
<del> for (var i = 0; i < n; i++) {
<del>
<del> res.push(this.values[i]);
<del>
<del> }
<del>
<del> return res;
<add> return this.values.slice(0);
<ide>
<ide> },
<ide> |
|
Java | mit | 826a04e8869bbd7dbc7b9a50f2fd3e88c869dc3d | 0 | bwkimmel/jmist | /**
*
*/
package ca.eandb.jmist.framework.measurement;
import java.util.Arrays;
import ca.eandb.jmist.math.MathUtil;
import ca.eandb.jmist.math.SphericalCoordinates;
import ca.eandb.jmist.math.Vector3;
/**
* A <code>CollectorSphere</code> where each stack of sensors spans the same
* polar angle.
* @author Brad Kimmel
*/
public final class EqualPolarAnglesCollectorSphere extends
AbstractCollectorSphere {
/**
* Creates a new <code>EqualPolarAnglesCollectorSphere</code>.
* @param stacks The number of stacks to divide each hemisphere into.
* @param slices The number of slices to divide the sphere into (about the
* azimuthal angle).
* @param upper A value indicating whether to record hits for the upper
* hemisphere.
* @param lower A value indicating whether to record hits for the lower
* hemisphere.
* @throws IllegalArgumentException if both <code>upper</code> and
* <code>lower</code> are <code>false</code>.
*/
public EqualPolarAnglesCollectorSphere(int stacks, int slices, boolean upper, boolean lower) {
super();
if (!upper && !lower) {
throw new IllegalArgumentException("One of upper or lower must be true.");
}
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
/* Each stack has "slices" sensors, except for the ones at the very top
* of the upper hemisphere and the bottom of the lower hemisphere,
* which have one (circular) patch.
*/
int sensors = hemispheres * ((stacks - 1) * slices + 1);
super.initialize(sensors);
this.stacks = stacks;
this.slices = slices;
this.upper = upper;
this.lower = lower;
if (stacks == 1) {
boundaries = new double[]{ Math.PI / 2.0 };
} else {
double theta = 0.5 * Math.PI / (double) (stacks - 1);
double A = (((double) slices) + 2.0 * Math.cos(theta)) / (double) (slices + 2);
double B;
boundaries = new double[stacks];
boundaries[0] = Math.acos(A);
for (int i = 1; i < stacks - 1; i++) {
theta = 0.5 * Math.PI * ((double) i / (double) (stacks - 1));
B = 2.0 * Math.cos(theta) - A;
boundaries[i] = Math.acos(B);
System.err.printf("theta=%f; theta_interval=(%f, %f)", Math.toDegrees(theta), Math.toDegrees(boundaries[i - 1]), Math.toDegrees(boundaries[i]));
System.err.println();
assert(MathUtil.inRangeOO(theta, boundaries[i-1], boundaries[i]));
A = B;
}
boundaries[stacks - 1] = 0.5 * Math.PI;
}
}
/**
* Creates a copy of an existing
* <code>EqualPolarAnglesCollectorSphere</code>.
* @param other The <code>EqualPolarAnglesCollectorSphere</code> to copy.
*/
public EqualPolarAnglesCollectorSphere(EqualPolarAnglesCollectorSphere other) {
super(other);
this.stacks = other.stacks;
this.slices = other.slices;
this.upper = other.upper;
this.lower = other.lower;
this.boundaries = other.boundaries;
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#clone()
*/
@Override
public CollectorSphere clone() {
return new EqualPolarAnglesCollectorSphere(this);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorCenter(int)
*/
public SphericalCoordinates getSensorCenter(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
assert(hemispheres > 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the center of
* a patch on the lower hemisphere, then compute the center of the
* corresponding patch on the upper hemisphere and then adjust it
* after.
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
int stack;
int slice;
if (sensor == 0) {
/* The first sensor is the one at the top (or bottom). */
stack = slice = 0;
} else { /* sensor > 0 */
stack = (sensor - 1) / slices + 1;
slice = (sensor - 1) % slices;
if (this.upper && this.lower && sensorOnLower) {
slice = slices - 1 - slice;
}
}
double phi = 2.0 * Math.PI * ((double) slice / (double) slices);
double theta = 0.5 * Math.PI * ((double) stack / (double) (stacks - 1));
if (sensorOnLower) {
theta = Math.PI - theta;
}
return SphericalCoordinates.canonical(theta, phi);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorProjectedSolidAngle(int)
*/
public double getSensorProjectedSolidAngle(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the projected
* solid angle of a patch on the lower hemisphere, then compute the
* projected solid angle of the corresponding patch on the upper
* hemisphere (they will be equal).
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
assert(0 <= sensor && sensor < patchesPerHemisphere);
int stack = (sensor > 0) ? (sensor - 1) / slices + 1 : 0;
if (sensor > 0) {
assert(stack > 0);
return 0.5 * Math.PI * (Math.cos(2.0 * boundaries[stack - 1]) - Math.cos(2.0 * boundaries[stack])) / (double) slices;
} else { /* sensor == 0 */
return 0.5 * Math.PI * (1.0 - Math.cos(2.0 * boundaries[0]));
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorSolidAngle(int)
*/
public double getSensorSolidAngle(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the projected
* solid angle of a patch on the lower hemisphere, then compute the
* projected solid angle of the corresponding patch on the upper
* hemisphere (they will be equal).
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
assert(0 <= sensor && sensor < patchesPerHemisphere);
int stack = (sensor > 0) ? (sensor - 1) / slices + 1 : 0;
if (sensor > 0) {
assert(stack > 0);
return 2.0 * Math.PI * (Math.cos(boundaries[stack - 1]) - Math.cos(boundaries[stack])) / (double) slices;
} else { /* sensor == 0 */
return 2.0 * Math.PI * (1.0 - Math.cos(boundaries[0]));
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#getSensor(ca.eandb.jmist.toolkit.SphericalCoordinates)
*/
@Override
protected int getSensor(SphericalCoordinates v) {
v = v.canonical();
double theta = v.polar();
double phi = v.azimuthal();
boolean hitUpper = theta < (0.5 * Math.PI);
if ((hitUpper && !upper) || (!hitUpper && !lower)) {
return AbstractCollectorSphere.MISS;
}
theta = upper ? theta : Math.PI - theta;
// int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int stack;
if (theta < 0.5 * Math.PI) {
stack = Arrays.binarySearch(boundaries, theta);
if (stack < 0) {
stack = -(stack + 1);
}
assert(stack < stacks);
} else { /* theta > 0.5 * Math.PI */
stack = Arrays.binarySearch(boundaries, Math.PI - theta);
if (stack < 0) {
stack = -(stack + 1);
}
assert(stack < stacks);
stack = 2 * stacks - 1 - stack;
}
if (stack == 0) {
return 0;
} else if (stack == 2 * stacks - 1) {
return sensors() - 1;
} else { /* 0 < stack < 2 * stacks - 1 */
phi += Math.PI / (double) slices;
if (phi < 0.0) phi += 2.0 * Math.PI;
if (phi >= 2.0 * Math.PI) phi -= 2.0 * Math.PI;
int slice = (int) ((double) slices * (phi / (2.0 * Math.PI)));
slice = MathUtil.threshold(slice, 0, slices - 1);
return 1 + (stack - 1) * slices + slice;
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#getSensor(ca.eandb.jmist.toolkit.Vector3)
*/
@Override
protected int getSensor(Vector3 v) {
return this.getSensor(SphericalCoordinates.fromCartesian(v));
}
/** The number of stacks per hemisphere. */
private final int stacks;
/** The number of slices. */
private final int slices;
/** A value indicating whether the upper hemisphere is measured. */
private final boolean upper;
/** A value indicating whether the lower hemisphere is measured. */
private final boolean lower;
private final double[] boundaries;
/**
* Serialization version ID.
*/
private static final long serialVersionUID = 6947672588017728172L;
}
| src/ca/eandb/jmist/framework/measurement/EqualPolarAnglesCollectorSphere.java | /**
*
*/
package ca.eandb.jmist.framework.measurement;
import java.util.Arrays;
import ca.eandb.jmist.math.MathUtil;
import ca.eandb.jmist.math.SphericalCoordinates;
import ca.eandb.jmist.math.Vector3;
/**
* A <code>CollectorSphere</code> where each stack of sensors spans the same
* polar angle.
* @author Brad Kimmel
*/
public final class EqualPolarAnglesCollectorSphere extends
AbstractCollectorSphere {
/**
* Creates a new <code>EqualPolarAnglesCollectorSphere</code>.
* @param stacks The number of stacks to divide each hemisphere into.
* @param slices The number of slices to divide the sphere into (about the
* azimuthal angle).
* @param upper A value indicating whether to record hits for the upper
* hemisphere.
* @param lower A value indicating whether to record hits for the lower
* hemisphere.
* @throws IllegalArgumentException if both <code>upper</code> and
* <code>lower</code> are <code>false</code>.
*/
public EqualPolarAnglesCollectorSphere(int stacks, int slices, boolean upper, boolean lower) {
super();
if (!upper && !lower) {
throw new IllegalArgumentException("One of upper or lower must be true.");
}
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
/* Each stack has "slices" sensors, except for the ones at the very top
* of the upper hemisphere and the bottom of the lower hemisphere,
* which have one (circular) patch.
*/
int sensors = hemispheres * ((stacks - 1) * slices + 1);
super.initialize(sensors);
this.stacks = stacks;
this.slices = slices;
this.upper = upper;
this.lower = lower;
if (stacks == 1) {
boundaries = new double[]{ Math.PI / 2.0 };
} else {
double theta = 0.5 * Math.PI / (double) (stacks - 1);
double A = (((double) slices) + 2.0 * Math.cos(theta)) / (double) (slices + 2);
double B;
boundaries = new double[stacks];
boundaries[0] = Math.acos(A);
for (int i = 1; i < stacks - 1; i++) {
theta = 0.5 * Math.PI * ((double) i / (double) (stacks - 1));
B = 2.0 * Math.cos(theta) - A;
boundaries[i] = Math.acos(B);
System.err.printf("theta=%f; theta_interval=(%f, %f)", Math.toDegrees(theta), Math.toDegrees(boundaries[i - 1]), Math.toDegrees(boundaries[i]));
System.err.println();
assert(MathUtil.inRangeOO(theta, boundaries[i-1], boundaries[i]));
A = B;
}
boundaries[stacks - 1] = 0.5 * Math.PI;
}
}
/**
* Creates a copy of an existing
* <code>EqualPolarAnglesCollectorSphere</code>.
* @param other The <code>EqualPolarAnglesCollectorSphere</code> to copy.
*/
public EqualPolarAnglesCollectorSphere(EqualPolarAnglesCollectorSphere other) {
super(other);
this.stacks = other.stacks;
this.slices = other.slices;
this.upper = other.upper;
this.lower = other.lower;
this.boundaries = other.boundaries;
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#clone()
*/
@Override
public CollectorSphere clone() {
return new EqualPolarAnglesCollectorSphere(this);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorCenter(int)
*/
public SphericalCoordinates getSensorCenter(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
assert(hemispheres > 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the center of
* a patch on the lower hemisphere, then compute the center of the
* corresponding patch on the upper hemisphere and then adjust it
* after.
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
int stack;
int slice;
if (sensor == 0) {
/* The first sensor is the one at the top (or bottom). */
stack = slice = 0;
} else { /* sensor > 0 */
stack = (sensor - 1) / slices + 1;
slice = (sensor - 1) % slices;
if (this.upper && this.lower && sensorOnLower) {
slice = slices - 1 - slice;
}
}
double phi = 2.0 * Math.PI * ((double) slice / (double) slices);
double theta = 0.5 * Math.PI * ((double) stack / (double) (stacks - 1));
if (sensorOnLower) {
theta = Math.PI - theta;
}
return SphericalCoordinates.canonical(theta, phi);
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorProjectedSolidAngle(int)
*/
public double getSensorProjectedSolidAngle(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the projected
* solid angle of a patch on the lower hemisphere, then compute the
* projected solid angle of the corresponding patch on the upper
* hemisphere (they will be equal).
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
assert(0 <= sensor && sensor < patchesPerHemisphere);
int stack = (sensor > 0) ? (sensor - 1) / slices + 1 : 0;
if (sensor > 0) {
assert(stack > 0);
return 0.5 * Math.PI * (Math.cos(2.0 * boundaries[stack - 1]) - Math.cos(2.0 * boundaries[stack])) / (double) slices;
} else { /* sensor == 0 */
return 0.5 * Math.PI * (1.0 - Math.cos(2.0 * boundaries[0]));
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.CollectorSphere#getSensorSolidAngle(int)
*/
public double getSensorSolidAngle(int sensor) {
int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int patchesPerHemisphere = this.sensors() / hemispheres;
/* The sensor is on the lower hemisphere if there is no upper
* hemisphere or if the sensor ID is in the second half of the
* sensors.
*/
boolean sensorOnLower = !upper || sensor >= patchesPerHemisphere;
/* If both hemispheres are present, and we are computing the projected
* solid angle of a patch on the lower hemisphere, then compute the
* projected solid angle of the corresponding patch on the upper
* hemisphere (they will be equal).
*/
if (upper && lower && sensorOnLower) {
sensor = this.sensors() - 1 - sensor;
}
assert(0 <= sensor && sensor < patchesPerHemisphere);
int stack = (sensor > 0) ? (sensor - 1) / slices + 1 : 0;
if (sensor > 0) {
assert(stack > 0);
return 2.0 * Math.PI * (Math.cos(boundaries[stack - 1]) - Math.cos(boundaries[stack])) / (double) slices;
} else { /* sensor == 0 */
return 2.0 * Math.PI * (1.0 - Math.cos(boundaries[0]));
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#getSensor(ca.eandb.jmist.toolkit.SphericalCoordinates)
*/
@Override
protected int getSensor(SphericalCoordinates v) {
v = v.canonical();
double theta = v.polar();
double phi = v.azimuthal();
boolean hitUpper = theta < (0.5 * Math.PI);
if ((hitUpper && !upper) || (!hitUpper && !lower)) {
return AbstractCollectorSphere.MISS;
}
theta = upper ? theta : Math.PI - theta;
// int hemispheres = (upper ? 1 : 0) + (lower ? 1 : 0);
int stack;
if (theta < 0.5 * Math.PI) {
stack = Arrays.binarySearch(boundaries, theta);
if (stack < 0) {
stack = -(stack + 1);
}
assert(stack < stacks);
} else { /* theta > 0.5 * Math.PI */
stack = Arrays.binarySearch(boundaries, Math.PI - theta);
if (stack < 0) {
stack = -(stack + 1);
}
assert(stack < stacks);
stack = 2 * stacks - 1 - stack;
}
if (stack == 0) {
return 0;
} else if (stack == 2 * stacks - 1) {
return sensors() - 1;
} else { /* 0 < stack < 2 * stacks - 1 */
if (phi < 0.0) phi += 2.0 * Math.PI;
if (phi >= 2.0 * Math.PI) phi -= 2.0 * Math.PI;
int slice = (int) ((double) slices / (phi / (2.0 * Math.PI)));
slice = MathUtil.threshold(slice, 0, slices - 1);
return 1 + (stack - 1) * slices + slice;
}
}
/* (non-Javadoc)
* @see ca.eandb.jmist.framework.measurement.AbstractCollectorSphere#getSensor(ca.eandb.jmist.toolkit.Vector3)
*/
@Override
protected int getSensor(Vector3 v) {
return this.getSensor(SphericalCoordinates.fromCartesian(v));
}
/** The number of stacks per hemisphere. */
private final int stacks;
/** The number of slices. */
private final int slices;
/** A value indicating whether the upper hemisphere is measured. */
private final boolean upper;
/** A value indicating whether the lower hemisphere is measured. */
private final boolean lower;
private final double[] boundaries;
/**
* Serialization version ID.
*/
private static final long serialVersionUID = 6947672588017728172L;
}
| Bug fix: EqualPolarAnglesCollectorSphere not computing correct slice based on azimuthal angle.
| src/ca/eandb/jmist/framework/measurement/EqualPolarAnglesCollectorSphere.java | Bug fix: EqualPolarAnglesCollectorSphere not computing correct slice based on azimuthal angle. | <ide><path>rc/ca/eandb/jmist/framework/measurement/EqualPolarAnglesCollectorSphere.java
<ide> } else if (stack == 2 * stacks - 1) {
<ide> return sensors() - 1;
<ide> } else { /* 0 < stack < 2 * stacks - 1 */
<add> phi += Math.PI / (double) slices;
<add>
<ide> if (phi < 0.0) phi += 2.0 * Math.PI;
<ide> if (phi >= 2.0 * Math.PI) phi -= 2.0 * Math.PI;
<ide>
<del> int slice = (int) ((double) slices / (phi / (2.0 * Math.PI)));
<add> int slice = (int) ((double) slices * (phi / (2.0 * Math.PI)));
<ide> slice = MathUtil.threshold(slice, 0, slices - 1);
<ide>
<ide> return 1 + (stack - 1) * slices + slice; |
|
Java | apache-2.0 | c38f4ff77cc187654cf427215b824c9240258dd8 | 0 | danielsun1106/groovy-parser,danielsun1106/groovy-parser | /*
* 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.groovy.parser.antlr4;
import groovy.lang.IntRange;
import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.groovy.parser.antlr4.internal.AtnManager;
import org.apache.groovy.parser.antlr4.internal.DescriptiveErrorStrategy;
import org.apache.groovy.parser.antlr4.util.StringUtils;
import org.apache.groovy.util.Maps;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.antlr.EnumHelper;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.EnumConstantClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.ImportNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.NodeMetaDataHandler;
import org.codehaus.groovy.ast.PackageNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.expr.AnnotationConstantExpression;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.AttributeExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BitwiseNegationExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ClosureListExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.ElvisOperatorExpression;
import org.codehaus.groovy.ast.expr.EmptyExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.LambdaExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.MethodPointerExpression;
import org.codehaus.groovy.ast.expr.MethodReferenceExpression;
import org.codehaus.groovy.ast.expr.NamedArgumentListExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.SpreadExpression;
import org.codehaus.groovy.ast.expr.SpreadMapExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.UnaryMinusExpression;
import org.codehaus.groovy.ast.expr.UnaryPlusExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.runtime.StringGroovyMethods;
import org.codehaus.groovy.syntax.Numbers;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.Types;
import org.objectweb.asm.Opcodes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.groovy.parser.antlr4.GroovyLangParser.*;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.last;
/**
* Building the AST from the parse tree generated by Antlr4
*
* @author <a href="mailto:[email protected]">Daniel.Sun</a>
* Created on 2016/08/14
*/
public class AstBuilder extends GroovyParserBaseVisitor<Object> implements GroovyParserVisitor<Object> {
public AstBuilder(SourceUnit sourceUnit, ClassLoader classLoader) {
this.sourceUnit = sourceUnit;
this.moduleNode = new ModuleNode(sourceUnit);
this.classLoader = classLoader; // unused for the time being
CharStream charStream = createCharStream(sourceUnit);
this.lexer = new GroovyLangLexer(charStream);
this.parser =
new GroovyLangParser(
new CommonTokenStream(this.lexer));
this.parser.setErrorHandler(new DescriptiveErrorStrategy(charStream));
this.tryWithResourcesASTTransformation = new TryWithResourcesASTTransformation(this);
this.groovydocManager = new GroovydocManager(this);
}
private CharStream createCharStream(SourceUnit sourceUnit) {
CharStream charStream;
try {
charStream = CharStreams.fromReader(
new BufferedReader(sourceUnit.getSource().getReader()),
sourceUnit.getName());
} catch (IOException e) {
throw new RuntimeException("Error occurred when reading source code.", e);
}
return charStream;
}
private GroovyParserRuleContext buildCST() throws CompilationFailedException {
GroovyParserRuleContext result;
try {
// parsing have to wait util clearing is complete.
AtnManager.RRWL.readLock().lock();
try {
result = buildCST(PredictionMode.SLL);
} catch (Throwable t) {
// if some syntax error occurred in the lexer, no need to retry the powerful LL mode
if (t instanceof GroovySyntaxError && GroovySyntaxError.LEXER == ((GroovySyntaxError) t).getSource()) {
throw t;
}
result = buildCST(PredictionMode.LL);
} finally {
AtnManager.RRWL.readLock().unlock();
}
} catch (Throwable t) {
throw convertException(t);
}
return result;
}
private GroovyParserRuleContext buildCST(PredictionMode predictionMode) {
parser.getInterpreter().setPredictionMode(predictionMode);
if (PredictionMode.SLL.equals(predictionMode)) {
this.removeErrorListeners();
} else {
parser.getInputStream().seek(0);
this.addErrorListeners();
}
return parser.compilationUnit();
}
private CompilationFailedException convertException(Throwable t) {
CompilationFailedException cfe;
if (t instanceof CompilationFailedException) {
cfe = (CompilationFailedException) t;
} else if (t instanceof ParseCancellationException) {
cfe = createParsingFailedException(t.getCause());
} else {
cfe = createParsingFailedException(t);
}
return cfe;
}
public ModuleNode buildAST() {
try {
return (ModuleNode) this.visit(this.buildCST());
} catch (Throwable t) {
throw convertException(t);
}
}
@Override
public ModuleNode visitCompilationUnit(CompilationUnitContext ctx) {
this.visit(ctx.packageDeclaration());
ctx.statement().stream()
.map(this::visit)
// .filter(e -> e instanceof Statement)
.forEach(e -> {
if (e instanceof DeclarationListStatement) { // local variable declaration
((DeclarationListStatement) e).getDeclarationStatements().forEach(moduleNode::addStatement);
} else if (e instanceof Statement) {
moduleNode.addStatement((Statement) e);
} else if (e instanceof MethodNode) { // script method
moduleNode.addMethod((MethodNode) e);
}
});
this.classNodeList.forEach(moduleNode::addClass);
if (this.isPackageInfoDeclaration()) {
this.addPackageInfoClassNode();
} else {
// if groovy source file only contains blank(including EOF), add "return null" to the AST
if (this.isBlankScript(ctx)) {
this.addEmptyReturnStatement();
}
}
this.configureScriptClassNode();
if (null != this.numberFormatError) {
throw createParsingFailedException(this.numberFormatError.value.getMessage(), this.numberFormatError.key);
}
return moduleNode;
}
@Override
public PackageNode visitPackageDeclaration(PackageDeclarationContext ctx) {
String packageName = this.visitQualifiedName(ctx.qualifiedName());
moduleNode.setPackageName(packageName + DOT_STR);
PackageNode packageNode = moduleNode.getPackage();
packageNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return this.configureAST(packageNode, ctx);
}
@Override
public ImportNode visitImportDeclaration(ImportDeclarationContext ctx) {
ImportNode importNode;
boolean hasStatic = asBoolean(ctx.STATIC());
boolean hasStar = asBoolean(ctx.MUL());
boolean hasAlias = asBoolean(ctx.alias);
List<AnnotationNode> annotationNodeList = this.visitAnnotationsOpt(ctx.annotationsOpt());
if (hasStatic) {
if (hasStar) { // e.g. import static java.lang.Math.*
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
ClassNode type = ClassHelper.make(qualifiedName);
this.configureAST(type, ctx);
moduleNode.addStaticStarImport(type.getText(), type, annotationNodeList);
importNode = last(moduleNode.getStaticStarImports().values());
} else { // e.g. import static java.lang.Math.pow
List<GroovyParserRuleContext> identifierList = new LinkedList<>(ctx.qualifiedName().qualifiedNameElement());
int identifierListSize = identifierList.size();
String name = identifierList.get(identifierListSize - 1).getText();
ClassNode classNode =
ClassHelper.make(
identifierList.stream()
.limit(identifierListSize - 1)
.map(ParseTree::getText)
.collect(Collectors.joining(DOT_STR)));
String alias = hasAlias
? ctx.alias.getText()
: name;
this.configureAST(classNode, ctx);
moduleNode.addStaticImport(classNode, name, alias, annotationNodeList);
importNode = last(moduleNode.getStaticImports().values());
}
} else {
if (hasStar) { // e.g. import java.util.*
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
moduleNode.addStarImport(qualifiedName + DOT_STR, annotationNodeList);
importNode = last(moduleNode.getStarImports());
} else { // e.g. import java.util.Map
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
String name = last(ctx.qualifiedName().qualifiedNameElement()).getText();
ClassNode classNode = ClassHelper.make(qualifiedName);
String alias = hasAlias
? ctx.alias.getText()
: name;
this.configureAST(classNode, ctx);
moduleNode.addImport(alias, classNode, annotationNodeList);
importNode = last(moduleNode.getImports());
}
}
return this.configureAST(importNode, ctx);
}
// statement { --------------------------------------------------------------------
@Override
public AssertStatement visitAssertStatement(AssertStatementContext ctx) {
Expression conditionExpression = (Expression) this.visit(ctx.ce);
if (conditionExpression instanceof BinaryExpression) {
BinaryExpression binaryExpression = (BinaryExpression) conditionExpression;
if (binaryExpression.getOperation().getType() == Types.ASSIGN) {
throw createParsingFailedException("Assignment expression is not allowed in the assert statement", conditionExpression);
}
}
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
if (!asBoolean(ctx.me)) {
return this.configureAST(
new AssertStatement(booleanExpression), ctx);
}
return this.configureAST(new AssertStatement(booleanExpression,
(Expression) this.visit(ctx.me)),
ctx);
}
@Override
public AssertStatement visitAssertStmtAlt(AssertStmtAltContext ctx) {
return this.configureAST(this.visitAssertStatement(ctx.assertStatement()), ctx);
}
@Override
public IfStatement visitIfElseStmtAlt(IfElseStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
Statement ifBlock =
this.unpackStatement(
(Statement) this.visit(ctx.tb));
Statement elseBlock =
this.unpackStatement(
asBoolean(ctx.ELSE())
? (Statement) this.visit(ctx.fb)
: EmptyStatement.INSTANCE);
return this.configureAST(new IfStatement(booleanExpression, ifBlock, elseBlock), ctx);
}
@Override
public Statement visitLoopStmtAlt(LoopStmtAltContext ctx) {
return this.configureAST((Statement) this.visit(ctx.loopStatement()), ctx);
}
@Override
public ForStatement visitForStmtAlt(ForStmtAltContext ctx) {
Pair<Parameter, Expression> controlPair = this.visitForControl(ctx.forControl());
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new ForStatement(controlPair.getKey(), controlPair.getValue(), asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public Pair<Parameter, Expression> visitForControl(ForControlContext ctx) {
if (asBoolean(ctx.enhancedForControl())) { // e.g. for(int i in 0..<10) {}
return this.visitEnhancedForControl(ctx.enhancedForControl());
}
if (asBoolean(ctx.classicalForControl())) { // e.g. for(int i = 0; i < 10; i++) {}
return this.visitClassicalForControl(ctx.classicalForControl());
}
throw createParsingFailedException("Unsupported for control: " + ctx.getText(), ctx);
}
@Override
public Expression visitForInit(ForInitContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
if (asBoolean(ctx.localVariableDeclaration())) {
DeclarationListStatement declarationListStatement = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration());
List<?> declarationExpressionList = declarationListStatement.getDeclarationExpressions();
if (declarationExpressionList.size() == 1) {
return this.configureAST((Expression) declarationExpressionList.get(0), ctx);
} else {
return this.configureAST(new ClosureListExpression((List<Expression>) declarationExpressionList), ctx);
}
}
if (asBoolean(ctx.expressionList())) {
return this.translateExpressionList(ctx.expressionList());
}
throw createParsingFailedException("Unsupported for init: " + ctx.getText(), ctx);
}
@Override
public Expression visitForUpdate(ForUpdateContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
return this.translateExpressionList(ctx.expressionList());
}
private Expression translateExpressionList(ExpressionListContext ctx) {
List<Expression> expressionList = this.visitExpressionList(ctx);
if (expressionList.size() == 1) {
return this.configureAST(expressionList.get(0), ctx);
} else {
return this.configureAST(new ClosureListExpression(expressionList), ctx);
}
}
@Override
public Pair<Parameter, Expression> visitEnhancedForControl(EnhancedForControlContext ctx) {
Parameter parameter = this.configureAST(
new Parameter(this.visitType(ctx.type()), this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()),
ctx.variableDeclaratorId());
// FIXME Groovy will ignore variableModifier of parameter in the for control
// In order to make the new parser behave same with the old one, we do not process variableModifier*
return new Pair<>(parameter, (Expression) this.visit(ctx.expression()));
}
@Override
public Pair<Parameter, Expression> visitClassicalForControl(ClassicalForControlContext ctx) {
ClosureListExpression closureListExpression = new ClosureListExpression();
closureListExpression.addExpression(this.visitForInit(ctx.forInit()));
closureListExpression.addExpression(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : EmptyExpression.INSTANCE);
closureListExpression.addExpression(this.visitForUpdate(ctx.forUpdate()));
return new Pair<>(ForStatement.FOR_LOOP_DUMMY, closureListExpression);
}
@Override
public WhileStatement visitWhileStmtAlt(WhileStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new WhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public DoWhileStatement visitDoWhileStmtAlt(DoWhileStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression),
conditionExpression
);
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new DoWhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public Statement visitTryCatchStmtAlt(TryCatchStmtAltContext ctx) {
return this.configureAST(this.visitTryCatchStatement(ctx.tryCatchStatement()), ctx);
}
@Override
public Statement visitTryCatchStatement(TryCatchStatementContext ctx) {
TryCatchStatement tryCatchStatement =
new TryCatchStatement((Statement) this.visit(ctx.block()),
this.visitFinallyBlock(ctx.finallyBlock()));
if (asBoolean(ctx.resources())) {
this.visitResources(ctx.resources()).forEach(tryCatchStatement::addResource);
}
ctx.catchClause().stream().map(this::visitCatchClause)
.reduce(new LinkedList<CatchStatement>(), (r, e) -> {
r.addAll(e); // merge several LinkedList<CatchStatement> instances into one LinkedList<CatchStatement> instance
return r;
})
.forEach(tryCatchStatement::addCatch);
return this.configureAST(
tryWithResourcesASTTransformation.transform(
this.configureAST(tryCatchStatement, ctx)),
ctx);
}
@Override
public List<ExpressionStatement> visitResources(ResourcesContext ctx) {
return this.visitResourceList(ctx.resourceList());
}
@Override
public List<ExpressionStatement> visitResourceList(ResourceListContext ctx) {
return ctx.resource().stream().map(this::visitResource).collect(Collectors.toList());
}
@Override
public ExpressionStatement visitResource(ResourceContext ctx) {
if (asBoolean(ctx.localVariableDeclaration())) {
List<ExpressionStatement> declarationStatements = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()).getDeclarationStatements();
if (declarationStatements.size() > 1) {
throw createParsingFailedException("Multi resources can not be declared in one statement", ctx);
}
return declarationStatements.get(0);
} else if (asBoolean(ctx.expression())) {
Expression expression = (Expression) this.visit(ctx.expression());
if (!(expression instanceof BinaryExpression
&& Types.ASSIGN == ((BinaryExpression) expression).getOperation().getType()
&& ((BinaryExpression) expression).getLeftExpression() instanceof VariableExpression)) {
throw createParsingFailedException("Only variable declarations are allowed to declare resource", ctx);
}
BinaryExpression assignmentExpression = (BinaryExpression) expression;
return this.configureAST(
new ExpressionStatement(
this.configureAST(
new DeclarationExpression(
this.configureAST(
new VariableExpression(assignmentExpression.getLeftExpression().getText()),
assignmentExpression.getLeftExpression()
),
assignmentExpression.getOperation(),
assignmentExpression.getRightExpression()
), ctx)
), ctx);
}
throw createParsingFailedException("Unsupported resource declaration: " + ctx.getText(), ctx);
}
/**
* Multi-catch(1..*) clause will be unpacked to several normal catch clauses, so the return type is List
*
* @param ctx the parse tree
* @return a list of CatchStatement instances
*/
@Override
public List<CatchStatement> visitCatchClause(CatchClauseContext ctx) {
// FIXME Groovy will ignore variableModifier of parameter in the catch clause
// In order to make the new parser behave same with the old one, we do not process variableModifier*
return this.visitCatchType(ctx.catchType()).stream()
.map(e -> this.configureAST(
new CatchStatement(
// FIXME The old parser does not set location info for the parameter of the catch clause.
// we could make it better
//this.configureAST(new Parameter(e, this.visitIdentifier(ctx.identifier())), ctx.Identifier()),
new Parameter(e, this.visitIdentifier(ctx.identifier())),
this.visitBlock(ctx.block())),
ctx))
.collect(Collectors.toList());
}
@Override
public List<ClassNode> visitCatchType(CatchTypeContext ctx) {
if (!asBoolean(ctx)) {
return Collections.singletonList(ClassHelper.OBJECT_TYPE);
}
return ctx.qualifiedClassName().stream()
.map(this::visitQualifiedClassName)
.collect(Collectors.toList());
}
@Override
public Statement visitFinallyBlock(FinallyBlockContext ctx) {
if (!asBoolean(ctx)) {
return EmptyStatement.INSTANCE;
}
return this.configureAST(
this.createBlockStatement((Statement) this.visit(ctx.block())),
ctx);
}
@Override
public SwitchStatement visitSwitchStmtAlt(SwitchStmtAltContext ctx) {
return this.configureAST(this.visitSwitchStatement(ctx.switchStatement()), ctx);
}
public SwitchStatement visitSwitchStatement(SwitchStatementContext ctx) {
List<Statement> statementList =
ctx.switchBlockStatementGroup().stream()
.map(this::visitSwitchBlockStatementGroup)
.reduce(new LinkedList<>(), (r, e) -> {
r.addAll(e);
return r;
});
List<CaseStatement> caseStatementList = new LinkedList<>();
List<Statement> defaultStatementList = new LinkedList<>();
statementList.forEach(e -> {
if (e instanceof CaseStatement) {
caseStatementList.add((CaseStatement) e);
} else if (isTrue(e, IS_SWITCH_DEFAULT)) {
defaultStatementList.add(e);
}
});
int defaultStatementListSize = defaultStatementList.size();
if (defaultStatementListSize > 1) {
throw createParsingFailedException("switch statement should have only one default case, which should appear at last", defaultStatementList.get(0));
}
if (defaultStatementListSize > 0 && last(statementList) instanceof CaseStatement) {
throw createParsingFailedException("default case should appear at last", defaultStatementList.get(0));
}
return this.configureAST(
new SwitchStatement(
this.visitExpressionInPar(ctx.expressionInPar()),
caseStatementList,
defaultStatementListSize == 0 ? EmptyStatement.INSTANCE : defaultStatementList.get(0)
),
ctx);
}
@Override
@SuppressWarnings({"unchecked"})
public List<Statement> visitSwitchBlockStatementGroup(SwitchBlockStatementGroupContext ctx) {
int labelCnt = ctx.switchLabel().size();
List<Token> firstLabelHolder = new ArrayList<>(1);
return (List<Statement>) ctx.switchLabel().stream()
.map(e -> (Object) this.visitSwitchLabel(e))
.reduce(new ArrayList<Statement>(4), (r, e) -> {
List<Statement> statementList = (List<Statement>) r;
Pair<Token, Expression> pair = (Pair<Token, Expression>) e;
boolean isLast = labelCnt - 1 == statementList.size();
switch (pair.getKey().getType()) {
case CASE: {
if (!asBoolean(statementList)) {
firstLabelHolder.add(pair.getKey());
}
statementList.add(
this.configureAST(
new CaseStatement(
pair.getValue(),
// check whether processing the last label. if yes, block statement should be attached.
isLast ? this.visitBlockStatements(ctx.blockStatements())
: EmptyStatement.INSTANCE
),
firstLabelHolder.get(0)));
break;
}
case DEFAULT: {
BlockStatement blockStatement = this.visitBlockStatements(ctx.blockStatements());
blockStatement.putNodeMetaData(IS_SWITCH_DEFAULT, true);
statementList.add(
// this.configureAST(blockStatement, pair.getKey())
blockStatement
);
break;
}
}
return statementList;
});
}
@Override
public Pair<Token, Expression> visitSwitchLabel(SwitchLabelContext ctx) {
if (asBoolean(ctx.CASE())) {
return new Pair<>(ctx.CASE().getSymbol(), (Expression) this.visit(ctx.expression()));
} else if (asBoolean(ctx.DEFAULT())) {
return new Pair<>(ctx.DEFAULT().getSymbol(), EmptyExpression.INSTANCE);
}
throw createParsingFailedException("Unsupported switch label: " + ctx.getText(), ctx);
}
@Override
public SynchronizedStatement visitSynchronizedStmtAlt(SynchronizedStmtAltContext ctx) {
return this.configureAST(
new SynchronizedStatement(this.visitExpressionInPar(ctx.expressionInPar()), this.visitBlock(ctx.block())),
ctx);
}
@Override
public ExpressionStatement visitExpressionStmtAlt(ExpressionStmtAltContext ctx) {
return (ExpressionStatement) this.visit(ctx.statementExpression());
}
@Override
public ReturnStatement visitReturnStmtAlt(ReturnStmtAltContext ctx) {
return this.configureAST(new ReturnStatement(asBoolean(ctx.expression())
? (Expression) this.visit(ctx.expression())
: ConstantExpression.EMPTY_EXPRESSION),
ctx);
}
@Override
public ThrowStatement visitThrowStmtAlt(ThrowStmtAltContext ctx) {
return this.configureAST(
new ThrowStatement((Expression) this.visit(ctx.expression())),
ctx);
}
@Override
public Statement visitLabeledStmtAlt(LabeledStmtAltContext ctx) {
Statement statement = (Statement) this.visit(ctx.statement());
statement.addStatementLabel(this.visitIdentifier(ctx.identifier()));
return statement; // this.configureAST(statement, ctx);
}
@Override
public BreakStatement visitBreakStatement(BreakStatementContext ctx) {
String label = asBoolean(ctx.identifier())
? this.visitIdentifier(ctx.identifier())
: null;
return this.configureAST(new BreakStatement(label), ctx);
}
@Override
public BreakStatement visitBreakStmtAlt(BreakStmtAltContext ctx) {
return this.configureAST(this.visitBreakStatement(ctx.breakStatement()), ctx);
}
@Override
public ContinueStatement visitContinueStatement(ContinueStatementContext ctx) {
String label = asBoolean(ctx.identifier())
? this.visitIdentifier(ctx.identifier())
: null;
return this.configureAST(new ContinueStatement(label), ctx);
}
@Override
public ContinueStatement visitContinueStmtAlt(ContinueStmtAltContext ctx) {
return this.configureAST(this.visitContinueStatement(ctx.continueStatement()), ctx);
}
@Override
public ImportNode visitImportStmtAlt(ImportStmtAltContext ctx) {
return this.configureAST(this.visitImportDeclaration(ctx.importDeclaration()), ctx);
}
@Override
public ClassNode visitTypeDeclarationStmtAlt(TypeDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitTypeDeclaration(ctx.typeDeclaration()), ctx);
}
@Override
public Statement visitLocalVariableDeclarationStmtAlt(LocalVariableDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx);
}
@Override
public MethodNode visitMethodDeclarationStmtAlt(MethodDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitMethodDeclaration(ctx.methodDeclaration()), ctx);
}
// } statement --------------------------------------------------------------------
@Override
public ClassNode visitTypeDeclaration(TypeDeclarationContext ctx) {
if (asBoolean(ctx.classDeclaration())) { // e.g. class A {}
ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitClassOrInterfaceModifiersOpt(ctx.classOrInterfaceModifiersOpt()));
return this.configureAST(this.visitClassDeclaration(ctx.classDeclaration()), ctx);
}
throw createParsingFailedException("Unsupported type declaration: " + ctx.getText(), ctx);
}
private void initUsingGenerics(ClassNode classNode) {
if (classNode.isUsingGenerics()) {
return;
}
if (!classNode.isEnum()) {
classNode.setUsingGenerics(classNode.getSuperClass().isUsingGenerics());
}
if (!classNode.isUsingGenerics() && null != classNode.getInterfaces()) {
for (ClassNode anInterface : classNode.getInterfaces()) {
classNode.setUsingGenerics(classNode.isUsingGenerics() || anInterface.isUsingGenerics());
if (classNode.isUsingGenerics())
break;
}
}
}
@Override
public ClassNode visitClassDeclaration(ClassDeclarationContext ctx) {
String packageName = moduleNode.getPackageName();
packageName = null != packageName ? packageName : "";
List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(TYPE_DECLARATION_MODIFIERS);
Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null");
ModifierManager modifierManager = new ModifierManager(this, modifierNodeList);
int modifiers = modifierManager.getClassModifiersOpValue();
boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0);
modifiers &= ~Opcodes.ACC_SYNTHETIC;
final ClassNode outerClass = classNodeStack.peek();
ClassNode classNode;
String className = this.visitIdentifier(ctx.identifier());
if (asBoolean(ctx.ENUM())) {
classNode =
EnumHelper.makeEnumNode(
asBoolean(outerClass) ? className : packageName + className,
modifiers, null, outerClass);
} else {
if (asBoolean(outerClass)) {
classNode =
new InnerClassNode(
outerClass,
outerClass.getName() + "$" + className,
modifiers | (outerClass.isInterface() ? Opcodes.ACC_STATIC : 0),
ClassHelper.OBJECT_TYPE);
} else {
classNode =
new ClassNode(
packageName + className,
modifiers,
ClassHelper.OBJECT_TYPE);
}
}
this.configureAST(classNode, ctx);
classNode.putNodeMetaData(CLASS_NAME, className);
classNode.setSyntheticPublic(syntheticPublic);
if (asBoolean(ctx.TRAIT())) {
classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT)));
}
classNode.addAnnotations(modifierManager.getAnnotations());
classNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters()));
boolean isInterface = asBoolean(ctx.INTERFACE()) && !asBoolean(ctx.AT());
boolean isInterfaceWithDefaultMethods = false;
// declaring interface with default method
if (isInterface && this.containsDefaultMethods(ctx)) {
isInterfaceWithDefaultMethods = true;
classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT)));
classNode.putNodeMetaData(IS_INTERFACE_WITH_DEFAULT_METHODS, true);
}
if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()) || isInterfaceWithDefaultMethods) { // class OR trait OR interface with default methods
classNode.setSuperClass(this.visitType(ctx.sc));
classNode.setInterfaces(this.visitTypeList(ctx.is));
this.initUsingGenerics(classNode);
} else if (isInterface) { // interface(NOT annotation)
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT);
classNode.setSuperClass(ClassHelper.OBJECT_TYPE);
classNode.setInterfaces(this.visitTypeList(ctx.scs));
this.initUsingGenerics(classNode);
this.hackMixins(classNode);
} else if (asBoolean(ctx.ENUM())) { // enum
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_ENUM | Opcodes.ACC_FINAL);
classNode.setInterfaces(this.visitTypeList(ctx.is));
this.initUsingGenerics(classNode);
} else if (asBoolean(ctx.AT())) { // annotation
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_ANNOTATION);
classNode.addInterface(ClassHelper.Annotation_TYPE);
this.hackMixins(classNode);
} else {
throw createParsingFailedException("Unsupported class declaration: " + ctx.getText(), ctx);
}
// we put the class already in output to avoid the most inner classes
// will be used as first class later in the loader. The first class
// there determines what GCL#parseClass for example will return, so we
// have here to ensure it won't be the inner class
if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT())) {
classNodeList.add(classNode);
}
int oldAnonymousInnerClassCounter = this.anonymousInnerClassCounter;
classNodeStack.push(classNode);
ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassBody(ctx.classBody());
classNodeStack.pop();
this.anonymousInnerClassCounter = oldAnonymousInnerClassCounter;
if (!(asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()))) {
classNodeList.add(classNode);
}
groovydocManager.handle(classNode, ctx);
return classNode;
}
@SuppressWarnings({"unchecked"})
private boolean containsDefaultMethods(ClassDeclarationContext ctx) {
List<MethodDeclarationContext> methodDeclarationContextList =
(List<MethodDeclarationContext>) ctx.classBody().classBodyDeclaration().stream()
.map(ClassBodyDeclarationContext::memberDeclaration)
.filter(Objects::nonNull)
.map(e -> (Object) e.methodDeclaration())
.filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> {
MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e;
if (createModifierManager(methodDeclarationContext).contains(DEFAULT)) {
((List) r).add(methodDeclarationContext);
}
return r;
});
return !methodDeclarationContextList.isEmpty();
}
@Override
public Void visitClassBody(ClassBodyContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.enumConstants())) {
ctx.enumConstants().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitEnumConstants(ctx.enumConstants());
}
ctx.classBodyDeclaration().forEach(e -> {
e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassBodyDeclaration(e);
});
return null;
}
@Override
public List<FieldNode> visitEnumConstants(EnumConstantsContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
return ctx.enumConstant().stream()
.map(e -> {
e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
return this.visitEnumConstant(e);
})
.collect(Collectors.toList());
}
@Override
public FieldNode visitEnumConstant(EnumConstantContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
InnerClassNode anonymousInnerClassNode = null;
if (asBoolean(ctx.anonymousInnerClassDeclaration())) {
ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode);
anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration());
}
FieldNode enumConstant =
EnumHelper.addEnumConstant(
classNode,
this.visitIdentifier(ctx.identifier()),
createEnumConstantInitExpression(ctx.arguments(), anonymousInnerClassNode));
enumConstant.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
groovydocManager.handle(enumConstant, ctx);
return this.configureAST(enumConstant, ctx);
}
private Expression createEnumConstantInitExpression(ArgumentsContext ctx, InnerClassNode anonymousInnerClassNode) {
if (!asBoolean(ctx) && !asBoolean(anonymousInnerClassNode)) {
return null;
}
TupleExpression argumentListExpression = (TupleExpression) this.visitArguments(ctx);
List<Expression> expressions = argumentListExpression.getExpressions();
if (expressions.size() == 1) {
Expression expression = expressions.get(0);
if (expression instanceof NamedArgumentListExpression) { // e.g. SOME_ENUM_CONSTANT(a: "1", b: "2")
List<MapEntryExpression> mapEntryExpressionList = ((NamedArgumentListExpression) expression).getMapEntryExpressions();
ListExpression listExpression =
new ListExpression(
mapEntryExpressionList.stream()
.map(e -> (Expression) e)
.collect(Collectors.toList()));
if (asBoolean(anonymousInnerClassNode)) {
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
}
if (mapEntryExpressionList.size() > 1) {
listExpression.setWrapped(true);
}
return this.configureAST(listExpression, ctx);
}
if (!asBoolean(anonymousInnerClassNode)) {
if (expression instanceof ListExpression) {
ListExpression listExpression = new ListExpression();
listExpression.addExpression(expression);
return this.configureAST(listExpression, ctx);
}
return expression;
}
ListExpression listExpression = new ListExpression();
if (expression instanceof ListExpression) {
((ListExpression) expression).getExpressions().forEach(listExpression::addExpression);
} else {
listExpression.addExpression(expression);
}
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
return this.configureAST(listExpression, ctx);
}
ListExpression listExpression = new ListExpression(expressions);
if (asBoolean(anonymousInnerClassNode)) {
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
}
if (asBoolean(ctx)) {
listExpression.setWrapped(true);
}
return asBoolean(ctx)
? this.configureAST(listExpression, ctx)
: this.configureAST(listExpression, anonymousInnerClassNode);
}
@Override
public Void visitClassBodyDeclaration(ClassBodyDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.memberDeclaration())) {
ctx.memberDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitMemberDeclaration(ctx.memberDeclaration());
} else if (asBoolean(ctx.block())) {
Statement statement = this.visitBlock(ctx.block());
if (asBoolean(ctx.STATIC())) { // e.g. static { }
classNode.addStaticInitializerStatements(Collections.singletonList(statement), false);
} else { // e.g. { }
classNode.addObjectInitializerStatements(
this.configureAST(
this.createBlockStatement(statement),
statement));
}
}
return null;
}
@Override
public Void visitMemberDeclaration(MemberDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.methodDeclaration())) {
ctx.methodDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitMethodDeclaration(ctx.methodDeclaration());
} else if (asBoolean(ctx.fieldDeclaration())) {
ctx.fieldDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitFieldDeclaration(ctx.fieldDeclaration());
} else if (asBoolean(ctx.classDeclaration())) {
ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitModifiersOpt(ctx.modifiersOpt()));
ctx.classDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassDeclaration(ctx.classDeclaration());
}
return null;
}
@Override
public GenericsType[] visitTypeParameters(TypeParametersContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return ctx.typeParameter().stream()
.map(this::visitTypeParameter)
.toArray(GenericsType[]::new);
}
@Override
public GenericsType visitTypeParameter(TypeParameterContext ctx) {
return this.configureAST(
new GenericsType(
this.configureAST(ClassHelper.make(this.visitClassName(ctx.className())), ctx),
this.visitTypeBound(ctx.typeBound()),
null
),
ctx);
}
@Override
public ClassNode[] visitTypeBound(TypeBoundContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return ctx.type().stream()
.map(this::visitType)
.toArray(ClassNode[]::new);
}
@Override
public Void visitFieldDeclaration(FieldDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
ctx.variableDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitVariableDeclaration(ctx.variableDeclaration());
return null;
}
private ConstructorCallExpression checkThisAndSuperConstructorCall(Statement statement) {
if (!(statement instanceof BlockStatement)) { // method code must be a BlockStatement
return null;
}
BlockStatement blockStatement = (BlockStatement) statement;
List<Statement> statementList = blockStatement.getStatements();
for (int i = 0, n = statementList.size(); i < n; i++) {
Statement s = statementList.get(i);
if (s instanceof ExpressionStatement) {
Expression expression = ((ExpressionStatement) s).getExpression();
if ((expression instanceof ConstructorCallExpression) && 0 != i) {
return (ConstructorCallExpression) expression;
}
}
}
return null;
}
private ModifierManager createModifierManager(MethodDeclarationContext ctx) {
List<ModifierNode> modifierNodeList = Collections.emptyList();
if (asBoolean(ctx.modifiers())) {
modifierNodeList = this.visitModifiers(ctx.modifiers());
} else if (asBoolean(ctx.modifiersOpt())) {
modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt());
}
return new ModifierManager(this, modifierNodeList);
}
private void validateParametersOfMethodDeclaration(Parameter[] parameters, ClassNode classNode) {
if (!classNode.isInterface()) {
return;
}
for (Parameter parameter : parameters) {
if (parameter.hasInitialExpression()) {
throw createParsingFailedException("Cannot specify default value for method parameter '" + parameter.getName() + " = " + parameter.getInitialExpression().getText() + "' inside an interface", parameter);
}
}
}
@Override
public MethodNode visitMethodDeclaration(MethodDeclarationContext ctx) {
ModifierManager modifierManager = createModifierManager(ctx);
String methodName = this.visitMethodName(ctx.methodName());
ClassNode returnType = this.visitReturnType(ctx.returnType());
Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters());
ClassNode[] exceptions = this.visitQualifiedClassNameList(ctx.qualifiedClassNameList());
anonymousInnerClassesDefinedInMethodStack.push(new LinkedList<>());
Statement code = this.visitMethodBody(ctx.methodBody());
List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.pop();
MethodNode methodNode;
// if classNode is not null, the method declaration is for class declaration
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
if (asBoolean(classNode)) {
validateParametersOfMethodDeclaration(parameters, classNode);
methodNode = createConstructorOrMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode);
} else { // script method declaration
methodNode = createScriptMethodNode(modifierManager, methodName, returnType, parameters, exceptions, code);
}
anonymousInnerClassList.forEach(e -> e.setEnclosingMethod(methodNode));
methodNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters()));
methodNode.setSyntheticPublic(
this.isSyntheticPublic(
this.isAnnotationDeclaration(classNode),
classNode instanceof EnumConstantClassNode,
asBoolean(ctx.returnType()),
modifierManager));
if (modifierManager.contains(STATIC)) {
for (Parameter parameter : methodNode.getParameters()) {
parameter.setInStaticContext(true);
}
methodNode.getVariableScope().setInStaticContext(true);
}
this.configureAST(methodNode, ctx);
validateMethodDeclaration(ctx, methodNode, modifierManager, classNode);
groovydocManager.handle(methodNode, ctx);
return methodNode;
}
private void validateMethodDeclaration(MethodDeclarationContext ctx, MethodNode methodNode, ModifierManager modifierManager, ClassNode classNode) {
boolean isAbstractMethod = methodNode.isAbstract();
boolean hasMethodBody = asBoolean(methodNode.getCode());
if (9 == ctx.ct) { // script
if (isAbstractMethod || !hasMethodBody) { // method should not be declared abstract in the script
throw createParsingFailedException("You can not define a " + (isAbstractMethod ? "abstract" : "") + " method[" + methodNode.getName() + "] " + (!hasMethodBody ? "without method body" : "") + " in the script. Try " + (isAbstractMethod ? "removing the 'abstract'" : "") + (isAbstractMethod && !hasMethodBody ? " and" : "") + (!hasMethodBody ? " adding a method body" : ""), methodNode);
}
} else {
if (!isAbstractMethod && !hasMethodBody) { // non-abstract method without body in the non-script(e.g. class, enum, trait) is not allowed!
throw createParsingFailedException("You defined a method[" + methodNode.getName() + "] without body. Try adding a method body, or declare it abstract", methodNode);
}
boolean isInterfaceOrAbstractClass = asBoolean(classNode) && classNode.isAbstract() && !classNode.isAnnotationDefinition();
if (isInterfaceOrAbstractClass && !modifierManager.contains(DEFAULT) && isAbstractMethod && hasMethodBody) {
throw createParsingFailedException("You defined an abstract method[" + methodNode.getName() + "] with body. Try removing the method body" + (classNode.isInterface() ? ", or declare it default" : ""), methodNode);
}
}
modifierManager.validate(methodNode);
if (methodNode instanceof ConstructorNode) {
modifierManager.validate((ConstructorNode) methodNode);
}
}
private MethodNode createScriptMethodNode(ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
MethodNode methodNode;
methodNode =
new MethodNode(
methodName,
modifierManager.contains(PRIVATE) ? Opcodes.ACC_PRIVATE : Opcodes.ACC_PUBLIC,
returnType,
parameters,
exceptions,
code);
modifierManager.processMethodNode(methodNode);
return methodNode;
}
private MethodNode createConstructorOrMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode) {
MethodNode methodNode;
String className = classNode.getNodeMetaData(CLASS_NAME);
int modifiers = modifierManager.getClassMemberModifiersOpValue();
boolean hasReturnType = asBoolean(ctx.returnType());
boolean hasMethodBody = asBoolean(ctx.methodBody());
if (!hasReturnType
&& hasMethodBody
&& methodName.equals(className)) { // constructor declaration
methodNode = createConstructorNodeForClass(methodName, parameters, exceptions, code, classNode, modifiers);
} else { // class memeber method declaration
if (!hasReturnType && hasMethodBody && (0 == modifierManager.getModifierCount())) {
throw createParsingFailedException("Invalid method declaration: " + methodName, ctx);
}
methodNode = createMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode, modifiers);
}
modifierManager.attachAnnotations(methodNode);
return methodNode;
}
private MethodNode createMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) {
MethodNode methodNode;
if (asBoolean(ctx.elementValue())) { // the code of annotation method
code = this.configureAST(
new ExpressionStatement(
this.visitElementValue(ctx.elementValue())),
ctx.elementValue());
}
modifiers |= !modifierManager.contains(STATIC) && (classNode.isInterface() || (isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && !modifierManager.contains(DEFAULT))) ? Opcodes.ACC_ABSTRACT : 0;
checkWhetherMethodNodeWithSameSignatureExists(classNode, methodName, parameters, ctx);
methodNode = classNode.addMethod(methodName, modifiers, returnType, parameters, exceptions, code);
methodNode.setAnnotationDefault(asBoolean(ctx.elementValue()));
return methodNode;
}
private void checkWhetherMethodNodeWithSameSignatureExists(ClassNode classNode, String methodName, Parameter[] parameters, MethodDeclarationContext ctx) {
MethodNode sameSigMethodNode = classNode.getDeclaredMethod(methodName, parameters);
if (null == sameSigMethodNode) {
return;
}
throw createParsingFailedException("The method " + sameSigMethodNode.getText() + " duplicates another method of the same signature", ctx);
}
private ConstructorNode createConstructorNodeForClass(String methodName, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) {
ConstructorCallExpression thisOrSuperConstructorCallExpression = this.checkThisAndSuperConstructorCall(code);
if (asBoolean(thisOrSuperConstructorCallExpression)) {
throw createParsingFailedException(thisOrSuperConstructorCallExpression.getText() + " should be the first statement in the constructor[" + methodName + "]", thisOrSuperConstructorCallExpression);
}
return classNode.addConstructor(
modifiers,
parameters,
exceptions,
code);
}
@Override
public String visitMethodName(MethodNameContext ctx) {
if (asBoolean(ctx.identifier())) {
return this.visitIdentifier(ctx.identifier());
}
if (asBoolean(ctx.stringLiteral())) {
return this.visitStringLiteral(ctx.stringLiteral()).getText();
}
throw createParsingFailedException("Unsupported method name: " + ctx.getText(), ctx);
}
@Override
public ClassNode visitReturnType(ReturnTypeContext ctx) {
if (!asBoolean(ctx)) {
return ClassHelper.OBJECT_TYPE;
}
if (asBoolean(ctx.type())) {
return this.visitType(ctx.type());
}
if (asBoolean(ctx.VOID())) {
return ClassHelper.VOID_TYPE;
}
throw createParsingFailedException("Unsupported return type: " + ctx.getText(), ctx);
}
@Override
public Statement visitMethodBody(MethodBodyContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return this.configureAST(this.visitBlock(ctx.block()), ctx);
}
@Override
public DeclarationListStatement visitLocalVariableDeclaration(LocalVariableDeclarationContext ctx) {
return this.configureAST(this.visitVariableDeclaration(ctx.variableDeclaration()), ctx);
}
private ModifierManager createModifierManager(VariableDeclarationContext ctx) {
List<ModifierNode> modifierNodeList = Collections.emptyList();
if (asBoolean(ctx.variableModifiers())) {
modifierNodeList = this.visitVariableModifiers(ctx.variableModifiers());
} else if (asBoolean(ctx.variableModifiersOpt())) {
modifierNodeList = this.visitVariableModifiersOpt(ctx.variableModifiersOpt());
} else if (asBoolean(ctx.modifiers())) {
modifierNodeList = this.visitModifiers(ctx.modifiers());
} else if (asBoolean(ctx.modifiersOpt())) {
modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt());
}
return new ModifierManager(this, modifierNodeList);
}
private DeclarationListStatement createMultiAssignmentDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager) {
if (!modifierManager.contains(DEF)) {
throw createParsingFailedException("keyword def is required to declare tuple, e.g. def (int a, int b) = [1, 2]", ctx);
}
return this.configureAST(
new DeclarationListStatement(
this.configureAST(
modifierManager.attachAnnotations(
new DeclarationExpression(
new ArgumentListExpression(
this.visitTypeNamePairs(ctx.typeNamePairs()).stream()
.peek(e -> modifierManager.processVariableExpression((VariableExpression) e))
.collect(Collectors.toList())
),
this.createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN),
this.visitVariableInitializer(ctx.variableInitializer())
)
),
ctx
)
),
ctx
);
}
@Override
public DeclarationListStatement visitVariableDeclaration(VariableDeclarationContext ctx) {
ModifierManager modifierManager = this.createModifierManager(ctx);
if (asBoolean(ctx.typeNamePairs())) { // e.g. def (int a, int b) = [1, 2]
return this.createMultiAssignmentDeclarationListStatement(ctx, modifierManager);
}
ClassNode variableType = this.visitType(ctx.type());
ctx.variableDeclarators().putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType);
List<DeclarationExpression> declarationExpressionList = this.visitVariableDeclarators(ctx.variableDeclarators());
// if classNode is not null, the variable declaration is for class declaration. In other words, it is a field declaration
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
if (asBoolean(classNode)) {
return createFieldDeclarationListStatement(ctx, modifierManager, variableType, declarationExpressionList, classNode);
}
declarationExpressionList.forEach(e -> {
VariableExpression variableExpression = (VariableExpression) e.getLeftExpression();
modifierManager.processVariableExpression(variableExpression);
modifierManager.attachAnnotations(e);
});
int size = declarationExpressionList.size();
if (size > 0) {
DeclarationExpression declarationExpression = declarationExpressionList.get(0);
if (1 == size) {
this.configureAST(declarationExpression, ctx);
} else {
// Tweak start of first declaration
declarationExpression.setLineNumber(ctx.getStart().getLine());
declarationExpression.setColumnNumber(ctx.getStart().getCharPositionInLine() + 1);
}
}
return this.configureAST(new DeclarationListStatement(declarationExpressionList), ctx);
}
private DeclarationListStatement createFieldDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, List<DeclarationExpression> declarationExpressionList, ClassNode classNode) {
for (int i = 0, n = declarationExpressionList.size(); i < n; i++) {
DeclarationExpression declarationExpression = declarationExpressionList.get(i);
VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression();
String fieldName = variableExpression.getName();
int modifiers = modifierManager.getClassMemberModifiersOpValue();
Expression initialValue = EmptyExpression.INSTANCE.equals(declarationExpression.getRightExpression()) ? null : declarationExpression.getRightExpression();
Object defaultValue = findDefaultValueByType(variableType);
if (classNode.isInterface()) {
if (!asBoolean(initialValue)) {
initialValue = !asBoolean(defaultValue) ? null : new ConstantExpression(defaultValue);
}
modifiers |= Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
}
if (isFieldDeclaration(modifierManager, classNode)) {
declareField(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue);
} else {
declareProperty(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue);
}
}
return null;
}
private void declareProperty(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) {
if (classNode.hasProperty(fieldName)) {
throw createParsingFailedException("The property '" + fieldName + "' is declared multiple times", ctx);
}
PropertyNode propertyNode;
FieldNode fieldNode = classNode.getDeclaredField(fieldName);
if (fieldNode != null && !classNode.hasProperty(fieldName)) {
classNode.getFields().remove(fieldNode);
propertyNode = new PropertyNode(fieldNode, modifiers | Opcodes.ACC_PUBLIC, null, null);
classNode.addProperty(propertyNode);
} else {
propertyNode =
classNode.addProperty(
fieldName,
modifiers | Opcodes.ACC_PUBLIC,
variableType,
initialValue,
null,
null);
fieldNode = propertyNode.getField();
}
fieldNode.setModifiers(modifiers & ~Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE);
fieldNode.setSynthetic(!classNode.isInterface());
modifierManager.attachAnnotations(fieldNode);
groovydocManager.handle(fieldNode, ctx);
groovydocManager.handle(propertyNode, ctx);
if (0 == i) {
this.configureAST(fieldNode, ctx, initialValue);
this.configureAST(propertyNode, ctx, initialValue);
} else {
this.configureAST(fieldNode, variableExpression, initialValue);
this.configureAST(propertyNode, variableExpression, initialValue);
}
}
private void declareField(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) {
FieldNode existingFieldNode = classNode.getDeclaredField(fieldName);
if (null != existingFieldNode && !existingFieldNode.isSynthetic()) {
throw createParsingFailedException("The field '" + fieldName + "' is declared multiple times", ctx);
}
FieldNode fieldNode;
PropertyNode propertyNode = classNode.getProperty(fieldName);
if (null != propertyNode && propertyNode.getField().isSynthetic()) {
classNode.getFields().remove(propertyNode.getField());
fieldNode = new FieldNode(fieldName, modifiers, variableType, classNode.redirect(), initialValue);
propertyNode.setField(fieldNode);
classNode.addField(fieldNode);
} else {
fieldNode =
classNode.addField(
fieldName,
modifiers,
variableType,
initialValue);
}
modifierManager.attachAnnotations(fieldNode);
groovydocManager.handle(fieldNode, ctx);
if (0 == i) {
this.configureAST(fieldNode, ctx, initialValue);
} else {
this.configureAST(fieldNode, variableExpression, initialValue);
}
}
private boolean isFieldDeclaration(ModifierManager modifierManager, ClassNode classNode) {
return classNode.isInterface() || modifierManager.containsVisibilityModifier();
}
@Override
public List<Expression> visitTypeNamePairs(TypeNamePairsContext ctx) {
return ctx.typeNamePair().stream().map(this::visitTypeNamePair).collect(Collectors.toList());
}
@Override
public VariableExpression visitTypeNamePair(TypeNamePairContext ctx) {
return this.configureAST(
new VariableExpression(
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(),
this.visitType(ctx.type())),
ctx);
}
@Override
public List<DeclarationExpression> visitVariableDeclarators(VariableDeclaratorsContext ctx) {
ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE);
Objects.requireNonNull(variableType, "variableType should not be null");
return ctx.variableDeclarator().stream()
.map(e -> {
e.putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType);
return this.visitVariableDeclarator(e);
// return this.configureAST(this.visitVariableDeclarator(e), ctx);
})
.collect(Collectors.toList());
}
@Override
public DeclarationExpression visitVariableDeclarator(VariableDeclaratorContext ctx) {
ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE);
Objects.requireNonNull(variableType, "variableType should not be null");
org.codehaus.groovy.syntax.Token token;
if (asBoolean(ctx.ASSIGN())) {
token = createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN);
} else {
token = new org.codehaus.groovy.syntax.Token(Types.ASSIGN, ASSIGN_STR, ctx.start.getLine(), 1);
}
return this.configureAST(
new DeclarationExpression(
this.configureAST(
new VariableExpression(
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(),
variableType
),
ctx.variableDeclaratorId()),
token,
this.visitVariableInitializer(ctx.variableInitializer())),
ctx);
}
@Override
public Expression visitVariableInitializer(VariableInitializerContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
return this.configureAST(
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()),
ctx);
}
@Override
public List<Expression> visitVariableInitializers(VariableInitializersContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return ctx.variableInitializer().stream()
.map(this::visitVariableInitializer)
.collect(Collectors.toList());
}
@Override
public List<Expression> visitArrayInitializer(ArrayInitializerContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.visitVariableInitializers(ctx.variableInitializers());
}
@Override
public Statement visitBlock(BlockContext ctx) {
if (!asBoolean(ctx)) {
return this.createBlockStatement();
}
return this.configureAST(
this.visitBlockStatementsOpt(ctx.blockStatementsOpt()),
ctx);
}
@Override
public ExpressionStatement visitNormalExprAlt(NormalExprAltContext ctx) {
return this.configureAST(new ExpressionStatement((Expression) this.visit(ctx.expression())), ctx);
}
@Override
public ExpressionStatement visitCommandExprAlt(CommandExprAltContext ctx) {
return this.configureAST(new ExpressionStatement(this.visitCommandExpression(ctx.commandExpression())), ctx);
}
@Override
public Expression visitCommandExpression(CommandExpressionContext ctx) {
Expression baseExpr = this.visitPathExpression(ctx.pathExpression());
Expression arguments = this.visitEnhancedArgumentList(ctx.enhancedArgumentList());
MethodCallExpression methodCallExpression;
if (baseExpr instanceof PropertyExpression) { // e.g. obj.a 1, 2
methodCallExpression =
this.configureAST(
this.createMethodCallExpression(
(PropertyExpression) baseExpr, arguments),
arguments);
} else if (baseExpr instanceof MethodCallExpression && !isInsideParentheses(baseExpr)) { // e.g. m {} a, b OR m(...) a, b
if (asBoolean(arguments)) {
// The error should never be thrown.
throw new GroovyBugError("When baseExpr is a instance of MethodCallExpression, which should follow NO argumentList");
}
methodCallExpression = (MethodCallExpression) baseExpr;
} else if (
!isInsideParentheses(baseExpr)
&& (baseExpr instanceof VariableExpression /* e.g. m 1, 2 */
|| baseExpr instanceof GStringExpression /* e.g. "$m" 1, 2 */
|| (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING)) /* e.g. "m" 1, 2 */)
) {
methodCallExpression =
this.configureAST(
this.createMethodCallExpression(baseExpr, arguments),
arguments);
} else { // e.g. a[x] b, new A() b, etc.
methodCallExpression =
this.configureAST(
new MethodCallExpression(
baseExpr,
CALL_STR,
arguments
),
arguments
);
methodCallExpression.setImplicitThis(false);
}
if (!asBoolean(ctx.commandArgument())) {
return this.configureAST(methodCallExpression, ctx);
}
return this.configureAST(
(Expression) ctx.commandArgument().stream()
.map(e -> (Object) e)
.reduce(methodCallExpression,
(r, e) -> {
CommandArgumentContext commandArgumentContext = (CommandArgumentContext) e;
commandArgumentContext.putNodeMetaData(CMD_EXPRESSION_BASE_EXPR, r);
return this.visitCommandArgument(commandArgumentContext);
}
),
ctx);
}
@Override
public Expression visitCommandArgument(CommandArgumentContext ctx) {
// e.g. x y a b we call "x y" as the base expression
Expression baseExpr = ctx.getNodeMetaData(CMD_EXPRESSION_BASE_EXPR);
Expression primaryExpr = (Expression) this.visit(ctx.primary());
if (asBoolean(ctx.enhancedArgumentList())) { // e.g. x y a b
if (baseExpr instanceof PropertyExpression) { // the branch should never reach, because a.b.c will be parsed as a path expression, not a method call
throw createParsingFailedException("Unsupported command argument: " + ctx.getText(), ctx);
}
// the following code will process "a b" of "x y a b"
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
this.createConstantExpression(primaryExpr),
this.visitEnhancedArgumentList(ctx.enhancedArgumentList())
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
} else if (asBoolean(ctx.pathElement())) { // e.g. x y a.b
Expression pathExpression =
this.createPathExpression(
this.configureAST(
new PropertyExpression(baseExpr, this.createConstantExpression(primaryExpr)),
primaryExpr
),
ctx.pathElement()
);
return this.configureAST(pathExpression, ctx);
}
// e.g. x y a
return this.configureAST(
new PropertyExpression(
baseExpr,
primaryExpr instanceof VariableExpression
? this.createConstantExpression(primaryExpr)
: primaryExpr
),
primaryExpr
);
}
// expression { --------------------------------------------------------------------
@Override
public ClassNode visitCastParExpression(CastParExpressionContext ctx) {
return this.visitType(ctx.type());
}
@Override
public Expression visitParExpression(ParExpressionContext ctx) {
Expression expression = this.visitExpressionInPar(ctx.expressionInPar());
Integer insideParenLevel = expression.getNodeMetaData(INSIDE_PARENTHESES_LEVEL);
if (null != insideParenLevel) {
insideParenLevel++;
} else {
insideParenLevel = 1;
}
expression.putNodeMetaData(INSIDE_PARENTHESES_LEVEL, insideParenLevel);
return this.configureAST(expression, ctx);
}
@Override
public Expression visitExpressionInPar(ExpressionInParContext ctx) {
return this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression());
}
@Override
public Expression visitEnhancedStatementExpression(EnhancedStatementExpressionContext ctx) {
Expression expression;
if (asBoolean(ctx.statementExpression())) {
expression = ((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression();
} else if (asBoolean(ctx.standardLambdaExpression())) {
expression = this.visitStandardLambdaExpression(ctx.standardLambdaExpression());
} else {
throw createParsingFailedException("Unsupported enhanced statement expression: " + ctx.getText(), ctx);
}
return this.configureAST(expression, ctx);
}
@Override
public Expression visitPathExpression(PathExpressionContext ctx) {
return //this.configureAST(
this.createPathExpression((Expression) this.visit(ctx.primary()), ctx.pathElement());
//ctx);
}
@Override
public Expression visitPathElement(PathElementContext ctx) {
Expression baseExpr = ctx.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR);
Objects.requireNonNull(baseExpr, "baseExpr is required!");
if (asBoolean(ctx.namePart())) {
Expression namePartExpr = this.visitNamePart(ctx.namePart());
GenericsType[] genericsTypes = this.visitNonWildcardTypeArguments(ctx.nonWildcardTypeArguments());
if (asBoolean(ctx.DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj.@a
return this.configureAST(new AttributeExpression(baseExpr, namePartExpr), ctx);
} else { // e.g. obj.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
return this.configureAST(propertyExpression, ctx);
}
} else if (asBoolean(ctx.SAFE_DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj?.@a
return this.configureAST(new AttributeExpression(baseExpr, namePartExpr, true), ctx);
} else { // e.g. obj?.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
return this.configureAST(propertyExpression, ctx);
}
} else if (asBoolean(ctx.METHOD_POINTER())) { // e.g. obj.&m
return this.configureAST(new MethodPointerExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.METHOD_REFERENCE())) { // e.g. obj::m
return this.configureAST(new MethodReferenceExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.SPREAD_DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj*.@a
AttributeExpression attributeExpression = new AttributeExpression(baseExpr, namePartExpr, true);
attributeExpression.setSpreadSafe(true);
return this.configureAST(attributeExpression, ctx);
} else { // e.g. obj*.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
propertyExpression.setSpreadSafe(true);
return this.configureAST(propertyExpression, ctx);
}
}
}
if (asBoolean(ctx.indexPropertyArgs())) { // e.g. list[1, 3, 5]
Pair<Token, Expression> pair = this.visitIndexPropertyArgs(ctx.indexPropertyArgs());
return this.configureAST(
new BinaryExpression(baseExpr, createGroovyToken(pair.getKey()), pair.getValue(), asBoolean(ctx.indexPropertyArgs().QUESTION())),
ctx);
}
if (asBoolean(ctx.namedPropertyArgs())) { // this is a special way to new instance, e.g. Person(name: 'Daniel.Sun', location: 'Shanghai')
List<MapEntryExpression> mapEntryExpressionList =
this.visitNamedPropertyArgs(ctx.namedPropertyArgs());
Expression right;
if (mapEntryExpressionList.size() == 1) {
MapEntryExpression mapEntryExpression = mapEntryExpressionList.get(0);
if (mapEntryExpression.getKeyExpression() instanceof SpreadMapExpression) {
right = mapEntryExpression.getKeyExpression();
} else {
right = mapEntryExpression;
}
} else {
ListExpression listExpression =
this.configureAST(
new ListExpression(
mapEntryExpressionList.stream()
.map(
e -> {
if (e.getKeyExpression() instanceof SpreadMapExpression) {
return e.getKeyExpression();
}
return e;
}
)
.collect(Collectors.toList())),
ctx.namedPropertyArgs()
);
listExpression.setWrapped(true);
right = listExpression;
}
return this.configureAST(
new BinaryExpression(baseExpr, createGroovyToken(ctx.namedPropertyArgs().LBRACK().getSymbol()), right),
ctx);
}
if (asBoolean(ctx.arguments())) {
Expression argumentsExpr = this.visitArguments(ctx.arguments());
this.configureAST(argumentsExpr, ctx);
if (isInsideParentheses(baseExpr)) { // e.g. (obj.x)(), (obj.@x)()
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
CALL_STR,
argumentsExpr
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof AttributeExpression) { // e.g. obj.@a(1, 2)
AttributeExpression attributeExpression = (AttributeExpression) baseExpr;
attributeExpression.setSpreadSafe(false); // whether attributeExpression is spread safe or not, we must reset it as false
MethodCallExpression methodCallExpression =
new MethodCallExpression(
attributeExpression,
CALL_STR,
argumentsExpr
);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof PropertyExpression) { // e.g. obj.a(1, 2)
MethodCallExpression methodCallExpression =
this.createMethodCallExpression((PropertyExpression) baseExpr, argumentsExpr);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof VariableExpression) { // void and primitive type AST node must be an instance of VariableExpression
String baseExprText = baseExpr.getText();
if (VOID_STR.equals(baseExprText)) { // e.g. void()
MethodCallExpression methodCallExpression =
new MethodCallExpression(
this.createConstantExpression(baseExpr),
CALL_STR,
argumentsExpr
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
} else if (PRIMITIVE_TYPE_SET.contains(baseExprText)) { // e.g. int(), long(), float(), etc.
throw createParsingFailedException("Primitive type literal: " + baseExprText + " cannot be used as a method name", ctx);
}
}
if (baseExpr instanceof VariableExpression
|| baseExpr instanceof GStringExpression
|| (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING))) { // e.g. m(), "$m"(), "m"()
String baseExprText = baseExpr.getText();
if (SUPER_STR.equals(baseExprText) || THIS_STR.equals(baseExprText)) { // e.g. this(...), super(...)
// class declaration is not allowed in the closure,
// so if this and super is inside the closure, it will not be constructor call.
// e.g. src/test/org/codehaus/groovy/transform/MapConstructorTransformTest.groovy:
// @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() })
if (ctx.isInsideClosure) {
return this.configureAST(
new MethodCallExpression(
baseExpr,
baseExprText,
argumentsExpr
),
ctx);
}
return this.configureAST(
new ConstructorCallExpression(
SUPER_STR.equals(baseExprText)
? ClassNode.SUPER
: ClassNode.THIS,
argumentsExpr
),
ctx);
}
MethodCallExpression methodCallExpression =
this.createMethodCallExpression(baseExpr, argumentsExpr);
return this.configureAST(methodCallExpression, ctx);
}
// e.g. 1(), 1.1(), ((int) 1 / 2)(1, 2), {a, b -> a + b }(1, 2), m()()
MethodCallExpression methodCallExpression =
new MethodCallExpression(baseExpr, CALL_STR, argumentsExpr);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (asBoolean(ctx.closure())) {
ClosureExpression closureExpression = this.visitClosure(ctx.closure());
if (baseExpr instanceof MethodCallExpression) {
MethodCallExpression methodCallExpression = (MethodCallExpression) baseExpr;
Expression argumentsExpression = methodCallExpression.getArguments();
if (argumentsExpression instanceof ArgumentListExpression) { // normal arguments, e.g. 1, 2
ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentsExpression;
argumentListExpression.getExpressions().add(closureExpression);
return this.configureAST(methodCallExpression, ctx);
}
if (argumentsExpression instanceof TupleExpression) { // named arguments, e.g. x: 1, y: 2
TupleExpression tupleExpression = (TupleExpression) argumentsExpression;
NamedArgumentListExpression namedArgumentListExpression = (NamedArgumentListExpression) tupleExpression.getExpression(0);
if (asBoolean(tupleExpression.getExpressions())) {
methodCallExpression.setArguments(
this.configureAST(
new ArgumentListExpression(
Stream.of(
this.configureAST(
new MapExpression(namedArgumentListExpression.getMapEntryExpressions()),
namedArgumentListExpression
),
closureExpression
).collect(Collectors.toList())
),
tupleExpression
)
);
} else {
// the branch should never reach, because named arguments must not be empty
methodCallExpression.setArguments(
this.configureAST(
new ArgumentListExpression(closureExpression),
tupleExpression));
}
return this.configureAST(methodCallExpression, ctx);
}
}
// e.g. 1 {}, 1.1 {}
if (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_NUMERIC)) {
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
CALL_STR,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression
)
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof PropertyExpression) { // e.g. obj.m { }
PropertyExpression propertyExpression = (PropertyExpression) baseExpr;
MethodCallExpression methodCallExpression =
this.createMethodCallExpression(
propertyExpression,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression
)
);
return this.configureAST(methodCallExpression, ctx);
}
// e.g. m { return 1; }
MethodCallExpression methodCallExpression =
new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
(baseExpr instanceof VariableExpression)
? this.createConstantExpression(baseExpr)
: baseExpr,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression)
);
return this.configureAST(methodCallExpression, ctx);
}
throw createParsingFailedException("Unsupported path element: " + ctx.getText(), ctx);
}
@Override
public GenericsType[] visitNonWildcardTypeArguments(NonWildcardTypeArgumentsContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return Arrays.stream(this.visitTypeList(ctx.typeList()))
.map(this::createGenericsType)
.toArray(GenericsType[]::new);
}
@Override
public ClassNode[] visitTypeList(TypeListContext ctx) {
if (!asBoolean(ctx)) {
return new ClassNode[0];
}
return ctx.type().stream()
.map(this::visitType)
.toArray(ClassNode[]::new);
}
@Override
public Expression visitArguments(ArgumentsContext ctx) {
if (!asBoolean(ctx) || !asBoolean(ctx.enhancedArgumentList())) {
return new ArgumentListExpression();
}
return this.configureAST(this.visitEnhancedArgumentList(ctx.enhancedArgumentList()), ctx);
}
@Override
public Expression visitEnhancedArgumentList(EnhancedArgumentListContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
List<Expression> expressionList = new LinkedList<>();
List<MapEntryExpression> mapEntryExpressionList = new LinkedList<>();
ctx.enhancedArgumentListElement().stream()
.map(this::visitEnhancedArgumentListElement)
.forEach(e -> {
if (e instanceof MapEntryExpression) {
MapEntryExpression mapEntryExpression = (MapEntryExpression) e;
validateDuplicatedNamedParameter(mapEntryExpressionList, mapEntryExpression);
mapEntryExpressionList.add(mapEntryExpression);
} else {
expressionList.add(e);
}
});
if (!asBoolean(mapEntryExpressionList)) { // e.g. arguments like 1, 2 OR someArg, e -> e
return this.configureAST(
new ArgumentListExpression(expressionList),
ctx);
}
if (!asBoolean(expressionList)) { // e.g. arguments like x: 1, y: 2
return this.configureAST(
new TupleExpression(
this.configureAST(
new NamedArgumentListExpression(mapEntryExpressionList),
ctx)),
ctx);
}
if (asBoolean(mapEntryExpressionList) && asBoolean(expressionList)) { // e.g. arguments like x: 1, 'a', y: 2, 'b', z: 3
ArgumentListExpression argumentListExpression = new ArgumentListExpression(expressionList);
argumentListExpression.getExpressions().add(0, new MapExpression(mapEntryExpressionList)); // TODO: confirm BUG OR NOT? All map entries will be put at first, which is not friendly to Groovy developers
return this.configureAST(argumentListExpression, ctx);
}
throw createParsingFailedException("Unsupported argument list: " + ctx.getText(), ctx);
}
private void validateDuplicatedNamedParameter(List<MapEntryExpression> mapEntryExpressionList, MapEntryExpression mapEntryExpression) {
Expression keyExpression = mapEntryExpression.getKeyExpression();
if (null == keyExpression) {
return;
}
String parameterName = keyExpression.getText();
boolean isDuplicatedNamedParameter = mapEntryExpressionList.stream().anyMatch(m -> m.getKeyExpression().getText().equals(parameterName));
if (!isDuplicatedNamedParameter) {
return;
}
throw createParsingFailedException("Duplicated named parameter '" + parameterName + "' found", mapEntryExpression);
}
@Override
public Expression visitEnhancedArgumentListElement(EnhancedArgumentListElementContext ctx) {
if (asBoolean(ctx.expressionListElement())) {
return this.configureAST(this.visitExpressionListElement(ctx.expressionListElement()), ctx);
}
if (asBoolean(ctx.standardLambdaExpression())) {
return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx);
}
if (asBoolean(ctx.mapEntry())) {
return this.configureAST(this.visitMapEntry(ctx.mapEntry()), ctx);
}
throw createParsingFailedException("Unsupported enhanced argument list element: " + ctx.getText(), ctx);
}
@Override
public ConstantExpression visitStringLiteral(StringLiteralContext ctx) {
String text = ctx.StringLiteral().getText();
int slashyType = text.startsWith("/") ? StringUtils.SLASHY :
text.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY;
if (text.startsWith("'''") || text.startsWith("\"\"\"")) {
text = StringUtils.removeCR(text); // remove CR in the multiline string
text = StringUtils.trimQuotations(text, 3);
} else if (text.startsWith("'") || text.startsWith("/") || text.startsWith("\"")) {
if (text.startsWith("/")) { // the slashy string can span rows, so we have to remove CR for it
text = StringUtils.removeCR(text); // remove CR in the multiline string
}
text = StringUtils.trimQuotations(text, 1);
} else if (text.startsWith("$/")) {
text = StringUtils.removeCR(text);
text = StringUtils.trimQuotations(text, 2);
}
//handle escapes.
text = StringUtils.replaceEscapes(text, slashyType);
ConstantExpression constantExpression = new ConstantExpression(text, true);
constantExpression.putNodeMetaData(IS_STRING, true);
return this.configureAST(constantExpression, ctx);
}
@Override
public Pair<Token, Expression> visitIndexPropertyArgs(IndexPropertyArgsContext ctx) {
List<Expression> expressionList = this.visitExpressionList(ctx.expressionList());
if (expressionList.size() == 1) {
Expression expr = expressionList.get(0);
Expression indexExpr;
if (expr instanceof SpreadExpression) { // e.g. a[*[1, 2]]
ListExpression listExpression = new ListExpression(expressionList);
listExpression.setWrapped(false);
indexExpr = listExpression;
} else { // e.g. a[1]
indexExpr = expr;
}
return new Pair<>(ctx.LBRACK().getSymbol(), indexExpr);
}
// e.g. a[1, 2]
ListExpression listExpression = new ListExpression(expressionList);
listExpression.setWrapped(true);
return new Pair<>(ctx.LBRACK().getSymbol(), this.configureAST(listExpression, ctx));
}
@Override
public List<MapEntryExpression> visitNamedPropertyArgs(NamedPropertyArgsContext ctx) {
return this.visitMapEntryList(ctx.mapEntryList());
}
@Override
public Expression visitNamePart(NamePartContext ctx) {
if (asBoolean(ctx.identifier())) {
return this.configureAST(new ConstantExpression(this.visitIdentifier(ctx.identifier())), ctx);
} else if (asBoolean(ctx.stringLiteral())) {
return this.configureAST(this.visitStringLiteral(ctx.stringLiteral()), ctx);
} else if (asBoolean(ctx.dynamicMemberName())) {
return this.configureAST(this.visitDynamicMemberName(ctx.dynamicMemberName()), ctx);
} else if (asBoolean(ctx.keywords())) {
return this.configureAST(new ConstantExpression(ctx.keywords().getText()), ctx);
}
throw createParsingFailedException("Unsupported name part: " + ctx.getText(), ctx);
}
@Override
public Expression visitDynamicMemberName(DynamicMemberNameContext ctx) {
if (asBoolean(ctx.parExpression())) {
return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx);
} else if (asBoolean(ctx.gstring())) {
return this.configureAST(this.visitGstring(ctx.gstring()), ctx);
}
throw createParsingFailedException("Unsupported dynamic member name: " + ctx.getText(), ctx);
}
@Override
public Expression visitPostfixExpression(PostfixExpressionContext ctx) {
Expression pathExpr = this.visitPathExpression(ctx.pathExpression());
if (asBoolean(ctx.op)) {
PostfixExpression postfixExpression = new PostfixExpression(pathExpr, createGroovyToken(ctx.op));
if (ctx.isInsideAssert) {
// powerassert requires different column for values, so we have to copy the location of op
return this.configureAST(postfixExpression, ctx.op);
} else {
return this.configureAST(postfixExpression, ctx);
}
}
return this.configureAST(pathExpr, ctx);
}
@Override
public Expression visitPostfixExprAlt(PostfixExprAltContext ctx) {
return this.visitPostfixExpression(ctx.postfixExpression());
}
@Override
public Expression visitUnaryNotExprAlt(UnaryNotExprAltContext ctx) {
if (asBoolean(ctx.NOT())) {
return this.configureAST(
new NotExpression((Expression) this.visit(ctx.expression())),
ctx);
}
if (asBoolean(ctx.BITNOT())) {
return this.configureAST(
new BitwiseNegationExpression((Expression) this.visit(ctx.expression())),
ctx);
}
throw createParsingFailedException("Unsupported unary expression: " + ctx.getText(), ctx);
}
@Override
public CastExpression visitCastExprAlt(CastExprAltContext ctx) {
return this.configureAST(
new CastExpression(
this.visitCastParExpression(ctx.castParExpression()),
(Expression) this.visit(ctx.expression())
),
ctx
);
}
@Override
public BinaryExpression visitPowerExprAlt(PowerExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public Expression visitUnaryAddExprAlt(UnaryAddExprAltContext ctx) {
ExpressionContext expressionCtx = ctx.expression();
Expression expression = (Expression) this.visit(expressionCtx);
Boolean insidePar = isInsideParentheses(expression);
switch (ctx.op.getType()) {
case ADD: {
if (expression instanceof ConstantExpression && !insidePar) {
return this.configureAST(expression, ctx);
}
return this.configureAST(new UnaryPlusExpression(expression), ctx);
}
case SUB: {
if (expression instanceof ConstantExpression && !insidePar) {
ConstantExpression constantExpression = (ConstantExpression) expression;
try {
String integerLiteralText = constantExpression.getNodeMetaData(INTEGER_LITERAL_TEXT);
if (null != integerLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseInteger(null, SUB_STR + integerLiteralText));
this.numberFormatError = null; // reset the numberFormatError
return this.configureAST(result, ctx);
}
String floatingPointLiteralText = constantExpression.getNodeMetaData(FLOATING_POINT_LITERAL_TEXT);
if (null != floatingPointLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseDecimal(SUB_STR + floatingPointLiteralText));
this.numberFormatError = null; // reset the numberFormatError
return this.configureAST(result, ctx);
}
} catch (Exception e) {
throw createParsingFailedException(e.getMessage(), ctx);
}
throw new GroovyBugError("Failed to find the original number literal text: " + constantExpression.getText());
}
return this.configureAST(new UnaryMinusExpression(expression), ctx);
}
case INC:
case DEC:
return this.configureAST(new PrefixExpression(this.createGroovyToken(ctx.op), expression), ctx);
default:
throw createParsingFailedException("Unsupported unary operation: " + ctx.getText(), ctx);
}
}
@Override
public BinaryExpression visitMultiplicativeExprAlt(MultiplicativeExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitAdditiveExprAlt(AdditiveExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public Expression visitShiftExprAlt(ShiftExprAltContext ctx) {
Expression left = (Expression) this.visit(ctx.left);
Expression right = (Expression) this.visit(ctx.right);
if (asBoolean(ctx.rangeOp)) {
return this.configureAST(new RangeExpression(left, right, !ctx.rangeOp.getText().endsWith("<")), ctx);
}
org.codehaus.groovy.syntax.Token op;
Token antlrToken;
if (asBoolean(ctx.dlOp)) {
op = this.createGroovyToken(ctx.dlOp, 2);
antlrToken = ctx.dlOp;
} else if (asBoolean(ctx.dgOp)) {
op = this.createGroovyToken(ctx.dgOp, 2);
antlrToken = ctx.dgOp;
} else if (asBoolean(ctx.tgOp)) {
op = this.createGroovyToken(ctx.tgOp, 3);
antlrToken = ctx.tgOp;
} else {
throw createParsingFailedException("Unsupported shift expression: " + ctx.getText(), ctx);
}
BinaryExpression binaryExpression = new BinaryExpression(left, op, right);
if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) {
return this.configureAST(binaryExpression, antlrToken);
}
return this.configureAST(binaryExpression, ctx);
}
@Override
public Expression visitRelationalExprAlt(RelationalExprAltContext ctx) {
switch (ctx.op.getType()) {
case AS:
return this.configureAST(
CastExpression.asExpression(this.visitType(ctx.type()), (Expression) this.visit(ctx.left)),
ctx);
case INSTANCEOF:
case NOT_INSTANCEOF:
ctx.type().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, true);
return this.configureAST(
new BinaryExpression((Expression) this.visit(ctx.left),
this.createGroovyToken(ctx.op),
this.configureAST(new ClassExpression(this.visitType(ctx.type())), ctx.type())),
ctx);
case LE:
case GE:
case GT:
case LT:
case IN:
case NOT_IN: {
if (ctx.op.getType() == IN || ctx.op.getType() == NOT_IN ) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
default:
throw createParsingFailedException("Unsupported relational expression: " + ctx.getText(), ctx);
}
}
@Override
public BinaryExpression visitEqualityExprAlt(EqualityExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitRegexExprAlt(RegexExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitAndExprAlt(AndExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitExclusiveOrExprAlt(ExclusiveOrExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitInclusiveOrExprAlt(InclusiveOrExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitLogicalAndExprAlt(LogicalAndExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitLogicalOrExprAlt(LogicalOrExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public Expression visitConditionalExprAlt(ConditionalExprAltContext ctx) {
ctx.fb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true);
if (asBoolean(ctx.ELVIS())) { // e.g. a == 6 ?: 0
return this.configureAST(
new ElvisOperatorExpression((Expression) this.visit(ctx.con), (Expression) this.visit(ctx.fb)),
ctx);
}
ctx.tb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true);
return this.configureAST(
new TernaryExpression(
this.configureAST(new BooleanExpression((Expression) this.visit(ctx.con)),
ctx.con),
(Expression) this.visit(ctx.tb),
(Expression) this.visit(ctx.fb)),
ctx);
}
@Override
public BinaryExpression visitMultipleAssignmentExprAlt(MultipleAssignmentExprAltContext ctx) {
return this.configureAST(
new BinaryExpression(
this.visitVariableNames(ctx.left),
this.createGroovyToken(ctx.op),
((ExpressionStatement) this.visit(ctx.right)).getExpression()),
ctx);
}
@Override
public BinaryExpression visitAssignmentExprAlt(AssignmentExprAltContext ctx) {
Expression leftExpr = (Expression) this.visit(ctx.left);
if (leftExpr instanceof VariableExpression
&& isInsideParentheses(leftExpr)) { // it is a special multiple assignment whose variable count is only one, e.g. (a) = [1]
if ((Integer) leftExpr.getNodeMetaData(INSIDE_PARENTHESES_LEVEL) > 1) {
throw createParsingFailedException("Nested parenthesis is not allowed in multiple assignment, e.g. ((a)) = b", ctx);
}
return this.configureAST(
new BinaryExpression(
this.configureAST(new TupleExpression(leftExpr), ctx.left),
this.createGroovyToken(ctx.op),
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())),
ctx);
}
// the LHS expression should be a variable which is not inside any parentheses
if (
!(
(leftExpr instanceof VariableExpression
// && !(THIS_STR.equals(leftExpr.getText()) || SUPER_STR.equals(leftExpr.getText())) // commented, e.g. this = value // this will be transformed to $this
&& !isInsideParentheses(leftExpr)) // e.g. p = 123
|| leftExpr instanceof PropertyExpression // e.g. obj.p = 123
|| (leftExpr instanceof BinaryExpression
// && !(((BinaryExpression) leftExpr).getRightExpression() instanceof ListExpression) // commented, e.g. list[1, 2] = [11, 12]
&& Types.LEFT_SQUARE_BRACKET == ((BinaryExpression) leftExpr).getOperation().getType()) // e.g. map[a] = 123 OR map['a'] = 123 OR map["$a"] = 123
)
) {
throw createParsingFailedException("The LHS of an assignment should be a variable or a field accessing expression", ctx);
}
return this.configureAST(
new BinaryExpression(
leftExpr,
this.createGroovyToken(ctx.op),
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())),
ctx);
}
// } expression --------------------------------------------------------------------
// primary { --------------------------------------------------------------------
@Override
public VariableExpression visitIdentifierPrmrAlt(IdentifierPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx);
}
@Override
public ConstantExpression visitLiteralPrmrAlt(LiteralPrmrAltContext ctx) {
return this.configureAST((ConstantExpression) this.visit(ctx.literal()), ctx);
}
@Override
public GStringExpression visitGstringPrmrAlt(GstringPrmrAltContext ctx) {
return this.configureAST((GStringExpression) this.visit(ctx.gstring()), ctx);
}
@Override
public Expression visitNewPrmrAlt(NewPrmrAltContext ctx) {
return this.configureAST(this.visitCreator(ctx.creator()), ctx);
}
@Override
public VariableExpression visitThisPrmrAlt(ThisPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(ctx.THIS().getText()), ctx);
}
@Override
public VariableExpression visitSuperPrmrAlt(SuperPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(ctx.SUPER().getText()), ctx);
}
@Override
public Expression visitParenPrmrAlt(ParenPrmrAltContext ctx) {
return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx);
}
@Override
public ClosureExpression visitClosurePrmrAlt(ClosurePrmrAltContext ctx) {
return this.configureAST(this.visitClosure(ctx.closure()), ctx);
}
@Override
public ClosureExpression visitLambdaPrmrAlt(LambdaPrmrAltContext ctx) {
return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx);
}
@Override
public ListExpression visitListPrmrAlt(ListPrmrAltContext ctx) {
return this.configureAST(
this.visitList(ctx.list()),
ctx);
}
@Override
public MapExpression visitMapPrmrAlt(MapPrmrAltContext ctx) {
return this.configureAST(this.visitMap(ctx.map()), ctx);
}
@Override
public VariableExpression visitTypePrmrAlt(TypePrmrAltContext ctx) {
return this.configureAST(
this.visitBuiltInType(ctx.builtInType()),
ctx);
}
// } primary --------------------------------------------------------------------
@Override
public Expression visitCreator(CreatorContext ctx) {
ClassNode classNode = this.visitCreatedName(ctx.createdName());
Expression arguments = this.visitArguments(ctx.arguments());
if (asBoolean(ctx.arguments())) { // create instance of class
if (asBoolean(ctx.anonymousInnerClassDeclaration())) {
ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode);
InnerClassNode anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration());
List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.peek();
if (null != anonymousInnerClassList) { // if the anonymous class is created in a script, no anonymousInnerClassList is available.
anonymousInnerClassList.add(anonymousInnerClassNode);
}
ConstructorCallExpression constructorCallExpression = new ConstructorCallExpression(anonymousInnerClassNode, arguments);
constructorCallExpression.setUsingAnonymousInnerClass(true);
return this.configureAST(constructorCallExpression, ctx);
}
return this.configureAST(
new ConstructorCallExpression(classNode, arguments),
ctx);
}
if (asBoolean(ctx.LBRACK()) || asBoolean(ctx.dims())) { // create array
ArrayExpression arrayExpression;
List<List<AnnotationNode>> allDimList;
if (asBoolean(ctx.arrayInitializer())) {
ClassNode elementType = classNode;
allDimList = this.visitDims(ctx.dims());
for (int i = 0, n = allDimList.size() - 1; i < n; i++) {
elementType = elementType.makeArray();
}
arrayExpression =
new ArrayExpression(
elementType,
this.visitArrayInitializer(ctx.arrayInitializer()));
} else {
Expression[] empties;
List<List<AnnotationNode>> emptyDimList = this.visitDimsOpt(ctx.dimsOpt());
if (asBoolean(emptyDimList)) {
empties = new Expression[emptyDimList.size()];
Arrays.setAll(empties, i -> ConstantExpression.EMPTY_EXPRESSION);
} else {
empties = new Expression[0];
}
arrayExpression =
new ArrayExpression(
classNode,
null,
Stream.concat(
ctx.expression().stream()
.map(e -> (Expression) this.visit(e)),
Arrays.stream(empties)
).collect(Collectors.toList()));
List<List<AnnotationNode>> exprDimList = ctx.annotationsOpt().stream().map(this::visitAnnotationsOpt).collect(Collectors.toList());
allDimList = new ArrayList<>(exprDimList);
Collections.reverse(emptyDimList);
allDimList.addAll(emptyDimList);
Collections.reverse(allDimList);
}
arrayExpression.setType(createArrayType(classNode, allDimList));
return this.configureAST(arrayExpression, ctx);
}
throw createParsingFailedException("Unsupported creator: " + ctx.getText(), ctx);
}
private ClassNode createArrayType(ClassNode classNode, List<List<AnnotationNode>> dimList) {
ClassNode arrayType = classNode;
for (int i = 0, n = dimList.size(); i < n; i++) {
arrayType = arrayType.makeArray();
arrayType.addAnnotations(dimList.get(i));
}
return arrayType;
}
private String genAnonymousClassName(String outerClassName) {
return outerClassName + "$" + this.anonymousInnerClassCounter++;
}
@Override
public InnerClassNode visitAnonymousInnerClassDeclaration(AnonymousInnerClassDeclarationContext ctx) {
ClassNode superClass = ctx.getNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS);
Objects.requireNonNull(superClass, "superClass should not be null");
InnerClassNode anonymousInnerClass;
ClassNode outerClass = this.classNodeStack.peek();
outerClass = asBoolean(outerClass) ? outerClass : moduleNode.getScriptClassDummy();
String fullName = this.genAnonymousClassName(outerClass.getName());
if (1 == ctx.t) { // anonymous enum
anonymousInnerClass = new EnumConstantClassNode(outerClass, fullName, superClass.getModifiers() | Opcodes.ACC_FINAL, superClass.getPlainNodeReference());
// and remove the final modifier from classNode to allow the sub class
superClass.setModifiers(superClass.getModifiers() & ~Opcodes.ACC_FINAL);
} else { // anonymous inner class
anonymousInnerClass = new InnerClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, superClass);
}
anonymousInnerClass.setUsingGenerics(false);
anonymousInnerClass.setAnonymous(true);
anonymousInnerClass.putNodeMetaData(CLASS_NAME, fullName);
this.configureAST(anonymousInnerClass, ctx);
classNodeStack.push(anonymousInnerClass);
ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, anonymousInnerClass);
this.visitClassBody(ctx.classBody());
classNodeStack.pop();
classNodeList.add(anonymousInnerClass);
return anonymousInnerClass;
}
@Override
public ClassNode visitCreatedName(CreatedNameContext ctx) {
ClassNode classNode = null;
if (asBoolean(ctx.qualifiedClassName())) {
classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
if (asBoolean(ctx.typeArgumentsOrDiamond())) {
classNode.setGenericsTypes(
this.visitTypeArgumentsOrDiamond(ctx.typeArgumentsOrDiamond()));
}
classNode = this.configureAST(classNode, ctx);
} else if (asBoolean(ctx.primitiveType())) {
classNode = this.configureAST(
this.visitPrimitiveType(ctx.primitiveType()),
ctx);
}
if (!asBoolean(classNode)) {
throw createParsingFailedException("Unsupported created name: " + ctx.getText(), ctx);
}
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return classNode;
}
@Override
public MapExpression visitMap(MapContext ctx) {
return this.configureAST(
new MapExpression(this.visitMapEntryList(ctx.mapEntryList())),
ctx);
}
@Override
public List<MapEntryExpression> visitMapEntryList(MapEntryListContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.createMapEntryList(ctx.mapEntry());
}
private List<MapEntryExpression> createMapEntryList(List<? extends MapEntryContext> mapEntryContextList) {
if (!asBoolean(mapEntryContextList)) {
return Collections.emptyList();
}
return mapEntryContextList.stream()
.map(this::visitMapEntry)
.collect(Collectors.toList());
}
@Override
public MapEntryExpression visitMapEntry(MapEntryContext ctx) {
Expression keyExpr;
Expression valueExpr = (Expression) this.visit(ctx.expression());
if (asBoolean(ctx.MUL())) {
keyExpr = this.configureAST(new SpreadMapExpression(valueExpr), ctx);
} else if (asBoolean(ctx.mapEntryLabel())) {
keyExpr = this.visitMapEntryLabel(ctx.mapEntryLabel());
} else {
throw createParsingFailedException("Unsupported map entry: " + ctx.getText(), ctx);
}
return this.configureAST(
new MapEntryExpression(keyExpr, valueExpr),
ctx);
}
@Override
public Expression visitMapEntryLabel(MapEntryLabelContext ctx) {
if (asBoolean(ctx.keywords())) {
return this.configureAST(this.visitKeywords(ctx.keywords()), ctx);
} else if (asBoolean(ctx.primary())) {
Expression expression = (Expression) this.visit(ctx.primary());
// if the key is variable and not inside parentheses, convert it to a constant, e.g. [a:1, b:2]
if (expression instanceof VariableExpression && !isInsideParentheses(expression)) {
expression =
this.configureAST(
new ConstantExpression(((VariableExpression) expression).getName()),
expression);
}
return this.configureAST(expression, ctx);
}
throw createParsingFailedException("Unsupported map entry label: " + ctx.getText(), ctx);
}
@Override
public ConstantExpression visitKeywords(KeywordsContext ctx) {
return this.configureAST(new ConstantExpression(ctx.getText()), ctx);
}
/*
@Override
public VariableExpression visitIdentifier(IdentifierContext ctx) {
return this.configureAST(new VariableExpression(ctx.getText()), ctx);
}
*/
@Override
public VariableExpression visitBuiltInType(BuiltInTypeContext ctx) {
String text;
if (asBoolean(ctx.VOID())) {
text = ctx.VOID().getText();
} else if (asBoolean(ctx.BuiltInPrimitiveType())) {
text = ctx.BuiltInPrimitiveType().getText();
} else {
throw createParsingFailedException("Unsupported built-in type: " + ctx, ctx);
}
return this.configureAST(new VariableExpression(text), ctx);
}
@Override
public ListExpression visitList(ListContext ctx) {
return this.configureAST(
new ListExpression(
this.visitExpressionList(ctx.expressionList())),
ctx);
}
@Override
public List<Expression> visitExpressionList(ExpressionListContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.createExpressionList(ctx.expressionListElement());
}
private List<Expression> createExpressionList(List<? extends ExpressionListElementContext> expressionListElementContextList) {
if (!asBoolean(expressionListElementContextList)) {
return Collections.emptyList();
}
return expressionListElementContextList.stream()
.map(this::visitExpressionListElement)
.collect(Collectors.toList());
}
@Override
public Expression visitExpressionListElement(ExpressionListElementContext ctx) {
Expression expression = (Expression) this.visit(ctx.expression());
if (asBoolean(ctx.MUL())) {
return this.configureAST(new SpreadExpression(expression), ctx);
}
return this.configureAST(expression, ctx);
}
// literal { --------------------------------------------------------------------
@Override
public ConstantExpression visitIntegerLiteralAlt(IntegerLiteralAltContext ctx) {
String text = ctx.IntegerLiteral().getText();
Number num = null;
try {
num = Numbers.parseInteger(null, text);
} catch (Exception e) {
this.numberFormatError = new Pair<>(ctx, e);
}
ConstantExpression constantExpression = new ConstantExpression(num, !text.startsWith(SUB_STR));
constantExpression.putNodeMetaData(IS_NUMERIC, true);
constantExpression.putNodeMetaData(INTEGER_LITERAL_TEXT, text);
return this.configureAST(constantExpression, ctx);
}
@Override
public ConstantExpression visitFloatingPointLiteralAlt(FloatingPointLiteralAltContext ctx) {
String text = ctx.FloatingPointLiteral().getText();
Number num = null;
try {
num = Numbers.parseDecimal(text);
} catch (Exception e) {
this.numberFormatError = new Pair<>(ctx, e);
}
ConstantExpression constantExpression = new ConstantExpression(num, !text.startsWith(SUB_STR));
constantExpression.putNodeMetaData(IS_NUMERIC, true);
constantExpression.putNodeMetaData(FLOATING_POINT_LITERAL_TEXT, text);
return this.configureAST(constantExpression, ctx);
}
@Override
public ConstantExpression visitStringLiteralAlt(StringLiteralAltContext ctx) {
return this.configureAST(
this.visitStringLiteral(ctx.stringLiteral()),
ctx);
}
@Override
public ConstantExpression visitBooleanLiteralAlt(BooleanLiteralAltContext ctx) {
return this.configureAST(new ConstantExpression("true".equals(ctx.BooleanLiteral().getText()), true), ctx);
}
@Override
public ConstantExpression visitNullLiteralAlt(NullLiteralAltContext ctx) {
return this.configureAST(new ConstantExpression(null), ctx);
}
// } literal --------------------------------------------------------------------
// gstring { --------------------------------------------------------------------
@Override
public GStringExpression visitGstring(GstringContext ctx) {
List<ConstantExpression> strings = new LinkedList<>();
String begin = ctx.GStringBegin().getText();
final int slashyType = begin.startsWith("/")
? StringUtils.SLASHY
: begin.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY;
{
String it = begin;
if (it.startsWith("\"\"\"")) {
it = StringUtils.removeCR(it);
it = it.substring(2); // translate leading """ to "
} else if (it.startsWith("$/")) {
it = StringUtils.removeCR(it);
it = "\"" + it.substring(2); // translate leading $/ to "
} else if (it.startsWith("/")) {
it = StringUtils.removeCR(it);
}
it = StringUtils.replaceEscapes(it, slashyType);
it = (it.length() == 2)
? ""
: StringGroovyMethods.getAt(it, new IntRange(true, 1, -2));
strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringBegin()));
}
List<ConstantExpression> partStrings =
ctx.GStringPart().stream()
.map(e -> {
String it = e.getText();
it = StringUtils.removeCR(it);
it = StringUtils.replaceEscapes(it, slashyType);
it = it.length() == 1 ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2));
return this.configureAST(new ConstantExpression(it), e);
}).collect(Collectors.toList());
strings.addAll(partStrings);
{
String it = ctx.GStringEnd().getText();
if (it.endsWith("\"\"\"")) {
it = StringUtils.removeCR(it);
it = StringGroovyMethods.getAt(it, new IntRange(true, 0, -3)); // translate tailing """ to "
} else if (it.endsWith("/$")) {
it = StringUtils.removeCR(it);
it = StringGroovyMethods.getAt(it, new IntRange(false, 0, -2)) + "\""; // translate tailing /$ to "
} else if (it.endsWith("/")) {
it = StringUtils.removeCR(it);
}
it = StringUtils.replaceEscapes(it, slashyType);
it = (it.length() == 1)
? ""
: StringGroovyMethods.getAt(it, new IntRange(true, 0, -2));
strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringEnd()));
}
List<Expression> values = ctx.gstringValue().stream()
.map(e -> {
Expression expression = this.visitGstringValue(e);
if (expression instanceof ClosureExpression && !asBoolean(e.closure().ARROW())) {
List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements();
if (statementList.stream().noneMatch(x -> asBoolean(x))) {
return this.configureAST(new ConstantExpression(null), e);
}
return this.configureAST(new MethodCallExpression(expression, CALL_STR, new ArgumentListExpression()), e);
}
return expression;
})
.collect(Collectors.toList());
StringBuilder verbatimText = new StringBuilder(ctx.getText().length());
for (int i = 0, n = strings.size(), s = values.size(); i < n; i++) {
verbatimText.append(strings.get(i).getValue());
if (i == s) {
continue;
}
Expression value = values.get(i);
if (!asBoolean(value)) {
continue;
}
verbatimText.append(DOLLAR_STR);
verbatimText.append(value.getText());
}
return this.configureAST(new GStringExpression(verbatimText.toString(), strings, values), ctx);
}
@Override
public Expression visitGstringValue(GstringValueContext ctx) {
if (asBoolean(ctx.gstringPath())) {
return this.configureAST(this.visitGstringPath(ctx.gstringPath()), ctx);
}
if (asBoolean(ctx.LBRACE())) {
if (asBoolean(ctx.statementExpression())) {
return this.configureAST(((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(), ctx.statementExpression());
} else { // e.g. "${}"
return this.configureAST(new ConstantExpression(null), ctx);
}
}
if (asBoolean(ctx.closure())) {
return this.configureAST(this.visitClosure(ctx.closure()), ctx);
}
throw createParsingFailedException("Unsupported gstring value: " + ctx.getText(), ctx);
}
@Override
public Expression visitGstringPath(GstringPathContext ctx) {
VariableExpression variableExpression = new VariableExpression(this.visitIdentifier(ctx.identifier()));
if (asBoolean(ctx.GStringPathPart())) {
Expression propertyExpression = ctx.GStringPathPart().stream()
.map(e -> this.configureAST((Expression) new ConstantExpression(e.getText().substring(1)), e))
.reduce(this.configureAST(variableExpression, ctx.identifier()), (r, e) -> this.configureAST(new PropertyExpression(r, e), e));
return this.configureAST(propertyExpression, ctx);
}
return this.configureAST(variableExpression, ctx);
}
// } gstring --------------------------------------------------------------------
@Override
public LambdaExpression visitStandardLambdaExpression(StandardLambdaExpressionContext ctx) {
return this.configureAST(this.createLambda(ctx.standardLambdaParameters(), ctx.lambdaBody()), ctx);
}
private LambdaExpression createLambda(StandardLambdaParametersContext standardLambdaParametersContext, LambdaBodyContext lambdaBodyContext) {
return new LambdaExpression(
this.visitStandardLambdaParameters(standardLambdaParametersContext),
this.visitLambdaBody(lambdaBodyContext));
}
@Override
public Parameter[] visitStandardLambdaParameters(StandardLambdaParametersContext ctx) {
if (asBoolean(ctx.variableDeclaratorId())) {
return new Parameter[]{
this.configureAST(
new Parameter(
ClassHelper.OBJECT_TYPE,
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()
),
ctx.variableDeclaratorId()
)
};
}
Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters());
if (0 == parameters.length) {
return null;
}
return parameters;
}
@Override
public Statement visitLambdaBody(LambdaBodyContext ctx) {
if (asBoolean(ctx.statementExpression())) {
return this.configureAST((ExpressionStatement) this.visit(ctx.statementExpression()), ctx);
}
if (asBoolean(ctx.block())) {
return this.configureAST(this.visitBlock(ctx.block()), ctx);
}
throw createParsingFailedException("Unsupported lambda body: " + ctx.getText(), ctx);
}
@Override
public ClosureExpression visitClosure(ClosureContext ctx) {
Parameter[] parameters = asBoolean(ctx.formalParameterList())
? this.visitFormalParameterList(ctx.formalParameterList())
: null;
if (!asBoolean(ctx.ARROW())) {
parameters = Parameter.EMPTY_ARRAY;
}
Statement code = this.visitBlockStatementsOpt(ctx.blockStatementsOpt());
return this.configureAST(new ClosureExpression(parameters, code), ctx);
}
@Override
public Parameter[] visitFormalParameters(FormalParametersContext ctx) {
if (!asBoolean(ctx)) {
return new Parameter[0];
}
return this.visitFormalParameterList(ctx.formalParameterList());
}
@Override
public Parameter[] visitFormalParameterList(FormalParameterListContext ctx) {
if (!asBoolean(ctx)) {
return new Parameter[0];
}
List<Parameter> parameterList = new LinkedList<>();
if (asBoolean(ctx.thisFormalParameter())) {
parameterList.add(this.visitThisFormalParameter(ctx.thisFormalParameter()));
}
List<? extends FormalParameterContext> formalParameterList = ctx.formalParameter();
if (asBoolean(formalParameterList)) {
validateVarArgParameter(formalParameterList);
parameterList.addAll(
formalParameterList.stream()
.map(this::visitFormalParameter)
.collect(Collectors.toList()));
}
validateParameterList(parameterList);
return parameterList.toArray(new Parameter[0]);
}
private void validateVarArgParameter(List<? extends FormalParameterContext> formalParameterList) {
for (int i = 0, n = formalParameterList.size(); i < n - 1; i++) {
FormalParameterContext formalParameterContext = formalParameterList.get(i);
if (asBoolean(formalParameterContext.ELLIPSIS())) {
throw createParsingFailedException("The var-arg parameter strs must be the last parameter", formalParameterContext);
}
}
}
private void validateParameterList(List<Parameter> parameterList) {
for (int n = parameterList.size(), i = n - 1; i >= 0; i--) {
Parameter parameter = parameterList.get(i);
for (Parameter otherParameter : parameterList) {
if (otherParameter == parameter) {
continue;
}
if (otherParameter.getName().equals(parameter.getName())) {
throw createParsingFailedException("Duplicated parameter '" + parameter.getName() + "' found.", parameter);
}
}
}
}
@Override
public Parameter visitFormalParameter(FormalParameterContext ctx) {
return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), ctx.ELLIPSIS(), ctx.variableDeclaratorId(), ctx.expression());
}
@Override
public Parameter visitThisFormalParameter(ThisFormalParameterContext ctx) {
return this.configureAST(new Parameter(this.visitType(ctx.type()), THIS_STR), ctx);
}
@Override
public List<ModifierNode> visitClassOrInterfaceModifiersOpt(ClassOrInterfaceModifiersOptContext ctx) {
if (asBoolean(ctx.classOrInterfaceModifiers())) {
return this.visitClassOrInterfaceModifiers(ctx.classOrInterfaceModifiers());
}
return Collections.emptyList();
}
@Override
public List<ModifierNode> visitClassOrInterfaceModifiers(ClassOrInterfaceModifiersContext ctx) {
return ctx.classOrInterfaceModifier().stream()
.map(this::visitClassOrInterfaceModifier)
.collect(Collectors.toList());
}
@Override
public ModifierNode visitClassOrInterfaceModifier(ClassOrInterfaceModifierContext ctx) {
if (asBoolean(ctx.annotation())) {
return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported class or interface modifier: " + ctx.getText(), ctx);
}
@Override
public ModifierNode visitModifier(ModifierContext ctx) {
if (asBoolean(ctx.classOrInterfaceModifier())) {
return this.configureAST(this.visitClassOrInterfaceModifier(ctx.classOrInterfaceModifier()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported modifier: " + ctx.getText(), ctx);
}
@Override
public List<ModifierNode> visitModifiers(ModifiersContext ctx) {
return ctx.modifier().stream()
.map(this::visitModifier)
.collect(Collectors.toList());
}
@Override
public List<ModifierNode> visitModifiersOpt(ModifiersOptContext ctx) {
if (asBoolean(ctx.modifiers())) {
return this.visitModifiers(ctx.modifiers());
}
return Collections.emptyList();
}
@Override
public ModifierNode visitVariableModifier(VariableModifierContext ctx) {
if (asBoolean(ctx.annotation())) {
return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported variable modifier", ctx);
}
@Override
public List<ModifierNode> visitVariableModifiersOpt(VariableModifiersOptContext ctx) {
if (asBoolean(ctx.variableModifiers())) {
return this.visitVariableModifiers(ctx.variableModifiers());
}
return Collections.emptyList();
}
@Override
public List<ModifierNode> visitVariableModifiers(VariableModifiersContext ctx) {
return ctx.variableModifier().stream()
.map(this::visitVariableModifier)
.collect(Collectors.toList());
}
@Override
public List<List<AnnotationNode>> visitDims(DimsContext ctx) {
List<List<AnnotationNode>> dimList =
ctx.annotationsOpt().stream()
.map(this::visitAnnotationsOpt)
.collect(Collectors.toList());
Collections.reverse(dimList);
return dimList;
}
@Override
public List<List<AnnotationNode>> visitDimsOpt(DimsOptContext ctx) {
if (!asBoolean(ctx.dims())) {
return Collections.emptyList();
}
return this.visitDims(ctx.dims());
}
// type { --------------------------------------------------------------------
@Override
public ClassNode visitType(TypeContext ctx) {
if (!asBoolean(ctx)) {
return ClassHelper.OBJECT_TYPE;
}
ClassNode classNode = null;
if (asBoolean(ctx.classOrInterfaceType())) {
ctx.classOrInterfaceType().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitClassOrInterfaceType(ctx.classOrInterfaceType());
} else if (asBoolean(ctx.primitiveType())) {
classNode = this.visitPrimitiveType(ctx.primitiveType());
}
if (!asBoolean(classNode)) {
throw createParsingFailedException("Unsupported type: " + ctx.getText(), ctx);
}
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
List<List<AnnotationNode>> dimList = this.visitDimsOpt(ctx.dimsOpt());
if (asBoolean(dimList)) {
// clear array's generics type info. Groovy's bug? array's generics type will be ignored. e.g. List<String>[]... p
classNode.setGenericsTypes(null);
classNode.setUsingGenerics(false);
classNode = this.createArrayType(classNode, dimList);
}
return this.configureAST(classNode, ctx);
}
@Override
public ClassNode visitClassOrInterfaceType(ClassOrInterfaceTypeContext ctx) {
ClassNode classNode;
if (asBoolean(ctx.qualifiedClassName())) {
ctx.qualifiedClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
} else {
ctx.qualifiedStandardClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitQualifiedStandardClassName(ctx.qualifiedStandardClassName());
}
if (asBoolean(ctx.typeArguments())) {
classNode.setGenericsTypes(
this.visitTypeArguments(ctx.typeArguments()));
}
return this.configureAST(classNode, ctx);
}
@Override
public GenericsType[] visitTypeArgumentsOrDiamond(TypeArgumentsOrDiamondContext ctx) {
if (asBoolean(ctx.typeArguments())) {
return this.visitTypeArguments(ctx.typeArguments());
}
if (asBoolean(ctx.LT())) { // e.g. <>
return new GenericsType[0];
}
throw createParsingFailedException("Unsupported type arguments or diamond: " + ctx.getText(), ctx);
}
@Override
public GenericsType[] visitTypeArguments(TypeArgumentsContext ctx) {
return ctx.typeArgument().stream().map(this::visitTypeArgument).toArray(GenericsType[]::new);
}
@Override
public GenericsType visitTypeArgument(TypeArgumentContext ctx) {
if (asBoolean(ctx.QUESTION())) {
ClassNode baseType = this.configureAST(ClassHelper.makeWithoutCaching(QUESTION_STR), ctx.QUESTION());
baseType.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
if (!asBoolean(ctx.type())) {
GenericsType genericsType = new GenericsType(baseType);
genericsType.setWildcard(true);
genericsType.setName(QUESTION_STR);
return this.configureAST(genericsType, ctx);
}
ClassNode[] upperBounds = null;
ClassNode lowerBound = null;
ClassNode classNode = this.visitType(ctx.type());
if (asBoolean(ctx.EXTENDS())) {
upperBounds = new ClassNode[]{classNode};
} else if (asBoolean(ctx.SUPER())) {
lowerBound = classNode;
}
GenericsType genericsType = new GenericsType(baseType, upperBounds, lowerBound);
genericsType.setWildcard(true);
genericsType.setName(QUESTION_STR);
return this.configureAST(genericsType, ctx);
} else if (asBoolean(ctx.type())) {
return this.configureAST(
this.createGenericsType(
this.visitType(ctx.type())),
ctx);
}
throw createParsingFailedException("Unsupported type argument: " + ctx.getText(), ctx);
}
@Override
public ClassNode visitPrimitiveType(PrimitiveTypeContext ctx) {
return this.configureAST(ClassHelper.make(ctx.getText()), ctx);
}
// } type --------------------------------------------------------------------
@Override
public VariableExpression visitVariableDeclaratorId(VariableDeclaratorIdContext ctx) {
return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx);
}
@Override
public TupleExpression visitVariableNames(VariableNamesContext ctx) {
return this.configureAST(
new TupleExpression(
ctx.variableDeclaratorId().stream()
.map(this::visitVariableDeclaratorId)
.collect(Collectors.toList())
),
ctx);
}
@Override
public BlockStatement visitBlockStatementsOpt(BlockStatementsOptContext ctx) {
if (asBoolean(ctx.blockStatements())) {
return this.configureAST(this.visitBlockStatements(ctx.blockStatements()), ctx);
}
return this.configureAST(this.createBlockStatement(), ctx);
}
@Override
public BlockStatement visitBlockStatements(BlockStatementsContext ctx) {
return this.configureAST(
this.createBlockStatement(
ctx.blockStatement().stream()
.map(this::visitBlockStatement)
.filter(e -> asBoolean(e))
.collect(Collectors.toList())),
ctx);
}
@Override
public Statement visitBlockStatement(BlockStatementContext ctx) {
if (asBoolean(ctx.localVariableDeclaration())) {
return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx);
}
if (asBoolean(ctx.statement())) {
Object astNode = this.visit(ctx.statement()); //this.configureAST((Statement) this.visit(ctx.statement()), ctx);
if (astNode instanceof MethodNode) {
throw createParsingFailedException("Method definition not expected here", ctx);
} else {
return (Statement) astNode;
}
}
throw createParsingFailedException("Unsupported block statement: " + ctx.getText(), ctx);
}
@Override
public List<AnnotationNode> visitAnnotationsOpt(AnnotationsOptContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return ctx.annotation().stream()
.map(this::visitAnnotation)
.collect(Collectors.toList());
}
@Override
public AnnotationNode visitAnnotation(AnnotationContext ctx) {
String annotationName = this.visitAnnotationName(ctx.annotationName());
AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(annotationName));
List<Pair<String, Expression>> annotationElementValues = this.visitElementValues(ctx.elementValues());
annotationElementValues.forEach(e -> annotationNode.addMember(e.getKey(), e.getValue()));
return this.configureAST(annotationNode, ctx);
}
@Override
public List<Pair<String, Expression>> visitElementValues(ElementValuesContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
List<Pair<String, Expression>> annotationElementValues = new LinkedList<>();
if (asBoolean(ctx.elementValuePairs())) {
this.visitElementValuePairs(ctx.elementValuePairs()).entrySet().forEach(e -> {
annotationElementValues.add(new Pair<>(e.getKey(), e.getValue()));
});
} else if (asBoolean(ctx.elementValue())) {
annotationElementValues.add(new Pair<>(VALUE_STR, this.visitElementValue(ctx.elementValue())));
}
return annotationElementValues;
}
@Override
public String visitAnnotationName(AnnotationNameContext ctx) {
return this.visitQualifiedClassName(ctx.qualifiedClassName()).getName();
}
@Override
public Map<String, Expression> visitElementValuePairs(ElementValuePairsContext ctx) {
return ctx.elementValuePair().stream()
.map(this::visitElementValuePair)
.collect(Collectors.toMap(
Pair::getKey,
Pair::getValue,
(k, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", k));
},
LinkedHashMap::new
));
}
@Override
public Pair<String, Expression> visitElementValuePair(ElementValuePairContext ctx) {
return new Pair<>(ctx.elementValuePairName().getText(), this.visitElementValue(ctx.elementValue()));
}
@Override
public Expression visitElementValue(ElementValueContext ctx) {
if (asBoolean(ctx.expression())) {
return this.configureAST((Expression) this.visit(ctx.expression()), ctx);
}
if (asBoolean(ctx.annotation())) {
return this.configureAST(new AnnotationConstantExpression(this.visitAnnotation(ctx.annotation())), ctx);
}
if (asBoolean(ctx.elementValueArrayInitializer())) {
return this.configureAST(this.visitElementValueArrayInitializer(ctx.elementValueArrayInitializer()), ctx);
}
throw createParsingFailedException("Unsupported element value: " + ctx.getText(), ctx);
}
@Override
public ListExpression visitElementValueArrayInitializer(ElementValueArrayInitializerContext ctx) {
return this.configureAST(new ListExpression(ctx.elementValue().stream().map(this::visitElementValue).collect(Collectors.toList())), ctx);
}
@Override
public String visitClassName(ClassNameContext ctx) {
String text = ctx.getText();
if (!text.contains("\\")) {
return text;
}
return StringUtils.replaceHexEscapes(text);
}
@Override
public String visitIdentifier(IdentifierContext ctx) {
String text = ctx.getText();
if (!text.contains("\\")) {
return text;
}
return StringUtils.replaceHexEscapes(text);
}
@Override
public String visitQualifiedName(QualifiedNameContext ctx) {
return ctx.qualifiedNameElement().stream()
.map(ParseTree::getText)
.collect(Collectors.joining(DOT_STR));
}
@Override
public ClassNode visitAnnotatedQualifiedClassName(AnnotatedQualifiedClassNameContext ctx) {
ClassNode classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return classNode;
}
@Override
public ClassNode[] visitQualifiedClassNameList(QualifiedClassNameListContext ctx) {
if (!asBoolean(ctx)) {
return new ClassNode[0];
}
return ctx.annotatedQualifiedClassName().stream()
.map(this::visitAnnotatedQualifiedClassName)
.toArray(ClassNode[]::new);
}
@Override
public ClassNode visitQualifiedClassName(QualifiedClassNameContext ctx) {
return this.createClassNode(ctx);
}
@Override
public ClassNode visitQualifiedStandardClassName(QualifiedStandardClassNameContext ctx) {
return this.createClassNode(ctx);
}
private ClassNode createClassNode(GroovyParserRuleContext ctx) {
ClassNode result = ClassHelper.make(ctx.getText());
if (!isTrue(ctx, IS_INSIDE_INSTANCEOF_EXPR)) { // type in the "instanceof" expression should not have proxy to redirect to it
result = this.proxyClassNode(result);
}
return this.configureAST(result, ctx);
}
private ClassNode proxyClassNode(ClassNode classNode) {
if (!classNode.isUsingGenerics()) {
return classNode;
}
ClassNode cn = ClassHelper.makeWithoutCaching(classNode.getName());
cn.setRedirect(classNode);
return cn;
}
/**
* Visit tree safely, no NPE occurred when the tree is null.
*
* @param tree an AST node
* @return the visiting result
*/
@Override
public Object visit(ParseTree tree) {
if (!asBoolean(tree)) {
return null;
}
return super.visit(tree);
}
// e.g. obj.a(1, 2) or obj.a 1, 2
private MethodCallExpression createMethodCallExpression(PropertyExpression propertyExpression, Expression arguments) {
MethodCallExpression methodCallExpression =
new MethodCallExpression(
propertyExpression.getObjectExpression(),
propertyExpression.getProperty(),
arguments
);
methodCallExpression.setImplicitThis(false);
methodCallExpression.setSafe(propertyExpression.isSafe());
methodCallExpression.setSpreadSafe(propertyExpression.isSpreadSafe());
// method call obj*.m(): "safe"(false) and "spreadSafe"(true)
// property access obj*.p: "safe"(true) and "spreadSafe"(true)
// so we have to reset safe here.
if (propertyExpression.isSpreadSafe()) {
methodCallExpression.setSafe(false);
}
// if the generics types meta data is not empty, it is a generic method call, e.g. obj.<Integer>a(1, 2)
methodCallExpression.setGenericsTypes(
propertyExpression.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES));
return methodCallExpression;
}
// e.g. m(1, 2) or m 1, 2
private MethodCallExpression createMethodCallExpression(Expression baseExpr, Expression arguments) {
return new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
(baseExpr instanceof VariableExpression)
? this.createConstantExpression(baseExpr)
: baseExpr,
arguments
);
}
private Parameter processFormalParameter(GroovyParserRuleContext ctx,
VariableModifiersOptContext variableModifiersOptContext,
TypeContext typeContext,
TerminalNode ellipsis,
VariableDeclaratorIdContext variableDeclaratorIdContext,
ExpressionContext expressionContext) {
ClassNode classNode = this.visitType(typeContext);
if (asBoolean(ellipsis)) {
classNode = this.configureAST(classNode.makeArray(), classNode);
}
Parameter parameter =
new ModifierManager(this, this.visitVariableModifiersOpt(variableModifiersOptContext))
.processParameter(
this.configureAST(
new Parameter(
classNode,
this.visitVariableDeclaratorId(variableDeclaratorIdContext).getName()
),
ctx
)
);
if (asBoolean(expressionContext)) {
parameter.setInitialExpression((Expression) this.visit(expressionContext));
}
return parameter;
}
private Expression createPathExpression(Expression primaryExpr, List<? extends PathElementContext> pathElementContextList) {
return (Expression) pathElementContextList.stream()
.map(e -> (Object) e)
.reduce(primaryExpr,
(r, e) -> {
PathElementContext pathElementContext = (PathElementContext) e;
pathElementContext.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR, r);
return this.visitPathElement(pathElementContext);
}
);
}
private GenericsType createGenericsType(ClassNode classNode) {
return this.configureAST(new GenericsType(classNode), classNode);
}
private ConstantExpression createConstantExpression(Expression expression) {
if (expression instanceof ConstantExpression) {
return (ConstantExpression) expression;
}
return this.configureAST(new ConstantExpression(expression.getText()), expression);
}
private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right) {
return new BinaryExpression((Expression) this.visit(left), this.createGroovyToken(op), (Expression) this.visit(right));
}
private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right, ExpressionContext ctx) {
BinaryExpression binaryExpression = this.createBinaryExpression(left, op, right);
if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) {
return this.configureAST(binaryExpression, op);
}
return this.configureAST(binaryExpression, ctx);
}
private Statement unpackStatement(Statement statement) {
if (statement instanceof DeclarationListStatement) {
List<ExpressionStatement> expressionStatementList = ((DeclarationListStatement) statement).getDeclarationStatements();
if (1 == expressionStatementList.size()) {
return expressionStatementList.get(0);
}
return this.configureAST(this.createBlockStatement(statement), statement); // if DeclarationListStatement contains more than 1 declarations, maybe it's better to create a block to hold them
}
return statement;
}
public BlockStatement createBlockStatement(Statement... statements) {
return this.createBlockStatement(Arrays.asList(statements));
}
private BlockStatement createBlockStatement(List<Statement> statementList) {
return this.appendStatementsToBlockStatement(new BlockStatement(), statementList);
}
public BlockStatement appendStatementsToBlockStatement(BlockStatement bs, Statement... statements) {
return this.appendStatementsToBlockStatement(bs, Arrays.asList(statements));
}
private BlockStatement appendStatementsToBlockStatement(BlockStatement bs, List<Statement> statementList) {
return (BlockStatement) statementList.stream()
.reduce(bs, (r, e) -> {
BlockStatement blockStatement = (BlockStatement) r;
if (e instanceof DeclarationListStatement) {
((DeclarationListStatement) e).getDeclarationStatements().forEach(blockStatement::addStatement);
} else {
blockStatement.addStatement(e);
}
return blockStatement;
});
}
private boolean isAnnotationDeclaration(ClassNode classNode) {
return asBoolean(classNode) && classNode.isAnnotationDefinition();
}
private boolean isSyntheticPublic(
boolean isAnnotationDeclaration,
boolean isAnonymousInnerEnumDeclaration,
boolean hasReturnType,
ModifierManager modifierManager
) {
return this.isSyntheticPublic(
isAnnotationDeclaration,
isAnonymousInnerEnumDeclaration,
modifierManager.containsAnnotations(),
modifierManager.containsVisibilityModifier(),
modifierManager.containsNonVisibilityModifier(),
hasReturnType,
modifierManager.contains(DEF));
}
/**
* @param isAnnotationDeclaration whether the method is defined in an annotation
* @param isAnonymousInnerEnumDeclaration whether the method is defined in an anonymous inner enum
* @param hasAnnotation whether the method declaration has annotations
* @param hasVisibilityModifier whether the method declaration contains visibility modifier(e.g. public, protected, private)
* @param hasModifier whether the method declaration has modifier(e.g. visibility modifier, final, static and so on)
* @param hasReturnType whether the method declaration has an return type(e.g. String, generic types)
* @param hasDef whether the method declaration using def keyword
* @return the result
*/
private boolean isSyntheticPublic(
boolean isAnnotationDeclaration,
boolean isAnonymousInnerEnumDeclaration,
boolean hasAnnotation,
boolean hasVisibilityModifier,
boolean hasModifier,
boolean hasReturnType,
boolean hasDef) {
if (hasVisibilityModifier) {
return false;
}
if (isAnnotationDeclaration) {
return true;
}
if (hasDef && hasReturnType) {
return true;
}
if (hasModifier || hasAnnotation || !hasReturnType) {
return true;
}
return isAnonymousInnerEnumDeclaration;
}
// the mixins of interface and annotation should be null
private void hackMixins(ClassNode classNode) {
classNode.setMixins(null);
}
private static final Map<ClassNode, Object> TYPE_DEFAULT_VALUE_MAP = Maps.of(
ClassHelper.int_TYPE, 0,
ClassHelper.long_TYPE, 0L,
ClassHelper.double_TYPE, 0.0D,
ClassHelper.float_TYPE, 0.0F,
ClassHelper.short_TYPE, (short) 0,
ClassHelper.byte_TYPE, (byte) 0,
ClassHelper.char_TYPE, (char) 0,
ClassHelper.boolean_TYPE, Boolean.FALSE
);
private Object findDefaultValueByType(ClassNode type) {
return TYPE_DEFAULT_VALUE_MAP.get(type);
}
private boolean isPackageInfoDeclaration() {
String name = this.sourceUnit.getName();
return null != name && name.endsWith(PACKAGE_INFO_FILE_NAME);
}
private boolean isBlankScript(CompilationUnitContext ctx) {
return moduleNode.getStatementBlock().isEmpty() && moduleNode.getMethods().isEmpty() && moduleNode.getClasses().isEmpty();
}
private boolean isInsideParentheses(NodeMetaDataHandler nodeMetaDataHandler) {
Integer insideParenLevel = nodeMetaDataHandler.getNodeMetaData(INSIDE_PARENTHESES_LEVEL);
if (null != insideParenLevel) {
return insideParenLevel > 0;
}
return false;
}
private void addEmptyReturnStatement() {
moduleNode.addStatement(ReturnStatement.RETURN_NULL_OR_VOID);
}
private void addPackageInfoClassNode() {
List<ClassNode> classNodeList = moduleNode.getClasses();
ClassNode packageInfoClassNode = ClassHelper.make(moduleNode.getPackageName() + PACKAGE_INFO);
if (!classNodeList.contains(packageInfoClassNode)) {
moduleNode.addClass(packageInfoClassNode);
}
}
private org.codehaus.groovy.syntax.Token createGroovyTokenByType(Token token, int type) {
if (null == token) {
throw new IllegalArgumentException("token should not be null");
}
return new org.codehaus.groovy.syntax.Token(type, token.getText(), token.getLine(), token.getCharPositionInLine());
}
private org.codehaus.groovy.syntax.Token createGroovyToken(Token token) {
return this.createGroovyToken(token, 1);
}
private org.codehaus.groovy.syntax.Token createGroovyToken(Token token, int cardinality) {
String text = StringGroovyMethods.multiply((CharSequence) token.getText(), cardinality);
return new org.codehaus.groovy.syntax.Token(
"..<".equals(token.getText()) || "..".equals(token.getText())
? Types.RANGE_OPERATOR
: Types.lookup(text, Types.ANY),
text,
token.getLine(),
token.getCharPositionInLine() + 1
);
}
/*
private org.codehaus.groovy.syntax.Token createGroovyToken(String text, int startLine, int startColumn) {
return new org.codehaus.groovy.syntax.Token(
Types.lookup(text, Types.ANY),
text,
startLine,
startColumn
);
}
*/
/**
* set the script source position
*/
private void configureScriptClassNode() {
ClassNode scriptClassNode = moduleNode.getScriptClassDummy();
if (!asBoolean(scriptClassNode)) {
return;
}
List<Statement> statements = moduleNode.getStatementBlock().getStatements();
if (!statements.isEmpty()) {
Statement firstStatement = statements.get(0);
Statement lastStatement = statements.get(statements.size() - 1);
scriptClassNode.setSourcePosition(firstStatement);
scriptClassNode.setLastColumnNumber(lastStatement.getLastColumnNumber());
scriptClassNode.setLastLineNumber(lastStatement.getLastLineNumber());
}
}
/**
* Sets location(lineNumber, colNumber, lastLineNumber, lastColumnNumber) for node using standard context information.
* Note: this method is implemented to be closed over ASTNode. It returns same node as it received in arguments.
*
* @param astNode Node to be modified.
* @param ctx Context from which information is obtained.
* @return Modified astNode.
*/
private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx) {
Token start = ctx.getStart();
Token stop = ctx.getStop();
astNode.setLineNumber(start.getLine());
astNode.setColumnNumber(start.getCharPositionInLine() + 1);
Pair<Integer, Integer> stopTokenEndPosition = endPosition(stop);
astNode.setLastLineNumber(stopTokenEndPosition.getKey());
astNode.setLastColumnNumber(stopTokenEndPosition.getValue());
return astNode;
}
private Pair<Integer, Integer> endPosition(Token token) {
String stopText = token.getText();
int stopTextLength = 0;
int newLineCnt = 0;
if (null != stopText) {
stopTextLength = stopText.length();
newLineCnt = (int) StringUtils.countChar(stopText, '\n');
}
if (0 == newLineCnt) {
return new Pair<Integer, Integer>(token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length());
} else { // e.g. GStringEnd contains newlines, we should fix the location info
return new Pair<Integer, Integer>(token.getLine() + newLineCnt, stopTextLength - stopText.lastIndexOf('\n'));
}
}
private <T extends ASTNode> T configureAST(T astNode, TerminalNode terminalNode) {
return this.configureAST(astNode, terminalNode.getSymbol());
}
private <T extends ASTNode> T configureAST(T astNode, Token token) {
astNode.setLineNumber(token.getLine());
astNode.setColumnNumber(token.getCharPositionInLine() + 1);
astNode.setLastLineNumber(token.getLine());
astNode.setLastColumnNumber(token.getCharPositionInLine() + 1 + token.getText().length());
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, ASTNode source) {
astNode.setLineNumber(source.getLineNumber());
astNode.setColumnNumber(source.getColumnNumber());
astNode.setLastLineNumber(source.getLastLineNumber());
astNode.setLastColumnNumber(source.getLastColumnNumber());
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx, ASTNode stop) {
Token start = ctx.getStart();
astNode.setLineNumber(start.getLine());
astNode.setColumnNumber(start.getCharPositionInLine() + 1);
if (asBoolean(stop)) {
astNode.setLastLineNumber(stop.getLastLineNumber());
astNode.setLastColumnNumber(stop.getLastColumnNumber());
} else {
Pair<Integer, Integer> endPosition = endPosition(start);
astNode.setLastLineNumber(endPosition.getKey());
astNode.setLastColumnNumber(endPosition.getValue());
}
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, ASTNode start, ASTNode stop) {
astNode.setLineNumber(start.getLineNumber());
astNode.setColumnNumber(start.getColumnNumber());
if (asBoolean(stop)) {
astNode.setLastLineNumber(stop.getLastLineNumber());
astNode.setLastColumnNumber(stop.getLastColumnNumber());
} else {
astNode.setLastLineNumber(start.getLastLineNumber());
astNode.setLastColumnNumber(start.getLastColumnNumber());
}
return astNode;
}
private boolean isTrue(NodeMetaDataHandler nodeMetaDataHandler, String key) {
Object nmd = nodeMetaDataHandler.getNodeMetaData(key);
if (null == nmd) {
return false;
}
if (!(nmd instanceof Boolean)) {
throw new GroovyBugError(nodeMetaDataHandler + " node meta data[" + key + "] is not an instance of Boolean");
}
return (Boolean) nmd;
}
private CompilationFailedException createParsingFailedException(String msg, GroovyParserRuleContext ctx) {
return createParsingFailedException(
new SyntaxException(msg,
ctx.start.getLine(),
ctx.start.getCharPositionInLine() + 1,
ctx.stop.getLine(),
ctx.stop.getCharPositionInLine() + 1 + ctx.stop.getText().length()));
}
public CompilationFailedException createParsingFailedException(String msg, ASTNode node) {
Objects.requireNonNull(node, "node passed into createParsingFailedException should not be null");
return createParsingFailedException(
new SyntaxException(msg,
node.getLineNumber(),
node.getColumnNumber(),
node.getLastLineNumber(),
node.getLastColumnNumber()));
}
/*
private CompilationFailedException createParsingFailedException(String msg, Token token) {
return createParsingFailedException(
new SyntaxException(msg,
token.getLine(),
token.getCharPositionInLine() + 1,
token.getLine(),
token.getCharPositionInLine() + 1 + token.getText().length()));
}
*/
private CompilationFailedException createParsingFailedException(Throwable t) {
if (t instanceof SyntaxException) {
this.collectSyntaxError((SyntaxException) t);
} else if (t instanceof GroovySyntaxError) {
GroovySyntaxError groovySyntaxError = (GroovySyntaxError) t;
this.collectSyntaxError(
new SyntaxException(
groovySyntaxError.getMessage(),
groovySyntaxError,
groovySyntaxError.getLine(),
groovySyntaxError.getColumn()));
} else if (t instanceof Exception) {
this.collectException((Exception) t);
}
return new CompilationFailedException(
CompilePhase.PARSING.getPhaseNumber(),
this.sourceUnit,
t);
}
private void collectSyntaxError(SyntaxException e) {
sourceUnit.getErrorCollector().addFatalError(new SyntaxErrorMessage(e, sourceUnit));
}
private void collectException(Exception e) {
sourceUnit.getErrorCollector().addException(e, this.sourceUnit);
}
private ANTLRErrorListener createANTLRErrorListener() {
return new ANTLRErrorListener() {
@Override
public void syntaxError(
Recognizer recognizer,
Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e) {
collectSyntaxError(new SyntaxException(msg, line, charPositionInLine + 1));
}
};
}
private void removeErrorListeners() {
lexer.removeErrorListeners();
parser.removeErrorListeners();
}
private void addErrorListeners() {
lexer.removeErrorListeners();
lexer.addErrorListener(this.createANTLRErrorListener());
parser.removeErrorListeners();
parser.addErrorListener(this.createANTLRErrorListener());
}
private String createExceptionMessage(Throwable t) {
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
t.printStackTrace(pw);
}
return sw.toString();
}
private class DeclarationListStatement extends Statement {
private final List<ExpressionStatement> declarationStatements;
public DeclarationListStatement(DeclarationExpression... declarations) {
this(Arrays.asList(declarations));
}
public DeclarationListStatement(List<DeclarationExpression> declarations) {
this.declarationStatements =
declarations.stream()
.map(e -> configureAST(new ExpressionStatement(e), e))
.collect(Collectors.toList());
}
public List<ExpressionStatement> getDeclarationStatements() {
List<String> declarationListStatementLabels = this.getStatementLabels();
this.declarationStatements.forEach(e -> {
if (null != declarationListStatementLabels) {
// clear existing statement labels before setting labels
if (null != e.getStatementLabels()) {
e.getStatementLabels().clear();
}
declarationListStatementLabels.forEach(e::addStatementLabel);
}
});
return this.declarationStatements;
}
public List<DeclarationExpression> getDeclarationExpressions() {
return this.declarationStatements.stream()
.map(e -> (DeclarationExpression) e.getExpression())
.collect(Collectors.toList());
}
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(key, pair.key) &&
Objects.equals(value, pair.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}
private final ModuleNode moduleNode;
private final SourceUnit sourceUnit;
private final ClassLoader classLoader; // Our ClassLoader, which provides information on external types
private final GroovyLangLexer lexer;
private final GroovyLangParser parser;
private final TryWithResourcesASTTransformation tryWithResourcesASTTransformation;
private final GroovydocManager groovydocManager;
private final List<ClassNode> classNodeList = new LinkedList<>();
private final Deque<ClassNode> classNodeStack = new ArrayDeque<>();
private final Deque<List<InnerClassNode>> anonymousInnerClassesDefinedInMethodStack = new ArrayDeque<>();
private int anonymousInnerClassCounter = 1;
private Pair<GroovyParserRuleContext, Exception> numberFormatError;
private static final String QUESTION_STR = "?";
private static final String DOT_STR = ".";
private static final String SUB_STR = "-";
private static final String ASSIGN_STR = "=";
private static final String VALUE_STR = "value";
private static final String DOLLAR_STR = "$";
private static final String CALL_STR = "call";
private static final String THIS_STR = "this";
private static final String SUPER_STR = "super";
private static final String VOID_STR = "void";
private static final String PACKAGE_INFO = "package-info";
private static final String PACKAGE_INFO_FILE_NAME = PACKAGE_INFO + ".groovy";
private static final String GROOVY_TRANSFORM_TRAIT = "groovy.transform.Trait";
private static final Set<String> PRIMITIVE_TYPE_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double")));
private static final Logger LOGGER = Logger.getLogger(AstBuilder.class.getName());
private static final String INSIDE_PARENTHESES_LEVEL = "_INSIDE_PARENTHESES_LEVEL";
private static final String IS_INSIDE_INSTANCEOF_EXPR = "_IS_INSIDE_INSTANCEOF_EXPR";
private static final String IS_SWITCH_DEFAULT = "_IS_SWITCH_DEFAULT";
private static final String IS_NUMERIC = "_IS_NUMERIC";
private static final String IS_STRING = "_IS_STRING";
private static final String IS_INTERFACE_WITH_DEFAULT_METHODS = "_IS_INTERFACE_WITH_DEFAULT_METHODS";
private static final String IS_INSIDE_CONDITIONAL_EXPRESSION = "_IS_INSIDE_CONDITIONAL_EXPRESSION";
private static final String PATH_EXPRESSION_BASE_EXPR = "_PATH_EXPRESSION_BASE_EXPR";
private static final String PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES = "_PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES";
private static final String CMD_EXPRESSION_BASE_EXPR = "_CMD_EXPRESSION_BASE_EXPR";
private static final String TYPE_DECLARATION_MODIFIERS = "_TYPE_DECLARATION_MODIFIERS";
private static final String CLASS_DECLARATION_CLASS_NODE = "_CLASS_DECLARATION_CLASS_NODE";
private static final String VARIABLE_DECLARATION_VARIABLE_TYPE = "_VARIABLE_DECLARATION_VARIABLE_TYPE";
private static final String ANONYMOUS_INNER_CLASS_SUPER_CLASS = "_ANONYMOUS_INNER_CLASS_SUPER_CLASS";
private static final String INTEGER_LITERAL_TEXT = "_INTEGER_LITERAL_TEXT";
private static final String FLOATING_POINT_LITERAL_TEXT = "_FLOATING_POINT_LITERAL_TEXT";
private static final String CLASS_NAME = "_CLASS_NAME";
}
| src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.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.groovy.parser.antlr4;
import groovy.lang.IntRange;
import org.antlr.v4.runtime.ANTLRErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.apache.groovy.parser.antlr4.internal.AtnManager;
import org.apache.groovy.parser.antlr4.internal.DescriptiveErrorStrategy;
import org.apache.groovy.parser.antlr4.util.StringUtils;
import org.apache.groovy.util.Maps;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.antlr.EnumHelper;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ConstructorNode;
import org.codehaus.groovy.ast.EnumConstantClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.GenericsType;
import org.codehaus.groovy.ast.ImportNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.NodeMetaDataHandler;
import org.codehaus.groovy.ast.PackageNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.expr.AnnotationConstantExpression;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ArrayExpression;
import org.codehaus.groovy.ast.expr.AttributeExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BitwiseNegationExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ClosureListExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.ElvisOperatorExpression;
import org.codehaus.groovy.ast.expr.EmptyExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.GStringExpression;
import org.codehaus.groovy.ast.expr.LambdaExpression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.MapEntryExpression;
import org.codehaus.groovy.ast.expr.MapExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.MethodPointerExpression;
import org.codehaus.groovy.ast.expr.MethodReferenceExpression;
import org.codehaus.groovy.ast.expr.NamedArgumentListExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PostfixExpression;
import org.codehaus.groovy.ast.expr.PrefixExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.RangeExpression;
import org.codehaus.groovy.ast.expr.SpreadExpression;
import org.codehaus.groovy.ast.expr.SpreadMapExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.expr.UnaryMinusExpression;
import org.codehaus.groovy.ast.expr.UnaryPlusExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.AssertStatement;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.BreakStatement;
import org.codehaus.groovy.ast.stmt.CaseStatement;
import org.codehaus.groovy.ast.stmt.CatchStatement;
import org.codehaus.groovy.ast.stmt.ContinueStatement;
import org.codehaus.groovy.ast.stmt.DoWhileStatement;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.ast.stmt.SwitchStatement;
import org.codehaus.groovy.ast.stmt.SynchronizedStatement;
import org.codehaus.groovy.ast.stmt.ThrowStatement;
import org.codehaus.groovy.ast.stmt.TryCatchStatement;
import org.codehaus.groovy.ast.stmt.WhileStatement;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.messages.SyntaxErrorMessage;
import org.codehaus.groovy.runtime.StringGroovyMethods;
import org.codehaus.groovy.syntax.Numbers;
import org.codehaus.groovy.syntax.SyntaxException;
import org.codehaus.groovy.syntax.Types;
import org.objectweb.asm.Opcodes;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.groovy.parser.antlr4.GroovyLangParser.*;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.asBoolean;
import static org.codehaus.groovy.runtime.DefaultGroovyMethods.last;
/**
* Building the AST from the parse tree generated by Antlr4
*
* @author <a href="mailto:[email protected]">Daniel.Sun</a>
* Created on 2016/08/14
*/
public class AstBuilder extends GroovyParserBaseVisitor<Object> implements GroovyParserVisitor<Object> {
public AstBuilder(SourceUnit sourceUnit, ClassLoader classLoader) {
this.sourceUnit = sourceUnit;
this.moduleNode = new ModuleNode(sourceUnit);
this.classLoader = classLoader; // unused for the time being
CharStream charStream = createCharStream(sourceUnit);
this.lexer = new GroovyLangLexer(charStream);
this.parser =
new GroovyLangParser(
new CommonTokenStream(this.lexer));
this.parser.setErrorHandler(new DescriptiveErrorStrategy(charStream));
this.tryWithResourcesASTTransformation = new TryWithResourcesASTTransformation(this);
this.groovydocManager = new GroovydocManager(this);
}
private CharStream createCharStream(SourceUnit sourceUnit) {
CharStream charStream;
try {
charStream = CharStreams.fromReader(
new BufferedReader(sourceUnit.getSource().getReader()),
sourceUnit.getName());
} catch (IOException e) {
throw new RuntimeException("Error occurred when reading source code.", e);
}
return charStream;
}
private GroovyParserRuleContext buildCST() throws CompilationFailedException {
GroovyParserRuleContext result;
try {
// parsing have to wait util clearing is complete.
AtnManager.RRWL.readLock().lock();
try {
result = buildCST(PredictionMode.SLL);
} catch (Throwable t) {
// if some syntax error occurred in the lexer, no need to retry the powerful LL mode
if (t instanceof GroovySyntaxError && GroovySyntaxError.LEXER == ((GroovySyntaxError) t).getSource()) {
throw t;
}
result = buildCST(PredictionMode.LL);
} finally {
AtnManager.RRWL.readLock().unlock();
}
} catch (Throwable t) {
throw convertException(t);
}
return result;
}
private GroovyParserRuleContext buildCST(PredictionMode predictionMode) {
parser.getInterpreter().setPredictionMode(predictionMode);
if (PredictionMode.SLL.equals(predictionMode)) {
this.removeErrorListeners();
} else {
parser.getInputStream().seek(0);
this.addErrorListeners();
}
return parser.compilationUnit();
}
private CompilationFailedException convertException(Throwable t) {
CompilationFailedException cfe;
if (t instanceof CompilationFailedException) {
cfe = (CompilationFailedException) t;
} else if (t instanceof ParseCancellationException) {
cfe = createParsingFailedException(t.getCause());
} else {
cfe = createParsingFailedException(t);
}
return cfe;
}
public ModuleNode buildAST() {
try {
return (ModuleNode) this.visit(this.buildCST());
} catch (Throwable t) {
throw convertException(t);
}
}
@Override
public ModuleNode visitCompilationUnit(CompilationUnitContext ctx) {
this.visit(ctx.packageDeclaration());
ctx.statement().stream()
.map(this::visit)
// .filter(e -> e instanceof Statement)
.forEach(e -> {
if (e instanceof DeclarationListStatement) { // local variable declaration
((DeclarationListStatement) e).getDeclarationStatements().forEach(moduleNode::addStatement);
} else if (e instanceof Statement) {
moduleNode.addStatement((Statement) e);
} else if (e instanceof MethodNode) { // script method
moduleNode.addMethod((MethodNode) e);
}
});
this.classNodeList.forEach(moduleNode::addClass);
if (this.isPackageInfoDeclaration()) {
this.addPackageInfoClassNode();
} else {
// if groovy source file only contains blank(including EOF), add "return null" to the AST
if (this.isBlankScript(ctx)) {
this.addEmptyReturnStatement();
}
}
this.configureScriptClassNode();
if (null != this.numberFormatError) {
throw createParsingFailedException(this.numberFormatError.value.getMessage(), this.numberFormatError.key);
}
return moduleNode;
}
@Override
public PackageNode visitPackageDeclaration(PackageDeclarationContext ctx) {
String packageName = this.visitQualifiedName(ctx.qualifiedName());
moduleNode.setPackageName(packageName + DOT_STR);
PackageNode packageNode = moduleNode.getPackage();
packageNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return this.configureAST(packageNode, ctx);
}
@Override
public ImportNode visitImportDeclaration(ImportDeclarationContext ctx) {
ImportNode importNode;
boolean hasStatic = asBoolean(ctx.STATIC());
boolean hasStar = asBoolean(ctx.MUL());
boolean hasAlias = asBoolean(ctx.alias);
List<AnnotationNode> annotationNodeList = this.visitAnnotationsOpt(ctx.annotationsOpt());
if (hasStatic) {
if (hasStar) { // e.g. import static java.lang.Math.*
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
ClassNode type = ClassHelper.make(qualifiedName);
this.configureAST(type, ctx);
moduleNode.addStaticStarImport(type.getText(), type, annotationNodeList);
importNode = last(moduleNode.getStaticStarImports().values());
} else { // e.g. import static java.lang.Math.pow
List<GroovyParserRuleContext> identifierList = new LinkedList<>(ctx.qualifiedName().qualifiedNameElement());
int identifierListSize = identifierList.size();
String name = identifierList.get(identifierListSize - 1).getText();
ClassNode classNode =
ClassHelper.make(
identifierList.stream()
.limit(identifierListSize - 1)
.map(ParseTree::getText)
.collect(Collectors.joining(DOT_STR)));
String alias = hasAlias
? ctx.alias.getText()
: name;
this.configureAST(classNode, ctx);
moduleNode.addStaticImport(classNode, name, alias, annotationNodeList);
importNode = last(moduleNode.getStaticImports().values());
}
} else {
if (hasStar) { // e.g. import java.util.*
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
moduleNode.addStarImport(qualifiedName + DOT_STR, annotationNodeList);
importNode = last(moduleNode.getStarImports());
} else { // e.g. import java.util.Map
String qualifiedName = this.visitQualifiedName(ctx.qualifiedName());
String name = last(ctx.qualifiedName().qualifiedNameElement()).getText();
ClassNode classNode = ClassHelper.make(qualifiedName);
String alias = hasAlias
? ctx.alias.getText()
: name;
this.configureAST(classNode, ctx);
moduleNode.addImport(alias, classNode, annotationNodeList);
importNode = last(moduleNode.getImports());
}
}
return this.configureAST(importNode, ctx);
}
// statement { --------------------------------------------------------------------
@Override
public AssertStatement visitAssertStatement(AssertStatementContext ctx) {
Expression conditionExpression = (Expression) this.visit(ctx.ce);
if (conditionExpression instanceof BinaryExpression) {
BinaryExpression binaryExpression = (BinaryExpression) conditionExpression;
if (binaryExpression.getOperation().getType() == Types.ASSIGN) {
throw createParsingFailedException("Assignment expression is not allowed in the assert statement", conditionExpression);
}
}
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
if (!asBoolean(ctx.me)) {
return this.configureAST(
new AssertStatement(booleanExpression), ctx);
}
return this.configureAST(new AssertStatement(booleanExpression,
(Expression) this.visit(ctx.me)),
ctx);
}
@Override
public AssertStatement visitAssertStmtAlt(AssertStmtAltContext ctx) {
return this.configureAST(this.visitAssertStatement(ctx.assertStatement()), ctx);
}
@Override
public IfStatement visitIfElseStmtAlt(IfElseStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
Statement ifBlock =
this.unpackStatement(
(Statement) this.visit(ctx.tb));
Statement elseBlock =
this.unpackStatement(
asBoolean(ctx.ELSE())
? (Statement) this.visit(ctx.fb)
: EmptyStatement.INSTANCE);
return this.configureAST(new IfStatement(booleanExpression, ifBlock, elseBlock), ctx);
}
@Override
public Statement visitLoopStmtAlt(LoopStmtAltContext ctx) {
return this.configureAST((Statement) this.visit(ctx.loopStatement()), ctx);
}
@Override
public ForStatement visitForStmtAlt(ForStmtAltContext ctx) {
Pair<Parameter, Expression> controlPair = this.visitForControl(ctx.forControl());
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new ForStatement(controlPair.getKey(), controlPair.getValue(), asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public Pair<Parameter, Expression> visitForControl(ForControlContext ctx) {
if (asBoolean(ctx.enhancedForControl())) { // e.g. for(int i in 0..<10) {}
return this.visitEnhancedForControl(ctx.enhancedForControl());
}
if (asBoolean(ctx.classicalForControl())) { // e.g. for(int i = 0; i < 10; i++) {}
return this.visitClassicalForControl(ctx.classicalForControl());
}
throw createParsingFailedException("Unsupported for control: " + ctx.getText(), ctx);
}
@Override
public Expression visitForInit(ForInitContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
if (asBoolean(ctx.localVariableDeclaration())) {
DeclarationListStatement declarationListStatement = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration());
List<?> declarationExpressionList = declarationListStatement.getDeclarationExpressions();
if (declarationExpressionList.size() == 1) {
return this.configureAST((Expression) declarationExpressionList.get(0), ctx);
} else {
return this.configureAST(new ClosureListExpression((List<Expression>) declarationExpressionList), ctx);
}
}
if (asBoolean(ctx.expressionList())) {
return this.translateExpressionList(ctx.expressionList());
}
throw createParsingFailedException("Unsupported for init: " + ctx.getText(), ctx);
}
@Override
public Expression visitForUpdate(ForUpdateContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
return this.translateExpressionList(ctx.expressionList());
}
private Expression translateExpressionList(ExpressionListContext ctx) {
List<Expression> expressionList = this.visitExpressionList(ctx);
if (expressionList.size() == 1) {
return this.configureAST(expressionList.get(0), ctx);
} else {
return this.configureAST(new ClosureListExpression(expressionList), ctx);
}
}
@Override
public Pair<Parameter, Expression> visitEnhancedForControl(EnhancedForControlContext ctx) {
Parameter parameter = this.configureAST(
new Parameter(this.visitType(ctx.type()), this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()),
ctx.variableDeclaratorId());
// FIXME Groovy will ignore variableModifier of parameter in the for control
// In order to make the new parser behave same with the old one, we do not process variableModifier*
return new Pair<>(parameter, (Expression) this.visit(ctx.expression()));
}
@Override
public Pair<Parameter, Expression> visitClassicalForControl(ClassicalForControlContext ctx) {
ClosureListExpression closureListExpression = new ClosureListExpression();
closureListExpression.addExpression(this.visitForInit(ctx.forInit()));
closureListExpression.addExpression(asBoolean(ctx.expression()) ? (Expression) this.visit(ctx.expression()) : EmptyExpression.INSTANCE);
closureListExpression.addExpression(this.visitForUpdate(ctx.forUpdate()));
return new Pair<>(ForStatement.FOR_LOOP_DUMMY, closureListExpression);
}
@Override
public WhileStatement visitWhileStmtAlt(WhileStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression), conditionExpression);
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new WhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public DoWhileStatement visitDoWhileStmtAlt(DoWhileStmtAltContext ctx) {
Expression conditionExpression = this.visitExpressionInPar(ctx.expressionInPar());
BooleanExpression booleanExpression =
this.configureAST(
new BooleanExpression(conditionExpression),
conditionExpression
);
Statement loopBlock = this.unpackStatement((Statement) this.visit(ctx.statement()));
return this.configureAST(
new DoWhileStatement(booleanExpression, asBoolean(loopBlock) ? loopBlock : EmptyStatement.INSTANCE),
ctx);
}
@Override
public Statement visitTryCatchStmtAlt(TryCatchStmtAltContext ctx) {
return this.configureAST(this.visitTryCatchStatement(ctx.tryCatchStatement()), ctx);
}
@Override
public Statement visitTryCatchStatement(TryCatchStatementContext ctx) {
TryCatchStatement tryCatchStatement =
new TryCatchStatement((Statement) this.visit(ctx.block()),
this.visitFinallyBlock(ctx.finallyBlock()));
if (asBoolean(ctx.resources())) {
this.visitResources(ctx.resources()).forEach(tryCatchStatement::addResource);
}
ctx.catchClause().stream().map(this::visitCatchClause)
.reduce(new LinkedList<CatchStatement>(), (r, e) -> {
r.addAll(e); // merge several LinkedList<CatchStatement> instances into one LinkedList<CatchStatement> instance
return r;
})
.forEach(tryCatchStatement::addCatch);
return this.configureAST(
tryWithResourcesASTTransformation.transform(
this.configureAST(tryCatchStatement, ctx)),
ctx);
}
@Override
public List<ExpressionStatement> visitResources(ResourcesContext ctx) {
return this.visitResourceList(ctx.resourceList());
}
@Override
public List<ExpressionStatement> visitResourceList(ResourceListContext ctx) {
return ctx.resource().stream().map(this::visitResource).collect(Collectors.toList());
}
@Override
public ExpressionStatement visitResource(ResourceContext ctx) {
if (asBoolean(ctx.localVariableDeclaration())) {
List<ExpressionStatement> declarationStatements = this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()).getDeclarationStatements();
if (declarationStatements.size() > 1) {
throw createParsingFailedException("Multi resources can not be declared in one statement", ctx);
}
return declarationStatements.get(0);
} else if (asBoolean(ctx.expression())) {
Expression expression = (Expression) this.visit(ctx.expression());
if (!(expression instanceof BinaryExpression
&& Types.ASSIGN == ((BinaryExpression) expression).getOperation().getType()
&& ((BinaryExpression) expression).getLeftExpression() instanceof VariableExpression)) {
throw createParsingFailedException("Only variable declarations are allowed to declare resource", ctx);
}
BinaryExpression assignmentExpression = (BinaryExpression) expression;
return this.configureAST(
new ExpressionStatement(
this.configureAST(
new DeclarationExpression(
this.configureAST(
new VariableExpression(assignmentExpression.getLeftExpression().getText()),
assignmentExpression.getLeftExpression()
),
assignmentExpression.getOperation(),
assignmentExpression.getRightExpression()
), ctx)
), ctx);
}
throw createParsingFailedException("Unsupported resource declaration: " + ctx.getText(), ctx);
}
/**
* Multi-catch(1..*) clause will be unpacked to several normal catch clauses, so the return type is List
*
* @param ctx the parse tree
* @return a list of CatchStatement instances
*/
@Override
public List<CatchStatement> visitCatchClause(CatchClauseContext ctx) {
// FIXME Groovy will ignore variableModifier of parameter in the catch clause
// In order to make the new parser behave same with the old one, we do not process variableModifier*
return this.visitCatchType(ctx.catchType()).stream()
.map(e -> this.configureAST(
new CatchStatement(
// FIXME The old parser does not set location info for the parameter of the catch clause.
// we could make it better
//this.configureAST(new Parameter(e, this.visitIdentifier(ctx.identifier())), ctx.Identifier()),
new Parameter(e, this.visitIdentifier(ctx.identifier())),
this.visitBlock(ctx.block())),
ctx))
.collect(Collectors.toList());
}
@Override
public List<ClassNode> visitCatchType(CatchTypeContext ctx) {
if (!asBoolean(ctx)) {
return Collections.singletonList(ClassHelper.OBJECT_TYPE);
}
return ctx.qualifiedClassName().stream()
.map(this::visitQualifiedClassName)
.collect(Collectors.toList());
}
@Override
public Statement visitFinallyBlock(FinallyBlockContext ctx) {
if (!asBoolean(ctx)) {
return EmptyStatement.INSTANCE;
}
return this.configureAST(
this.createBlockStatement((Statement) this.visit(ctx.block())),
ctx);
}
@Override
public SwitchStatement visitSwitchStmtAlt(SwitchStmtAltContext ctx) {
return this.configureAST(this.visitSwitchStatement(ctx.switchStatement()), ctx);
}
public SwitchStatement visitSwitchStatement(SwitchStatementContext ctx) {
List<Statement> statementList =
ctx.switchBlockStatementGroup().stream()
.map(this::visitSwitchBlockStatementGroup)
.reduce(new LinkedList<>(), (r, e) -> {
r.addAll(e);
return r;
});
List<CaseStatement> caseStatementList = new LinkedList<>();
List<Statement> defaultStatementList = new LinkedList<>();
statementList.forEach(e -> {
if (e instanceof CaseStatement) {
caseStatementList.add((CaseStatement) e);
} else if (isTrue(e, IS_SWITCH_DEFAULT)) {
defaultStatementList.add(e);
}
});
int defaultStatementListSize = defaultStatementList.size();
if (defaultStatementListSize > 1) {
throw createParsingFailedException("switch statement should have only one default case, which should appear at last", defaultStatementList.get(0));
}
if (defaultStatementListSize > 0 && last(statementList) instanceof CaseStatement) {
throw createParsingFailedException("default case should appear at last", defaultStatementList.get(0));
}
return this.configureAST(
new SwitchStatement(
this.visitExpressionInPar(ctx.expressionInPar()),
caseStatementList,
defaultStatementListSize == 0 ? EmptyStatement.INSTANCE : defaultStatementList.get(0)
),
ctx);
}
@Override
@SuppressWarnings({"unchecked"})
public List<Statement> visitSwitchBlockStatementGroup(SwitchBlockStatementGroupContext ctx) {
int labelCnt = ctx.switchLabel().size();
List<Token> firstLabelHolder = new ArrayList<>(1);
return (List<Statement>) ctx.switchLabel().stream()
.map(e -> (Object) this.visitSwitchLabel(e))
.reduce(new ArrayList<Statement>(4), (r, e) -> {
List<Statement> statementList = (List<Statement>) r;
Pair<Token, Expression> pair = (Pair<Token, Expression>) e;
boolean isLast = labelCnt - 1 == statementList.size();
switch (pair.getKey().getType()) {
case CASE: {
if (!asBoolean(statementList)) {
firstLabelHolder.add(pair.getKey());
}
statementList.add(
this.configureAST(
new CaseStatement(
pair.getValue(),
// check whether processing the last label. if yes, block statement should be attached.
isLast ? this.visitBlockStatements(ctx.blockStatements())
: EmptyStatement.INSTANCE
),
firstLabelHolder.get(0)));
break;
}
case DEFAULT: {
BlockStatement blockStatement = this.visitBlockStatements(ctx.blockStatements());
blockStatement.putNodeMetaData(IS_SWITCH_DEFAULT, true);
statementList.add(
// this.configureAST(blockStatement, pair.getKey())
blockStatement
);
break;
}
}
return statementList;
});
}
@Override
public Pair<Token, Expression> visitSwitchLabel(SwitchLabelContext ctx) {
if (asBoolean(ctx.CASE())) {
return new Pair<>(ctx.CASE().getSymbol(), (Expression) this.visit(ctx.expression()));
} else if (asBoolean(ctx.DEFAULT())) {
return new Pair<>(ctx.DEFAULT().getSymbol(), EmptyExpression.INSTANCE);
}
throw createParsingFailedException("Unsupported switch label: " + ctx.getText(), ctx);
}
@Override
public SynchronizedStatement visitSynchronizedStmtAlt(SynchronizedStmtAltContext ctx) {
return this.configureAST(
new SynchronizedStatement(this.visitExpressionInPar(ctx.expressionInPar()), this.visitBlock(ctx.block())),
ctx);
}
@Override
public ExpressionStatement visitExpressionStmtAlt(ExpressionStmtAltContext ctx) {
return (ExpressionStatement) this.visit(ctx.statementExpression());
}
@Override
public ReturnStatement visitReturnStmtAlt(ReturnStmtAltContext ctx) {
return this.configureAST(new ReturnStatement(asBoolean(ctx.expression())
? (Expression) this.visit(ctx.expression())
: ConstantExpression.EMPTY_EXPRESSION),
ctx);
}
@Override
public ThrowStatement visitThrowStmtAlt(ThrowStmtAltContext ctx) {
return this.configureAST(
new ThrowStatement((Expression) this.visit(ctx.expression())),
ctx);
}
@Override
public Statement visitLabeledStmtAlt(LabeledStmtAltContext ctx) {
Statement statement = (Statement) this.visit(ctx.statement());
statement.addStatementLabel(this.visitIdentifier(ctx.identifier()));
return statement; // this.configureAST(statement, ctx);
}
@Override
public BreakStatement visitBreakStatement(BreakStatementContext ctx) {
String label = asBoolean(ctx.identifier())
? this.visitIdentifier(ctx.identifier())
: null;
return this.configureAST(new BreakStatement(label), ctx);
}
@Override
public BreakStatement visitBreakStmtAlt(BreakStmtAltContext ctx) {
return this.configureAST(this.visitBreakStatement(ctx.breakStatement()), ctx);
}
@Override
public ContinueStatement visitContinueStatement(ContinueStatementContext ctx) {
String label = asBoolean(ctx.identifier())
? this.visitIdentifier(ctx.identifier())
: null;
return this.configureAST(new ContinueStatement(label), ctx);
}
@Override
public ContinueStatement visitContinueStmtAlt(ContinueStmtAltContext ctx) {
return this.configureAST(this.visitContinueStatement(ctx.continueStatement()), ctx);
}
@Override
public ImportNode visitImportStmtAlt(ImportStmtAltContext ctx) {
return this.configureAST(this.visitImportDeclaration(ctx.importDeclaration()), ctx);
}
@Override
public ClassNode visitTypeDeclarationStmtAlt(TypeDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitTypeDeclaration(ctx.typeDeclaration()), ctx);
}
@Override
public Statement visitLocalVariableDeclarationStmtAlt(LocalVariableDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx);
}
@Override
public MethodNode visitMethodDeclarationStmtAlt(MethodDeclarationStmtAltContext ctx) {
return this.configureAST(this.visitMethodDeclaration(ctx.methodDeclaration()), ctx);
}
// } statement --------------------------------------------------------------------
@Override
public ClassNode visitTypeDeclaration(TypeDeclarationContext ctx) {
if (asBoolean(ctx.classDeclaration())) { // e.g. class A {}
ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitClassOrInterfaceModifiersOpt(ctx.classOrInterfaceModifiersOpt()));
return this.configureAST(this.visitClassDeclaration(ctx.classDeclaration()), ctx);
}
throw createParsingFailedException("Unsupported type declaration: " + ctx.getText(), ctx);
}
private void initUsingGenerics(ClassNode classNode) {
if (classNode.isUsingGenerics()) {
return;
}
if (!classNode.isEnum()) {
classNode.setUsingGenerics(classNode.getSuperClass().isUsingGenerics());
}
if (!classNode.isUsingGenerics() && null != classNode.getInterfaces()) {
for (ClassNode anInterface : classNode.getInterfaces()) {
classNode.setUsingGenerics(classNode.isUsingGenerics() || anInterface.isUsingGenerics());
if (classNode.isUsingGenerics())
break;
}
}
}
@Override
public ClassNode visitClassDeclaration(ClassDeclarationContext ctx) {
String packageName = moduleNode.getPackageName();
packageName = null != packageName ? packageName : "";
List<ModifierNode> modifierNodeList = ctx.getNodeMetaData(TYPE_DECLARATION_MODIFIERS);
Objects.requireNonNull(modifierNodeList, "modifierNodeList should not be null");
ModifierManager modifierManager = new ModifierManager(this, modifierNodeList);
int modifiers = modifierManager.getClassModifiersOpValue();
boolean syntheticPublic = ((modifiers & Opcodes.ACC_SYNTHETIC) != 0);
modifiers &= ~Opcodes.ACC_SYNTHETIC;
final ClassNode outerClass = classNodeStack.peek();
ClassNode classNode;
String className = this.visitIdentifier(ctx.identifier());
if (asBoolean(ctx.ENUM())) {
classNode =
EnumHelper.makeEnumNode(
asBoolean(outerClass) ? className : packageName + className,
modifiers, null, outerClass);
} else {
if (asBoolean(outerClass)) {
classNode =
new InnerClassNode(
outerClass,
outerClass.getName() + "$" + className,
modifiers | (outerClass.isInterface() ? Opcodes.ACC_STATIC : 0),
ClassHelper.OBJECT_TYPE);
} else {
classNode =
new ClassNode(
packageName + className,
modifiers,
ClassHelper.OBJECT_TYPE);
}
}
this.configureAST(classNode, ctx);
classNode.putNodeMetaData(CLASS_NAME, className);
classNode.setSyntheticPublic(syntheticPublic);
if (asBoolean(ctx.TRAIT())) {
classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT)));
}
classNode.addAnnotations(modifierManager.getAnnotations());
classNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters()));
boolean isInterface = asBoolean(ctx.INTERFACE()) && !asBoolean(ctx.AT());
boolean isInterfaceWithDefaultMethods = false;
// declaring interface with default method
if (isInterface && this.containsDefaultMethods(ctx)) {
isInterfaceWithDefaultMethods = true;
classNode.addAnnotation(new AnnotationNode(ClassHelper.make(GROOVY_TRANSFORM_TRAIT)));
classNode.putNodeMetaData(IS_INTERFACE_WITH_DEFAULT_METHODS, true);
}
if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()) || isInterfaceWithDefaultMethods) { // class OR trait OR interface with default methods
classNode.setSuperClass(this.visitType(ctx.sc));
classNode.setInterfaces(this.visitTypeList(ctx.is));
this.initUsingGenerics(classNode);
} else if (isInterface) { // interface(NOT annotation)
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT);
classNode.setSuperClass(ClassHelper.OBJECT_TYPE);
classNode.setInterfaces(this.visitTypeList(ctx.scs));
this.initUsingGenerics(classNode);
this.hackMixins(classNode);
} else if (asBoolean(ctx.ENUM())) { // enum
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_ENUM | Opcodes.ACC_FINAL);
classNode.setInterfaces(this.visitTypeList(ctx.is));
this.initUsingGenerics(classNode);
} else if (asBoolean(ctx.AT())) { // annotation
classNode.setModifiers(classNode.getModifiers() | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_ANNOTATION);
classNode.addInterface(ClassHelper.Annotation_TYPE);
this.hackMixins(classNode);
} else {
throw createParsingFailedException("Unsupported class declaration: " + ctx.getText(), ctx);
}
// we put the class already in output to avoid the most inner classes
// will be used as first class later in the loader. The first class
// there determines what GCL#parseClass for example will return, so we
// have here to ensure it won't be the inner class
if (asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT())) {
classNodeList.add(classNode);
}
int oldAnonymousInnerClassCounter = this.anonymousInnerClassCounter;
classNodeStack.push(classNode);
ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassBody(ctx.classBody());
classNodeStack.pop();
this.anonymousInnerClassCounter = oldAnonymousInnerClassCounter;
if (!(asBoolean(ctx.CLASS()) || asBoolean(ctx.TRAIT()))) {
classNodeList.add(classNode);
}
groovydocManager.handle(classNode, ctx);
return classNode;
}
@SuppressWarnings({"unchecked"})
private boolean containsDefaultMethods(ClassDeclarationContext ctx) {
List<MethodDeclarationContext> methodDeclarationContextList =
(List<MethodDeclarationContext>) ctx.classBody().classBodyDeclaration().stream()
.map(ClassBodyDeclarationContext::memberDeclaration)
.filter(Objects::nonNull)
.map(e -> (Object) e.methodDeclaration())
.filter(Objects::nonNull).reduce(new LinkedList<MethodDeclarationContext>(), (r, e) -> {
MethodDeclarationContext methodDeclarationContext = (MethodDeclarationContext) e;
if (createModifierManager(methodDeclarationContext).contains(DEFAULT)) {
((List) r).add(methodDeclarationContext);
}
return r;
});
return !methodDeclarationContextList.isEmpty();
}
@Override
public Void visitClassBody(ClassBodyContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.enumConstants())) {
ctx.enumConstants().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitEnumConstants(ctx.enumConstants());
}
ctx.classBodyDeclaration().forEach(e -> {
e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassBodyDeclaration(e);
});
return null;
}
@Override
public List<FieldNode> visitEnumConstants(EnumConstantsContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
return ctx.enumConstant().stream()
.map(e -> {
e.putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
return this.visitEnumConstant(e);
})
.collect(Collectors.toList());
}
@Override
public FieldNode visitEnumConstant(EnumConstantContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
InnerClassNode anonymousInnerClassNode = null;
if (asBoolean(ctx.anonymousInnerClassDeclaration())) {
ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode);
anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration());
}
FieldNode enumConstant =
EnumHelper.addEnumConstant(
classNode,
this.visitIdentifier(ctx.identifier()),
createEnumConstantInitExpression(ctx.arguments(), anonymousInnerClassNode));
enumConstant.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
groovydocManager.handle(enumConstant, ctx);
return this.configureAST(enumConstant, ctx);
}
private Expression createEnumConstantInitExpression(ArgumentsContext ctx, InnerClassNode anonymousInnerClassNode) {
if (!asBoolean(ctx) && !asBoolean(anonymousInnerClassNode)) {
return null;
}
TupleExpression argumentListExpression = (TupleExpression) this.visitArguments(ctx);
List<Expression> expressions = argumentListExpression.getExpressions();
if (expressions.size() == 1) {
Expression expression = expressions.get(0);
if (expression instanceof NamedArgumentListExpression) { // e.g. SOME_ENUM_CONSTANT(a: "1", b: "2")
List<MapEntryExpression> mapEntryExpressionList = ((NamedArgumentListExpression) expression).getMapEntryExpressions();
ListExpression listExpression =
new ListExpression(
mapEntryExpressionList.stream()
.map(e -> (Expression) e)
.collect(Collectors.toList()));
if (asBoolean(anonymousInnerClassNode)) {
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
}
if (mapEntryExpressionList.size() > 1) {
listExpression.setWrapped(true);
}
return this.configureAST(listExpression, ctx);
}
if (!asBoolean(anonymousInnerClassNode)) {
if (expression instanceof ListExpression) {
ListExpression listExpression = new ListExpression();
listExpression.addExpression(expression);
return this.configureAST(listExpression, ctx);
}
return expression;
}
ListExpression listExpression = new ListExpression();
if (expression instanceof ListExpression) {
((ListExpression) expression).getExpressions().forEach(listExpression::addExpression);
} else {
listExpression.addExpression(expression);
}
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
return this.configureAST(listExpression, ctx);
}
ListExpression listExpression = new ListExpression(expressions);
if (asBoolean(anonymousInnerClassNode)) {
listExpression.addExpression(
this.configureAST(
new ClassExpression(anonymousInnerClassNode),
anonymousInnerClassNode));
}
if (asBoolean(ctx)) {
listExpression.setWrapped(true);
}
return asBoolean(ctx)
? this.configureAST(listExpression, ctx)
: this.configureAST(listExpression, anonymousInnerClassNode);
}
@Override
public Void visitClassBodyDeclaration(ClassBodyDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.memberDeclaration())) {
ctx.memberDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitMemberDeclaration(ctx.memberDeclaration());
} else if (asBoolean(ctx.block())) {
Statement statement = this.visitBlock(ctx.block());
if (asBoolean(ctx.STATIC())) { // e.g. static { }
classNode.addStaticInitializerStatements(Collections.singletonList(statement), false);
} else { // e.g. { }
classNode.addObjectInitializerStatements(
this.configureAST(
this.createBlockStatement(statement),
statement));
}
}
return null;
}
@Override
public Void visitMemberDeclaration(MemberDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
if (asBoolean(ctx.methodDeclaration())) {
ctx.methodDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitMethodDeclaration(ctx.methodDeclaration());
} else if (asBoolean(ctx.fieldDeclaration())) {
ctx.fieldDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitFieldDeclaration(ctx.fieldDeclaration());
} else if (asBoolean(ctx.classDeclaration())) {
ctx.classDeclaration().putNodeMetaData(TYPE_DECLARATION_MODIFIERS, this.visitModifiersOpt(ctx.modifiersOpt()));
ctx.classDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitClassDeclaration(ctx.classDeclaration());
}
return null;
}
@Override
public GenericsType[] visitTypeParameters(TypeParametersContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return ctx.typeParameter().stream()
.map(this::visitTypeParameter)
.toArray(GenericsType[]::new);
}
@Override
public GenericsType visitTypeParameter(TypeParameterContext ctx) {
return this.configureAST(
new GenericsType(
this.configureAST(ClassHelper.make(this.visitClassName(ctx.className())), ctx),
this.visitTypeBound(ctx.typeBound()),
null
),
ctx);
}
@Override
public ClassNode[] visitTypeBound(TypeBoundContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return ctx.type().stream()
.map(this::visitType)
.toArray(ClassNode[]::new);
}
@Override
public Void visitFieldDeclaration(FieldDeclarationContext ctx) {
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
Objects.requireNonNull(classNode, "classNode should not be null");
ctx.variableDeclaration().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, classNode);
this.visitVariableDeclaration(ctx.variableDeclaration());
return null;
}
private ConstructorCallExpression checkThisAndSuperConstructorCall(Statement statement) {
if (!(statement instanceof BlockStatement)) { // method code must be a BlockStatement
return null;
}
BlockStatement blockStatement = (BlockStatement) statement;
List<Statement> statementList = blockStatement.getStatements();
for (int i = 0, n = statementList.size(); i < n; i++) {
Statement s = statementList.get(i);
if (s instanceof ExpressionStatement) {
Expression expression = ((ExpressionStatement) s).getExpression();
if ((expression instanceof ConstructorCallExpression) && 0 != i) {
return (ConstructorCallExpression) expression;
}
}
}
return null;
}
private ModifierManager createModifierManager(MethodDeclarationContext ctx) {
List<ModifierNode> modifierNodeList = Collections.emptyList();
if (asBoolean(ctx.modifiers())) {
modifierNodeList = this.visitModifiers(ctx.modifiers());
} else if (asBoolean(ctx.modifiersOpt())) {
modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt());
}
return new ModifierManager(this, modifierNodeList);
}
private void validateParametersOfMethodDeclaration(Parameter[] parameters, ClassNode classNode) {
if (!classNode.isInterface()) {
return;
}
for (Parameter parameter : parameters) {
if (parameter.hasInitialExpression()) {
throw createParsingFailedException("Cannot specify default value for method parameter '" + parameter.getName() + " = " + parameter.getInitialExpression().getText() + "' inside an interface", parameter);
}
}
}
@Override
public MethodNode visitMethodDeclaration(MethodDeclarationContext ctx) {
ModifierManager modifierManager = createModifierManager(ctx);
String methodName = this.visitMethodName(ctx.methodName());
ClassNode returnType = this.visitReturnType(ctx.returnType());
Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters());
ClassNode[] exceptions = this.visitQualifiedClassNameList(ctx.qualifiedClassNameList());
anonymousInnerClassesDefinedInMethodStack.push(new LinkedList<>());
Statement code = this.visitMethodBody(ctx.methodBody());
List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.pop();
MethodNode methodNode;
// if classNode is not null, the method declaration is for class declaration
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
if (asBoolean(classNode)) {
validateParametersOfMethodDeclaration(parameters, classNode);
methodNode = createConstructorOrMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode);
} else { // script method declaration
methodNode = createScriptMethodNode(modifierManager, methodName, returnType, parameters, exceptions, code);
}
anonymousInnerClassList.forEach(e -> e.setEnclosingMethod(methodNode));
methodNode.setGenericsTypes(this.visitTypeParameters(ctx.typeParameters()));
methodNode.setSyntheticPublic(
this.isSyntheticPublic(
this.isAnnotationDeclaration(classNode),
classNode instanceof EnumConstantClassNode,
asBoolean(ctx.returnType()),
modifierManager));
if (modifierManager.contains(STATIC)) {
for (Parameter parameter : methodNode.getParameters()) {
parameter.setInStaticContext(true);
}
methodNode.getVariableScope().setInStaticContext(true);
}
this.configureAST(methodNode, ctx);
validateMethodDeclaration(ctx, methodNode, modifierManager, classNode);
groovydocManager.handle(methodNode, ctx);
return methodNode;
}
private void validateMethodDeclaration(MethodDeclarationContext ctx, MethodNode methodNode, ModifierManager modifierManager, ClassNode classNode) {
boolean isAbstractMethod = methodNode.isAbstract();
boolean hasMethodBody = asBoolean(methodNode.getCode());
if (9 == ctx.ct) { // script
if (isAbstractMethod || !hasMethodBody) { // method should not be declared abstract in the script
throw createParsingFailedException("You can not define a " + (isAbstractMethod ? "abstract" : "") + " method[" + methodNode.getName() + "] " + (!hasMethodBody ? "without method body" : "") + " in the script. Try " + (isAbstractMethod ? "removing the 'abstract'" : "") + (isAbstractMethod && !hasMethodBody ? " and" : "") + (!hasMethodBody ? " adding a method body" : ""), methodNode);
}
} else {
if (!isAbstractMethod && !hasMethodBody) { // non-abstract method without body in the non-script(e.g. class, enum, trait) is not allowed!
throw createParsingFailedException("You defined a method[" + methodNode.getName() + "] without body. Try adding a method body, or declare it abstract", methodNode);
}
boolean isInterfaceOrAbstractClass = asBoolean(classNode) && classNode.isAbstract() && !classNode.isAnnotationDefinition();
if (isInterfaceOrAbstractClass && !modifierManager.contains(DEFAULT) && isAbstractMethod && hasMethodBody) {
throw createParsingFailedException("You defined an abstract method[" + methodNode.getName() + "] with body. Try removing the method body" + (classNode.isInterface() ? ", or declare it default" : ""), methodNode);
}
}
modifierManager.validate(methodNode);
if (methodNode instanceof ConstructorNode) {
modifierManager.validate((ConstructorNode) methodNode);
}
}
private MethodNode createScriptMethodNode(ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
MethodNode methodNode;
methodNode =
new MethodNode(
methodName,
modifierManager.contains(PRIVATE) ? Opcodes.ACC_PRIVATE : Opcodes.ACC_PUBLIC,
returnType,
parameters,
exceptions,
code);
modifierManager.processMethodNode(methodNode);
return methodNode;
}
private MethodNode createConstructorOrMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode) {
MethodNode methodNode;
String className = classNode.getNodeMetaData(CLASS_NAME);
int modifiers = modifierManager.getClassMemberModifiersOpValue();
boolean hasReturnType = asBoolean(ctx.returnType());
boolean hasMethodBody = asBoolean(ctx.methodBody());
if (!hasReturnType
&& hasMethodBody
&& methodName.equals(className)) { // constructor declaration
methodNode = createConstructorNodeForClass(methodName, parameters, exceptions, code, classNode, modifiers);
} else { // class memeber method declaration
if (!hasReturnType && hasMethodBody && (0 == modifierManager.getModifierCount())) {
throw createParsingFailedException("Invalid method declaration: " + methodName, ctx);
}
methodNode = createMethodNodeForClass(ctx, modifierManager, methodName, returnType, parameters, exceptions, code, classNode, modifiers);
}
modifierManager.attachAnnotations(methodNode);
return methodNode;
}
private MethodNode createMethodNodeForClass(MethodDeclarationContext ctx, ModifierManager modifierManager, String methodName, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) {
MethodNode methodNode;
if (asBoolean(ctx.elementValue())) { // the code of annotation method
code = this.configureAST(
new ExpressionStatement(
this.visitElementValue(ctx.elementValue())),
ctx.elementValue());
}
modifiers |= !modifierManager.contains(STATIC) && (classNode.isInterface() || (isTrue(classNode, IS_INTERFACE_WITH_DEFAULT_METHODS) && !modifierManager.contains(DEFAULT))) ? Opcodes.ACC_ABSTRACT : 0;
checkWhetherMethodNodeWithSameSignatureExists(classNode, methodName, parameters, ctx);
methodNode = classNode.addMethod(methodName, modifiers, returnType, parameters, exceptions, code);
methodNode.setAnnotationDefault(asBoolean(ctx.elementValue()));
return methodNode;
}
private void checkWhetherMethodNodeWithSameSignatureExists(ClassNode classNode, String methodName, Parameter[] parameters, MethodDeclarationContext ctx) {
MethodNode sameSigMethodNode = classNode.getDeclaredMethod(methodName, parameters);
if (null == sameSigMethodNode) {
return;
}
throw createParsingFailedException("The method " + sameSigMethodNode.getText() + " duplicates another method of the same signature", ctx);
}
private ConstructorNode createConstructorNodeForClass(String methodName, Parameter[] parameters, ClassNode[] exceptions, Statement code, ClassNode classNode, int modifiers) {
ConstructorCallExpression thisOrSuperConstructorCallExpression = this.checkThisAndSuperConstructorCall(code);
if (asBoolean(thisOrSuperConstructorCallExpression)) {
throw createParsingFailedException(thisOrSuperConstructorCallExpression.getText() + " should be the first statement in the constructor[" + methodName + "]", thisOrSuperConstructorCallExpression);
}
return classNode.addConstructor(
modifiers,
parameters,
exceptions,
code);
}
@Override
public String visitMethodName(MethodNameContext ctx) {
if (asBoolean(ctx.identifier())) {
return this.visitIdentifier(ctx.identifier());
}
if (asBoolean(ctx.stringLiteral())) {
return this.visitStringLiteral(ctx.stringLiteral()).getText();
}
throw createParsingFailedException("Unsupported method name: " + ctx.getText(), ctx);
}
@Override
public ClassNode visitReturnType(ReturnTypeContext ctx) {
if (!asBoolean(ctx)) {
return ClassHelper.OBJECT_TYPE;
}
if (asBoolean(ctx.type())) {
return this.visitType(ctx.type());
}
if (asBoolean(ctx.VOID())) {
return ClassHelper.VOID_TYPE;
}
throw createParsingFailedException("Unsupported return type: " + ctx.getText(), ctx);
}
@Override
public Statement visitMethodBody(MethodBodyContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return this.configureAST(this.visitBlock(ctx.block()), ctx);
}
@Override
public DeclarationListStatement visitLocalVariableDeclaration(LocalVariableDeclarationContext ctx) {
return this.configureAST(this.visitVariableDeclaration(ctx.variableDeclaration()), ctx);
}
private ModifierManager createModifierManager(VariableDeclarationContext ctx) {
List<ModifierNode> modifierNodeList = Collections.emptyList();
if (asBoolean(ctx.variableModifiers())) {
modifierNodeList = this.visitVariableModifiers(ctx.variableModifiers());
} else if (asBoolean(ctx.variableModifiersOpt())) {
modifierNodeList = this.visitVariableModifiersOpt(ctx.variableModifiersOpt());
} else if (asBoolean(ctx.modifiers())) {
modifierNodeList = this.visitModifiers(ctx.modifiers());
} else if (asBoolean(ctx.modifiersOpt())) {
modifierNodeList = this.visitModifiersOpt(ctx.modifiersOpt());
}
return new ModifierManager(this, modifierNodeList);
}
private DeclarationListStatement createMultiAssignmentDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager) {
if (!modifierManager.contains(DEF)) {
throw createParsingFailedException("keyword def is required to declare tuple, e.g. def (int a, int b) = [1, 2]", ctx);
}
return this.configureAST(
new DeclarationListStatement(
this.configureAST(
modifierManager.attachAnnotations(
new DeclarationExpression(
new ArgumentListExpression(
this.visitTypeNamePairs(ctx.typeNamePairs()).stream()
.peek(e -> modifierManager.processVariableExpression((VariableExpression) e))
.collect(Collectors.toList())
),
this.createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN),
this.visitVariableInitializer(ctx.variableInitializer())
)
),
ctx
)
),
ctx
);
}
@Override
public DeclarationListStatement visitVariableDeclaration(VariableDeclarationContext ctx) {
ModifierManager modifierManager = this.createModifierManager(ctx);
if (asBoolean(ctx.typeNamePairs())) { // e.g. def (int a, int b) = [1, 2]
return this.createMultiAssignmentDeclarationListStatement(ctx, modifierManager);
}
ClassNode variableType = this.visitType(ctx.type());
ctx.variableDeclarators().putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType);
List<DeclarationExpression> declarationExpressionList = this.visitVariableDeclarators(ctx.variableDeclarators());
// if classNode is not null, the variable declaration is for class declaration. In other words, it is a field declaration
ClassNode classNode = ctx.getNodeMetaData(CLASS_DECLARATION_CLASS_NODE);
if (asBoolean(classNode)) {
return createFieldDeclarationListStatement(ctx, modifierManager, variableType, declarationExpressionList, classNode);
}
declarationExpressionList.forEach(e -> {
VariableExpression variableExpression = (VariableExpression) e.getLeftExpression();
modifierManager.processVariableExpression(variableExpression);
modifierManager.attachAnnotations(e);
});
int size = declarationExpressionList.size();
if (size > 0) {
DeclarationExpression declarationExpression = declarationExpressionList.get(0);
if (1 == size) {
this.configureAST(declarationExpression, ctx);
} else {
// Tweak start of first declaration
declarationExpression.setLineNumber(ctx.getStart().getLine());
declarationExpression.setColumnNumber(ctx.getStart().getCharPositionInLine() + 1);
}
}
return this.configureAST(new DeclarationListStatement(declarationExpressionList), ctx);
}
private DeclarationListStatement createFieldDeclarationListStatement(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, List<DeclarationExpression> declarationExpressionList, ClassNode classNode) {
for (int i = 0, n = declarationExpressionList.size(); i < n; i++) {
DeclarationExpression declarationExpression = declarationExpressionList.get(i);
VariableExpression variableExpression = (VariableExpression) declarationExpression.getLeftExpression();
String fieldName = variableExpression.getName();
int modifiers = modifierManager.getClassMemberModifiersOpValue();
Expression initialValue = EmptyExpression.INSTANCE.equals(declarationExpression.getRightExpression()) ? null : declarationExpression.getRightExpression();
Object defaultValue = findDefaultValueByType(variableType);
if (classNode.isInterface()) {
if (!asBoolean(initialValue)) {
initialValue = !asBoolean(defaultValue) ? null : new ConstantExpression(defaultValue);
}
modifiers |= Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
}
if (isFieldDeclaration(modifierManager, classNode)) {
declareField(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue);
} else {
declareProperty(ctx, modifierManager, variableType, classNode, i, variableExpression, fieldName, modifiers, initialValue);
}
}
return null;
}
private void declareProperty(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) {
if (classNode.hasProperty(fieldName)) {
throw createParsingFailedException("The property '" + fieldName + "' is declared multiple times", ctx);
}
PropertyNode propertyNode;
FieldNode fieldNode = classNode.getDeclaredField(fieldName);
if (fieldNode != null && !classNode.hasProperty(fieldName)) {
classNode.getFields().remove(fieldNode);
propertyNode = new PropertyNode(fieldNode, modifiers | Opcodes.ACC_PUBLIC, null, null);
classNode.addProperty(propertyNode);
} else {
propertyNode =
classNode.addProperty(
fieldName,
modifiers | Opcodes.ACC_PUBLIC,
variableType,
initialValue,
null,
null);
fieldNode = propertyNode.getField();
}
fieldNode.setModifiers(modifiers & ~Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE);
fieldNode.setSynthetic(!classNode.isInterface());
modifierManager.attachAnnotations(fieldNode);
groovydocManager.handle(fieldNode, ctx);
groovydocManager.handle(propertyNode, ctx);
if (0 == i) {
this.configureAST(fieldNode, ctx, initialValue);
this.configureAST(propertyNode, ctx, initialValue);
} else {
this.configureAST(fieldNode, variableExpression, initialValue);
this.configureAST(propertyNode, variableExpression, initialValue);
}
}
private void declareField(VariableDeclarationContext ctx, ModifierManager modifierManager, ClassNode variableType, ClassNode classNode, int i, VariableExpression variableExpression, String fieldName, int modifiers, Expression initialValue) {
FieldNode existingFieldNode = classNode.getDeclaredField(fieldName);
if (null != existingFieldNode && !existingFieldNode.isSynthetic()) {
throw createParsingFailedException("The field '" + fieldName + "' is declared multiple times", ctx);
}
FieldNode fieldNode;
PropertyNode propertyNode = classNode.getProperty(fieldName);
if (null != propertyNode && propertyNode.getField().isSynthetic()) {
classNode.getFields().remove(propertyNode.getField());
fieldNode = new FieldNode(fieldName, modifiers, variableType, classNode.redirect(), initialValue);
propertyNode.setField(fieldNode);
classNode.addField(fieldNode);
} else {
fieldNode =
classNode.addField(
fieldName,
modifiers,
variableType,
initialValue);
}
modifierManager.attachAnnotations(fieldNode);
groovydocManager.handle(fieldNode, ctx);
if (0 == i) {
this.configureAST(fieldNode, ctx, initialValue);
} else {
this.configureAST(fieldNode, variableExpression, initialValue);
}
}
private boolean isFieldDeclaration(ModifierManager modifierManager, ClassNode classNode) {
return classNode.isInterface() || modifierManager.containsVisibilityModifier();
}
@Override
public List<Expression> visitTypeNamePairs(TypeNamePairsContext ctx) {
return ctx.typeNamePair().stream().map(this::visitTypeNamePair).collect(Collectors.toList());
}
@Override
public VariableExpression visitTypeNamePair(TypeNamePairContext ctx) {
return this.configureAST(
new VariableExpression(
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(),
this.visitType(ctx.type())),
ctx);
}
@Override
public List<DeclarationExpression> visitVariableDeclarators(VariableDeclaratorsContext ctx) {
ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE);
Objects.requireNonNull(variableType, "variableType should not be null");
return ctx.variableDeclarator().stream()
.map(e -> {
e.putNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE, variableType);
return this.visitVariableDeclarator(e);
// return this.configureAST(this.visitVariableDeclarator(e), ctx);
})
.collect(Collectors.toList());
}
@Override
public DeclarationExpression visitVariableDeclarator(VariableDeclaratorContext ctx) {
ClassNode variableType = ctx.getNodeMetaData(VARIABLE_DECLARATION_VARIABLE_TYPE);
Objects.requireNonNull(variableType, "variableType should not be null");
org.codehaus.groovy.syntax.Token token;
if (asBoolean(ctx.ASSIGN())) {
token = createGroovyTokenByType(ctx.ASSIGN().getSymbol(), Types.ASSIGN);
} else {
token = new org.codehaus.groovy.syntax.Token(Types.ASSIGN, ASSIGN_STR, ctx.start.getLine(), 1);
}
return this.configureAST(
new DeclarationExpression(
this.configureAST(
new VariableExpression(
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName(),
variableType
),
ctx.variableDeclaratorId()),
token,
this.visitVariableInitializer(ctx.variableInitializer())),
ctx);
}
@Override
public Expression visitVariableInitializer(VariableInitializerContext ctx) {
if (!asBoolean(ctx)) {
return EmptyExpression.INSTANCE;
}
return this.configureAST(
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression()),
ctx);
}
@Override
public List<Expression> visitVariableInitializers(VariableInitializersContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return ctx.variableInitializer().stream()
.map(this::visitVariableInitializer)
.collect(Collectors.toList());
}
@Override
public List<Expression> visitArrayInitializer(ArrayInitializerContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.visitVariableInitializers(ctx.variableInitializers());
}
@Override
public Statement visitBlock(BlockContext ctx) {
if (!asBoolean(ctx)) {
return this.createBlockStatement();
}
return this.configureAST(
this.visitBlockStatementsOpt(ctx.blockStatementsOpt()),
ctx);
}
@Override
public ExpressionStatement visitNormalExprAlt(NormalExprAltContext ctx) {
return this.configureAST(new ExpressionStatement((Expression) this.visit(ctx.expression())), ctx);
}
@Override
public ExpressionStatement visitCommandExprAlt(CommandExprAltContext ctx) {
return this.configureAST(new ExpressionStatement(this.visitCommandExpression(ctx.commandExpression())), ctx);
}
@Override
public Expression visitCommandExpression(CommandExpressionContext ctx) {
Expression baseExpr = this.visitPathExpression(ctx.pathExpression());
Expression arguments = this.visitEnhancedArgumentList(ctx.enhancedArgumentList());
MethodCallExpression methodCallExpression;
if (baseExpr instanceof PropertyExpression) { // e.g. obj.a 1, 2
methodCallExpression =
this.configureAST(
this.createMethodCallExpression(
(PropertyExpression) baseExpr, arguments),
arguments);
} else if (baseExpr instanceof MethodCallExpression && !isInsideParentheses(baseExpr)) { // e.g. m {} a, b OR m(...) a, b
if (asBoolean(arguments)) {
// The error should never be thrown.
throw new GroovyBugError("When baseExpr is a instance of MethodCallExpression, which should follow NO argumentList");
}
methodCallExpression = (MethodCallExpression) baseExpr;
} else if (
!isInsideParentheses(baseExpr)
&& (baseExpr instanceof VariableExpression /* e.g. m 1, 2 */
|| baseExpr instanceof GStringExpression /* e.g. "$m" 1, 2 */
|| (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING)) /* e.g. "m" 1, 2 */)
) {
methodCallExpression =
this.configureAST(
this.createMethodCallExpression(baseExpr, arguments),
arguments);
} else { // e.g. a[x] b, new A() b, etc.
methodCallExpression =
this.configureAST(
new MethodCallExpression(
baseExpr,
CALL_STR,
arguments
),
arguments
);
methodCallExpression.setImplicitThis(false);
}
if (!asBoolean(ctx.commandArgument())) {
return this.configureAST(methodCallExpression, ctx);
}
return this.configureAST(
(Expression) ctx.commandArgument().stream()
.map(e -> (Object) e)
.reduce(methodCallExpression,
(r, e) -> {
CommandArgumentContext commandArgumentContext = (CommandArgumentContext) e;
commandArgumentContext.putNodeMetaData(CMD_EXPRESSION_BASE_EXPR, r);
return this.visitCommandArgument(commandArgumentContext);
}
),
ctx);
}
@Override
public Expression visitCommandArgument(CommandArgumentContext ctx) {
// e.g. x y a b we call "x y" as the base expression
Expression baseExpr = ctx.getNodeMetaData(CMD_EXPRESSION_BASE_EXPR);
Expression primaryExpr = (Expression) this.visit(ctx.primary());
if (asBoolean(ctx.enhancedArgumentList())) { // e.g. x y a b
if (baseExpr instanceof PropertyExpression) { // the branch should never reach, because a.b.c will be parsed as a path expression, not a method call
throw createParsingFailedException("Unsupported command argument: " + ctx.getText(), ctx);
}
// the following code will process "a b" of "x y a b"
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
this.createConstantExpression(primaryExpr),
this.visitEnhancedArgumentList(ctx.enhancedArgumentList())
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
} else if (asBoolean(ctx.pathElement())) { // e.g. x y a.b
Expression pathExpression =
this.createPathExpression(
this.configureAST(
new PropertyExpression(baseExpr, this.createConstantExpression(primaryExpr)),
primaryExpr
),
ctx.pathElement()
);
return this.configureAST(pathExpression, ctx);
}
// e.g. x y a
return this.configureAST(
new PropertyExpression(
baseExpr,
primaryExpr instanceof VariableExpression
? this.createConstantExpression(primaryExpr)
: primaryExpr
),
primaryExpr
);
}
// expression { --------------------------------------------------------------------
@Override
public ClassNode visitCastParExpression(CastParExpressionContext ctx) {
return this.visitType(ctx.type());
}
@Override
public Expression visitParExpression(ParExpressionContext ctx) {
Expression expression = this.visitExpressionInPar(ctx.expressionInPar());
Integer insideParenLevel = expression.getNodeMetaData(INSIDE_PARENTHESES_LEVEL);
if (null != insideParenLevel) {
insideParenLevel++;
} else {
insideParenLevel = 1;
}
expression.putNodeMetaData(INSIDE_PARENTHESES_LEVEL, insideParenLevel);
return this.configureAST(expression, ctx);
}
@Override
public Expression visitExpressionInPar(ExpressionInParContext ctx) {
return this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression());
}
@Override
public Expression visitEnhancedStatementExpression(EnhancedStatementExpressionContext ctx) {
Expression expression;
if (asBoolean(ctx.statementExpression())) {
expression = ((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression();
} else if (asBoolean(ctx.standardLambdaExpression())) {
expression = this.visitStandardLambdaExpression(ctx.standardLambdaExpression());
} else {
throw createParsingFailedException("Unsupported enhanced statement expression: " + ctx.getText(), ctx);
}
return this.configureAST(expression, ctx);
}
@Override
public Expression visitPathExpression(PathExpressionContext ctx) {
return //this.configureAST(
this.createPathExpression((Expression) this.visit(ctx.primary()), ctx.pathElement());
//ctx);
}
@Override
public Expression visitPathElement(PathElementContext ctx) {
Expression baseExpr = ctx.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR);
Objects.requireNonNull(baseExpr, "baseExpr is required!");
if (asBoolean(ctx.namePart())) {
Expression namePartExpr = this.visitNamePart(ctx.namePart());
GenericsType[] genericsTypes = this.visitNonWildcardTypeArguments(ctx.nonWildcardTypeArguments());
if (asBoolean(ctx.DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj.@a
return this.configureAST(new AttributeExpression(baseExpr, namePartExpr), ctx);
} else { // e.g. obj.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
return this.configureAST(propertyExpression, ctx);
}
} else if (asBoolean(ctx.SAFE_DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj?.@a
return this.configureAST(new AttributeExpression(baseExpr, namePartExpr, true), ctx);
} else { // e.g. obj?.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
return this.configureAST(propertyExpression, ctx);
}
} else if (asBoolean(ctx.METHOD_POINTER())) { // e.g. obj.&m
return this.configureAST(new MethodPointerExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.METHOD_REFERENCE())) { // e.g. obj::m
return this.configureAST(new MethodReferenceExpression(baseExpr, namePartExpr), ctx);
} else if (asBoolean(ctx.SPREAD_DOT())) {
if (asBoolean(ctx.AT())) { // e.g. obj*.@a
AttributeExpression attributeExpression = new AttributeExpression(baseExpr, namePartExpr, true);
attributeExpression.setSpreadSafe(true);
return this.configureAST(attributeExpression, ctx);
} else { // e.g. obj*.p
PropertyExpression propertyExpression = new PropertyExpression(baseExpr, namePartExpr, true);
propertyExpression.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES, genericsTypes);
propertyExpression.setSpreadSafe(true);
return this.configureAST(propertyExpression, ctx);
}
}
}
if (asBoolean(ctx.indexPropertyArgs())) { // e.g. list[1, 3, 5]
Pair<Token, Expression> pair = this.visitIndexPropertyArgs(ctx.indexPropertyArgs());
return this.configureAST(
new BinaryExpression(baseExpr, createGroovyToken(pair.getKey()), pair.getValue(), asBoolean(ctx.indexPropertyArgs().QUESTION())),
ctx);
}
if (asBoolean(ctx.namedPropertyArgs())) { // this is a special way to new instance, e.g. Person(name: 'Daniel.Sun', location: 'Shanghai')
List<MapEntryExpression> mapEntryExpressionList =
this.visitNamedPropertyArgs(ctx.namedPropertyArgs());
Expression right;
if (mapEntryExpressionList.size() == 1) {
MapEntryExpression mapEntryExpression = mapEntryExpressionList.get(0);
if (mapEntryExpression.getKeyExpression() instanceof SpreadMapExpression) {
right = mapEntryExpression.getKeyExpression();
} else {
right = mapEntryExpression;
}
} else {
ListExpression listExpression =
this.configureAST(
new ListExpression(
mapEntryExpressionList.stream()
.map(
e -> {
if (e.getKeyExpression() instanceof SpreadMapExpression) {
return e.getKeyExpression();
}
return e;
}
)
.collect(Collectors.toList())),
ctx.namedPropertyArgs()
);
listExpression.setWrapped(true);
right = listExpression;
}
return this.configureAST(
new BinaryExpression(baseExpr, createGroovyToken(ctx.namedPropertyArgs().LBRACK().getSymbol()), right),
ctx);
}
if (asBoolean(ctx.arguments())) {
Expression argumentsExpr = this.visitArguments(ctx.arguments());
this.configureAST(argumentsExpr, ctx);
if (isInsideParentheses(baseExpr)) { // e.g. (obj.x)(), (obj.@x)()
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
CALL_STR,
argumentsExpr
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof AttributeExpression) { // e.g. obj.@a(1, 2)
AttributeExpression attributeExpression = (AttributeExpression) baseExpr;
attributeExpression.setSpreadSafe(false); // whether attributeExpression is spread safe or not, we must reset it as false
MethodCallExpression methodCallExpression =
new MethodCallExpression(
attributeExpression,
CALL_STR,
argumentsExpr
);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof PropertyExpression) { // e.g. obj.a(1, 2)
MethodCallExpression methodCallExpression =
this.createMethodCallExpression((PropertyExpression) baseExpr, argumentsExpr);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof VariableExpression) { // void and primitive type AST node must be an instance of VariableExpression
String baseExprText = baseExpr.getText();
if (VOID_STR.equals(baseExprText)) { // e.g. void()
MethodCallExpression methodCallExpression =
new MethodCallExpression(
this.createConstantExpression(baseExpr),
CALL_STR,
argumentsExpr
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
} else if (PRIMITIVE_TYPE_SET.contains(baseExprText)) { // e.g. int(), long(), float(), etc.
throw createParsingFailedException("Primitive type literal: " + baseExprText + " cannot be used as a method name", ctx);
}
}
if (baseExpr instanceof VariableExpression
|| baseExpr instanceof GStringExpression
|| (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_STRING))) { // e.g. m(), "$m"(), "m"()
String baseExprText = baseExpr.getText();
if (SUPER_STR.equals(baseExprText) || THIS_STR.equals(baseExprText)) { // e.g. this(...), super(...)
// class declaration is not allowed in the closure,
// so if this and super is inside the closure, it will not be constructor call.
// e.g. src/test/org/codehaus/groovy/transform/MapConstructorTransformTest.groovy:
// @MapConstructor(pre={ super(args?.first, args?.last); args = args ?: [:] }, post = { first = first?.toUpperCase() })
if (ctx.isInsideClosure) {
return this.configureAST(
new MethodCallExpression(
baseExpr,
baseExprText,
argumentsExpr
),
ctx);
}
return this.configureAST(
new ConstructorCallExpression(
SUPER_STR.equals(baseExprText)
? ClassNode.SUPER
: ClassNode.THIS,
argumentsExpr
),
ctx);
}
MethodCallExpression methodCallExpression =
this.createMethodCallExpression(baseExpr, argumentsExpr);
return this.configureAST(methodCallExpression, ctx);
}
// e.g. 1(), 1.1(), ((int) 1 / 2)(1, 2), {a, b -> a + b }(1, 2), m()()
MethodCallExpression methodCallExpression =
new MethodCallExpression(baseExpr, CALL_STR, argumentsExpr);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (asBoolean(ctx.closure())) {
ClosureExpression closureExpression = this.visitClosure(ctx.closure());
if (baseExpr instanceof MethodCallExpression) {
MethodCallExpression methodCallExpression = (MethodCallExpression) baseExpr;
Expression argumentsExpression = methodCallExpression.getArguments();
if (argumentsExpression instanceof ArgumentListExpression) { // normal arguments, e.g. 1, 2
ArgumentListExpression argumentListExpression = (ArgumentListExpression) argumentsExpression;
argumentListExpression.getExpressions().add(closureExpression);
return this.configureAST(methodCallExpression, ctx);
}
if (argumentsExpression instanceof TupleExpression) { // named arguments, e.g. x: 1, y: 2
TupleExpression tupleExpression = (TupleExpression) argumentsExpression;
NamedArgumentListExpression namedArgumentListExpression = (NamedArgumentListExpression) tupleExpression.getExpression(0);
if (asBoolean(tupleExpression.getExpressions())) {
methodCallExpression.setArguments(
this.configureAST(
new ArgumentListExpression(
Stream.of(
this.configureAST(
new MapExpression(namedArgumentListExpression.getMapEntryExpressions()),
namedArgumentListExpression
),
closureExpression
).collect(Collectors.toList())
),
tupleExpression
)
);
} else {
// the branch should never reach, because named arguments must not be empty
methodCallExpression.setArguments(
this.configureAST(
new ArgumentListExpression(closureExpression),
tupleExpression));
}
return this.configureAST(methodCallExpression, ctx);
}
}
// e.g. 1 {}, 1.1 {}
if (baseExpr instanceof ConstantExpression && isTrue(baseExpr, IS_NUMERIC)) {
MethodCallExpression methodCallExpression =
new MethodCallExpression(
baseExpr,
CALL_STR,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression
)
);
methodCallExpression.setImplicitThis(false);
return this.configureAST(methodCallExpression, ctx);
}
if (baseExpr instanceof PropertyExpression) { // e.g. obj.m { }
PropertyExpression propertyExpression = (PropertyExpression) baseExpr;
MethodCallExpression methodCallExpression =
this.createMethodCallExpression(
propertyExpression,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression
)
);
return this.configureAST(methodCallExpression, ctx);
}
// e.g. m { return 1; }
MethodCallExpression methodCallExpression =
new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
(baseExpr instanceof VariableExpression)
? this.createConstantExpression(baseExpr)
: baseExpr,
this.configureAST(
new ArgumentListExpression(closureExpression),
closureExpression)
);
return this.configureAST(methodCallExpression, ctx);
}
throw createParsingFailedException("Unsupported path element: " + ctx.getText(), ctx);
}
@Override
public GenericsType[] visitNonWildcardTypeArguments(NonWildcardTypeArgumentsContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
return Arrays.stream(this.visitTypeList(ctx.typeList()))
.map(this::createGenericsType)
.toArray(GenericsType[]::new);
}
@Override
public ClassNode[] visitTypeList(TypeListContext ctx) {
if (!asBoolean(ctx)) {
return new ClassNode[0];
}
return ctx.type().stream()
.map(this::visitType)
.toArray(ClassNode[]::new);
}
@Override
public Expression visitArguments(ArgumentsContext ctx) {
if (!asBoolean(ctx) || !asBoolean(ctx.enhancedArgumentList())) {
return new ArgumentListExpression();
}
return this.configureAST(this.visitEnhancedArgumentList(ctx.enhancedArgumentList()), ctx);
}
@Override
public Expression visitEnhancedArgumentList(EnhancedArgumentListContext ctx) {
if (!asBoolean(ctx)) {
return null;
}
List<Expression> expressionList = new LinkedList<>();
List<MapEntryExpression> mapEntryExpressionList = new LinkedList<>();
ctx.enhancedArgumentListElement().stream()
.map(this::visitEnhancedArgumentListElement)
.forEach(e -> {
if (e instanceof MapEntryExpression) {
MapEntryExpression mapEntryExpression = (MapEntryExpression) e;
validateDuplicatedNamedParameter(mapEntryExpressionList, mapEntryExpression);
mapEntryExpressionList.add(mapEntryExpression);
} else {
expressionList.add(e);
}
});
if (!asBoolean(mapEntryExpressionList)) { // e.g. arguments like 1, 2 OR someArg, e -> e
return this.configureAST(
new ArgumentListExpression(expressionList),
ctx);
}
if (!asBoolean(expressionList)) { // e.g. arguments like x: 1, y: 2
return this.configureAST(
new TupleExpression(
this.configureAST(
new NamedArgumentListExpression(mapEntryExpressionList),
ctx)),
ctx);
}
if (asBoolean(mapEntryExpressionList) && asBoolean(expressionList)) { // e.g. arguments like x: 1, 'a', y: 2, 'b', z: 3
ArgumentListExpression argumentListExpression = new ArgumentListExpression(expressionList);
argumentListExpression.getExpressions().add(0, new MapExpression(mapEntryExpressionList)); // TODO: confirm BUG OR NOT? All map entries will be put at first, which is not friendly to Groovy developers
return this.configureAST(argumentListExpression, ctx);
}
throw createParsingFailedException("Unsupported argument list: " + ctx.getText(), ctx);
}
private void validateDuplicatedNamedParameter(List<MapEntryExpression> mapEntryExpressionList, MapEntryExpression mapEntryExpression) {
Expression keyExpression = mapEntryExpression.getKeyExpression();
if (null == keyExpression) {
return;
}
String parameterName = keyExpression.getText();
boolean isDuplicatedNamedParameter = mapEntryExpressionList.stream().anyMatch(m -> m.getKeyExpression().getText().equals(parameterName));
if (!isDuplicatedNamedParameter) {
return;
}
throw createParsingFailedException("Duplicated named parameter '" + parameterName + "' found", mapEntryExpression);
}
@Override
public Expression visitEnhancedArgumentListElement(EnhancedArgumentListElementContext ctx) {
if (asBoolean(ctx.expressionListElement())) {
return this.configureAST(this.visitExpressionListElement(ctx.expressionListElement()), ctx);
}
if (asBoolean(ctx.standardLambdaExpression())) {
return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx);
}
if (asBoolean(ctx.mapEntry())) {
return this.configureAST(this.visitMapEntry(ctx.mapEntry()), ctx);
}
throw createParsingFailedException("Unsupported enhanced argument list element: " + ctx.getText(), ctx);
}
@Override
public ConstantExpression visitStringLiteral(StringLiteralContext ctx) {
String text = ctx.StringLiteral().getText();
int slashyType = text.startsWith("/") ? StringUtils.SLASHY :
text.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY;
if (text.startsWith("'''") || text.startsWith("\"\"\"")) {
text = StringUtils.removeCR(text); // remove CR in the multiline string
text = StringUtils.trimQuotations(text, 3);
} else if (text.startsWith("'") || text.startsWith("/") || text.startsWith("\"")) {
if (text.startsWith("/")) { // the slashy string can span rows, so we have to remove CR for it
text = StringUtils.removeCR(text); // remove CR in the multiline string
}
text = StringUtils.trimQuotations(text, 1);
} else if (text.startsWith("$/")) {
text = StringUtils.removeCR(text);
text = StringUtils.trimQuotations(text, 2);
}
//handle escapes.
text = StringUtils.replaceEscapes(text, slashyType);
ConstantExpression constantExpression = new ConstantExpression(text, true);
constantExpression.putNodeMetaData(IS_STRING, true);
return this.configureAST(constantExpression, ctx);
}
@Override
public Pair<Token, Expression> visitIndexPropertyArgs(IndexPropertyArgsContext ctx) {
List<Expression> expressionList = this.visitExpressionList(ctx.expressionList());
if (expressionList.size() == 1) {
Expression expr = expressionList.get(0);
Expression indexExpr;
if (expr instanceof SpreadExpression) { // e.g. a[*[1, 2]]
ListExpression listExpression = new ListExpression(expressionList);
listExpression.setWrapped(false);
indexExpr = listExpression;
} else { // e.g. a[1]
indexExpr = expr;
}
return new Pair<>(ctx.LBRACK().getSymbol(), indexExpr);
}
// e.g. a[1, 2]
ListExpression listExpression = new ListExpression(expressionList);
listExpression.setWrapped(true);
return new Pair<>(ctx.LBRACK().getSymbol(), this.configureAST(listExpression, ctx));
}
@Override
public List<MapEntryExpression> visitNamedPropertyArgs(NamedPropertyArgsContext ctx) {
return this.visitMapEntryList(ctx.mapEntryList());
}
@Override
public Expression visitNamePart(NamePartContext ctx) {
if (asBoolean(ctx.identifier())) {
return this.configureAST(new ConstantExpression(this.visitIdentifier(ctx.identifier())), ctx);
} else if (asBoolean(ctx.stringLiteral())) {
return this.configureAST(this.visitStringLiteral(ctx.stringLiteral()), ctx);
} else if (asBoolean(ctx.dynamicMemberName())) {
return this.configureAST(this.visitDynamicMemberName(ctx.dynamicMemberName()), ctx);
} else if (asBoolean(ctx.keywords())) {
return this.configureAST(new ConstantExpression(ctx.keywords().getText()), ctx);
}
throw createParsingFailedException("Unsupported name part: " + ctx.getText(), ctx);
}
@Override
public Expression visitDynamicMemberName(DynamicMemberNameContext ctx) {
if (asBoolean(ctx.parExpression())) {
return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx);
} else if (asBoolean(ctx.gstring())) {
return this.configureAST(this.visitGstring(ctx.gstring()), ctx);
}
throw createParsingFailedException("Unsupported dynamic member name: " + ctx.getText(), ctx);
}
@Override
public Expression visitPostfixExpression(PostfixExpressionContext ctx) {
Expression pathExpr = this.visitPathExpression(ctx.pathExpression());
if (asBoolean(ctx.op)) {
PostfixExpression postfixExpression = new PostfixExpression(pathExpr, createGroovyToken(ctx.op));
if (ctx.isInsideAssert) {
// powerassert requires different column for values, so we have to copy the location of op
return this.configureAST(postfixExpression, ctx.op);
} else {
return this.configureAST(postfixExpression, ctx);
}
}
return this.configureAST(pathExpr, ctx);
}
@Override
public Expression visitPostfixExprAlt(PostfixExprAltContext ctx) {
return this.visitPostfixExpression(ctx.postfixExpression());
}
@Override
public Expression visitUnaryNotExprAlt(UnaryNotExprAltContext ctx) {
if (asBoolean(ctx.NOT())) {
return this.configureAST(
new NotExpression((Expression) this.visit(ctx.expression())),
ctx);
}
if (asBoolean(ctx.BITNOT())) {
return this.configureAST(
new BitwiseNegationExpression((Expression) this.visit(ctx.expression())),
ctx);
}
throw createParsingFailedException("Unsupported unary expression: " + ctx.getText(), ctx);
}
@Override
public CastExpression visitCastExprAlt(CastExprAltContext ctx) {
return this.configureAST(
new CastExpression(
this.visitCastParExpression(ctx.castParExpression()),
(Expression) this.visit(ctx.expression())
),
ctx
);
}
@Override
public BinaryExpression visitPowerExprAlt(PowerExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public Expression visitUnaryAddExprAlt(UnaryAddExprAltContext ctx) {
ExpressionContext expressionCtx = ctx.expression();
Expression expression = (Expression) this.visit(expressionCtx);
Boolean insidePar = isInsideParentheses(expression);
switch (ctx.op.getType()) {
case ADD: {
if (expression instanceof ConstantExpression && !insidePar) {
return this.configureAST(expression, ctx);
}
return this.configureAST(new UnaryPlusExpression(expression), ctx);
}
case SUB: {
if (expression instanceof ConstantExpression && !insidePar) {
ConstantExpression constantExpression = (ConstantExpression) expression;
try {
String integerLiteralText = constantExpression.getNodeMetaData(INTEGER_LITERAL_TEXT);
if (null != integerLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseInteger(null, SUB_STR + integerLiteralText));
this.numberFormatError = null; // reset the numberFormatError
return this.configureAST(result, ctx);
}
String floatingPointLiteralText = constantExpression.getNodeMetaData(FLOATING_POINT_LITERAL_TEXT);
if (null != floatingPointLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseDecimal(SUB_STR + floatingPointLiteralText));
this.numberFormatError = null; // reset the numberFormatError
return this.configureAST(result, ctx);
}
} catch (Exception e) {
throw createParsingFailedException(e.getMessage(), ctx);
}
throw new GroovyBugError("Failed to find the original number literal text: " + constantExpression.getText());
}
return this.configureAST(new UnaryMinusExpression(expression), ctx);
}
case INC:
case DEC:
return this.configureAST(new PrefixExpression(this.createGroovyToken(ctx.op), expression), ctx);
default:
throw createParsingFailedException("Unsupported unary operation: " + ctx.getText(), ctx);
}
}
@Override
public BinaryExpression visitMultiplicativeExprAlt(MultiplicativeExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitAdditiveExprAlt(AdditiveExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public Expression visitShiftExprAlt(ShiftExprAltContext ctx) {
Expression left = (Expression) this.visit(ctx.left);
Expression right = (Expression) this.visit(ctx.right);
if (asBoolean(ctx.rangeOp)) {
return this.configureAST(new RangeExpression(left, right, !ctx.rangeOp.getText().endsWith("<")), ctx);
}
org.codehaus.groovy.syntax.Token op;
Token antlrToken;
if (asBoolean(ctx.dlOp)) {
op = this.createGroovyToken(ctx.dlOp, 2);
antlrToken = ctx.dlOp;
} else if (asBoolean(ctx.dgOp)) {
op = this.createGroovyToken(ctx.dgOp, 2);
antlrToken = ctx.dgOp;
} else if (asBoolean(ctx.tgOp)) {
op = this.createGroovyToken(ctx.tgOp, 3);
antlrToken = ctx.tgOp;
} else {
throw createParsingFailedException("Unsupported shift expression: " + ctx.getText(), ctx);
}
BinaryExpression binaryExpression = new BinaryExpression(left, op, right);
if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) {
return this.configureAST(binaryExpression, antlrToken);
}
return this.configureAST(binaryExpression, ctx);
}
@Override
public Expression visitRelationalExprAlt(RelationalExprAltContext ctx) {
switch (ctx.op.getType()) {
case AS:
return this.configureAST(
CastExpression.asExpression(this.visitType(ctx.type()), (Expression) this.visit(ctx.left)),
ctx);
case INSTANCEOF:
case NOT_INSTANCEOF:
ctx.type().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, true);
return this.configureAST(
new BinaryExpression((Expression) this.visit(ctx.left),
this.createGroovyToken(ctx.op),
this.configureAST(new ClassExpression(this.visitType(ctx.type())), ctx.type())),
ctx);
case LE:
case GE:
case GT:
case LT:
case IN:
case NOT_IN: {
if (ctx.op.getType() == IN || ctx.op.getType() == NOT_IN ) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
default:
throw createParsingFailedException("Unsupported relational expression: " + ctx.getText(), ctx);
}
}
@Override
public BinaryExpression visitEqualityExprAlt(EqualityExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitRegexExprAlt(RegexExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitAndExprAlt(AndExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitExclusiveOrExprAlt(ExclusiveOrExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitInclusiveOrExprAlt(InclusiveOrExprAltContext ctx) {
return this.createBinaryExpression(ctx.left, ctx.op, ctx.right, ctx);
}
@Override
public BinaryExpression visitLogicalAndExprAlt(LogicalAndExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public BinaryExpression visitLogicalOrExprAlt(LogicalOrExprAltContext ctx) {
return this.configureAST(
this.createBinaryExpression(ctx.left, ctx.op, ctx.right),
ctx);
}
@Override
public Expression visitConditionalExprAlt(ConditionalExprAltContext ctx) {
ctx.fb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true);
if (asBoolean(ctx.ELVIS())) { // e.g. a == 6 ?: 0
return this.configureAST(
new ElvisOperatorExpression((Expression) this.visit(ctx.con), (Expression) this.visit(ctx.fb)),
ctx);
}
ctx.tb.putNodeMetaData(IS_INSIDE_CONDITIONAL_EXPRESSION, true);
return this.configureAST(
new TernaryExpression(
this.configureAST(new BooleanExpression((Expression) this.visit(ctx.con)),
ctx.con),
(Expression) this.visit(ctx.tb),
(Expression) this.visit(ctx.fb)),
ctx);
}
@Override
public BinaryExpression visitMultipleAssignmentExprAlt(MultipleAssignmentExprAltContext ctx) {
return this.configureAST(
new BinaryExpression(
this.visitVariableNames(ctx.left),
this.createGroovyToken(ctx.op),
((ExpressionStatement) this.visit(ctx.right)).getExpression()),
ctx);
}
@Override
public BinaryExpression visitAssignmentExprAlt(AssignmentExprAltContext ctx) {
Expression leftExpr = (Expression) this.visit(ctx.left);
if (leftExpr instanceof VariableExpression
&& isInsideParentheses(leftExpr)) { // it is a special multiple assignment whose variable count is only one, e.g. (a) = [1]
if ((Integer) leftExpr.getNodeMetaData(INSIDE_PARENTHESES_LEVEL) > 1) {
throw createParsingFailedException("Nested parenthesis is not allowed in multiple assignment, e.g. ((a)) = b", ctx);
}
return this.configureAST(
new BinaryExpression(
this.configureAST(new TupleExpression(leftExpr), ctx.left),
this.createGroovyToken(ctx.op),
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())),
ctx);
}
// the LHS expression should be a variable which is not inside any parentheses
if (
!(
(leftExpr instanceof VariableExpression
// && !(THIS_STR.equals(leftExpr.getText()) || SUPER_STR.equals(leftExpr.getText())) // commented, e.g. this = value // this will be transformed to $this
&& !isInsideParentheses(leftExpr)) // e.g. p = 123
|| leftExpr instanceof PropertyExpression // e.g. obj.p = 123
|| (leftExpr instanceof BinaryExpression
// && !(((BinaryExpression) leftExpr).getRightExpression() instanceof ListExpression) // commented, e.g. list[1, 2] = [11, 12]
&& Types.LEFT_SQUARE_BRACKET == ((BinaryExpression) leftExpr).getOperation().getType()) // e.g. map[a] = 123 OR map['a'] = 123 OR map["$a"] = 123
)
) {
throw createParsingFailedException("The LHS of an assignment should be a variable or a field accessing expression", ctx);
}
return this.configureAST(
new BinaryExpression(
leftExpr,
this.createGroovyToken(ctx.op),
this.visitEnhancedStatementExpression(ctx.enhancedStatementExpression())),
ctx);
}
// } expression --------------------------------------------------------------------
// primary { --------------------------------------------------------------------
@Override
public VariableExpression visitIdentifierPrmrAlt(IdentifierPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx);
}
@Override
public ConstantExpression visitLiteralPrmrAlt(LiteralPrmrAltContext ctx) {
return this.configureAST((ConstantExpression) this.visit(ctx.literal()), ctx);
}
@Override
public GStringExpression visitGstringPrmrAlt(GstringPrmrAltContext ctx) {
return this.configureAST((GStringExpression) this.visit(ctx.gstring()), ctx);
}
@Override
public Expression visitNewPrmrAlt(NewPrmrAltContext ctx) {
return this.configureAST(this.visitCreator(ctx.creator()), ctx);
}
@Override
public VariableExpression visitThisPrmrAlt(ThisPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(ctx.THIS().getText()), ctx);
}
@Override
public VariableExpression visitSuperPrmrAlt(SuperPrmrAltContext ctx) {
return this.configureAST(new VariableExpression(ctx.SUPER().getText()), ctx);
}
@Override
public Expression visitParenPrmrAlt(ParenPrmrAltContext ctx) {
return this.configureAST(this.visitParExpression(ctx.parExpression()), ctx);
}
@Override
public ClosureExpression visitClosurePrmrAlt(ClosurePrmrAltContext ctx) {
return this.configureAST(this.visitClosure(ctx.closure()), ctx);
}
@Override
public ClosureExpression visitLambdaPrmrAlt(LambdaPrmrAltContext ctx) {
return this.configureAST(this.visitStandardLambdaExpression(ctx.standardLambdaExpression()), ctx);
}
@Override
public ListExpression visitListPrmrAlt(ListPrmrAltContext ctx) {
return this.configureAST(
this.visitList(ctx.list()),
ctx);
}
@Override
public MapExpression visitMapPrmrAlt(MapPrmrAltContext ctx) {
return this.configureAST(this.visitMap(ctx.map()), ctx);
}
@Override
public VariableExpression visitTypePrmrAlt(TypePrmrAltContext ctx) {
return this.configureAST(
this.visitBuiltInType(ctx.builtInType()),
ctx);
}
// } primary --------------------------------------------------------------------
@Override
public Expression visitCreator(CreatorContext ctx) {
ClassNode classNode = this.visitCreatedName(ctx.createdName());
Expression arguments = this.visitArguments(ctx.arguments());
if (asBoolean(ctx.arguments())) { // create instance of class
if (asBoolean(ctx.anonymousInnerClassDeclaration())) {
ctx.anonymousInnerClassDeclaration().putNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS, classNode);
InnerClassNode anonymousInnerClassNode = this.visitAnonymousInnerClassDeclaration(ctx.anonymousInnerClassDeclaration());
List<InnerClassNode> anonymousInnerClassList = anonymousInnerClassesDefinedInMethodStack.peek();
if (null != anonymousInnerClassList) { // if the anonymous class is created in a script, no anonymousInnerClassList is available.
anonymousInnerClassList.add(anonymousInnerClassNode);
}
ConstructorCallExpression constructorCallExpression = new ConstructorCallExpression(anonymousInnerClassNode, arguments);
constructorCallExpression.setUsingAnonymousInnerClass(true);
return this.configureAST(constructorCallExpression, ctx);
}
return this.configureAST(
new ConstructorCallExpression(classNode, arguments),
ctx);
}
if (asBoolean(ctx.LBRACK()) || asBoolean(ctx.dims())) { // create array
ArrayExpression arrayExpression;
List<List<AnnotationNode>> allDimList;
if (asBoolean(ctx.arrayInitializer())) {
ClassNode elementType = classNode;
allDimList = this.visitDims(ctx.dims());
for (int i = 0, n = allDimList.size() - 1; i < n; i++) {
elementType = elementType.makeArray();
}
arrayExpression =
new ArrayExpression(
elementType,
this.visitArrayInitializer(ctx.arrayInitializer()));
} else {
Expression[] empties;
List<List<AnnotationNode>> emptyDimList = this.visitDimsOpt(ctx.dimsOpt());
if (asBoolean(emptyDimList)) {
empties = new Expression[emptyDimList.size()];
Arrays.setAll(empties, i -> ConstantExpression.EMPTY_EXPRESSION);
} else {
empties = new Expression[0];
}
arrayExpression =
new ArrayExpression(
classNode,
null,
Stream.concat(
ctx.expression().stream()
.map(e -> (Expression) this.visit(e)),
Arrays.stream(empties)
).collect(Collectors.toList()));
List<List<AnnotationNode>> exprDimList = ctx.annotationsOpt().stream().map(this::visitAnnotationsOpt).collect(Collectors.toList());
allDimList = new ArrayList<>(exprDimList);
Collections.reverse(emptyDimList);
allDimList.addAll(emptyDimList);
Collections.reverse(allDimList);
}
arrayExpression.setType(createArrayType(classNode, allDimList));
return this.configureAST(arrayExpression, ctx);
}
throw createParsingFailedException("Unsupported creator: " + ctx.getText(), ctx);
}
private ClassNode createArrayType(ClassNode classNode, List<List<AnnotationNode>> dimList) {
ClassNode arrayType = classNode;
for (int i = 0, n = dimList.size(); i < n; i++) {
arrayType = arrayType.makeArray();
arrayType.addAnnotations(dimList.get(i));
}
return arrayType;
}
private String genAnonymousClassName(String outerClassName) {
return outerClassName + "$" + this.anonymousInnerClassCounter++;
}
@Override
public InnerClassNode visitAnonymousInnerClassDeclaration(AnonymousInnerClassDeclarationContext ctx) {
ClassNode superClass = ctx.getNodeMetaData(ANONYMOUS_INNER_CLASS_SUPER_CLASS);
Objects.requireNonNull(superClass, "superClass should not be null");
InnerClassNode anonymousInnerClass;
ClassNode outerClass = this.classNodeStack.peek();
outerClass = asBoolean(outerClass) ? outerClass : moduleNode.getScriptClassDummy();
String fullName = this.genAnonymousClassName(outerClass.getName());
if (1 == ctx.t) { // anonymous enum
anonymousInnerClass = new EnumConstantClassNode(outerClass, fullName, superClass.getModifiers() | Opcodes.ACC_FINAL, superClass.getPlainNodeReference());
// and remove the final modifier from classNode to allow the sub class
superClass.setModifiers(superClass.getModifiers() & ~Opcodes.ACC_FINAL);
} else { // anonymous inner class
anonymousInnerClass = new InnerClassNode(outerClass, fullName, Opcodes.ACC_PUBLIC, superClass);
}
anonymousInnerClass.setUsingGenerics(false);
anonymousInnerClass.setAnonymous(true);
anonymousInnerClass.putNodeMetaData(CLASS_NAME, fullName);
this.configureAST(anonymousInnerClass, ctx);
classNodeStack.push(anonymousInnerClass);
ctx.classBody().putNodeMetaData(CLASS_DECLARATION_CLASS_NODE, anonymousInnerClass);
this.visitClassBody(ctx.classBody());
classNodeStack.pop();
classNodeList.add(anonymousInnerClass);
return anonymousInnerClass;
}
@Override
public ClassNode visitCreatedName(CreatedNameContext ctx) {
ClassNode classNode = null;
if (asBoolean(ctx.qualifiedClassName())) {
classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
if (asBoolean(ctx.typeArgumentsOrDiamond())) {
classNode.setGenericsTypes(
this.visitTypeArgumentsOrDiamond(ctx.typeArgumentsOrDiamond()));
}
classNode = this.configureAST(classNode, ctx);
} else if (asBoolean(ctx.primitiveType())) {
classNode = this.configureAST(
this.visitPrimitiveType(ctx.primitiveType()),
ctx);
}
if (!asBoolean(classNode)) {
throw createParsingFailedException("Unsupported created name: " + ctx.getText(), ctx);
}
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return classNode;
}
@Override
public MapExpression visitMap(MapContext ctx) {
return this.configureAST(
new MapExpression(this.visitMapEntryList(ctx.mapEntryList())),
ctx);
}
@Override
public List<MapEntryExpression> visitMapEntryList(MapEntryListContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.createMapEntryList(ctx.mapEntry());
}
private List<MapEntryExpression> createMapEntryList(List<? extends MapEntryContext> mapEntryContextList) {
if (!asBoolean(mapEntryContextList)) {
return Collections.emptyList();
}
return mapEntryContextList.stream()
.map(this::visitMapEntry)
.collect(Collectors.toList());
}
@Override
public MapEntryExpression visitMapEntry(MapEntryContext ctx) {
Expression keyExpr;
Expression valueExpr = (Expression) this.visit(ctx.expression());
if (asBoolean(ctx.MUL())) {
keyExpr = this.configureAST(new SpreadMapExpression(valueExpr), ctx);
} else if (asBoolean(ctx.mapEntryLabel())) {
keyExpr = this.visitMapEntryLabel(ctx.mapEntryLabel());
} else {
throw createParsingFailedException("Unsupported map entry: " + ctx.getText(), ctx);
}
return this.configureAST(
new MapEntryExpression(keyExpr, valueExpr),
ctx);
}
@Override
public Expression visitMapEntryLabel(MapEntryLabelContext ctx) {
if (asBoolean(ctx.keywords())) {
return this.configureAST(this.visitKeywords(ctx.keywords()), ctx);
} else if (asBoolean(ctx.primary())) {
Expression expression = (Expression) this.visit(ctx.primary());
// if the key is variable and not inside parentheses, convert it to a constant, e.g. [a:1, b:2]
if (expression instanceof VariableExpression && !isInsideParentheses(expression)) {
expression =
this.configureAST(
new ConstantExpression(((VariableExpression) expression).getName()),
expression);
}
return this.configureAST(expression, ctx);
}
throw createParsingFailedException("Unsupported map entry label: " + ctx.getText(), ctx);
}
@Override
public ConstantExpression visitKeywords(KeywordsContext ctx) {
return this.configureAST(new ConstantExpression(ctx.getText()), ctx);
}
/*
@Override
public VariableExpression visitIdentifier(IdentifierContext ctx) {
return this.configureAST(new VariableExpression(ctx.getText()), ctx);
}
*/
@Override
public VariableExpression visitBuiltInType(BuiltInTypeContext ctx) {
String text;
if (asBoolean(ctx.VOID())) {
text = ctx.VOID().getText();
} else if (asBoolean(ctx.BuiltInPrimitiveType())) {
text = ctx.BuiltInPrimitiveType().getText();
} else {
throw createParsingFailedException("Unsupported built-in type: " + ctx, ctx);
}
return this.configureAST(new VariableExpression(text), ctx);
}
@Override
public ListExpression visitList(ListContext ctx) {
return this.configureAST(
new ListExpression(
this.visitExpressionList(ctx.expressionList())),
ctx);
}
@Override
public List<Expression> visitExpressionList(ExpressionListContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return this.createExpressionList(ctx.expressionListElement());
}
private List<Expression> createExpressionList(List<? extends ExpressionListElementContext> expressionListElementContextList) {
if (!asBoolean(expressionListElementContextList)) {
return Collections.emptyList();
}
return expressionListElementContextList.stream()
.map(this::visitExpressionListElement)
.collect(Collectors.toList());
}
@Override
public Expression visitExpressionListElement(ExpressionListElementContext ctx) {
Expression expression = (Expression) this.visit(ctx.expression());
if (asBoolean(ctx.MUL())) {
return this.configureAST(new SpreadExpression(expression), ctx);
}
return this.configureAST(expression, ctx);
}
// literal { --------------------------------------------------------------------
@Override
public ConstantExpression visitIntegerLiteralAlt(IntegerLiteralAltContext ctx) {
String text = ctx.IntegerLiteral().getText();
Number num = null;
try {
num = Numbers.parseInteger(null, text);
} catch (Exception e) {
this.numberFormatError = new Pair<>(ctx, e);
}
ConstantExpression constantExpression = new ConstantExpression(num, !text.startsWith(SUB_STR));
constantExpression.putNodeMetaData(IS_NUMERIC, true);
constantExpression.putNodeMetaData(INTEGER_LITERAL_TEXT, text);
return this.configureAST(constantExpression, ctx);
}
@Override
public ConstantExpression visitFloatingPointLiteralAlt(FloatingPointLiteralAltContext ctx) {
String text = ctx.FloatingPointLiteral().getText();
Number num = null;
try {
num = Numbers.parseDecimal(text);
} catch (Exception e) {
this.numberFormatError = new Pair<>(ctx, e);
}
ConstantExpression constantExpression = new ConstantExpression(num, !text.startsWith(SUB_STR));
constantExpression.putNodeMetaData(IS_NUMERIC, true);
constantExpression.putNodeMetaData(FLOATING_POINT_LITERAL_TEXT, text);
return this.configureAST(constantExpression, ctx);
}
@Override
public ConstantExpression visitStringLiteralAlt(StringLiteralAltContext ctx) {
return this.configureAST(
this.visitStringLiteral(ctx.stringLiteral()),
ctx);
}
@Override
public ConstantExpression visitBooleanLiteralAlt(BooleanLiteralAltContext ctx) {
return this.configureAST(new ConstantExpression("true".equals(ctx.BooleanLiteral().getText()), true), ctx);
}
@Override
public ConstantExpression visitNullLiteralAlt(NullLiteralAltContext ctx) {
return this.configureAST(new ConstantExpression(null), ctx);
}
// } literal --------------------------------------------------------------------
// gstring { --------------------------------------------------------------------
@Override
public GStringExpression visitGstring(GstringContext ctx) {
List<ConstantExpression> strings = new LinkedList<>();
String begin = ctx.GStringBegin().getText();
final int slashyType = begin.startsWith("/")
? StringUtils.SLASHY
: begin.startsWith("$/") ? StringUtils.DOLLAR_SLASHY : StringUtils.NONE_SLASHY;
{
String it = begin;
if (it.startsWith("\"\"\"")) {
it = StringUtils.removeCR(it);
it = it.substring(2); // translate leading """ to "
} else if (it.startsWith("$/")) {
it = StringUtils.removeCR(it);
it = "\"" + it.substring(2); // translate leading $/ to "
} else if (it.startsWith("/")) {
it = StringUtils.removeCR(it);
}
it = StringUtils.replaceEscapes(it, slashyType);
it = (it.length() == 2)
? ""
: StringGroovyMethods.getAt(it, new IntRange(true, 1, -2));
strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringBegin()));
}
List<ConstantExpression> partStrings =
ctx.GStringPart().stream()
.map(e -> {
String it = e.getText();
it = StringUtils.removeCR(it);
it = StringUtils.replaceEscapes(it, slashyType);
it = it.length() == 1 ? "" : StringGroovyMethods.getAt(it, new IntRange(true, 0, -2));
return this.configureAST(new ConstantExpression(it), e);
}).collect(Collectors.toList());
strings.addAll(partStrings);
{
String it = ctx.GStringEnd().getText();
if (it.endsWith("\"\"\"")) {
it = StringUtils.removeCR(it);
it = StringGroovyMethods.getAt(it, new IntRange(true, 0, -3)); // translate tailing """ to "
} else if (it.endsWith("/$")) {
it = StringUtils.removeCR(it);
it = StringGroovyMethods.getAt(it, new IntRange(false, 0, -2)) + "\""; // translate tailing /$ to "
} else if (it.endsWith("/")) {
it = StringUtils.removeCR(it);
}
it = StringUtils.replaceEscapes(it, slashyType);
it = (it.length() == 1)
? ""
: StringGroovyMethods.getAt(it, new IntRange(true, 0, -2));
strings.add(this.configureAST(new ConstantExpression(it), ctx.GStringEnd()));
}
List<Expression> values = ctx.gstringValue().stream()
.map(e -> {
Expression expression = this.visitGstringValue(e);
if (expression instanceof ClosureExpression && !asBoolean(e.closure().ARROW())) {
List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements();
if (statementList.stream().allMatch(x -> !asBoolean(x))) {
return this.configureAST(new ConstantExpression(null), e);
}
return this.configureAST(new MethodCallExpression(expression, CALL_STR, new ArgumentListExpression()), e);
}
return expression;
})
.collect(Collectors.toList());
StringBuilder verbatimText = new StringBuilder(ctx.getText().length());
for (int i = 0, n = strings.size(), s = values.size(); i < n; i++) {
verbatimText.append(strings.get(i).getValue());
if (i == s) {
continue;
}
Expression value = values.get(i);
if (!asBoolean(value)) {
continue;
}
verbatimText.append(DOLLAR_STR);
verbatimText.append(value.getText());
}
return this.configureAST(new GStringExpression(verbatimText.toString(), strings, values), ctx);
}
@Override
public Expression visitGstringValue(GstringValueContext ctx) {
if (asBoolean(ctx.gstringPath())) {
return this.configureAST(this.visitGstringPath(ctx.gstringPath()), ctx);
}
if (asBoolean(ctx.LBRACE())) {
if (asBoolean(ctx.statementExpression())) {
return this.configureAST(((ExpressionStatement) this.visit(ctx.statementExpression())).getExpression(), ctx.statementExpression());
} else { // e.g. "${}"
return this.configureAST(new ConstantExpression(null), ctx);
}
}
if (asBoolean(ctx.closure())) {
return this.configureAST(this.visitClosure(ctx.closure()), ctx);
}
throw createParsingFailedException("Unsupported gstring value: " + ctx.getText(), ctx);
}
@Override
public Expression visitGstringPath(GstringPathContext ctx) {
VariableExpression variableExpression = new VariableExpression(this.visitIdentifier(ctx.identifier()));
if (asBoolean(ctx.GStringPathPart())) {
Expression propertyExpression = ctx.GStringPathPart().stream()
.map(e -> this.configureAST((Expression) new ConstantExpression(e.getText().substring(1)), e))
.reduce(this.configureAST(variableExpression, ctx.identifier()), (r, e) -> this.configureAST(new PropertyExpression(r, e), e));
return this.configureAST(propertyExpression, ctx);
}
return this.configureAST(variableExpression, ctx);
}
// } gstring --------------------------------------------------------------------
@Override
public LambdaExpression visitStandardLambdaExpression(StandardLambdaExpressionContext ctx) {
return this.configureAST(this.createLambda(ctx.standardLambdaParameters(), ctx.lambdaBody()), ctx);
}
private LambdaExpression createLambda(StandardLambdaParametersContext standardLambdaParametersContext, LambdaBodyContext lambdaBodyContext) {
return new LambdaExpression(
this.visitStandardLambdaParameters(standardLambdaParametersContext),
this.visitLambdaBody(lambdaBodyContext));
}
@Override
public Parameter[] visitStandardLambdaParameters(StandardLambdaParametersContext ctx) {
if (asBoolean(ctx.variableDeclaratorId())) {
return new Parameter[]{
this.configureAST(
new Parameter(
ClassHelper.OBJECT_TYPE,
this.visitVariableDeclaratorId(ctx.variableDeclaratorId()).getName()
),
ctx.variableDeclaratorId()
)
};
}
Parameter[] parameters = this.visitFormalParameters(ctx.formalParameters());
if (0 == parameters.length) {
return null;
}
return parameters;
}
@Override
public Statement visitLambdaBody(LambdaBodyContext ctx) {
if (asBoolean(ctx.statementExpression())) {
return this.configureAST((ExpressionStatement) this.visit(ctx.statementExpression()), ctx);
}
if (asBoolean(ctx.block())) {
return this.configureAST(this.visitBlock(ctx.block()), ctx);
}
throw createParsingFailedException("Unsupported lambda body: " + ctx.getText(), ctx);
}
@Override
public ClosureExpression visitClosure(ClosureContext ctx) {
Parameter[] parameters = asBoolean(ctx.formalParameterList())
? this.visitFormalParameterList(ctx.formalParameterList())
: null;
if (!asBoolean(ctx.ARROW())) {
parameters = Parameter.EMPTY_ARRAY;
}
Statement code = this.visitBlockStatementsOpt(ctx.blockStatementsOpt());
return this.configureAST(new ClosureExpression(parameters, code), ctx);
}
@Override
public Parameter[] visitFormalParameters(FormalParametersContext ctx) {
if (!asBoolean(ctx)) {
return new Parameter[0];
}
return this.visitFormalParameterList(ctx.formalParameterList());
}
@Override
public Parameter[] visitFormalParameterList(FormalParameterListContext ctx) {
if (!asBoolean(ctx)) {
return new Parameter[0];
}
List<Parameter> parameterList = new LinkedList<>();
if (asBoolean(ctx.thisFormalParameter())) {
parameterList.add(this.visitThisFormalParameter(ctx.thisFormalParameter()));
}
List<? extends FormalParameterContext> formalParameterList = ctx.formalParameter();
if (asBoolean(formalParameterList)) {
validateVarArgParameter(formalParameterList);
parameterList.addAll(
formalParameterList.stream()
.map(this::visitFormalParameter)
.collect(Collectors.toList()));
}
validateParameterList(parameterList);
return parameterList.toArray(new Parameter[0]);
}
private void validateVarArgParameter(List<? extends FormalParameterContext> formalParameterList) {
for (int i = 0, n = formalParameterList.size(); i < n - 1; i++) {
FormalParameterContext formalParameterContext = formalParameterList.get(i);
if (asBoolean(formalParameterContext.ELLIPSIS())) {
throw createParsingFailedException("The var-arg parameter strs must be the last parameter", formalParameterContext);
}
}
}
private void validateParameterList(List<Parameter> parameterList) {
for (int n = parameterList.size(), i = n - 1; i >= 0; i--) {
Parameter parameter = parameterList.get(i);
for (Parameter otherParameter : parameterList) {
if (otherParameter == parameter) {
continue;
}
if (otherParameter.getName().equals(parameter.getName())) {
throw createParsingFailedException("Duplicated parameter '" + parameter.getName() + "' found.", parameter);
}
}
}
}
@Override
public Parameter visitFormalParameter(FormalParameterContext ctx) {
return this.processFormalParameter(ctx, ctx.variableModifiersOpt(), ctx.type(), ctx.ELLIPSIS(), ctx.variableDeclaratorId(), ctx.expression());
}
@Override
public Parameter visitThisFormalParameter(ThisFormalParameterContext ctx) {
return this.configureAST(new Parameter(this.visitType(ctx.type()), THIS_STR), ctx);
}
@Override
public List<ModifierNode> visitClassOrInterfaceModifiersOpt(ClassOrInterfaceModifiersOptContext ctx) {
if (asBoolean(ctx.classOrInterfaceModifiers())) {
return this.visitClassOrInterfaceModifiers(ctx.classOrInterfaceModifiers());
}
return Collections.emptyList();
}
@Override
public List<ModifierNode> visitClassOrInterfaceModifiers(ClassOrInterfaceModifiersContext ctx) {
return ctx.classOrInterfaceModifier().stream()
.map(this::visitClassOrInterfaceModifier)
.collect(Collectors.toList());
}
@Override
public ModifierNode visitClassOrInterfaceModifier(ClassOrInterfaceModifierContext ctx) {
if (asBoolean(ctx.annotation())) {
return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported class or interface modifier: " + ctx.getText(), ctx);
}
@Override
public ModifierNode visitModifier(ModifierContext ctx) {
if (asBoolean(ctx.classOrInterfaceModifier())) {
return this.configureAST(this.visitClassOrInterfaceModifier(ctx.classOrInterfaceModifier()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported modifier: " + ctx.getText(), ctx);
}
@Override
public List<ModifierNode> visitModifiers(ModifiersContext ctx) {
return ctx.modifier().stream()
.map(this::visitModifier)
.collect(Collectors.toList());
}
@Override
public List<ModifierNode> visitModifiersOpt(ModifiersOptContext ctx) {
if (asBoolean(ctx.modifiers())) {
return this.visitModifiers(ctx.modifiers());
}
return Collections.emptyList();
}
@Override
public ModifierNode visitVariableModifier(VariableModifierContext ctx) {
if (asBoolean(ctx.annotation())) {
return this.configureAST(new ModifierNode(this.visitAnnotation(ctx.annotation()), ctx.getText()), ctx);
}
if (asBoolean(ctx.m)) {
return this.configureAST(new ModifierNode(ctx.m.getType(), ctx.getText()), ctx);
}
throw createParsingFailedException("Unsupported variable modifier", ctx);
}
@Override
public List<ModifierNode> visitVariableModifiersOpt(VariableModifiersOptContext ctx) {
if (asBoolean(ctx.variableModifiers())) {
return this.visitVariableModifiers(ctx.variableModifiers());
}
return Collections.emptyList();
}
@Override
public List<ModifierNode> visitVariableModifiers(VariableModifiersContext ctx) {
return ctx.variableModifier().stream()
.map(this::visitVariableModifier)
.collect(Collectors.toList());
}
@Override
public List<List<AnnotationNode>> visitDims(DimsContext ctx) {
List<List<AnnotationNode>> dimList =
ctx.annotationsOpt().stream()
.map(this::visitAnnotationsOpt)
.collect(Collectors.toList());
Collections.reverse(dimList);
return dimList;
}
@Override
public List<List<AnnotationNode>> visitDimsOpt(DimsOptContext ctx) {
if (!asBoolean(ctx.dims())) {
return Collections.emptyList();
}
return this.visitDims(ctx.dims());
}
// type { --------------------------------------------------------------------
@Override
public ClassNode visitType(TypeContext ctx) {
if (!asBoolean(ctx)) {
return ClassHelper.OBJECT_TYPE;
}
ClassNode classNode = null;
if (asBoolean(ctx.classOrInterfaceType())) {
ctx.classOrInterfaceType().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitClassOrInterfaceType(ctx.classOrInterfaceType());
} else if (asBoolean(ctx.primitiveType())) {
classNode = this.visitPrimitiveType(ctx.primitiveType());
}
if (!asBoolean(classNode)) {
throw createParsingFailedException("Unsupported type: " + ctx.getText(), ctx);
}
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
List<List<AnnotationNode>> dimList = this.visitDimsOpt(ctx.dimsOpt());
if (asBoolean(dimList)) {
// clear array's generics type info. Groovy's bug? array's generics type will be ignored. e.g. List<String>[]... p
classNode.setGenericsTypes(null);
classNode.setUsingGenerics(false);
classNode = this.createArrayType(classNode, dimList);
}
return this.configureAST(classNode, ctx);
}
@Override
public ClassNode visitClassOrInterfaceType(ClassOrInterfaceTypeContext ctx) {
ClassNode classNode;
if (asBoolean(ctx.qualifiedClassName())) {
ctx.qualifiedClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
} else {
ctx.qualifiedStandardClassName().putNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR, ctx.getNodeMetaData(IS_INSIDE_INSTANCEOF_EXPR));
classNode = this.visitQualifiedStandardClassName(ctx.qualifiedStandardClassName());
}
if (asBoolean(ctx.typeArguments())) {
classNode.setGenericsTypes(
this.visitTypeArguments(ctx.typeArguments()));
}
return this.configureAST(classNode, ctx);
}
@Override
public GenericsType[] visitTypeArgumentsOrDiamond(TypeArgumentsOrDiamondContext ctx) {
if (asBoolean(ctx.typeArguments())) {
return this.visitTypeArguments(ctx.typeArguments());
}
if (asBoolean(ctx.LT())) { // e.g. <>
return new GenericsType[0];
}
throw createParsingFailedException("Unsupported type arguments or diamond: " + ctx.getText(), ctx);
}
@Override
public GenericsType[] visitTypeArguments(TypeArgumentsContext ctx) {
return ctx.typeArgument().stream().map(this::visitTypeArgument).toArray(GenericsType[]::new);
}
@Override
public GenericsType visitTypeArgument(TypeArgumentContext ctx) {
if (asBoolean(ctx.QUESTION())) {
ClassNode baseType = this.configureAST(ClassHelper.makeWithoutCaching(QUESTION_STR), ctx.QUESTION());
baseType.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
if (!asBoolean(ctx.type())) {
GenericsType genericsType = new GenericsType(baseType);
genericsType.setWildcard(true);
genericsType.setName(QUESTION_STR);
return this.configureAST(genericsType, ctx);
}
ClassNode[] upperBounds = null;
ClassNode lowerBound = null;
ClassNode classNode = this.visitType(ctx.type());
if (asBoolean(ctx.EXTENDS())) {
upperBounds = new ClassNode[]{classNode};
} else if (asBoolean(ctx.SUPER())) {
lowerBound = classNode;
}
GenericsType genericsType = new GenericsType(baseType, upperBounds, lowerBound);
genericsType.setWildcard(true);
genericsType.setName(QUESTION_STR);
return this.configureAST(genericsType, ctx);
} else if (asBoolean(ctx.type())) {
return this.configureAST(
this.createGenericsType(
this.visitType(ctx.type())),
ctx);
}
throw createParsingFailedException("Unsupported type argument: " + ctx.getText(), ctx);
}
@Override
public ClassNode visitPrimitiveType(PrimitiveTypeContext ctx) {
return this.configureAST(ClassHelper.make(ctx.getText()), ctx);
}
// } type --------------------------------------------------------------------
@Override
public VariableExpression visitVariableDeclaratorId(VariableDeclaratorIdContext ctx) {
return this.configureAST(new VariableExpression(this.visitIdentifier(ctx.identifier())), ctx);
}
@Override
public TupleExpression visitVariableNames(VariableNamesContext ctx) {
return this.configureAST(
new TupleExpression(
ctx.variableDeclaratorId().stream()
.map(this::visitVariableDeclaratorId)
.collect(Collectors.toList())
),
ctx);
}
@Override
public BlockStatement visitBlockStatementsOpt(BlockStatementsOptContext ctx) {
if (asBoolean(ctx.blockStatements())) {
return this.configureAST(this.visitBlockStatements(ctx.blockStatements()), ctx);
}
return this.configureAST(this.createBlockStatement(), ctx);
}
@Override
public BlockStatement visitBlockStatements(BlockStatementsContext ctx) {
return this.configureAST(
this.createBlockStatement(
ctx.blockStatement().stream()
.map(this::visitBlockStatement)
.filter(e -> asBoolean(e))
.collect(Collectors.toList())),
ctx);
}
@Override
public Statement visitBlockStatement(BlockStatementContext ctx) {
if (asBoolean(ctx.localVariableDeclaration())) {
return this.configureAST(this.visitLocalVariableDeclaration(ctx.localVariableDeclaration()), ctx);
}
if (asBoolean(ctx.statement())) {
Object astNode = this.visit(ctx.statement()); //this.configureAST((Statement) this.visit(ctx.statement()), ctx);
if (astNode instanceof MethodNode) {
throw createParsingFailedException("Method definition not expected here", ctx);
} else {
return (Statement) astNode;
}
}
throw createParsingFailedException("Unsupported block statement: " + ctx.getText(), ctx);
}
@Override
public List<AnnotationNode> visitAnnotationsOpt(AnnotationsOptContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
return ctx.annotation().stream()
.map(this::visitAnnotation)
.collect(Collectors.toList());
}
@Override
public AnnotationNode visitAnnotation(AnnotationContext ctx) {
String annotationName = this.visitAnnotationName(ctx.annotationName());
AnnotationNode annotationNode = new AnnotationNode(ClassHelper.make(annotationName));
List<Pair<String, Expression>> annotationElementValues = this.visitElementValues(ctx.elementValues());
annotationElementValues.forEach(e -> annotationNode.addMember(e.getKey(), e.getValue()));
return this.configureAST(annotationNode, ctx);
}
@Override
public List<Pair<String, Expression>> visitElementValues(ElementValuesContext ctx) {
if (!asBoolean(ctx)) {
return Collections.emptyList();
}
List<Pair<String, Expression>> annotationElementValues = new LinkedList<>();
if (asBoolean(ctx.elementValuePairs())) {
this.visitElementValuePairs(ctx.elementValuePairs()).entrySet().forEach(e -> {
annotationElementValues.add(new Pair<>(e.getKey(), e.getValue()));
});
} else if (asBoolean(ctx.elementValue())) {
annotationElementValues.add(new Pair<>(VALUE_STR, this.visitElementValue(ctx.elementValue())));
}
return annotationElementValues;
}
@Override
public String visitAnnotationName(AnnotationNameContext ctx) {
return this.visitQualifiedClassName(ctx.qualifiedClassName()).getName();
}
@Override
public Map<String, Expression> visitElementValuePairs(ElementValuePairsContext ctx) {
return ctx.elementValuePair().stream()
.map(this::visitElementValuePair)
.collect(Collectors.toMap(
Pair::getKey,
Pair::getValue,
(k, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", k));
},
LinkedHashMap::new
));
}
@Override
public Pair<String, Expression> visitElementValuePair(ElementValuePairContext ctx) {
return new Pair<>(ctx.elementValuePairName().getText(), this.visitElementValue(ctx.elementValue()));
}
@Override
public Expression visitElementValue(ElementValueContext ctx) {
if (asBoolean(ctx.expression())) {
return this.configureAST((Expression) this.visit(ctx.expression()), ctx);
}
if (asBoolean(ctx.annotation())) {
return this.configureAST(new AnnotationConstantExpression(this.visitAnnotation(ctx.annotation())), ctx);
}
if (asBoolean(ctx.elementValueArrayInitializer())) {
return this.configureAST(this.visitElementValueArrayInitializer(ctx.elementValueArrayInitializer()), ctx);
}
throw createParsingFailedException("Unsupported element value: " + ctx.getText(), ctx);
}
@Override
public ListExpression visitElementValueArrayInitializer(ElementValueArrayInitializerContext ctx) {
return this.configureAST(new ListExpression(ctx.elementValue().stream().map(this::visitElementValue).collect(Collectors.toList())), ctx);
}
@Override
public String visitClassName(ClassNameContext ctx) {
String text = ctx.getText();
if (!text.contains("\\")) {
return text;
}
return StringUtils.replaceHexEscapes(text);
}
@Override
public String visitIdentifier(IdentifierContext ctx) {
String text = ctx.getText();
if (!text.contains("\\")) {
return text;
}
return StringUtils.replaceHexEscapes(text);
}
@Override
public String visitQualifiedName(QualifiedNameContext ctx) {
return ctx.qualifiedNameElement().stream()
.map(ParseTree::getText)
.collect(Collectors.joining(DOT_STR));
}
@Override
public ClassNode visitAnnotatedQualifiedClassName(AnnotatedQualifiedClassNameContext ctx) {
ClassNode classNode = this.visitQualifiedClassName(ctx.qualifiedClassName());
classNode.addAnnotations(this.visitAnnotationsOpt(ctx.annotationsOpt()));
return classNode;
}
@Override
public ClassNode[] visitQualifiedClassNameList(QualifiedClassNameListContext ctx) {
if (!asBoolean(ctx)) {
return new ClassNode[0];
}
return ctx.annotatedQualifiedClassName().stream()
.map(this::visitAnnotatedQualifiedClassName)
.toArray(ClassNode[]::new);
}
@Override
public ClassNode visitQualifiedClassName(QualifiedClassNameContext ctx) {
return this.createClassNode(ctx);
}
@Override
public ClassNode visitQualifiedStandardClassName(QualifiedStandardClassNameContext ctx) {
return this.createClassNode(ctx);
}
private ClassNode createClassNode(GroovyParserRuleContext ctx) {
ClassNode result = ClassHelper.make(ctx.getText());
if (!isTrue(ctx, IS_INSIDE_INSTANCEOF_EXPR)) { // type in the "instanceof" expression should not have proxy to redirect to it
result = this.proxyClassNode(result);
}
return this.configureAST(result, ctx);
}
private ClassNode proxyClassNode(ClassNode classNode) {
if (!classNode.isUsingGenerics()) {
return classNode;
}
ClassNode cn = ClassHelper.makeWithoutCaching(classNode.getName());
cn.setRedirect(classNode);
return cn;
}
/**
* Visit tree safely, no NPE occurred when the tree is null.
*
* @param tree an AST node
* @return the visiting result
*/
@Override
public Object visit(ParseTree tree) {
if (!asBoolean(tree)) {
return null;
}
return super.visit(tree);
}
// e.g. obj.a(1, 2) or obj.a 1, 2
private MethodCallExpression createMethodCallExpression(PropertyExpression propertyExpression, Expression arguments) {
MethodCallExpression methodCallExpression =
new MethodCallExpression(
propertyExpression.getObjectExpression(),
propertyExpression.getProperty(),
arguments
);
methodCallExpression.setImplicitThis(false);
methodCallExpression.setSafe(propertyExpression.isSafe());
methodCallExpression.setSpreadSafe(propertyExpression.isSpreadSafe());
// method call obj*.m(): "safe"(false) and "spreadSafe"(true)
// property access obj*.p: "safe"(true) and "spreadSafe"(true)
// so we have to reset safe here.
if (propertyExpression.isSpreadSafe()) {
methodCallExpression.setSafe(false);
}
// if the generics types meta data is not empty, it is a generic method call, e.g. obj.<Integer>a(1, 2)
methodCallExpression.setGenericsTypes(
propertyExpression.getNodeMetaData(PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES));
return methodCallExpression;
}
// e.g. m(1, 2) or m 1, 2
private MethodCallExpression createMethodCallExpression(Expression baseExpr, Expression arguments) {
return new MethodCallExpression(
VariableExpression.THIS_EXPRESSION,
(baseExpr instanceof VariableExpression)
? this.createConstantExpression(baseExpr)
: baseExpr,
arguments
);
}
private Parameter processFormalParameter(GroovyParserRuleContext ctx,
VariableModifiersOptContext variableModifiersOptContext,
TypeContext typeContext,
TerminalNode ellipsis,
VariableDeclaratorIdContext variableDeclaratorIdContext,
ExpressionContext expressionContext) {
ClassNode classNode = this.visitType(typeContext);
if (asBoolean(ellipsis)) {
classNode = this.configureAST(classNode.makeArray(), classNode);
}
Parameter parameter =
new ModifierManager(this, this.visitVariableModifiersOpt(variableModifiersOptContext))
.processParameter(
this.configureAST(
new Parameter(
classNode,
this.visitVariableDeclaratorId(variableDeclaratorIdContext).getName()
),
ctx
)
);
if (asBoolean(expressionContext)) {
parameter.setInitialExpression((Expression) this.visit(expressionContext));
}
return parameter;
}
private Expression createPathExpression(Expression primaryExpr, List<? extends PathElementContext> pathElementContextList) {
return (Expression) pathElementContextList.stream()
.map(e -> (Object) e)
.reduce(primaryExpr,
(r, e) -> {
PathElementContext pathElementContext = (PathElementContext) e;
pathElementContext.putNodeMetaData(PATH_EXPRESSION_BASE_EXPR, r);
return this.visitPathElement(pathElementContext);
}
);
}
private GenericsType createGenericsType(ClassNode classNode) {
return this.configureAST(new GenericsType(classNode), classNode);
}
private ConstantExpression createConstantExpression(Expression expression) {
if (expression instanceof ConstantExpression) {
return (ConstantExpression) expression;
}
return this.configureAST(new ConstantExpression(expression.getText()), expression);
}
private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right) {
return new BinaryExpression((Expression) this.visit(left), this.createGroovyToken(op), (Expression) this.visit(right));
}
private BinaryExpression createBinaryExpression(ExpressionContext left, Token op, ExpressionContext right, ExpressionContext ctx) {
BinaryExpression binaryExpression = this.createBinaryExpression(left, op, right);
if (isTrue(ctx, IS_INSIDE_CONDITIONAL_EXPRESSION)) {
return this.configureAST(binaryExpression, op);
}
return this.configureAST(binaryExpression, ctx);
}
private Statement unpackStatement(Statement statement) {
if (statement instanceof DeclarationListStatement) {
List<ExpressionStatement> expressionStatementList = ((DeclarationListStatement) statement).getDeclarationStatements();
if (1 == expressionStatementList.size()) {
return expressionStatementList.get(0);
}
return this.configureAST(this.createBlockStatement(statement), statement); // if DeclarationListStatement contains more than 1 declarations, maybe it's better to create a block to hold them
}
return statement;
}
public BlockStatement createBlockStatement(Statement... statements) {
return this.createBlockStatement(Arrays.asList(statements));
}
private BlockStatement createBlockStatement(List<Statement> statementList) {
return this.appendStatementsToBlockStatement(new BlockStatement(), statementList);
}
public BlockStatement appendStatementsToBlockStatement(BlockStatement bs, Statement... statements) {
return this.appendStatementsToBlockStatement(bs, Arrays.asList(statements));
}
private BlockStatement appendStatementsToBlockStatement(BlockStatement bs, List<Statement> statementList) {
return (BlockStatement) statementList.stream()
.reduce(bs, (r, e) -> {
BlockStatement blockStatement = (BlockStatement) r;
if (e instanceof DeclarationListStatement) {
((DeclarationListStatement) e).getDeclarationStatements().forEach(blockStatement::addStatement);
} else {
blockStatement.addStatement(e);
}
return blockStatement;
});
}
private boolean isAnnotationDeclaration(ClassNode classNode) {
return asBoolean(classNode) && classNode.isAnnotationDefinition();
}
private boolean isSyntheticPublic(
boolean isAnnotationDeclaration,
boolean isAnonymousInnerEnumDeclaration,
boolean hasReturnType,
ModifierManager modifierManager
) {
return this.isSyntheticPublic(
isAnnotationDeclaration,
isAnonymousInnerEnumDeclaration,
modifierManager.containsAnnotations(),
modifierManager.containsVisibilityModifier(),
modifierManager.containsNonVisibilityModifier(),
hasReturnType,
modifierManager.contains(DEF));
}
/**
* @param isAnnotationDeclaration whether the method is defined in an annotation
* @param isAnonymousInnerEnumDeclaration whether the method is defined in an anonymous inner enum
* @param hasAnnotation whether the method declaration has annotations
* @param hasVisibilityModifier whether the method declaration contains visibility modifier(e.g. public, protected, private)
* @param hasModifier whether the method declaration has modifier(e.g. visibility modifier, final, static and so on)
* @param hasReturnType whether the method declaration has an return type(e.g. String, generic types)
* @param hasDef whether the method declaration using def keyword
* @return the result
*/
private boolean isSyntheticPublic(
boolean isAnnotationDeclaration,
boolean isAnonymousInnerEnumDeclaration,
boolean hasAnnotation,
boolean hasVisibilityModifier,
boolean hasModifier,
boolean hasReturnType,
boolean hasDef) {
if (hasVisibilityModifier) {
return false;
}
if (isAnnotationDeclaration) {
return true;
}
if (hasDef && hasReturnType) {
return true;
}
if (hasModifier || hasAnnotation || !hasReturnType) {
return true;
}
return isAnonymousInnerEnumDeclaration;
}
// the mixins of interface and annotation should be null
private void hackMixins(ClassNode classNode) {
classNode.setMixins(null);
}
private static final Map<ClassNode, Object> TYPE_DEFAULT_VALUE_MAP = Maps.of(
ClassHelper.int_TYPE, 0,
ClassHelper.long_TYPE, 0L,
ClassHelper.double_TYPE, 0.0D,
ClassHelper.float_TYPE, 0.0F,
ClassHelper.short_TYPE, (short) 0,
ClassHelper.byte_TYPE, (byte) 0,
ClassHelper.char_TYPE, (char) 0,
ClassHelper.boolean_TYPE, Boolean.FALSE
);
private Object findDefaultValueByType(ClassNode type) {
return TYPE_DEFAULT_VALUE_MAP.get(type);
}
private boolean isPackageInfoDeclaration() {
String name = this.sourceUnit.getName();
return null != name && name.endsWith(PACKAGE_INFO_FILE_NAME);
}
private boolean isBlankScript(CompilationUnitContext ctx) {
return moduleNode.getStatementBlock().isEmpty() && moduleNode.getMethods().isEmpty() && moduleNode.getClasses().isEmpty();
}
private boolean isInsideParentheses(NodeMetaDataHandler nodeMetaDataHandler) {
Integer insideParenLevel = nodeMetaDataHandler.getNodeMetaData(INSIDE_PARENTHESES_LEVEL);
if (null != insideParenLevel) {
return insideParenLevel > 0;
}
return false;
}
private void addEmptyReturnStatement() {
moduleNode.addStatement(ReturnStatement.RETURN_NULL_OR_VOID);
}
private void addPackageInfoClassNode() {
List<ClassNode> classNodeList = moduleNode.getClasses();
ClassNode packageInfoClassNode = ClassHelper.make(moduleNode.getPackageName() + PACKAGE_INFO);
if (!classNodeList.contains(packageInfoClassNode)) {
moduleNode.addClass(packageInfoClassNode);
}
}
private org.codehaus.groovy.syntax.Token createGroovyTokenByType(Token token, int type) {
if (null == token) {
throw new IllegalArgumentException("token should not be null");
}
return new org.codehaus.groovy.syntax.Token(type, token.getText(), token.getLine(), token.getCharPositionInLine());
}
private org.codehaus.groovy.syntax.Token createGroovyToken(Token token) {
return this.createGroovyToken(token, 1);
}
private org.codehaus.groovy.syntax.Token createGroovyToken(Token token, int cardinality) {
String text = StringGroovyMethods.multiply((CharSequence) token.getText(), cardinality);
return new org.codehaus.groovy.syntax.Token(
"..<".equals(token.getText()) || "..".equals(token.getText())
? Types.RANGE_OPERATOR
: Types.lookup(text, Types.ANY),
text,
token.getLine(),
token.getCharPositionInLine() + 1
);
}
/*
private org.codehaus.groovy.syntax.Token createGroovyToken(String text, int startLine, int startColumn) {
return new org.codehaus.groovy.syntax.Token(
Types.lookup(text, Types.ANY),
text,
startLine,
startColumn
);
}
*/
/**
* set the script source position
*/
private void configureScriptClassNode() {
ClassNode scriptClassNode = moduleNode.getScriptClassDummy();
if (!asBoolean(scriptClassNode)) {
return;
}
List<Statement> statements = moduleNode.getStatementBlock().getStatements();
if (!statements.isEmpty()) {
Statement firstStatement = statements.get(0);
Statement lastStatement = statements.get(statements.size() - 1);
scriptClassNode.setSourcePosition(firstStatement);
scriptClassNode.setLastColumnNumber(lastStatement.getLastColumnNumber());
scriptClassNode.setLastLineNumber(lastStatement.getLastLineNumber());
}
}
/**
* Sets location(lineNumber, colNumber, lastLineNumber, lastColumnNumber) for node using standard context information.
* Note: this method is implemented to be closed over ASTNode. It returns same node as it received in arguments.
*
* @param astNode Node to be modified.
* @param ctx Context from which information is obtained.
* @return Modified astNode.
*/
private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx) {
Token start = ctx.getStart();
Token stop = ctx.getStop();
astNode.setLineNumber(start.getLine());
astNode.setColumnNumber(start.getCharPositionInLine() + 1);
Pair<Integer, Integer> stopTokenEndPosition = endPosition(stop);
astNode.setLastLineNumber(stopTokenEndPosition.getKey());
astNode.setLastColumnNumber(stopTokenEndPosition.getValue());
return astNode;
}
private Pair<Integer, Integer> endPosition(Token token) {
String stopText = token.getText();
int stopTextLength = 0;
int newLineCnt = 0;
if (null != stopText) {
stopTextLength = stopText.length();
newLineCnt = (int) StringUtils.countChar(stopText, '\n');
}
if (0 == newLineCnt) {
return new Pair<Integer, Integer>(token.getLine(), token.getCharPositionInLine() + 1 + token.getText().length());
} else { // e.g. GStringEnd contains newlines, we should fix the location info
return new Pair<Integer, Integer>(token.getLine() + newLineCnt, stopTextLength - stopText.lastIndexOf('\n'));
}
}
private <T extends ASTNode> T configureAST(T astNode, TerminalNode terminalNode) {
return this.configureAST(astNode, terminalNode.getSymbol());
}
private <T extends ASTNode> T configureAST(T astNode, Token token) {
astNode.setLineNumber(token.getLine());
astNode.setColumnNumber(token.getCharPositionInLine() + 1);
astNode.setLastLineNumber(token.getLine());
astNode.setLastColumnNumber(token.getCharPositionInLine() + 1 + token.getText().length());
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, ASTNode source) {
astNode.setLineNumber(source.getLineNumber());
astNode.setColumnNumber(source.getColumnNumber());
astNode.setLastLineNumber(source.getLastLineNumber());
astNode.setLastColumnNumber(source.getLastColumnNumber());
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, GroovyParserRuleContext ctx, ASTNode stop) {
Token start = ctx.getStart();
astNode.setLineNumber(start.getLine());
astNode.setColumnNumber(start.getCharPositionInLine() + 1);
if (asBoolean(stop)) {
astNode.setLastLineNumber(stop.getLastLineNumber());
astNode.setLastColumnNumber(stop.getLastColumnNumber());
} else {
Pair<Integer, Integer> endPosition = endPosition(start);
astNode.setLastLineNumber(endPosition.getKey());
astNode.setLastColumnNumber(endPosition.getValue());
}
return astNode;
}
private <T extends ASTNode> T configureAST(T astNode, ASTNode start, ASTNode stop) {
astNode.setLineNumber(start.getLineNumber());
astNode.setColumnNumber(start.getColumnNumber());
if (asBoolean(stop)) {
astNode.setLastLineNumber(stop.getLastLineNumber());
astNode.setLastColumnNumber(stop.getLastColumnNumber());
} else {
astNode.setLastLineNumber(start.getLastLineNumber());
astNode.setLastColumnNumber(start.getLastColumnNumber());
}
return astNode;
}
private boolean isTrue(NodeMetaDataHandler nodeMetaDataHandler, String key) {
Object nmd = nodeMetaDataHandler.getNodeMetaData(key);
if (null == nmd) {
return false;
}
if (!(nmd instanceof Boolean)) {
throw new GroovyBugError(nodeMetaDataHandler + " node meta data[" + key + "] is not an instance of Boolean");
}
return (Boolean) nmd;
}
private CompilationFailedException createParsingFailedException(String msg, GroovyParserRuleContext ctx) {
return createParsingFailedException(
new SyntaxException(msg,
ctx.start.getLine(),
ctx.start.getCharPositionInLine() + 1,
ctx.stop.getLine(),
ctx.stop.getCharPositionInLine() + 1 + ctx.stop.getText().length()));
}
public CompilationFailedException createParsingFailedException(String msg, ASTNode node) {
Objects.requireNonNull(node, "node passed into createParsingFailedException should not be null");
return createParsingFailedException(
new SyntaxException(msg,
node.getLineNumber(),
node.getColumnNumber(),
node.getLastLineNumber(),
node.getLastColumnNumber()));
}
/*
private CompilationFailedException createParsingFailedException(String msg, Token token) {
return createParsingFailedException(
new SyntaxException(msg,
token.getLine(),
token.getCharPositionInLine() + 1,
token.getLine(),
token.getCharPositionInLine() + 1 + token.getText().length()));
}
*/
private CompilationFailedException createParsingFailedException(Throwable t) {
if (t instanceof SyntaxException) {
this.collectSyntaxError((SyntaxException) t);
} else if (t instanceof GroovySyntaxError) {
GroovySyntaxError groovySyntaxError = (GroovySyntaxError) t;
this.collectSyntaxError(
new SyntaxException(
groovySyntaxError.getMessage(),
groovySyntaxError,
groovySyntaxError.getLine(),
groovySyntaxError.getColumn()));
} else if (t instanceof Exception) {
this.collectException((Exception) t);
}
return new CompilationFailedException(
CompilePhase.PARSING.getPhaseNumber(),
this.sourceUnit,
t);
}
private void collectSyntaxError(SyntaxException e) {
sourceUnit.getErrorCollector().addFatalError(new SyntaxErrorMessage(e, sourceUnit));
}
private void collectException(Exception e) {
sourceUnit.getErrorCollector().addException(e, this.sourceUnit);
}
private ANTLRErrorListener createANTLRErrorListener() {
return new ANTLRErrorListener() {
@Override
public void syntaxError(
Recognizer recognizer,
Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e) {
collectSyntaxError(new SyntaxException(msg, line, charPositionInLine + 1));
}
};
}
private void removeErrorListeners() {
lexer.removeErrorListeners();
parser.removeErrorListeners();
}
private void addErrorListeners() {
lexer.removeErrorListeners();
lexer.addErrorListener(this.createANTLRErrorListener());
parser.removeErrorListeners();
parser.addErrorListener(this.createANTLRErrorListener());
}
private String createExceptionMessage(Throwable t) {
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
t.printStackTrace(pw);
}
return sw.toString();
}
private class DeclarationListStatement extends Statement {
private final List<ExpressionStatement> declarationStatements;
public DeclarationListStatement(DeclarationExpression... declarations) {
this(Arrays.asList(declarations));
}
public DeclarationListStatement(List<DeclarationExpression> declarations) {
this.declarationStatements =
declarations.stream()
.map(e -> configureAST(new ExpressionStatement(e), e))
.collect(Collectors.toList());
}
public List<ExpressionStatement> getDeclarationStatements() {
List<String> declarationListStatementLabels = this.getStatementLabels();
this.declarationStatements.forEach(e -> {
if (null != declarationListStatementLabels) {
// clear existing statement labels before setting labels
if (null != e.getStatementLabels()) {
e.getStatementLabels().clear();
}
declarationListStatementLabels.forEach(e::addStatementLabel);
}
});
return this.declarationStatements;
}
public List<DeclarationExpression> getDeclarationExpressions() {
return this.declarationStatements.stream()
.map(e -> (DeclarationExpression) e.getExpression())
.collect(Collectors.toList());
}
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return Objects.equals(key, pair.key) &&
Objects.equals(value, pair.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
}
private final ModuleNode moduleNode;
private final SourceUnit sourceUnit;
private final ClassLoader classLoader; // Our ClassLoader, which provides information on external types
private final GroovyLangLexer lexer;
private final GroovyLangParser parser;
private final TryWithResourcesASTTransformation tryWithResourcesASTTransformation;
private final GroovydocManager groovydocManager;
private final List<ClassNode> classNodeList = new LinkedList<>();
private final Deque<ClassNode> classNodeStack = new ArrayDeque<>();
private final Deque<List<InnerClassNode>> anonymousInnerClassesDefinedInMethodStack = new ArrayDeque<>();
private int anonymousInnerClassCounter = 1;
private Pair<GroovyParserRuleContext, Exception> numberFormatError;
private static final String QUESTION_STR = "?";
private static final String DOT_STR = ".";
private static final String SUB_STR = "-";
private static final String ASSIGN_STR = "=";
private static final String VALUE_STR = "value";
private static final String DOLLAR_STR = "$";
private static final String CALL_STR = "call";
private static final String THIS_STR = "this";
private static final String SUPER_STR = "super";
private static final String VOID_STR = "void";
private static final String PACKAGE_INFO = "package-info";
private static final String PACKAGE_INFO_FILE_NAME = PACKAGE_INFO + ".groovy";
private static final String GROOVY_TRANSFORM_TRAIT = "groovy.transform.Trait";
private static final Set<String> PRIMITIVE_TYPE_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double")));
private static final Logger LOGGER = Logger.getLogger(AstBuilder.class.getName());
private static final String INSIDE_PARENTHESES_LEVEL = "_INSIDE_PARENTHESES_LEVEL";
private static final String IS_INSIDE_INSTANCEOF_EXPR = "_IS_INSIDE_INSTANCEOF_EXPR";
private static final String IS_SWITCH_DEFAULT = "_IS_SWITCH_DEFAULT";
private static final String IS_NUMERIC = "_IS_NUMERIC";
private static final String IS_STRING = "_IS_STRING";
private static final String IS_INTERFACE_WITH_DEFAULT_METHODS = "_IS_INTERFACE_WITH_DEFAULT_METHODS";
private static final String IS_INSIDE_CONDITIONAL_EXPRESSION = "_IS_INSIDE_CONDITIONAL_EXPRESSION";
private static final String PATH_EXPRESSION_BASE_EXPR = "_PATH_EXPRESSION_BASE_EXPR";
private static final String PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES = "_PATH_EXPRESSION_BASE_EXPR_GENERICS_TYPES";
private static final String CMD_EXPRESSION_BASE_EXPR = "_CMD_EXPRESSION_BASE_EXPR";
private static final String TYPE_DECLARATION_MODIFIERS = "_TYPE_DECLARATION_MODIFIERS";
private static final String CLASS_DECLARATION_CLASS_NODE = "_CLASS_DECLARATION_CLASS_NODE";
private static final String VARIABLE_DECLARATION_VARIABLE_TYPE = "_VARIABLE_DECLARATION_VARIABLE_TYPE";
private static final String ANONYMOUS_INNER_CLASS_SUPER_CLASS = "_ANONYMOUS_INNER_CLASS_SUPER_CLASS";
private static final String INTEGER_LITERAL_TEXT = "_INTEGER_LITERAL_TEXT";
private static final String FLOATING_POINT_LITERAL_TEXT = "_FLOATING_POINT_LITERAL_TEXT";
private static final String CLASS_NAME = "_CLASS_NAME";
}
| Minor refactoring
| src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java | Minor refactoring | <ide><path>rc/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
<ide> if (expression instanceof ClosureExpression && !asBoolean(e.closure().ARROW())) {
<ide> List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements();
<ide>
<del> if (statementList.stream().allMatch(x -> !asBoolean(x))) {
<add> if (statementList.stream().noneMatch(x -> asBoolean(x))) {
<ide> return this.configureAST(new ConstantExpression(null), e);
<ide> }
<ide> |
|
JavaScript | apache-2.0 | c49d78252f86ab1e24ab0be024d797a9c5f6f5f9 | 0 | icereval/osf.io,monikagrabowska/osf.io,mluo613/osf.io,cslzchen/osf.io,Nesiehr/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,laurenrevere/osf.io,Johnetordoff/osf.io,acshi/osf.io,Nesiehr/osf.io,mfraezz/osf.io,hmoco/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,alexschiller/osf.io,TomBaxter/osf.io,icereval/osf.io,adlius/osf.io,monikagrabowska/osf.io,saradbowman/osf.io,saradbowman/osf.io,Nesiehr/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,leb2dg/osf.io,erinspace/osf.io,cwisecarver/osf.io,cslzchen/osf.io,mattclark/osf.io,chennan47/osf.io,mattclark/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,sloria/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,erinspace/osf.io,acshi/osf.io,caseyrollins/osf.io,laurenrevere/osf.io,caseyrollins/osf.io,crcresearch/osf.io,pattisdr/osf.io,caneruguz/osf.io,mattclark/osf.io,felliott/osf.io,laurenrevere/osf.io,alexschiller/osf.io,caneruguz/osf.io,adlius/osf.io,icereval/osf.io,cslzchen/osf.io,hmoco/osf.io,caneruguz/osf.io,sloria/osf.io,hmoco/osf.io,TomBaxter/osf.io,caneruguz/osf.io,chrisseto/osf.io,caseyrollins/osf.io,binoculars/osf.io,pattisdr/osf.io,baylee-d/osf.io,adlius/osf.io,mluo613/osf.io,acshi/osf.io,baylee-d/osf.io,TomBaxter/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,rdhyee/osf.io,aaxelb/osf.io,cwisecarver/osf.io,Johnetordoff/osf.io,adlius/osf.io,brianjgeiger/osf.io,binoculars/osf.io,sloria/osf.io,erinspace/osf.io,chennan47/osf.io,alexschiller/osf.io,rdhyee/osf.io,leb2dg/osf.io,crcresearch/osf.io,chennan47/osf.io,alexschiller/osf.io,hmoco/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,cslzchen/osf.io,felliott/osf.io,leb2dg/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,acshi/osf.io,HalcyonChimera/osf.io,rdhyee/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,aaxelb/osf.io,acshi/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,binoculars/osf.io,felliott/osf.io,felliott/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io | var $ = require('jquery');
var m = require('mithril');
var mime = require('js/mime');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');
// Local requires
var utils = require('./util.js');
var FileEditor = require('./editor.js');
var makeClient = require('js/clipboard');
var FileRevisionsTable = require('./revisions.js');
var storageAddons = require('json!storageAddons.json');
var CommentModel = require('js/comment');
var History = require('exports?History!history');
var SocialShare = require('js/components/socialshare');
// Sanity
var Panel = utils.Panel;
var EDITORS = {'text': FileEditor};
var clipboardConfig = function(element, isInitialized) {
if (!isInitialized) {
makeClient(element);
}
};
var CopyButton = {
view: function(ctrl, params) {
return m('span.input-group-btn', m('button.btn.btn-default.btn-md[type="button"]' +
'[data-clipboard-text="' + params.link + '"]',
{config: clipboardConfig, style: {height: params.height}},
m('.fa.fa-copy')));
}
};
var SharePopover = {
view: function(ctrl, params) {
var copyButtonHeight = '34px';
var popoverWidth = '450px';
var renderLink = params.link;
var fileLink = window.location.href;
var mfrHost = renderLink.substring(0, renderLink.indexOf('render'));
return m('button#sharebutton.disabled.btn.btn-sm.btn-primary.file-share', {onclick: function popOverShow() {
var pop = document.getElementById('popOver');
//This is bad, should only happen for Firefox, thanks @chrisseto
if (!pop){
return window.setTimeout(popOverShow, 100);
}
m.render(document.getElementById('popOver'), [
m('ul.nav.nav-tabs.nav-justified', [
m('li.active', m('a[href="#share"][data-toggle="tab"]', 'Share')),
m('li', m('a[href="#embed"][data-toggle="tab"]', 'Embed'))
]), m('br'),
m('.tab-content', [
m('.tab-pane.active#share', [
m('.input-group', [
CopyButton.view(ctrl, {link: renderLink, height: copyButtonHeight}), //workaround to allow button to show up on first click
m('input.form-control[readonly][type="text"][value="'+ renderLink +'"]')
]),
SocialShare.ShareButtons.view(ctrl, {title: window.contextVars.file.name, url: fileLink})
]),
m('.tab-pane#embed', [
m('p', 'Dynamically render iframe with JavaScript'),
m('textarea.form-control[readonly][type="text"][value="' +
'<style>' +
'.embed-responsive{position:relative;height:100%;}' +
'.embed-responsive iframe{position:absolute;height:100%;}' +
'</style>' +
'<script>window.jQuery || document.write(\'<script src="//code.jquery.com/jquery-1.11.2.min.js">\\x3C/script>\') </script>' +
'<link href="' + mfrHost + 'static/css/mfr.css" media="all" rel="stylesheet">' +
'<div id="mfrIframe" class="mfr mfr-file"></div>' +
'<script src="' + mfrHost + 'static/js/mfr.js">' +
'</script> <script>' +
'var mfrRender = new mfr.Render("mfrIframe", "' + renderLink + '");' +
'</script>' + '"]'
), m('br'),
m('p', 'Direct iframe with fixed height and width'),
m('textarea.form-control[readonly][value="' +
'<iframe src="' + renderLink + '" width="100%" scrolling="yes" height="' + params.height + '" marginheight="0" frameborder="0" allowfullscreen webkitallowfullscreen>"]'
)
])
])
]);
},
config: function(element, isInitialized) {
if(!isInitialized){
var button = $(element).popover();
button.on('show.bs.popover', function(e){
//max-width used to override, and width used to create space for the mithril object to be injected
button.data()['bs.popover'].$tip.css('text-align', 'center').css('max-width', popoverWidth).css('width', popoverWidth);
});
}
},
'data-toggle': 'popover', 'data-placement': 'bottom',
'data-content': '<div id="popOver"></div>', 'title': 'Share',
'data-container': 'body', 'data-html': 'true'
}, 'Share');
}
};
var FileViewPage = {
controller: function(context) {
var self = this;
self.context = context;
self.file = self.context.file;
self.node = self.context.node;
self.editorMeta = self.context.editor;
self.file.checkoutUser = null;
self.requestDone = false;
self.isCheckoutUser = function() {
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/vnd.api+json'
},
method: 'get',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization
}).done(function(resp) {
self.requestDone = true;
self.file.checkoutUser = resp.data.relationships.checkout ? ((resp.data.relationships.checkout.links.related.href).split('users/')[1]).replace('/', ''): null;
if ((self.file.checkoutUser) && (self.file.checkoutUser !== self.context.currentUser.id)) {
m.render(document.getElementById('alertBar'), m('.alert.alert-warning[role="alert"]', m('span', [
m('strong', 'File is checked out.'),
' This file has been checked out by a ',
m('a[href="/' + self.file.checkoutUser + '"]', 'collaborator'),
'. It needs to be checked in before any changes can be made.'
])));
}
});
};
if (self.file.provider === 'osfstorage'){
self.canEdit = function() {
return ((!self.file.checkoutUser) || (self.file.checkoutUser === self.context.currentUser.id)) ? self.context.currentUser.canEdit : false;
};
self.isCheckoutUser();
} else {
self.requestDone = true;
self.canEdit = function() {
return self.context.currentUser.canEdit;
};
}
$.extend(self.file.urls, {
delete: waterbutler.buildDeleteUrl(self.file.path, self.file.provider, self.node.id),
metadata: waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id),
revisions: waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id),
content: waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render'})
});
if ($osf.urlParams().branch) {
var fileWebViewUrl = waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id, {branch : $osf.urlParams().branch});
$.ajax({
dataType: 'json',
async: true,
url: fileWebViewUrl,
beforeSend: $osf.setXHRAuthorization
}).done(function(response) {
window.contextVars.file.urls.external = response.data.extra.webView;
});
self.file.urls.revisions = waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id, {sha: $osf.urlParams().branch});
self.file.urls.content = waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render', branch: $osf.urlParams().branch});
}
$(document).on('fileviewpage:delete', function() {
bootbox.confirm({
title: 'Delete file?',
message: '<p class="overflow">' +
'Are you sure you want to delete <strong>' +
self.file.safeName + '</strong>?' +
'</p>',
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
type: 'DELETE',
url: self.file.urls.delete,
beforeSend: $osf.setXHRAuthorization
}).done(function() {
window.location = self.node.urls.files;
}).fail(function() {
$osf.growl('Error', 'Could not delete file.');
});
},
buttons:{
confirm:{
label:'Delete',
className:'btn-danger'
}
}
});
});
$(document).on('fileviewpage:checkout', function() {
bootbox.confirm({
title: 'Confirm file check out?',
message: 'This would mean ' +
'other contributors cannot edit, delete or upload new versions of this file ' +
'as long as it is checked out. You can check it back in at anytime.',
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: self.context.currentUser.id
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to check out file');
});
},
buttons:{
confirm:{
label: 'Check out file',
className: 'btn-warning'
}
}
});
});
$(document).on('fileviewpage:checkin', function() {
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: null
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to check in file');
});
});
$(document).on('fileviewpage:force_checkin', function() {
bootbox.confirm({
title: 'Force check in file?',
message: 'This will check in the file for all users, allowing it to be edited. Are you sure?',
buttons: {
confirm:{
label: 'Force check in',
className: 'btn-danger'
}
},
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: null
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to force check in file. Make sure you have admin privileges.');
});
}
});
});
$(document).on('fileviewpage:download', function() {
//replace mode=render with action=download for download count incrementation
window.location = self.file.urls.content.replace('mode=render', 'action=download');
return false;
});
self.shareJSObservables = {
activeUsers: m.prop([]),
status: m.prop('connecting'),
userId: self.context.currentUser.id
};
self.editHeader = function() {
return m('.row', [
m('.col-sm-12', m('span[style=display:block;]', [
m('h3.panel-title',[m('i.fa.fa-pencil-square-o'), ' Edit ']),
m('.pull-right', [
m('.progress.no-margin.pointer', {
'data-toggle': 'modal',
'data-target': '#' + self.shareJSObservables.status() + 'Modal'
}, [
m('.progress-bar.p-h-sm.progress-bar-success', {
connected: {
style: 'width: 100%',
class: 'progress-bar progress-bar-success'
},
connecting: {
style: 'width: 100%',
class: 'progress-bar progress-bar-warning progress-bar-striped active'
},
saving: {
style: 'width: 100%',
class: 'progress-bar progress-bar-info progress-bar-striped active'
}
}[self.shareJSObservables.status()] || {
style: 'width: 100%',
class: 'progress-bar progress-bar-danger'
}, [
m('span.progress-bar-content', [
{
connected: 'Live editing mode ',
connecting: 'Attempting to connect ',
unsupported: 'Unsupported browser ',
saving: 'Saving... '
}[self.shareJSObservables.status()] || 'Unavailable: Live editing ',
m('i.fa.fa-question-circle.fa-large')
])
])
])
])
]))
]);
};
// Hack to delay creation of the editor
// until we know this is the current file revision
self.enableEditing = function() {
// Sometimes we can get here twice, check just in case
if (self.editor || !self.canEdit()) {
m.redraw(true);
return;
}
var fileType = mime.lookup(self.file.name.toLowerCase());
// Only allow files < 1MB to be editable
if (self.file.size < 1048576 && fileType) { //May return false
var editor = EDITORS[fileType.split('/')[0]];
if (editor) {
self.editor = new Panel('Edit', self.editHeader, editor, [self.file.urls.content, self.file.urls.sharejs, self.editorMeta, self.shareJSObservables], false);
}
}
m.redraw(true);
};
//Hack to polyfill the Panel interface
//Ran into problems with mithrils caching messing up with multiple "Panels"
self.revisions = m.component(FileRevisionsTable, self.file, self.node, self.enableEditing, self.canEdit);
self.revisions.selected = false;
self.revisions.title = 'Revisions';
// inform the mfr of a change in display size performed via javascript,
// otherwise the mfr iframe will not update unless the document windows is changed.
self.triggerResize = $osf.throttle(function () {
$(document).trigger('fileviewpage:resize');
}, 1000);
self.mfrIframeParent = $('#mfrIframeParent');
function toggleRevisions(e){
if(self.editor){
self.editor.selected = false;
}
var viewable = self.mfrIframeParent.is(':visible');
var url = '';
if (viewable){
self.mfrIframeParent.toggle();
self.revisions.selected = true;
url = '?show=revision';
} else {
self.mfrIframeParent.toggle();
self.revisions.selected = false;
url = '?show=view';
}
var state = {
scrollTop: $(window).scrollTop(),
};
History.pushState(state, 'OSF | ' + window.contextVars.file.name, url);
}
function changeVersionHeader(){
document.getElementById('versionLink').style.display = 'inline';
m.render(document.getElementById('versionLink'), m('a', {onclick: toggleRevisions}, document.getElementById('versionLink').innerHTML));
}
var urlParams = $osf.urlParams();
// The parser found a query so lets check what we need to do
if ('show' in urlParams){
if(urlParams.show === 'revision'){
self.mfrIframeParent.toggle();
self.revisions.selected = true;
} else if (urlParams.show === 'view' || urlParams.show === 'edit'){
self.revisions.selected = false;
}
}
if(self.file.provider === 'osfstorage'){
changeVersionHeader();
}
},
view: function(ctrl) {
//This code was abstracted into a panel toggler at one point
//it was removed and shoved here due to issues with mithrils caching and interacting
//With other non-mithril components on the page
//anchor checking hack that will select if true
var state = {
scrollTop: $(window).scrollTop(),
};
var panelsShown = (
((ctrl.editor && ctrl.editor.selected) ? 1 : 0) + // Editor panel is active
(ctrl.mfrIframeParent.is(':visible') ? 1 : 0) // View panel is active
);
var mfrIframeParentLayout;
var fileViewPanelsLayout;
if (panelsShown === 2) {
// view | edit
mfrIframeParentLayout = 'col-sm-6';
fileViewPanelsLayout = 'col-sm-6';
} else {
// view
if (ctrl.mfrIframeParent.is(':visible')) {
mfrIframeParentLayout = 'col-sm-12';
fileViewPanelsLayout = '';
} else {
// edit or revisions
mfrIframeParentLayout = '';
fileViewPanelsLayout = 'col-sm-12';
}
}
$('#mfrIframeParent').removeClass().addClass(mfrIframeParentLayout);
$('.file-view-panels').removeClass().addClass('file-view-panels').addClass(fileViewPanelsLayout);
if(ctrl.file.urls.external && !ctrl.file.privateRepo) {
m.render(document.getElementById('externalView'), [
m('p.text-muted', 'View this file on ', [
m('a', {href:ctrl.file.urls.external}, storageAddons[ctrl.file.provider].fullName)
], '.')
]);
}
var editButton = function() {
if (ctrl.editor) {
return m('button.btn' + (ctrl.editor.selected ? '.btn-primary' : '.btn-default'), {
onclick: function (e) {
e.preventDefault();
// atleast one button must remain enabled.
if ((!ctrl.editor.selected || panelsShown > 1)) {
ctrl.editor.selected = !ctrl.editor.selected;
ctrl.revisions.selected = false;
var url = '?show=view';
state = {
scrollTop: $(window).scrollTop(),
};
History.pushState(state, 'OSF | ' + window.contextVars.file.name, url);
}
}
}, ctrl.editor.title);
}
};
var link = $('iframe').attr('src') ? $('iframe').attr('src').substring(0, $('iframe').attr('src').indexOf('download') + 8) +
'%26mode=render' : 'Data not available';
var height = $('iframe').attr('height') ? $('iframe').attr('height') : '0px';
m.render(document.getElementById('toggleBar'), m('.btn-toolbar.m-t-md', [
// Special case whether or not to show the delete button for published Dataverse files
(ctrl.canEdit() && (ctrl.file.provider !== 'osfstorage' || !ctrl.file.checkoutUser) && ctrl.requestDone && $(document).context.URL.indexOf('version=latest-published') < 0 ) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('button.btn.btn-sm.btn-danger.file-delete', {onclick: $(document).trigger.bind($(document), 'fileviewpage:delete')}, 'Delete') : null
]) : '',
ctrl.context.currentUser.canEdit && (!ctrl.canEdit()) && ctrl.requestDone && (ctrl.context.currentUser.isAdmin) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-danger', {onclick: $(document).trigger.bind($(document), 'fileviewpage:force_checkin')}, 'Force check in') : null
]) : '',
ctrl.canEdit() && (!ctrl.file.checkoutUser) && ctrl.requestDone && (ctrl.file.provider === 'osfstorage') ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-warning', {onclick: $(document).trigger.bind($(document), 'fileviewpage:checkout')}, 'Check out') : null
]) : '',
(ctrl.canEdit() && (ctrl.file.checkoutUser === ctrl.context.currentUser.id) && ctrl.requestDone) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-warning', {onclick: $(document).trigger.bind($(document), 'fileviewpage:checkin')}, 'Check in') : null
]) : '',
window.contextVars.node.isPublic? m('.btn-group.m-t-xs', [
m.component(SharePopover, {link: link, height: height})
]) : '',
m('.btn-group.m-t-xs', [
ctrl.editor ? m('button.btn.btn-sm.btn-primary.file-download', {onclick: $(document).trigger.bind($(document), 'fileviewpage:download')}, 'Download') : null
]),
m('.btn-group.btn-group-sm.m-t-xs', [
ctrl.editor ? m( '.btn.btn-default.disabled', 'Toggle view: ') : null
].concat(
m('button.btn' + (ctrl.mfrIframeParent.is(':visible') ? '.btn-primary' : '.btn-default'), {
onclick: function (e) {
e.preventDefault();
// at least one button must remain enabled.
if (!ctrl.mfrIframeParent.is(':visible') || panelsShown > 1) {
ctrl.mfrIframeParent.toggle();
ctrl.revisions.selected = false;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=view');
} else if (ctrl.mfrIframeParent.is(':visible') && !ctrl.editor){
ctrl.mfrIframeParent.toggle();
ctrl.revisions.selected = true;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=revision');
}
}
}, 'View'), editButton())
),
m('.btn-group.m-t-xs', [
m('button.btn.btn-sm' + (ctrl.revisions.selected ? '.btn-primary': '.btn-default'), {onclick: function(){
var editable = ctrl.editor && ctrl.editor.selected;
var viewable = ctrl.mfrIframeParent.is(':visible');
if (editable || viewable){
if (viewable){
ctrl.mfrIframeParent.toggle();
}
if (editable) {
ctrl.editor.selected = false;
}
ctrl.revisions.selected = true;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=revision');
} else {
ctrl.mfrIframeParent.toggle();
if (ctrl.editor) {
ctrl.editor.selected = false;
}
ctrl.revisions.selected = false;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=view');
}
}}, 'Revisions')
])
]));
if (ctrl.revisions.selected){
return m('.file-view-page', m('.panel-toggler', [
m('.row', ctrl.revisions)
]));
}
var editDisplay = (ctrl.editor && !ctrl.editor.selected) ? 'display:none' : '' ;
ctrl.triggerResize();
return m('.file-view-page', m('.panel-toggler', [
m('.row[style="' + editDisplay + '"]', m('.col-sm-12', ctrl.editor),
m('.row[style="display:none"]', ctrl.revisions))
]));
}
};
// Initialize file comment pane
var $comments = $('.comments');
if ($comments.length) {
var options = {
nodeId: window.contextVars.node.id,
nodeApiUrl: window.contextVars.node.urls.api,
isRegistration: window.contextVars.node.isRegistration,
page: 'files',
rootId: window.contextVars.file.guid,
fileId: window.contextVars.file.id,
canComment: window.contextVars.currentUser.canComment,
hasChildren: window.contextVars.node.hasChildren,
currentUser: window.contextVars.currentUser,
pageTitle: window.contextVars.file.name,
inputSelector: '.atwho-input'
};
CommentModel.init('#commentsLink', '.comment-pane', options);
}
module.exports = function(context) {
// Treebeard forces all mithril to load twice, to avoid
// destroying the page iframe this out side of mithril.
if (!context.file.urls.render) {
$('#mfrIframe').html(context.file.error);
} else {
var url = context.file.urls.render;
if (navigator.appVersion.indexOf('MSIE 9.') !== -1) {
url += url.indexOf('?') > -1 ? '&' : '?';
url += 'cookie=' + (document.cookie.match(window.contextVars.cookieName + '=(.+?);|$')[1] || '');
}
if (window.mfr !== undefined) {
var mfrRender = new mfr.Render('mfrIframe', url, {}, 'cos_logo.png');
$(document).on('fileviewpage:reload', function() {
mfrRender.reload();
});
$(document).on('fileviewpage:resize', function() {
mfrRender.resize();
});
}
}
return m.component(FileViewPage, context);
};
| website/static/js/filepage/index.js | var $ = require('jquery');
var m = require('mithril');
var mime = require('js/mime');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');
// Local requires
var utils = require('./util.js');
var FileEditor = require('./editor.js');
var makeClient = require('js/clipboard');
var FileRevisionsTable = require('./revisions.js');
var storageAddons = require('json!storageAddons.json');
var CommentModel = require('js/comment');
var History = require('exports?History!history');
var SocialShare = require('js/components/socialshare');
// Sanity
var Panel = utils.Panel;
var EDITORS = {'text': FileEditor};
var clipboardConfig = function(element, isInitialized) {
if (!isInitialized) {
makeClient(element);
}
};
var CopyButton = {
view: function(ctrl, params) {
return m('span.input-group-btn', m('button.btn.btn-default.btn-md[type="button"]' +
'[data-clipboard-text="' + params.link + '"]',
{config: clipboardConfig, style: {height: params.height}},
m('.fa.fa-copy')));
}
};
var SharePopover = {
view: function(ctrl, params) {
var copyButtonHeight = '34px';
var popoverWidth = '450px';
var renderLink = params.link;
var fileLink = window.location.href;
var mfrHost = renderLink.substring(0, renderLink.indexOf('render'));
return m('button#sharebutton.disabled.btn.btn-sm.btn-primary.file-share', {onclick: function popOverShow() {
var pop = document.getElementById('popOver');
//This is bad, should only happen for Firefox, thanks @chrisseto
if (!pop){
return window.setTimeout(popOverShow, 100);
}
m.render(document.getElementById('popOver'), [
m('ul.nav.nav-tabs.nav-justified', [
m('li.active', m('a[href="#share"][data-toggle="tab"]', 'Share')),
m('li', m('a[href="#embed"][data-toggle="tab"]', 'Embed'))
]), m('br'),
m('.tab-content', [
m('.tab-pane.active#share', [
m('.input-group', [
CopyButton.view(ctrl, {link: renderLink, height: copyButtonHeight}), //workaround to allow button to show up on first click
m('input.form-control[readonly][type="text"][value="'+ renderLink +'"]')
]),
SocialShare.ShareButtons.view(ctrl, {title: window.contextVars.file.name, url: fileLink})
]),
m('.tab-pane#embed', [
m('p', 'Dynamically render iframe with JavaScript'),
m('textarea.form-control[readonly][type="text"][value="' +
'<script>window.jQuery || document.write(\'<script src="//code.jquery.com/jquery-1.11.2.min.js">\\x3C/script>\') </script>'+
'<link href="' + mfrHost + 'static/css/mfr.css" media="all" rel="stylesheet">' +
'<div id="mfrIframe" class="mfr mfr-file"></div>' +
'<script src="' + mfrHost + 'static/js/mfr.js">' +
'</script> <script>' +
'var mfrRender = new mfr.Render("mfrIframe", "' + renderLink + '");' +
'</script>' + '"]'
), m('br'),
m('p', 'Direct iframe with fixed height and width'),
m('textarea.form-control[readonly][value="' +
'<iframe src="' + renderLink + '" width="100%" scrolling="yes" height="' + params.height + '" marginheight="0" frameborder="0" allowfullscreen webkitallowfullscreen>"]'
)
])
])
]);
},
config: function(element, isInitialized) {
if(!isInitialized){
var button = $(element).popover();
button.on('show.bs.popover', function(e){
//max-width used to override, and width used to create space for the mithril object to be injected
button.data()['bs.popover'].$tip.css('text-align', 'center').css('max-width', popoverWidth).css('width', popoverWidth);
});
}
},
'data-toggle': 'popover', 'data-placement': 'bottom',
'data-content': '<div id="popOver"></div>', 'title': 'Share',
'data-container': 'body', 'data-html': 'true'
}, 'Share');
}
};
var FileViewPage = {
controller: function(context) {
var self = this;
self.context = context;
self.file = self.context.file;
self.node = self.context.node;
self.editorMeta = self.context.editor;
self.file.checkoutUser = null;
self.requestDone = false;
self.isCheckoutUser = function() {
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/vnd.api+json'
},
method: 'get',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization
}).done(function(resp) {
self.requestDone = true;
self.file.checkoutUser = resp.data.relationships.checkout ? ((resp.data.relationships.checkout.links.related.href).split('users/')[1]).replace('/', ''): null;
if ((self.file.checkoutUser) && (self.file.checkoutUser !== self.context.currentUser.id)) {
m.render(document.getElementById('alertBar'), m('.alert.alert-warning[role="alert"]', m('span', [
m('strong', 'File is checked out.'),
' This file has been checked out by a ',
m('a[href="/' + self.file.checkoutUser + '"]', 'collaborator'),
'. It needs to be checked in before any changes can be made.'
])));
}
});
};
if (self.file.provider === 'osfstorage'){
self.canEdit = function() {
return ((!self.file.checkoutUser) || (self.file.checkoutUser === self.context.currentUser.id)) ? self.context.currentUser.canEdit : false;
};
self.isCheckoutUser();
} else {
self.requestDone = true;
self.canEdit = function() {
return self.context.currentUser.canEdit;
};
}
$.extend(self.file.urls, {
delete: waterbutler.buildDeleteUrl(self.file.path, self.file.provider, self.node.id),
metadata: waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id),
revisions: waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id),
content: waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render'})
});
if ($osf.urlParams().branch) {
var fileWebViewUrl = waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id, {branch : $osf.urlParams().branch});
$.ajax({
dataType: 'json',
async: true,
url: fileWebViewUrl,
beforeSend: $osf.setXHRAuthorization
}).done(function(response) {
window.contextVars.file.urls.external = response.data.extra.webView;
});
self.file.urls.revisions = waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id, {sha: $osf.urlParams().branch});
self.file.urls.content = waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render', branch: $osf.urlParams().branch});
}
$(document).on('fileviewpage:delete', function() {
bootbox.confirm({
title: 'Delete file?',
message: '<p class="overflow">' +
'Are you sure you want to delete <strong>' +
self.file.safeName + '</strong>?' +
'</p>',
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
type: 'DELETE',
url: self.file.urls.delete,
beforeSend: $osf.setXHRAuthorization
}).done(function() {
window.location = self.node.urls.files;
}).fail(function() {
$osf.growl('Error', 'Could not delete file.');
});
},
buttons:{
confirm:{
label:'Delete',
className:'btn-danger'
}
}
});
});
$(document).on('fileviewpage:checkout', function() {
bootbox.confirm({
title: 'Confirm file check out?',
message: 'This would mean ' +
'other contributors cannot edit, delete or upload new versions of this file ' +
'as long as it is checked out. You can check it back in at anytime.',
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: self.context.currentUser.id
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to check out file');
});
},
buttons:{
confirm:{
label: 'Check out file',
className: 'btn-warning'
}
}
});
});
$(document).on('fileviewpage:checkin', function() {
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: null
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to check in file');
});
});
$(document).on('fileviewpage:force_checkin', function() {
bootbox.confirm({
title: 'Force check in file?',
message: 'This will check in the file for all users, allowing it to be edited. Are you sure?',
buttons: {
confirm:{
label: 'Force check in',
className: 'btn-danger'
}
},
callback: function(confirm) {
if (!confirm) {
return;
}
$.ajax({
method: 'put',
url: window.contextVars.apiV2Prefix + 'files' + self.file.path + '/',
beforeSend: $osf.setXHRAuthorization,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
data: {
id: self.file.path.replace('/', ''),
type: 'files',
attributes: {
checkout: null
}
}
})
}).done(function(resp) {
window.location.reload();
}).fail(function(resp) {
$osf.growl('Error', 'Unable to force check in file. Make sure you have admin privileges.');
});
}
});
});
$(document).on('fileviewpage:download', function() {
//replace mode=render with action=download for download count incrementation
window.location = self.file.urls.content.replace('mode=render', 'action=download');
return false;
});
self.shareJSObservables = {
activeUsers: m.prop([]),
status: m.prop('connecting'),
userId: self.context.currentUser.id
};
self.editHeader = function() {
return m('.row', [
m('.col-sm-12', m('span[style=display:block;]', [
m('h3.panel-title',[m('i.fa.fa-pencil-square-o'), ' Edit ']),
m('.pull-right', [
m('.progress.no-margin.pointer', {
'data-toggle': 'modal',
'data-target': '#' + self.shareJSObservables.status() + 'Modal'
}, [
m('.progress-bar.p-h-sm.progress-bar-success', {
connected: {
style: 'width: 100%',
class: 'progress-bar progress-bar-success'
},
connecting: {
style: 'width: 100%',
class: 'progress-bar progress-bar-warning progress-bar-striped active'
},
saving: {
style: 'width: 100%',
class: 'progress-bar progress-bar-info progress-bar-striped active'
}
}[self.shareJSObservables.status()] || {
style: 'width: 100%',
class: 'progress-bar progress-bar-danger'
}, [
m('span.progress-bar-content', [
{
connected: 'Live editing mode ',
connecting: 'Attempting to connect ',
unsupported: 'Unsupported browser ',
saving: 'Saving... '
}[self.shareJSObservables.status()] || 'Unavailable: Live editing ',
m('i.fa.fa-question-circle.fa-large')
])
])
])
])
]))
]);
};
// Hack to delay creation of the editor
// until we know this is the current file revision
self.enableEditing = function() {
// Sometimes we can get here twice, check just in case
if (self.editor || !self.canEdit()) {
m.redraw(true);
return;
}
var fileType = mime.lookup(self.file.name.toLowerCase());
// Only allow files < 1MB to be editable
if (self.file.size < 1048576 && fileType) { //May return false
var editor = EDITORS[fileType.split('/')[0]];
if (editor) {
self.editor = new Panel('Edit', self.editHeader, editor, [self.file.urls.content, self.file.urls.sharejs, self.editorMeta, self.shareJSObservables], false);
}
}
m.redraw(true);
};
//Hack to polyfill the Panel interface
//Ran into problems with mithrils caching messing up with multiple "Panels"
self.revisions = m.component(FileRevisionsTable, self.file, self.node, self.enableEditing, self.canEdit);
self.revisions.selected = false;
self.revisions.title = 'Revisions';
// inform the mfr of a change in display size performed via javascript,
// otherwise the mfr iframe will not update unless the document windows is changed.
self.triggerResize = $osf.throttle(function () {
$(document).trigger('fileviewpage:resize');
}, 1000);
self.mfrIframeParent = $('#mfrIframeParent');
function toggleRevisions(e){
if(self.editor){
self.editor.selected = false;
}
var viewable = self.mfrIframeParent.is(':visible');
var url = '';
if (viewable){
self.mfrIframeParent.toggle();
self.revisions.selected = true;
url = '?show=revision';
} else {
self.mfrIframeParent.toggle();
self.revisions.selected = false;
url = '?show=view';
}
var state = {
scrollTop: $(window).scrollTop(),
};
History.pushState(state, 'OSF | ' + window.contextVars.file.name, url);
}
function changeVersionHeader(){
document.getElementById('versionLink').style.display = 'inline';
m.render(document.getElementById('versionLink'), m('a', {onclick: toggleRevisions}, document.getElementById('versionLink').innerHTML));
}
var urlParams = $osf.urlParams();
// The parser found a query so lets check what we need to do
if ('show' in urlParams){
if(urlParams.show === 'revision'){
self.mfrIframeParent.toggle();
self.revisions.selected = true;
} else if (urlParams.show === 'view' || urlParams.show === 'edit'){
self.revisions.selected = false;
}
}
if(self.file.provider === 'osfstorage'){
changeVersionHeader();
}
},
view: function(ctrl) {
//This code was abstracted into a panel toggler at one point
//it was removed and shoved here due to issues with mithrils caching and interacting
//With other non-mithril components on the page
//anchor checking hack that will select if true
var state = {
scrollTop: $(window).scrollTop(),
};
var panelsShown = (
((ctrl.editor && ctrl.editor.selected) ? 1 : 0) + // Editor panel is active
(ctrl.mfrIframeParent.is(':visible') ? 1 : 0) // View panel is active
);
var mfrIframeParentLayout;
var fileViewPanelsLayout;
if (panelsShown === 2) {
// view | edit
mfrIframeParentLayout = 'col-sm-6';
fileViewPanelsLayout = 'col-sm-6';
} else {
// view
if (ctrl.mfrIframeParent.is(':visible')) {
mfrIframeParentLayout = 'col-sm-12';
fileViewPanelsLayout = '';
} else {
// edit or revisions
mfrIframeParentLayout = '';
fileViewPanelsLayout = 'col-sm-12';
}
}
$('#mfrIframeParent').removeClass().addClass(mfrIframeParentLayout);
$('.file-view-panels').removeClass().addClass('file-view-panels').addClass(fileViewPanelsLayout);
if(ctrl.file.urls.external && !ctrl.file.privateRepo) {
m.render(document.getElementById('externalView'), [
m('p.text-muted', 'View this file on ', [
m('a', {href:ctrl.file.urls.external}, storageAddons[ctrl.file.provider].fullName)
], '.')
]);
}
var editButton = function() {
if (ctrl.editor) {
return m('button.btn' + (ctrl.editor.selected ? '.btn-primary' : '.btn-default'), {
onclick: function (e) {
e.preventDefault();
// atleast one button must remain enabled.
if ((!ctrl.editor.selected || panelsShown > 1)) {
ctrl.editor.selected = !ctrl.editor.selected;
ctrl.revisions.selected = false;
var url = '?show=view';
state = {
scrollTop: $(window).scrollTop(),
};
History.pushState(state, 'OSF | ' + window.contextVars.file.name, url);
}
}
}, ctrl.editor.title);
}
};
var link = $('iframe').attr('src') ? $('iframe').attr('src').substring(0, $('iframe').attr('src').indexOf('download') + 8) +
'%26mode=render' : 'Data not available';
var height = $('iframe').attr('height') ? $('iframe').attr('height') : '0px';
m.render(document.getElementById('toggleBar'), m('.btn-toolbar.m-t-md', [
// Special case whether or not to show the delete button for published Dataverse files
(ctrl.canEdit() && (ctrl.file.provider !== 'osfstorage' || !ctrl.file.checkoutUser) && ctrl.requestDone && $(document).context.URL.indexOf('version=latest-published') < 0 ) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('button.btn.btn-sm.btn-danger.file-delete', {onclick: $(document).trigger.bind($(document), 'fileviewpage:delete')}, 'Delete') : null
]) : '',
ctrl.context.currentUser.canEdit && (!ctrl.canEdit()) && ctrl.requestDone && (ctrl.context.currentUser.isAdmin) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-danger', {onclick: $(document).trigger.bind($(document), 'fileviewpage:force_checkin')}, 'Force check in') : null
]) : '',
ctrl.canEdit() && (!ctrl.file.checkoutUser) && ctrl.requestDone && (ctrl.file.provider === 'osfstorage') ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-warning', {onclick: $(document).trigger.bind($(document), 'fileviewpage:checkout')}, 'Check out') : null
]) : '',
(ctrl.canEdit() && (ctrl.file.checkoutUser === ctrl.context.currentUser.id) && ctrl.requestDone) ? m('.btn-group.m-l-xs.m-t-xs', [
ctrl.editor ? m('.btn.btn-sm.btn-warning', {onclick: $(document).trigger.bind($(document), 'fileviewpage:checkin')}, 'Check in') : null
]) : '',
window.contextVars.node.isPublic? m('.btn-group.m-t-xs', [
m.component(SharePopover, {link: link, height: height})
]) : '',
m('.btn-group.m-t-xs', [
ctrl.editor ? m('button.btn.btn-sm.btn-primary.file-download', {onclick: $(document).trigger.bind($(document), 'fileviewpage:download')}, 'Download') : null
]),
m('.btn-group.btn-group-sm.m-t-xs', [
ctrl.editor ? m( '.btn.btn-default.disabled', 'Toggle view: ') : null
].concat(
m('button.btn' + (ctrl.mfrIframeParent.is(':visible') ? '.btn-primary' : '.btn-default'), {
onclick: function (e) {
e.preventDefault();
// at least one button must remain enabled.
if (!ctrl.mfrIframeParent.is(':visible') || panelsShown > 1) {
ctrl.mfrIframeParent.toggle();
ctrl.revisions.selected = false;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=view');
} else if (ctrl.mfrIframeParent.is(':visible') && !ctrl.editor){
ctrl.mfrIframeParent.toggle();
ctrl.revisions.selected = true;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=revision');
}
}
}, 'View'), editButton())
),
m('.btn-group.m-t-xs', [
m('button.btn.btn-sm' + (ctrl.revisions.selected ? '.btn-primary': '.btn-default'), {onclick: function(){
var editable = ctrl.editor && ctrl.editor.selected;
var viewable = ctrl.mfrIframeParent.is(':visible');
if (editable || viewable){
if (viewable){
ctrl.mfrIframeParent.toggle();
}
if (editable) {
ctrl.editor.selected = false;
}
ctrl.revisions.selected = true;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=revision');
} else {
ctrl.mfrIframeParent.toggle();
if (ctrl.editor) {
ctrl.editor.selected = false;
}
ctrl.revisions.selected = false;
History.pushState(state, 'OSF | ' + window.contextVars.file.name, '?show=view');
}
}}, 'Revisions')
])
]));
if (ctrl.revisions.selected){
return m('.file-view-page', m('.panel-toggler', [
m('.row', ctrl.revisions)
]));
}
var editDisplay = (ctrl.editor && !ctrl.editor.selected) ? 'display:none' : '' ;
ctrl.triggerResize();
return m('.file-view-page', m('.panel-toggler', [
m('.row[style="' + editDisplay + '"]', m('.col-sm-12', ctrl.editor),
m('.row[style="display:none"]', ctrl.revisions))
]));
}
};
// Initialize file comment pane
var $comments = $('.comments');
if ($comments.length) {
var options = {
nodeId: window.contextVars.node.id,
nodeApiUrl: window.contextVars.node.urls.api,
isRegistration: window.contextVars.node.isRegistration,
page: 'files',
rootId: window.contextVars.file.guid,
fileId: window.contextVars.file.id,
canComment: window.contextVars.currentUser.canComment,
hasChildren: window.contextVars.node.hasChildren,
currentUser: window.contextVars.currentUser,
pageTitle: window.contextVars.file.name,
inputSelector: '.atwho-input'
};
CommentModel.init('#commentsLink', '.comment-pane', options);
}
module.exports = function(context) {
// Treebeard forces all mithril to load twice, to avoid
// destroying the page iframe this out side of mithril.
if (!context.file.urls.render) {
$('#mfrIframe').html(context.file.error);
} else {
var url = context.file.urls.render;
if (navigator.appVersion.indexOf('MSIE 9.') !== -1) {
url += url.indexOf('?') > -1 ? '&' : '?';
url += 'cookie=' + (document.cookie.match(window.contextVars.cookieName + '=(.+?);|$')[1] || '');
}
if (window.mfr !== undefined) {
var mfrRender = new mfr.Render('mfrIframe', url, {}, 'cos_logo.png');
$(document).on('fileviewpage:reload', function() {
mfrRender.reload();
});
$(document).on('fileviewpage:resize', function() {
mfrRender.resize();
});
}
}
return m.component(FileViewPage, context);
};
| added missing bootstrap styles that are needed for dynamic sizing of MFR PDFs
| website/static/js/filepage/index.js | added missing bootstrap styles that are needed for dynamic sizing of MFR PDFs | <ide><path>ebsite/static/js/filepage/index.js
<ide> m('.tab-pane#embed', [
<ide> m('p', 'Dynamically render iframe with JavaScript'),
<ide> m('textarea.form-control[readonly][type="text"][value="' +
<del> '<script>window.jQuery || document.write(\'<script src="//code.jquery.com/jquery-1.11.2.min.js">\\x3C/script>\') </script>'+
<add> '<style>' +
<add> '.embed-responsive{position:relative;height:100%;}' +
<add> '.embed-responsive iframe{position:absolute;height:100%;}' +
<add> '</style>' +
<add> '<script>window.jQuery || document.write(\'<script src="//code.jquery.com/jquery-1.11.2.min.js">\\x3C/script>\') </script>' +
<ide> '<link href="' + mfrHost + 'static/css/mfr.css" media="all" rel="stylesheet">' +
<ide> '<div id="mfrIframe" class="mfr mfr-file"></div>' +
<ide> '<script src="' + mfrHost + 'static/js/mfr.js">' + |
|
JavaScript | unlicense | 544625a33d71c4a81a79d6175d0489df223a7bb2 | 0 | JATS4R/jats4r.github.io,JATS4R/website,JATS4R/website,JATS4R/jats4r.github.io,JATS4R/website,JATS4R/jats4r.github.io,JATS4R/jats4r.github.io,JATS4R/website | // SAXON API: http://www.saxonica.com/ce/user-doc/1.1/html/api/xslt20processor/
// onSaxonLoad is called when Saxon has finished loading
var onSaxonLoad = function() {
var outputNode = document.getElementById('output');
outputNode.textContent = 'Choose a JATS XML file to validate.';
// insert the file selection form
var input = document.createElement('input');
input.setAttribute('type', 'file');
var form = document.createElement('form');
form.appendChild(input);
document.body.insertBefore(form, document.body.firstChild);
// listen for selected file
input.addEventListener('change', function() {
outputNode.textContent = 'Processing…';
var reader = new FileReader;
reader.onload = function() {
// run the Schematron tests
Saxon.run({
stylesheet: 'generated-xsl/jats4r-errlevel-0.xsl',
source: Saxon.parseXML(this.result),
method: 'transformToDocument',
success: function(processor) {
outputNode.textContent = 'Converting…';
// convert the output XML to HTML
Saxon.run({
stylesheet: 'output.xsl',
source: processor.getResultDocument(),
method: 'updateHTMLDocument'
});
outputNode.textContent = 'Finished';
}
});
}
reader.readAsText(this.files[0]);
});
}
| validate.js | // SAXON API: http://www.saxonica.com/ce/user-doc/1.1/html/api/xslt20processor/
// onSaxonLoad is called when Saxon has finished loading
var onSaxonLoad = function() {
var outputNode = document.getElementById('output');
outputNode.textContent = 'Choose a JATS XML file to validate.';
// insert the file selection form
var input = document.createElement('input');
input.setAttribute('type', 'file');
var form = document.createElement('form');
form.appendChild(input);
document.body.insertBefore(form, document.body.firstChild);
// listen for selected file
input.addEventListener('change', function() {
outputNode.textContent = 'Processing…';
var reader = new FileReader;
reader.responseType = 'document';
reader.onload = function() {
// run the Schematron tests
Saxon.run({
stylesheet: 'generated-xsl/jats4r-errlevel-0.xsl',
source: Saxon.parseXML(reader.result),
method: 'transformToDocument',
success: function(processor) {
outputNode.textContent = 'Converting…';
// convert the output XML to HTML
Saxon.run({
stylesheet: 'output.xsl',
source: processor.getResultDocument(),
method: 'updateHTMLDocument'
});
outputNode.textContent = 'Finished';
}
});
}
reader.readAsText(this.files[0]);
});
}
| FileReader result is text
| validate.js | FileReader result is text | <ide><path>alidate.js
<ide> outputNode.textContent = 'Processing…';
<ide>
<ide> var reader = new FileReader;
<del> reader.responseType = 'document';
<ide>
<ide> reader.onload = function() {
<ide> // run the Schematron tests
<ide> Saxon.run({
<ide> stylesheet: 'generated-xsl/jats4r-errlevel-0.xsl',
<del> source: Saxon.parseXML(reader.result),
<add> source: Saxon.parseXML(this.result),
<ide> method: 'transformToDocument',
<ide> success: function(processor) {
<ide> outputNode.textContent = 'Converting…'; |
|
JavaScript | unknown | 068fc0176fbe3babcfb380e090a630e7baed000e | 0 | sr229/owo-whats-this,ClarityMoe/Clara,awau/owo-whats-this,owo-dev-team/owo-whats-this,awau/Clara | /* eslint-env node */
const {parseArgs, parsePrefix} = require(`${__baseDir}/modules/messageParser`);
const {Context} = require(`${__baseDir}/modules/CommandHolder`);
const {formatUsername} = require(`${__baseDir}/modules/utils`);
module.exports = bot => {
bot.on('messageCreate', msg => {
if (!msg.author) console.log(msg);
if (!bot.allowCommandUse || !msg.author || msg.author.id === bot.user.id || msg.author.bot || bot.isBlacklisted(msg.author.id)) return;
if (!msg.channel.guild) {
logger.custom('cyan', 'dm', loggerPrefix(msg) + msg.cleanContent);
return;
}
let outer = {msg};
parsePrefix(msg.content, bot.prefixes).then(content => {
if (!content) return null;
return parseArgs(content);
}).then(res => {
if (!res) return null;
if (!bot.commands.checkCommand(res.cmd)) {
if (RegExp(`^<@!?${bot.user.id}> ?.+$`).test(msg.content) && bot.commands.getCommand('chat')) {
res.cmd = 'chat';
} else {
return;
}
}
res.cleanSuffix = msg.cleanContent.split(res.cmd).slice(1).join(res.cmd);
Object.assign(outer, res);
return bot.getGuildSettings(msg.channel.guild.id);
}).then(settings => {
if (!settings) return null;
outer.settings = {guild: settings};
return bot.getUserSettings(msg.author.id);
}).then(settings => {
if (!settings) return null;
outer.settings.user = settings;
outer.settings.locale = settings.locale !== localeManager.defaultLocale ? settings.locale : outer.settings.guild.locale;
outer.cleanSuffix = msg.cleanContent.split(outer.cmd).slice(1).join(outer.cmd);
outer.guildBot = msg.channel.guild.members.get(bot.user.id);
let ctx = new Context(outer);
return bot.commands.runCommand(ctx.cmd, ctx);
}).then(res => {
if (!res) return null;
logger.cmd(`${loggerPrefix(msg)}${outer.cmd}`);
}).catch(err => handleCmdErr(msg, outer.cmd, err));
});
/**
* Returns pre-formatted prefix to use in the logger.
*
* @param {Eris.Message} msg Message to use to get names of channels, user, etc.
* @returns {String} Formatted string.
*/
function loggerPrefix(msg) {
return msg.channel.guild ? `${msg.channel.guild.name} | ${msg.channel.name} > ${formatUsername(msg.author)} (${msg.author.id}): ` : `Direct Message > ${formatUsername(msg.author)} (${msg.author.id}): `;
}
/**
* Handle errors from commands.
*
* @param {Eris.Message} msg Message to pass for sending messages.
* @param {String} cmd Command name.
* @param {Object} err The error object to analyse.
* @returns {Promise} .
*/
function handleCmdErr(msg, cmd, err) {
return new Promise((resolve, reject) => {
let resp = typeof err.response === 'string' && /^\{'code':\d+, 'message':.*\}$/.test(err.response) ? JSON.parse(err.response) : null;
if (resp && resp.code === 50013 && !msg.channel.guild.members.get(bot.user.id).permissions.has('sendMessages')) {
logger.warn(`Can't send message in '#${msg.channel.name}' (${msg.channel.id}), cmd from user '${bot.formatUser(msg.author)}' (${msg.author.id})`);
msg.author.getDMChannel().then(dm => {
console.log(dm.id);
return dm.createMessage(`It appears I was unable to send a message in \`#${msg.channel.name}\` on the server \`${msg.channel.guild.name}\`.\nPlease give me the Send Messages permission or notify a mod or admin if you cannot do this.`);
}).then(resolve).catch(() => logger.warn(`Couldn't get DM channel for/send DM to ${bot.formatUser(msg.author)} (${msg.author.id})`));
} else if (resp && resp.code !== 50013) {
logger.warn(`${loggerPrefix(msg)}Discord error while running command "${cmd}":\n${err.stack}`);
let embed = {
title: 'Error',
description: `An error occurred while trying to execute command \`${cmd}\``,
color: 0xF44336,
timestamp: new Date(),
footer: {text: 'Powered by Clara'},
fields: [
{
name: '\u200b',
value: '```js\n'
+ `Code: ${resp.code}\n`
+ `Message: ${resp.message}\n`
+ '```\n'
+ 'This has been logged, but if you wish to report this now so it can get fixed faster, you can join my [**support server**](https://discord.gg/rmMTZue).'
}
]
};
if (!bot.hasPermission('embedLinks', msg.channel)) {
let content = bot.flattenEmbed(embed);
msg.channel.createMessage(content).then(resolve).catch(reject);
} else {
msg.channel.createMessage({embed}).then(resolve).catch(reject);
}
} else {
logger.error(`${loggerPrefix(msg)}Error running command "${cmd}":\n${err.stack}`);
let embed = {
title: 'Error',
description: `An error occurred while trying to execute command \`${cmd}\``,
color: 0xF44336,
timestamp: new Date(),
footer: {text: 'Powered by Clara'},
fields: [
{
name: '\u200b',
value: '```js\n'
+ `${err}\n`
+ '```\n'
+ 'This has been logged, but if you wish to report this now so it can get fixed faster, you can join my [**support server**](https://discord.gg/rmMTZue).'
}
]
};
if (!bot.hasPermission('embedLinks', msg.channel)) {
let content = bot.flattenEmbed(embed);
msg.channel.createMessage(content).then(resolve).catch(reject);
} else {
msg.channel.createMessage({embed}).then(resolve).catch(reject);
}
}
});
}
}; | src/events/commandHandler.js | /* eslint-env node */
//we'll use wolke's version of the lib
const chatbot = require('better-cleverbot-io');
// I don't care if everyone rips this out, we have unlimited API calls here anyways
const ayaneru = new chatbot({user: config.cbUser, key: config.cbKey, nick: 'H9dG2tvV'});
const {parseArgs, parsePrefix} = require(`${__baseDir}/modules/messageParser`);
const {Context} = require(`${__baseDir}/modules/CommandHolder`);
const {formatUsername} = require(`${__baseDir}/modules/utils`);
module.exports = bot => {
bot.on('messageCreate', msg => {
if (!msg.author) console.log(msg);
if (!bot.allowCommandUse || !msg.author || msg.author.id === bot.user.id || msg.author.bot || bot.isBlacklisted(msg.author.id)) return;
if (!msg.channel.guild) {
logger.custom('cyan', 'dm', loggerPrefix(msg) + msg.cleanContent);
return;
}
let outer = {msg};
parsePrefix(msg.content, bot.prefixes).then(content => {
if (!content) return null;
return parseArgs(content);
}).then(res => {
if (!res) return null;
if (!bot.commands.checkCommand(res.cmd)) {
return new Promise((resolve, reject) => {
ayaneru.ask(msg.content).then(res => {
msg.channel.createMessage(res);
}).catch(reject);
});
}
res.cleanSuffix = msg.cleanContent.split(res.cmd).slice(1).join(res.cmd);
Object.assign(outer, res);
return bot.getGuildSettings(msg.channel.guild.id);
}).then(settings => {
if (!settings) return null;
outer.settings = {guild: settings};
return bot.getUserSettings(msg.author.id);
}).then(settings => {
if (!settings) return null;
outer.settings.user = settings;
outer.settings.locale = settings.locale !== localeManager.defaultLocale ? settings.locale : outer.settings.guild.locale;
outer.cleanSuffix = msg.cleanContent.split(outer.cmd).slice(1).join(outer.cmd);
outer.guildBot = msg.channel.guild.members.get(bot.user.id);
let ctx = new Context(outer);
return bot.commands.runCommand(ctx.cmd, ctx);
}).then(res => {
if (!res) return null;
logger.cmd(`${loggerPrefix(msg)}${outer.cmd}`);
}).catch(err => handleCmdErr(msg, outer.cmd, err));
});
/**
* Returns pre-formatted prefix to use in the logger.
*
* @param {Eris.Message} msg Message to use to get names of channels, user, etc.
* @returns {String} Formatted string.
*/
function loggerPrefix(msg) {
return msg.channel.guild ? `${msg.channel.guild.name} | ${msg.channel.name} > ${formatUsername(msg.author)} (${msg.author.id}): ` : `Direct Message > ${formatUsername(msg.author)} (${msg.author.id}): `;
}
/**
* Handle errors from commands.
*
* @param {Eris.Message} msg Message to pass for sending messages.
* @param {String} cmd Command name.
* @param {Object} err The error object to analyse.
*/
function handleCmdErr(msg, cmd, err) {
return new Promise((resolve, reject) => {
let resp = typeof err.response === 'string' && /^\{'code':\d+, 'message':.*\}$/.test(err.response) ? JSON.parse(err.response) : null;
if (resp && resp.code === 50013 && !msg.channel.guild.members.get(bot.user.id).permissions.has('sendMessages')) {
logger.warn(`Can't send message in '#${msg.channel.name}' (${msg.channel.id}), cmd from user '${bot.formatUser(msg.author)}' (${msg.author.id})`);
msg.author.getDMChannel().then(dm => {
console.log(dm.id);
return dm.createMessage(`It appears I was unable to send a message in \`#${msg.channel.name}\` on the server \`${msg.channel.guild.name}\`.\nPlease give me the Send Messages permission or notify a mod or admin if you cannot do this.`);
}).then(resolve).catch(() => logger.warn(`Couldn't get DM channel for/send DM to ${bot.formatUser(msg.author)} (${msg.author.id})`));
} else if (resp && resp.code !== 50013) {
logger.warn(`${loggerPrefix(msg)}Discord error while running command "${cmd}":\n${err.stack}`);
let embed = {
title: 'Error',
description: `An error occurred while trying to execute command \`${cmd}\``,
color: 0xF44336,
timestamp: new Date(),
footer: {text: 'Powered by Clara'},
fields: [
{
name: '\u200b',
value: '```js\n'
+ `Code: ${resp.code}\n`
+ `Message: ${resp.message}\n`
+ '```\n'
+ 'This has been logged, but if you wish to report this now so it can get fixed faster, you can join my [**support server**](https://discord.gg/rmMTZue).'
}
]
};
if (!bot.hasPermission('embedLinks', msg.channel)) {
let content = bot.flattenEmbed(embed);
msg.channel.createMessage(content).then(resolve).catch(reject);
} else {
msg.channel.createMessage({embed}).then(resolve).catch(reject);
}
} else {
logger.error(`${loggerPrefix(msg)}Error running command "${cmd}":\n${err.stack}`);
let embed = {
title: 'Error',
description: `An error occurred while trying to execute command \`${cmd}\``,
color: 0xF44336,
timestamp: new Date(),
footer: {text: 'Powered by Clara'},
fields: [
{
name: '\u200b',
value: '```js\n'
+ `${err}\n`
+ '```\n'
+ 'This has been logged, but if you wish to report this now so it can get fixed faster, you can join my [**support server**](https://discord.gg/rmMTZue).'
}
]
};
if (!bot.hasPermission('embedLinks', msg.channel)) {
let content = bot.flattenEmbed(embed);
msg.channel.createMessage(content).then(resolve).catch(reject);
} else {
msg.channel.createMessage({embed}).then(resolve).catch(reject);
}
}
});
}
}; | Make auto cleverbot only work with mention and if the module is loaded
| src/events/commandHandler.js | Make auto cleverbot only work with mention and if the module is loaded | <ide><path>rc/events/commandHandler.js
<ide> /* eslint-env node */
<ide>
<del>//we'll use wolke's version of the lib
<del>const chatbot = require('better-cleverbot-io');
<del>// I don't care if everyone rips this out, we have unlimited API calls here anyways
<del>const ayaneru = new chatbot({user: config.cbUser, key: config.cbKey, nick: 'H9dG2tvV'});
<ide> const {parseArgs, parsePrefix} = require(`${__baseDir}/modules/messageParser`);
<ide> const {Context} = require(`${__baseDir}/modules/CommandHolder`);
<ide> const {formatUsername} = require(`${__baseDir}/modules/utils`);
<ide> }).then(res => {
<ide> if (!res) return null;
<ide> if (!bot.commands.checkCommand(res.cmd)) {
<del> return new Promise((resolve, reject) => {
<del> ayaneru.ask(msg.content).then(res => {
<del> msg.channel.createMessage(res);
<del> }).catch(reject);
<del> });
<add> if (RegExp(`^<@!?${bot.user.id}> ?.+$`).test(msg.content) && bot.commands.getCommand('chat')) {
<add> res.cmd = 'chat';
<add> } else {
<add> return;
<add> }
<ide> }
<ide>
<ide> res.cleanSuffix = msg.cleanContent.split(res.cmd).slice(1).join(res.cmd);
<ide> * @param {Eris.Message} msg Message to pass for sending messages.
<ide> * @param {String} cmd Command name.
<ide> * @param {Object} err The error object to analyse.
<add> * @returns {Promise} .
<ide> */
<ide> function handleCmdErr(msg, cmd, err) {
<ide> return new Promise((resolve, reject) => { |
|
Java | apache-2.0 | 8812e5fd78b714902e5b58956cdc27dbed5e565b | 0 | apache/santuario-java,apache/santuario-java,apache/santuario-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.xml.security.test.stax.signature;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.Key;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.implementations.Canonicalizer20010315OmitComments;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.KeyName;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.stax.config.Init;
import org.apache.xml.security.stax.config.TransformerAlgorithmMapper;
import org.apache.xml.security.stax.ext.*;
import org.apache.xml.security.stax.securityEvent.*;
import org.apache.xml.security.stax.securityToken.SecurityTokenConstants;
import org.apache.xml.security.test.stax.utils.StAX2DOM;
import org.apache.xml.security.test.stax.utils.TestUtils;
import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
import org.apache.xml.security.transforms.Transform;
import org.apache.xml.security.transforms.implementations.TransformC14N;
import org.apache.xml.security.utils.XMLUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* A set of test-cases for Signature verification.
*/
public class SignatureVerificationTest extends AbstractSignatureVerificationTest {
private XMLInputFactory xmlInputFactory;
private TransformerFactory transformerFactory = TransformerFactory.newInstance();
@Before
public void setUp() throws Exception {
Init.init(SignatureVerificationTest.class.getClassLoader().getResource("security-config.xml").toURI(),
this.getClass());
org.apache.xml.security.Init.init();
xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
}
@Test
public void testSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testMultipleElements() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
localNames.add("ShippingAddress");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementMultipleSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
List<SignedElementSecurityEvent> signedElementSecurityEventList = securityEventListener.getSecurityEvents(SecurityEventConstants.SignedElement);
Assert.assertEquals(2, signedElementSecurityEventList.size());
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID1 = signedElementSecurityEventList.get(0).getCorrelationID();
String signedElementCorrelationID2 = signedElementSecurityEventList.get(1).getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents1 = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents2 = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID1)) {
signedElementSecurityEvents1.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(signedElementCorrelationID2)) {
signedElementSecurityEvents2.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents1.size());
Assert.assertEquals(3, signedElementSecurityEvents2.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents1.size() + signedElementSecurityEvents2.size());
}
@Test
public void testEnvelopedSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
ReferenceInfo referenceInfo = new ReferenceInfo(
"",
new String[]{
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
},
"http://www.w3.org/2000/09/xmldsig#sha1",
false
);
List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
referenceInfos.add(referenceInfo);
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
@Test
public void testHMACSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
byte[] hmacKey = "secret".getBytes("ASCII");
SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
KeyName keyName = new KeyName(document, "SecretKey");
keyInfo.add(keyName);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(key);
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#hmac-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, null, key,
SecurityTokenConstants.KeyIdentifier_KeyName);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
KeyNameTokenSecurityEvent keyNameSecurityToken = securityEventListener.getSecurityEvent(SecurityEventConstants.KeyNameToken);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = keyNameSecurityToken.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testHMACSignatureVerificationWrongKey() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
byte[] hmacKey = "secret".getBytes("ASCII");
SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
KeyName keyName = new KeyName(document, "SecretKey");
keyInfo.add(keyName);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
byte[] badKey = "secret2".getBytes("ASCII");
key = new SecretKeySpec(badKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
properties.setSignatureVerificationKey(key);
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a bad key");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getCause() instanceof XMLSecurityException);
Assert.assertEquals("INVALID signature -- core validation failed.", ex.getCause().getMessage());
}
}
@Test
public void testECDSASignatureVerification() throws Exception {
if (Security.getProvider("BC") == null) {
return;
}
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource(
"org/apache/xml/security/samples/input/ecdsa.jks").openStream(),
"security".toCharArray()
);
Key key = keyStore.getKey("ECDSA", "security".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("ECDSA");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testDifferentC14nMethod() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#rsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testC14n11Method() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
"http://www.w3.org/2006/12/xml-c14n11"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2006/12/xml-c14n11",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#rsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testStrongSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", document, localNames, key,
"http://www.w3.org/2001/10/xml-exc-c14n#", "http://www.w3.org/2001/04/xmlenc#sha256"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2001/04/xmlenc#sha256",
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testIssuerSerial() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
XMLX509IssuerSerial issuerSerial =
new XMLX509IssuerSerial(sig.getDocument(), cert);
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.add(issuerSerial);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_IssuerSerial);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSubjectName() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.addSubjectName(cert);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509SubjectName);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSubjectSKI() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("JCEKS");
keyStore.load(
this.getClass().getClassLoader().getResource("test.jceks").openStream(),
"secret".toCharArray()
);
Key key = keyStore.getKey("rsakey", "secret".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("rsakey");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.addSKI(cert);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testKeyValue() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert.getPublicKey());
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, null, cert.getPublicKey(),
SecurityTokenConstants.KeyIdentifier_KeyValue);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
KeyValueTokenSecurityEvent keyValueTokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.KeyValueToken);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = keyValueTokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSignatureVerificationTransformBase64() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext-base64.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1",
document, localNames, "http://www.w3.org/2000/09/xmldsig#base64", key
);
// Add KeyInfo
sig.addKeyInfo(cert);
//XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testMaximumAllowedReferencesPerManifest() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("Item");
localNames.add("PaymentInfo");
localNames.add("ShippingAddress");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedReferencesPerManifest(2);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("4 references are contained in the Manifest, maximum 2 are allowed. You can raise the maximum " +
"via the \"MaximumAllowedReferencesPerManifest\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedReferencesPerManifest(oldval);
}
}
@Test
public void testMaximumAllowedTransformsPerReference() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedTransformsPerReference(0);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("1 transforms are contained in the Reference, maximum 0 are allowed. You can raise the maximum " +
"via the \"MaximumAllowedTransformsPerReference\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedTransformsPerReference(oldval);
}
}
@Test
public void testDisallowMD5Algorithm() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-md5", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("The use of MD5 algorithm is strongly discouraged. Nonetheless can it be enabled via the " +
"\"AllowMD5Algorithm\" property in the configuration.",
e.getCause().getMessage());
}
}
@Test
public void testAllowMD5Algorithm() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-md5", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
TestUtils.switchAllowMD5Algorithm(true);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
} finally {
TestUtils.switchAllowMD5Algorithm(false);
}
}
@Test
public void testMaximumAllowedXMLStructureDepth() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedXMLStructureDepth(5);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("Maximum depth (5) of the XML structure reached. You can raise the maximum via the " +
"\"MaximumAllowedXMLStructureDepth\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedXMLStructureDepth(oldval);
}
}
@Test
public void testCustomC14nAlgo() throws Exception {
final String customC14N = "customC14N";
Transform.register(customC14N, TransformC14N.class);
Canonicalizer.register(customC14N, Canonicalizer20010315OmitComments.class);
Field algorithmsClassMapInField = TransformerAlgorithmMapper.class.getDeclaredField("algorithmsClassMapIn");
algorithmsClassMapInField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, Class<?>> transformMap = (Map<String, Class<?>>)algorithmsClassMapInField.get(null);
transformMap.put(customC14N, org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_OmitCommentsTransformer.class);
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
customC14N, (List<ReferenceInfo>)null
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
@Test
public void testPartialSignedDocumentTampered_ContentFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testPartialSignedDocumentTampered_SignatureFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
//move signature below root element
Element sigElement = (Element)document.getElementsByTagNameNS(
XMLSecurityConstants.TAG_dsig_Signature.getNamespaceURI(),
XMLSecurityConstants.TAG_dsig_Signature.getLocalPart()).item(0);
document.getDocumentElement().insertBefore(sigElement,
XMLUtils.getNextElement(document.getDocumentElement().getFirstChild()));
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testEnvelopedSignatureTampered_ContentFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
ReferenceInfo referenceInfo = new ReferenceInfo(
"",
new String[]{
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
},
"http://www.w3.org/2000/09/xmldsig#sha1",
false
);
List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
referenceInfos.add(referenceInfo);
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testEnvelopedSignatureTampered_SignatureFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
ReferenceInfo referenceInfo = new ReferenceInfo(
"",
new String[]{
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
},
"http://www.w3.org/2000/09/xmldsig#sha1",
false
);
List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
referenceInfos.add(referenceInfo);
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
//move signature below root element
Element sigElement = (Element)document.getElementsByTagNameNS(
XMLSecurityConstants.TAG_dsig_Signature.getNamespaceURI(),
XMLSecurityConstants.TAG_dsig_Signature.getLocalPart()).item(0);
document.getDocumentElement().insertBefore(sigElement,
XMLUtils.getNextElement(document.getDocumentElement().getFirstChild()));
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
}
| src/test/java/org/apache/xml/security/test/stax/signature/SignatureVerificationTest.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.xml.security.test.stax.signature;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.security.Key;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.implementations.Canonicalizer20010315OmitComments;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.KeyName;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial;
import org.apache.xml.security.signature.XMLSignature;
import org.apache.xml.security.stax.config.Init;
import org.apache.xml.security.stax.config.TransformerAlgorithmMapper;
import org.apache.xml.security.stax.ext.*;
import org.apache.xml.security.stax.securityEvent.*;
import org.apache.xml.security.stax.securityToken.SecurityTokenConstants;
import org.apache.xml.security.test.stax.utils.StAX2DOM;
import org.apache.xml.security.test.stax.utils.TestUtils;
import org.apache.xml.security.test.stax.utils.XMLSecEventAllocator;
import org.apache.xml.security.transforms.Transform;
import org.apache.xml.security.transforms.implementations.TransformC14N;
import org.apache.xml.security.utils.XMLUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* A set of test-cases for Signature verification.
*/
public class SignatureVerificationTest extends AbstractSignatureVerificationTest {
private XMLInputFactory xmlInputFactory;
private TransformerFactory transformerFactory = TransformerFactory.newInstance();
@Before
public void setUp() throws Exception {
Init.init(SignatureVerificationTest.class.getClassLoader().getResource("security-config.xml").toURI(),
this.getClass());
org.apache.xml.security.Init.init();
xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setEventAllocator(new XMLSecEventAllocator());
}
@Test
public void testSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testMultipleElements() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
localNames.add("ShippingAddress");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementMultipleSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
List<SignedElementSecurityEvent> signedElementSecurityEventList = securityEventListener.getSecurityEvents(SecurityEventConstants.SignedElement);
Assert.assertEquals(2, signedElementSecurityEventList.size());
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID1 = signedElementSecurityEventList.get(0).getCorrelationID();
String signedElementCorrelationID2 = signedElementSecurityEventList.get(1).getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents1 = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents2 = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID1)) {
signedElementSecurityEvents1.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(signedElementCorrelationID2)) {
signedElementSecurityEvents2.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents1.size());
Assert.assertEquals(3, signedElementSecurityEvents2.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents1.size() + signedElementSecurityEvents2.size());
}
@Test
public void testHMACSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
byte[] hmacKey = "secret".getBytes("ASCII");
SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
KeyName keyName = new KeyName(document, "SecretKey");
keyInfo.add(keyName);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(key);
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#hmac-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, null, key,
SecurityTokenConstants.KeyIdentifier_KeyName);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
KeyNameTokenSecurityEvent keyNameSecurityToken = securityEventListener.getSecurityEvent(SecurityEventConstants.KeyNameToken);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = keyNameSecurityToken.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testHMACSignatureVerificationWrongKey() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
byte[] hmacKey = "secret".getBytes("ASCII");
SecretKey key = new SecretKeySpec(hmacKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#hmac-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
KeyName keyName = new KeyName(document, "SecretKey");
keyInfo.add(keyName);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
byte[] badKey = "secret2".getBytes("ASCII");
key = new SecretKeySpec(badKey, "http://www.w3.org/2000/09/xmldsig#hmac-sha1");
properties.setSignatureVerificationKey(key);
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a bad key");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getCause() instanceof XMLSecurityException);
Assert.assertEquals("INVALID signature -- core validation failed.", ex.getCause().getMessage());
}
}
@Test
public void testECDSASignatureVerification() throws Exception {
if (Security.getProvider("BC") == null) {
return;
}
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource(
"org/apache/xml/security/samples/input/ecdsa.jks").openStream(),
"security".toCharArray()
);
Key key = keyStore.getKey("ECDSA", "security".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("ECDSA");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testDifferentC14nMethod() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#rsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testC14n11Method() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
"http://www.w3.org/2006/12/xml-c14n11"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2006/12/xml-c14n11",
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2000/09/xmldsig#rsa-sha1");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testStrongSignatureVerification() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", document, localNames, key,
"http://www.w3.org/2001/10/xml-exc-c14n#", "http://www.w3.org/2001/04/xmlenc#sha256"
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener,
"http://www.w3.org/2001/10/xml-exc-c14n#",
"http://www.w3.org/2001/04/xmlenc#sha256",
"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509KeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testIssuerSerial() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
XMLX509IssuerSerial issuerSerial =
new XMLX509IssuerSerial(sig.getDocument(), cert);
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.add(issuerSerial);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_IssuerSerial);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSubjectName() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.addSubjectName(cert);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_X509SubjectName);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSubjectSKI() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("JCEKS");
keyStore.load(
this.getClass().getClassLoader().getResource("test.jceks").openStream(),
"secret".toCharArray()
);
Key key = keyStore.getKey("rsakey", "secret".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("rsakey");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
KeyInfo keyInfo = sig.getKeyInfo();
X509Data x509Data = new X509Data(sig.getDocument());
x509Data.addSKI(cert);
keyInfo.add(x509Data);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, cert, null,
SecurityTokenConstants.KeyIdentifier_SkiKeyIdentifier);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testKeyValue() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert.getPublicKey());
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
// Check the SecurityEvents
checkSecurityEvents(securityEventListener);
checkSignedElementSecurityEvents(securityEventListener);
checkSignatureToken(securityEventListener, null, cert.getPublicKey(),
SecurityTokenConstants.KeyIdentifier_KeyValue);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
KeyValueTokenSecurityEvent keyValueTokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.KeyValueToken);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = keyValueTokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testSignatureVerificationTransformBase64() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext-base64.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1",
document, localNames, "http://www.w3.org/2000/09/xmldsig#base64", key
);
// Add KeyInfo
sig.addKeyInfo(cert);
//XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
SignedElementSecurityEvent signedElementSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.SignedElement);
X509TokenSecurityEvent x509TokenSecurityEvent = securityEventListener.getSecurityEvent(SecurityEventConstants.X509Token);
String signedElementCorrelationID = signedElementSecurityEvent.getCorrelationID();
String x509TokenCorrelationID = x509TokenSecurityEvent.getCorrelationID();
List<SecurityEvent> signatureSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> signedElementSecurityEvents = new ArrayList<SecurityEvent>();
List<SecurityEvent> securityEvents = securityEventListener.getSecurityEvents();
for (int i = 0; i < securityEvents.size(); i++) {
SecurityEvent securityEvent = securityEvents.get(i);
if (securityEvent.getCorrelationID().equals(signedElementCorrelationID)) {
signedElementSecurityEvents.add(securityEvent);
} else if (securityEvent.getCorrelationID().equals(x509TokenCorrelationID)) {
signatureSecurityEvents.add(securityEvent);
}
}
Assert.assertEquals(4, signatureSecurityEvents.size());
Assert.assertEquals(3, signedElementSecurityEvents.size());
Assert.assertEquals(securityEventListener.getSecurityEvents().size(),
signatureSecurityEvents.size() + signedElementSecurityEvents.size());
}
@Test
public void testMaximumAllowedReferencesPerManifest() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("Item");
localNames.add("PaymentInfo");
localNames.add("ShippingAddress");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedReferencesPerManifest(2);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("4 references are contained in the Manifest, maximum 2 are allowed. You can raise the maximum " +
"via the \"MaximumAllowedReferencesPerManifest\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedReferencesPerManifest(oldval);
}
}
@Test
public void testMaximumAllowedTransformsPerReference() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedTransformsPerReference(0);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("1 transforms are contained in the Reference, maximum 0 are allowed. You can raise the maximum " +
"via the \"MaximumAllowedTransformsPerReference\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedTransformsPerReference(oldval);
}
}
@Test
public void testDisallowMD5Algorithm() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-md5", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("The use of MD5 algorithm is strongly discouraged. Nonetheless can it be enabled via the " +
"\"AllowMD5Algorithm\" property in the configuration.",
e.getCause().getMessage());
}
}
@Test
public void testAllowMD5Algorithm() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2001/04/xmldsig-more#rsa-md5", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
TestUtils.switchAllowMD5Algorithm(true);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
} finally {
TestUtils.switchAllowMD5Algorithm(false);
}
}
@Test
public void testMaximumAllowedXMLStructureDepth() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
int oldval = 0;
try {
oldval = TestUtils.changeValueOfMaximumAllowedXMLStructureDepth(5);
document = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Exception expected");
} catch (XMLStreamException e) {
assertTrue(e.getCause() instanceof XMLSecurityException);
assertEquals("Maximum depth (5) of the XML structure reached. You can raise the maximum via the " +
"\"MaximumAllowedXMLStructureDepth\" property in the configuration.",
e.getCause().getMessage());
} finally {
TestUtils.changeValueOfMaximumAllowedXMLStructureDepth(oldval);
}
}
@Test
public void testCustomC14nAlgo() throws Exception {
final String customC14N = "customC14N";
Transform.register(customC14N, TransformC14N.class);
Canonicalizer.register(customC14N, Canonicalizer20010315OmitComments.class);
Field algorithmsClassMapInField = TransformerAlgorithmMapper.class.getDeclaredField("algorithmsClassMapIn");
algorithmsClassMapInField.setAccessible(true);
@SuppressWarnings("unchecked")
Map<String, Class<?>> transformMap = (Map<String, Class<?>>)algorithmsClassMapInField.get(null);
transformMap.put(customC14N, org.apache.xml.security.stax.impl.transformer.canonicalizer.Canonicalizer20010315_OmitCommentsTransformer.class);
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key,
customC14N, (List<ReferenceInfo>)null
);
// Add KeyInfo
sig.addKeyInfo(cert);
// XMLUtils.outputDOM(document, System.out);
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
properties.setSignatureVerificationKey(cert.getPublicKey());
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
@Test
public void testPartialSignedDocumentTampered_ContentFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testPartialSignedDocumentTampered_SignatureFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
localNames.add("PaymentInfo");
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
//move signature below root element
Element sigElement = (Element)document.getElementsByTagNameNS(
XMLSecurityConstants.TAG_dsig_Signature.getNamespaceURI(),
XMLSecurityConstants.TAG_dsig_Signature.getLocalPart()).item(0);
document.getDocumentElement().insertBefore(sigElement,
XMLUtils.getNextElement(document.getDocumentElement().getFirstChild()));
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testEnvelopedSignatureTampered_ContentFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
ReferenceInfo referenceInfo = new ReferenceInfo(
"",
new String[]{
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
},
"http://www.w3.org/2000/09/xmldsig#sha1",
false
);
List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
referenceInfos.add(referenceInfo);
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
final Document res = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
@Test
public void testEnvelopedSignatureTampered_SignatureFirst() throws Exception {
// Read in plaintext document
InputStream sourceDocument =
this.getClass().getClassLoader().getResourceAsStream(
"ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
Document document = builder.parse(sourceDocument);
// Set up the Key
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(
this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
"default".toCharArray()
);
Key key = keyStore.getKey("transmitter", "default".toCharArray());
X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
// Sign using DOM
List<String> localNames = new ArrayList<String>();
ReferenceInfo referenceInfo = new ReferenceInfo(
"",
new String[]{
"http://www.w3.org/2000/09/xmldsig#enveloped-signature",
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
},
"http://www.w3.org/2000/09/xmldsig#sha1",
false
);
List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
referenceInfos.add(referenceInfo);
XMLSignature sig = signUsingDOM(
"http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
);
// Add KeyInfo
sig.addKeyInfo(cert);
// Now modify the context of PaymentInfo
Element paymentInfoElement =
(Element)document.getElementsByTagNameNS("urn:example:po", "BillingAddress").item(0);
paymentInfoElement.setTextContent("Dig PLC, 1 First Ave, Dublin 1, US");
//move signature below root element
Element sigElement = (Element)document.getElementsByTagNameNS(
XMLSecurityConstants.TAG_dsig_Signature.getNamespaceURI(),
XMLSecurityConstants.TAG_dsig_Signature.getLocalPart()).item(0);
document.getDocumentElement().insertBefore(sigElement,
XMLUtils.getNextElement(document.getDocumentElement().getFirstChild()));
// Convert Document to a Stream Reader
javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
transformer.transform(new DOMSource(document), new StreamResult(baos));
final XMLStreamReader xmlStreamReader =
xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
// Verify signature
XMLSecurityProperties properties = new XMLSecurityProperties();
InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
XMLStreamReader securityStreamReader =
inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
try {
final Document res = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
fail("Failure expected on a modified document");
} catch (XMLStreamException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
}
}
}
| Adding an enveloped test
git-svn-id: ee17208af0df0552975824e4840d757fdb463ab9@1683276 13f79535-47bb-0310-9956-ffa450edef68
| src/test/java/org/apache/xml/security/test/stax/signature/SignatureVerificationTest.java | Adding an enveloped test | <ide><path>rc/test/java/org/apache/xml/security/test/stax/signature/SignatureVerificationTest.java
<ide> }
<ide>
<ide> @Test
<add> public void testEnvelopedSignatureVerification() throws Exception {
<add> // Read in plaintext document
<add> InputStream sourceDocument =
<add> this.getClass().getClassLoader().getResourceAsStream(
<add> "ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
<add> DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
<add> Document document = builder.parse(sourceDocument);
<add>
<add> // Set up the Key
<add> KeyStore keyStore = KeyStore.getInstance("jks");
<add> keyStore.load(
<add> this.getClass().getClassLoader().getResource("transmitter.jks").openStream(),
<add> "default".toCharArray()
<add> );
<add> Key key = keyStore.getKey("transmitter", "default".toCharArray());
<add> X509Certificate cert = (X509Certificate)keyStore.getCertificate("transmitter");
<add>
<add> ReferenceInfo referenceInfo = new ReferenceInfo(
<add> "",
<add> new String[]{
<add> "http://www.w3.org/2000/09/xmldsig#enveloped-signature",
<add> "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
<add> },
<add> "http://www.w3.org/2000/09/xmldsig#sha1",
<add> false
<add> );
<add>
<add> List<ReferenceInfo> referenceInfos = new ArrayList<ReferenceInfo>();
<add> referenceInfos.add(referenceInfo);
<add>
<add> // Sign using DOM
<add> List<String> localNames = new ArrayList<String>();
<add> localNames.add("PaymentInfo");
<add> XMLSignature sig = signUsingDOM(
<add> "http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos
<add> );
<add>
<add> // Add KeyInfo
<add> sig.addKeyInfo(cert);
<add>
<add> // XMLUtils.outputDOM(document, System.out);
<add>
<add> // Convert Document to a Stream Reader
<add> javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
<add> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<add> transformer.transform(new DOMSource(document), new StreamResult(baos));
<add> final XMLStreamReader xmlStreamReader =
<add> xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()));
<add>
<add> // Verify signature
<add> XMLSecurityProperties properties = new XMLSecurityProperties();
<add> InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
<add> TestSecurityEventListener securityEventListener = new TestSecurityEventListener();
<add> XMLStreamReader securityStreamReader =
<add> inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
<add>
<add> StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
<add> }
<add>
<add>
<add> @Test
<ide> public void testHMACSignatureVerification() throws Exception {
<ide> // Read in plaintext document
<ide> InputStream sourceDocument =
<ide> inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
<ide>
<ide> try {
<del> final Document res = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
<add> StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
<ide> fail("Failure expected on a modified document");
<ide> } catch (XMLStreamException ex) {
<ide> Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference"));
<ide> inboundXMLSec.processInMessage(xmlStreamReader, null, securityEventListener);
<ide>
<ide> try {
<del> final Document res = StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
<add> StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
<ide> fail("Failure expected on a modified document");
<ide> } catch (XMLStreamException ex) {
<ide> Assert.assertTrue(ex.getMessage().contains("Invalid digest of reference")); |
|
Java | apache-2.0 | f401c22276ce058cfc908bff7a72d875898eb1e4 | 0 | SIROK/growthbeat-android,growthbeat/growthbeat-android | package com.growthbeat.message;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by mugi65 on 2016/06/29.
*/
public class MessageImageCacheManager extends LruCache<String, Bitmap> {
public MessageImageCacheManager() {
this((int) (Runtime.getRuntime().maxMemory() / 5));
}
public MessageImageCacheManager(int maxSize) {
super(maxSize);
}
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
}
| growthbeat/src/main/java/com/growthbeat/message/MessageImageCacheManager.java | package com.growthbeat.message;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by mugi65 on 2016/06/29.
*/
public class MessageImageCacheManager extends LruCache<String, Bitmap> {
public MessageImageCacheManager() {
this((int) (Runtime.getRuntime().maxMemory() / 10));
}
public MessageImageCacheManager(int maxSize) {
super(maxSize);
}
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
}
| adjust cache memory
| growthbeat/src/main/java/com/growthbeat/message/MessageImageCacheManager.java | adjust cache memory | <ide><path>rowthbeat/src/main/java/com/growthbeat/message/MessageImageCacheManager.java
<ide> public class MessageImageCacheManager extends LruCache<String, Bitmap> {
<ide>
<ide> public MessageImageCacheManager() {
<del> this((int) (Runtime.getRuntime().maxMemory() / 10));
<add> this((int) (Runtime.getRuntime().maxMemory() / 5));
<ide> }
<ide>
<ide> public MessageImageCacheManager(int maxSize) { |
|
Java | apache-2.0 | 67aae1adf518bf534853f6173400e1f8bbb73dff | 0 | NymphWeb/nymph | com/nymph/context/wrapper/JavassistUtil.java | package com.nymph.context.wrapper;
import java.lang.reflect.Method;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
public class JavassistUtil {
/**
* 获取方法参数名
* @param method
* @return
* @throws NotFoundException
*/
public static String[] getParamName(Method method) throws NotFoundException {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get(method.getDeclaringClass().getName());
CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
// 使用javassist的反射方法的参数名
MethodInfo methodInfo = ctMethod.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute)
codeAttribute.getAttribute(LocalVariableAttribute.tag);
int length = ctMethod.getParameterTypes().length;
String[] array = new String[length];
for (int i = 0; i < length; i++) {
array[i] = attr.variableName(i + 1);
}
return array;
}
}
| Delete JavassistUtil.java | com/nymph/context/wrapper/JavassistUtil.java | Delete JavassistUtil.java | <ide><path>om/nymph/context/wrapper/JavassistUtil.java
<del>package com.nymph.context.wrapper;
<del>
<del>import java.lang.reflect.Method;
<del>
<del>import javassist.ClassPool;
<del>import javassist.CtClass;
<del>import javassist.CtMethod;
<del>import javassist.NotFoundException;
<del>import javassist.bytecode.CodeAttribute;
<del>import javassist.bytecode.LocalVariableAttribute;
<del>import javassist.bytecode.MethodInfo;
<del>
<del>public class JavassistUtil {
<del>
<del> /**
<del> * 获取方法参数名
<del> * @param method
<del> * @return
<del> * @throws NotFoundException
<del> */
<del> public static String[] getParamName(Method method) throws NotFoundException {
<del> ClassPool pool = ClassPool.getDefault();
<del> CtClass ctClass = pool.get(method.getDeclaringClass().getName());
<del> CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
<del> // 使用javassist的反射方法的参数名
<del> MethodInfo methodInfo = ctMethod.getMethodInfo();
<del> CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
<del> LocalVariableAttribute attr = (LocalVariableAttribute)
<del> codeAttribute.getAttribute(LocalVariableAttribute.tag);
<del>
<del> int length = ctMethod.getParameterTypes().length;
<del> String[] array = new String[length];
<del> for (int i = 0; i < length; i++) {
<del> array[i] = attr.variableName(i + 1);
<del> }
<del> return array;
<del> }
<del>
<del>} |
||
JavaScript | agpl-3.0 | eaa189476a0015258dd927c99e0166f02c94847e | 0 | SciencesPo/isari,SciencesPo/isari,SciencesPo/isari,SciencesPo/isari | 'use strict'
const templates = require('../../specs/templates')
const { getMeta } = require('./specs')
const { RESERVED_FIELDS } = require('./schemas')
const { get, clone, isObject, isArray } = require('lodash/fp')
const memoize = require('memoizee')
const { mongo } = require('mongoose')
module.exports = {
applyTemplates,
populateAll,
populateAllQuery,
format,
filterConfidentialFields,
mongoID,
}
// Helper to safely get a string from Mongoose instance, ObjectId, or direct string (populate-proof)
// Object|ObjectID|String => String
function mongoID (o) {
return (o instanceof mongo.ObjectID) ? o.toHexString() : (o ? (o.id ? o.id : (o._id ? o._id.toHexString() : o)) : null)
}
const getRefFields = memoize((meta, depth) => _getRefFields('', meta, depth))
function applyTemplates (object, name, depth = 0) {
const meta = getMeta(name)
return _applyTemplates(object, meta, depth)
}
function _applyTemplates (object, meta, depth) {
if (Array.isArray(meta)) {
if (!Array.isArray(object)) {
throw new Error('Model inconsistency: meta declares array field, object is not an array')
}
return object.map(o => _applyTemplates(o, meta[0], depth))
}
if (!object) {
return object
}
if (typeof object !== 'object') {
return String(object)
}
if (!meta.template) {
return null
}
if (!templates[meta.template]) {
throw new Error(`Unknown template ${meta.template}`)
}
const string = templates[meta.template](object)
// No depth: simple string representation
if (depth === 0) {
return string
}
// Depth: generate string representations for fields
let result = {
// _string: string // TODO maybe include self-representation too?
}
const fields = Object.keys(meta).filter(f => !RESERVED_FIELDS.includes(f) && f[0] !== '/')
fields.forEach(f => result[f] = _applyTemplates(object[f], meta[f], depth - 1))
result._id = object._id
return result
}
// One pass only when done from query
function populateAllQuery (query, name, depth = Math.Infinity) {
let meta = getMeta(name)
if (Array.isArray(meta)) {
meta = meta[0]
}
const populates = getRefFields(meta, depth)
const fields = Object.keys(populates)
return fields.length > 0 ? query.populate(fields.join(' ')) : query
}
function populateAll (object, name, depth = Math.Infinity, passes = 1) {
const meta = getMeta(name)
return _populateAll(object, meta, depth, passes)
}
function _populateAll (object, meta, depth, passes) {
if (Array.isArray(meta)) {
meta = meta[0]
}
if (!object) {
return null
}
const populates = getRefFields(meta, depth)
const fields = Object.keys(populates)
const populated = fields.length > 0
? object.populate(fields.join(' ')).execPopulate()
: Promise.resolve(object)
if (passes > 1) {
return populated.then(o => Promise.all(fields.map(f => populateAll(get(f, o), populates[f], depth, passes - 1))).then(() => o))
} else {
return populated
}
}
function _getRefFields (baseName, meta, depth) {
if (depth === 0) {
return []
}
if (Array.isArray(meta)) {
meta = meta[0]
}
const fields = Object.keys(meta).filter(f => !RESERVED_FIELDS.includes(f) && f[0] !== '/')
const refFields = fields.filter(f => meta[f].ref)
const notRefFields = fields.filter(f => !meta[f].ref)
let result = {}
refFields.forEach(f => result[baseName ? (baseName + '.' + f) : f] = meta[f].ref)
notRefFields.forEach(f => Object.assign(result, _getRefFields(baseName ? (baseName + '.' + f) : f, meta[f], depth - 1)))
return result
}
const pathToRegExp = memoize(path => new RegExp('^' + path.replace('.', '\\.').replace('.*', '..+') + '$'))
const pathsTester = paths => {
const res = paths.map(pathToRegExp)
return path => res.some(re => re.test(path))
}
const retFalse = () => false
const REMOVED_CONFIDENTIAL_FIELD = Symbol()
function filterConfidentialFields (modelName, object, perms) {
const shouldRemove = perms.confidentials.viewable ? retFalse : pathsTester(perms && perms.confidentials && perms.confidentials.paths || [])
return _format(object, getMeta(modelName), shouldRemove, '', false)
}
function format (modelName, object, perms) {
const shouldRemove = perms.confidentials.viewable ? retFalse : pathsTester(perms && perms.confidentials && perms.confidentials.paths || [])
return _format(object, getMeta(modelName), shouldRemove, '', true)
}
function _format (object, schema, shouldRemove, path, transform) {
const keepId = path === ''
// Confidential not-viewable field: remove from output
if (shouldRemove(path)) {
return REMOVED_CONFIDENTIAL_FIELD
}
// Multi-valued field: format recursively
if (isArray(object)) {
if (schema && !isArray(schema)) {
throw new Error('Schema Inconsistency: Array expected')
}
if (shouldRemove(path + '.*')) {
// Multiple field marked as confidential: should remove whole array
return REMOVED_CONFIDENTIAL_FIELD
}
return object.map((o, i) => _format(o, schema && schema[0], shouldRemove, path ? path + '.' + i : String(i), transform))
}
// Scalar value? Nothing to format
if (!isObject(object)) {
if (schema && schema.type === 'object') {
throw new Error('Schema Inconsistency: Object expected')
}
return object
}
if (object instanceof mongo.ObjectID) {
return String(object)
}
// Work on a POJO: formatting must have no side-effect
let o = transform ? (object.toObject ? object.toObject() : clone(object)) : object
// Keep ID for later use (if keepId is set)
const id = o._id
// Format each sub-element recursively
Object.keys(o).forEach(f => {
if (f.substring(0, 3) === '$__') {
// Mongoose internal cache: ignore, thank you Mongoose for your biiiiiig semver respect
return
}
if (f[0] === '_' || f === 'id') { // Since mongoose 4.6 ObjectIds have a method toObject() returning { _bsontype, id } object
if (transform) {
delete o[f]
}
// Technical field: ignore
return
}
// If the value is a ref to another model, grab schema and format accordingly
const ref = schema && schema[f] && schema[f].ref
// unpopulate all the things (even when format = false)
if (ref) {
o[f] = mongoID(o[f])
} else {
const res = _format(o[f], schema[f], shouldRemove, path ? path + '.' + f : f, transform)
if (res !== REMOVED_CONFIDENTIAL_FIELD) {
o[f] = res
}
}
})
// Keep ID
if (transform && id && keepId) {
o.id = String(id)
}
return o
}
| server/lib/model-utils.js | 'use strict'
const templates = require('../../specs/templates')
const { getMeta } = require('./specs')
const { RESERVED_FIELDS } = require('./schemas')
const { get, clone, isObject, isArray } = require('lodash/fp')
const memoize = require('memoizee')
const { mongo } = require('mongoose')
module.exports = {
applyTemplates,
populateAll,
populateAllQuery,
format,
filterConfidentialFields,
mongoID,
}
// Helper to safely get a string from Mongoose instance, ObjectId, or direct string (populate-proof)
// Object|ObjectID|String => String
function mongoID (o) {
return (o instanceof mongo.ObjectID) ? o.toHexString() : (o ? (o.id ? o.id : (o._id ? o._id.toHexString() : o)) : null)
}
const getRefFields = memoize((meta, depth) => _getRefFields('', meta, depth))
function applyTemplates (object, name, depth = 0) {
const meta = getMeta(name)
return _applyTemplates(object, meta, depth)
}
function _applyTemplates (object, meta, depth) {
if (Array.isArray(meta)) {
if (!Array.isArray(object)) {
throw new Error('Model inconsistency: meta declares array field, object is not an array')
}
return object.map(o => _applyTemplates(o, meta[0], depth))
}
if (!object) {
return object
}
if (typeof object !== 'object') {
return String(object)
}
if (!meta.template) {
return null
}
if (!templates[meta.template]) {
throw new Error(`Unknown template ${meta.template}`)
}
const string = templates[meta.template](object)
// No depth: simple string representation
if (depth === 0) {
return string
}
// Depth: generate string representations for fields
let result = {
// _string: string // TODO maybe include self-representation too?
}
const fields = Object.keys(meta).filter(f => !RESERVED_FIELDS.includes(f) && f[0] !== '/')
fields.forEach(f => result[f] = _applyTemplates(object[f], meta[f], depth - 1))
result._id = object._id
return result
}
// One pass only when done from query
function populateAllQuery (query, name, depth = Math.Infinity) {
let meta = getMeta(name)
if (Array.isArray(meta)) {
meta = meta[0]
}
const populates = getRefFields(meta, depth)
const fields = Object.keys(populates)
return fields.length > 0 ? query.populate(fields.join(' ')) : query
}
function populateAll (object, name, depth = Math.Infinity, passes = 1) {
const meta = getMeta(name)
return _populateAll(object, meta, depth, passes)
}
function _populateAll (object, meta, depth, passes) {
if (Array.isArray(meta)) {
meta = meta[0]
}
if (!object) {
return null
}
const populates = getRefFields(meta, depth)
const fields = Object.keys(populates)
const populated = fields.length > 0
? object.populate(fields.join(' ')).execPopulate()
: Promise.resolve(object)
if (passes > 1) {
return populated.then(o => Promise.all(fields.map(f => populateAll(get(f, o), populates[f], depth, passes - 1))).then(() => o))
} else {
return populated
}
}
function _getRefFields (baseName, meta, depth) {
if (depth === 0) {
return []
}
if (Array.isArray(meta)) {
meta = meta[0]
}
const fields = Object.keys(meta).filter(f => !RESERVED_FIELDS.includes(f) && f[0] !== '/')
const refFields = fields.filter(f => meta[f].ref)
const notRefFields = fields.filter(f => !meta[f].ref)
let result = {}
refFields.forEach(f => result[baseName ? (baseName + '.' + f) : f] = meta[f].ref)
notRefFields.forEach(f => Object.assign(result, _getRefFields(baseName ? (baseName + '.' + f) : f, meta[f], depth - 1)))
return result
}
const pathToRegExp = memoize(path => new RegExp('^' + path.replace('.', '\\.').replace('.*', '..+') + '$'))
const pathsTester = paths => {
const res = paths.map(pathToRegExp)
return path => res.some(re => re.test(path))
}
const retFalse = () => false
const REMOVED_CONFIDENTIAL_FIELD = Symbol()
function filterConfidentialFields (modelName, object, perms) {
const shouldRemove = perms.confidentials.viewable ? retFalse : pathsTester(perms && perms.confidentials && perms.confidentials.paths || [])
return _format(object, getMeta(modelName), shouldRemove, '', false)
}
function format (modelName, object, perms) {
const shouldRemove = perms.confidentials.viewable ? retFalse : pathsTester(perms && perms.confidentials && perms.confidentials.paths || [])
return _format(object, getMeta(modelName), shouldRemove, '', true)
}
function _format (object, schema, shouldRemove, path, transform) {
const keepId = path === ''
// Confidential not-viewable field: remove from output
if (shouldRemove(path)) {
return REMOVED_CONFIDENTIAL_FIELD
}
// Multi-valued field: format recursively
if (isArray(object)) {
if (schema && !isArray(schema)) {
throw new Error('Schema Inconsistency: Array expected')
}
if (shouldRemove(path + '.*')) {
// Multiple field marked as confidential: should remove whole array
return REMOVED_CONFIDENTIAL_FIELD
}
return object.map((o, i) => _format(o, schema && schema[0], shouldRemove, path ? path + '.' + i : String(i), transform))
}
// Scalar value? Nothing to format
if (!isObject(object)) {
if (schema && schema.type === 'object') {
throw new Error('Schema Inconsistency: Object expected')
}
return object
}
if (object instanceof mongo.ObjectID) {
return String(object)
}
// Work on a POJO: formatting must have no side-effect
let o = transform ? (object.toObject ? object.toObject() : clone(object)) : object
// Keep ID for later use (if keepId is set)
const id = o._id
// Format each sub-element recursively
Object.keys(o).forEach(f => {
if (f[0] === '_' || f === 'id') { // Since mongoose 4.6 ObjectIds have a method toObject() returning { _bsontype, id } object
if (transform) {
delete o[f]
}
// Technical field: ignore
return
}
// If the value is a ref to another model, grab schema and format accordingly
const ref = schema && schema[f] && schema[f].ref
// unpopulate all the things (even when format = false)
if (ref) {
o[f] = mongoID(o[f])
} else {
const res = _format(o[f], schema[f], shouldRemove, path ? path + '.' + f : f, transform)
if (res !== REMOVED_CONFIDENTIAL_FIELD) {
o[f] = res
}
}
})
// Keep ID
if (transform && id && keepId) {
o.id = String(id)
}
return o
}
| fix(format): handling new reserved fields in mongoose (damn you)
| server/lib/model-utils.js | fix(format): handling new reserved fields in mongoose (damn you) | <ide><path>erver/lib/model-utils.js
<ide>
<ide> // Format each sub-element recursively
<ide> Object.keys(o).forEach(f => {
<add> if (f.substring(0, 3) === '$__') {
<add> // Mongoose internal cache: ignore, thank you Mongoose for your biiiiiig semver respect
<add> return
<add> }
<ide> if (f[0] === '_' || f === 'id') { // Since mongoose 4.6 ObjectIds have a method toObject() returning { _bsontype, id } object
<ide> if (transform) {
<ide> delete o[f] |
|
Java | apache-2.0 | 908b3e71a1d2f42d0a7199d43d5a18346e4959c1 | 0 | synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung | package org.synyx.urlaubsverwaltung.ui.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.synyx.urlaubsverwaltung.ui.Page;
import java.util.Map;
import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;
public class NavigationPage implements Page {
private static final By NEW_APPLICATION_SELECTOR = By.id("application-new-link");
private static final By SICK_NOTES_SELECTOR = By.cssSelector("[data-test-id=navigation-sick-notes-link]");
private static final By SETTINGS_SELECTOR = By.cssSelector("[data-test-id=navigation-settings-link]");
private final WebDriver driver;
private final AvatarMenu avatarMenu;
public final QuickAdd quickAdd;
public NavigationPage(WebDriver driver) {
this.avatarMenu = new AvatarMenu(driver);
this.quickAdd = new QuickAdd(driver);
this.driver = driver;
}
@Override
public boolean isVisible(WebDriver driver) {
return newApplicationLinkVisible(driver);
}
public void logout() {
avatarMenu.logout();
}
public void clickSickNotes() {
driver.findElement(SICK_NOTES_SELECTOR).click();
}
public void clickSettings() {
driver.findElement(SETTINGS_SELECTOR).click();
}
private static boolean newApplicationLinkVisible(WebDriver driver) {
final WebElement element = driver.findElement(NEW_APPLICATION_SELECTOR);
return element != null && element.isDisplayed();
}
public static class QuickAdd {
private static final By PLAIN_APPLICATION_SELECTOR = By.cssSelector("[data-test-id=new-application]");
private static final By BUTTON_SELECTOR = By.cssSelector("[data-test-id=add-something-new]");
private static final By POPUPMENU_SELECTOR = By.cssSelector("[data-test-id=add-something-new-popupmenu]");
private static final By APPLICATION_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-application]");
private static final By SICKNOTE_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-sicknote]");
private static final By OVERTIME_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-overtime]");
private final WebDriver driver;
private final WebDriverWait wait;
private QuickAdd(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, 20);
}
public boolean hasPopup() {
return !driver.findElements(POPUPMENU_SELECTOR).isEmpty()
&& driver.findElements(PLAIN_APPLICATION_SELECTOR).isEmpty();
}
public void click() {
if (hasPopup()) {
driver.findElement(BUTTON_SELECTOR).click();
} else {
driver.findElement(PLAIN_APPLICATION_SELECTOR).click();
}
}
public void newApplication() {
wait.until(elementToBeClickable(APPLICATION_SELECTOR));
driver.findElement(APPLICATION_SELECTOR).click();
}
public void newOvertime() {
wait.until(elementToBeClickable(OVERTIME_SELECTOR));
driver.findElement(OVERTIME_SELECTOR).click();
}
public void newSickNote() {
wait.until(elementToBeClickable(SICKNOTE_SELECTOR));
driver.findElement(SICKNOTE_SELECTOR).click();
}
}
private static class AvatarMenu {
private static final By AVATAR_SELECTOR = By.cssSelector("[data-test-id=avatar]");
private static final By AVATAR_POPUPMENU_SELECTOR = By.cssSelector("[data-test-id=avatar-popupmenu]");
private static final By LOGOUT_SELECTOR = By.cssSelector("[data-test-id=logout]");
private final WebDriver driver;
private final WebDriverWait wait;
AvatarMenu(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, 20);
}
void logout() {
driver.findElement(AVATAR_SELECTOR).click();
wait.until(waitForElementAnimationToFinish(LOGOUT_SELECTOR));
driver.findElement(LOGOUT_SELECTOR).click();
}
}
private static ExpectedCondition<Boolean> waitForElementAnimationToFinish(final By locator) {
return new ExpectedCondition<>() {
private double x = 0;
private double y = 0;
private double width = 0;
private double height = 0;
private double convertToDouble(Object longValue) {
if (longValue instanceof Long) {
return ((Long) longValue).doubleValue();
}
return (double) longValue;
}
@Override
public Boolean apply(WebDriver driver) {
final WebElement elem = driver.findElement(locator);
final JavascriptExecutor js = (JavascriptExecutor) driver;
final Map<String, Object> rect = (Map<String, Object>) js.executeScript("var rect = arguments[0].getBoundingClientRect(); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };", elem);
double newX = convertToDouble(rect.get("x"));
double newY = convertToDouble(rect.get("y"));
double newWidth = convertToDouble(rect.get("width"));
double newHeight = convertToDouble(rect.get("height"));
if (newX != x || newY != y || newWidth != width || newHeight != height) {
x = newX;
y = newY;
width = newWidth;
height = newHeight;
return false;
}
return true;
}
@Override
public String toString() {
return String.format("CSS Selector: \"%s\"", locator.toString());
}
};
}
}
| src/test/java/org/synyx/urlaubsverwaltung/ui/pages/NavigationPage.java | package org.synyx.urlaubsverwaltung.ui.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.synyx.urlaubsverwaltung.ui.Page;
import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;
public class NavigationPage implements Page {
private static final By NEW_APPLICATION_SELECTOR = By.id("application-new-link");
private static final By SICK_NOTES_SELECTOR = By.cssSelector("[data-test-id=navigation-sick-notes-link]");
private static final By SETTINGS_SELECTOR = By.cssSelector("[data-test-id=navigation-settings-link]");
private final WebDriver driver;
private final AvatarMenu avatarMenu;
public final QuickAdd quickAdd;
public NavigationPage(WebDriver driver) {
this.avatarMenu = new AvatarMenu(driver);
this.quickAdd = new QuickAdd(driver);
this.driver = driver;
}
@Override
public boolean isVisible(WebDriver driver) {
return newApplicationLinkVisible(driver);
}
public void logout() {
avatarMenu.logout();
}
public void clickSickNotes() {
driver.findElement(SICK_NOTES_SELECTOR).click();
}
public void clickSettings() {
driver.findElement(SETTINGS_SELECTOR).click();
}
private static boolean newApplicationLinkVisible(WebDriver driver) {
final WebElement element = driver.findElement(NEW_APPLICATION_SELECTOR);
return element != null && element.isDisplayed();
}
public static class QuickAdd {
private static final By PLAIN_APPLICATION_SELECTOR = By.cssSelector("[data-test-id=new-application]");
private static final By BUTTON_SELECTOR = By.cssSelector("[data-test-id=add-something-new]");
private static final By POPUPMENU_SELECTOR = By.cssSelector("[data-test-id=add-something-new-popupmenu]");
private static final By APPLICATION_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-application]");
private static final By SICKNOTE_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-sicknote]");
private static final By OVERTIME_SELECTOR = By.cssSelector("[data-test-id=quick-add-new-overtime]");
private final WebDriver driver;
private final WebDriverWait wait;
private QuickAdd(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, 20);
}
public boolean hasPopup() {
return !driver.findElements(POPUPMENU_SELECTOR).isEmpty()
&& driver.findElements(PLAIN_APPLICATION_SELECTOR).isEmpty();
}
public void click() {
if (hasPopup()) {
driver.findElement(BUTTON_SELECTOR).click();
} else {
driver.findElement(PLAIN_APPLICATION_SELECTOR).click();
}
}
public void newApplication() {
wait.until(elementToBeClickable(APPLICATION_SELECTOR));
driver.findElement(APPLICATION_SELECTOR).click();
}
public void newOvertime() {
wait.until(elementToBeClickable(OVERTIME_SELECTOR));
driver.findElement(OVERTIME_SELECTOR).click();
}
public void newSickNote() {
wait.until(elementToBeClickable(SICKNOTE_SELECTOR));
driver.findElement(SICKNOTE_SELECTOR).click();
}
}
private static class AvatarMenu {
private static final By AVATAR_SELECTOR = By.cssSelector("[data-test-id=avatar]");
private static final By AVATAR_POPUPMENU_SELECTOR = By.cssSelector("[data-test-id=avatar-popupmenu]");
private static final By LOGOUT_SELECTOR = By.cssSelector("[data-test-id=logout]");
private final WebDriver driver;
private final WebDriverWait wait;
AvatarMenu(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, 20);
}
void logout() {
driver.findElement(AVATAR_SELECTOR).click();
wait.until(elementToBeClickable(LOGOUT_SELECTOR));
driver.findElement(LOGOUT_SELECTOR).click();
}
}
}
| add waitForElementAnimationToFinish for selenium tests
| src/test/java/org/synyx/urlaubsverwaltung/ui/pages/NavigationPage.java | add waitForElementAnimationToFinish for selenium tests | <ide><path>rc/test/java/org/synyx/urlaubsverwaltung/ui/pages/NavigationPage.java
<ide> package org.synyx.urlaubsverwaltung.ui.pages;
<ide>
<ide> import org.openqa.selenium.By;
<add>import org.openqa.selenium.JavascriptExecutor;
<ide> import org.openqa.selenium.WebDriver;
<ide> import org.openqa.selenium.WebElement;
<add>import org.openqa.selenium.support.ui.ExpectedCondition;
<ide> import org.openqa.selenium.support.ui.WebDriverWait;
<ide> import org.synyx.urlaubsverwaltung.ui.Page;
<add>
<add>import java.util.Map;
<ide>
<ide> import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;
<ide>
<ide>
<ide> void logout() {
<ide> driver.findElement(AVATAR_SELECTOR).click();
<del> wait.until(elementToBeClickable(LOGOUT_SELECTOR));
<add> wait.until(waitForElementAnimationToFinish(LOGOUT_SELECTOR));
<ide> driver.findElement(LOGOUT_SELECTOR).click();
<ide> }
<ide> }
<add>
<add> private static ExpectedCondition<Boolean> waitForElementAnimationToFinish(final By locator) {
<add> return new ExpectedCondition<>() {
<add> private double x = 0;
<add> private double y = 0;
<add> private double width = 0;
<add> private double height = 0;
<add>
<add> private double convertToDouble(Object longValue) {
<add> if (longValue instanceof Long) {
<add> return ((Long) longValue).doubleValue();
<add> }
<add>
<add> return (double) longValue;
<add> }
<add>
<add> @Override
<add> public Boolean apply(WebDriver driver) {
<add> final WebElement elem = driver.findElement(locator);
<add> final JavascriptExecutor js = (JavascriptExecutor) driver;
<add> final Map<String, Object> rect = (Map<String, Object>) js.executeScript("var rect = arguments[0].getBoundingClientRect(); return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };", elem);
<add>
<add> double newX = convertToDouble(rect.get("x"));
<add> double newY = convertToDouble(rect.get("y"));
<add> double newWidth = convertToDouble(rect.get("width"));
<add> double newHeight = convertToDouble(rect.get("height"));
<add>
<add> if (newX != x || newY != y || newWidth != width || newHeight != height) {
<add> x = newX;
<add> y = newY;
<add> width = newWidth;
<add> height = newHeight;
<add> return false;
<add> }
<add>
<add> return true;
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return String.format("CSS Selector: \"%s\"", locator.toString());
<add> }
<add> };
<add> }
<ide> } |
|
Java | apache-2.0 | 8a6912a4e561ca150012725bf72f3da0f5325b21 | 0 | EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci,EBISPOT/goci | package uk.ac.ebi.spot.goci.curation.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException;
import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport;
import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter;
import uk.ac.ebi.spot.goci.curation.service.MailService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.CurationStatus;
import uk.ac.ebi.spot.goci.model.Curator;
import uk.ac.ebi.spot.goci.model.DiseaseTrait;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Ethnicity;
import uk.ac.ebi.spot.goci.model.Housekeeping;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.CurationStatusRepository;
import uk.ac.ebi.spot.goci.repository.CuratorRepository;
import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.EthnicityRepository;
import uk.ac.ebi.spot.goci.repository.HousekeepingRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import uk.ac.ebi.spot.goci.service.DefaultPubMedSearchService;
import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by emma on 20/11/14.
*
* @author emma Study Controller interprets user input and transform it into a study model that is represented to the
* user by the associated HTML page.
*/
@Controller
@RequestMapping("/studies")
public class StudyController {
// Repositories allowing access to database objects associated with a study
private StudyRepository studyRepository;
private HousekeepingRepository housekeepingRepository;
private DiseaseTraitRepository diseaseTraitRepository;
private EfoTraitRepository efoTraitRepository;
private CuratorRepository curatorRepository;
private CurationStatusRepository curationStatusRepository;
private AssociationRepository associationRepository;
private EthnicityRepository ethnicityRepository;
// Pubmed ID lookup service
private DefaultPubMedSearchService defaultPubMedSearchService;
private MailService mailService;
public static final int MAX_PAGE_ITEM_DISPLAY = 10;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public StudyController(StudyRepository studyRepository,
HousekeepingRepository housekeepingRepository,
DiseaseTraitRepository diseaseTraitRepository,
EfoTraitRepository efoTraitRepository,
CuratorRepository curatorRepository,
CurationStatusRepository curationStatusRepository,
AssociationRepository associationRepository,
EthnicityRepository ethnicityRepository,
DefaultPubMedSearchService defaultPubMedSearchService,
MailService mailService) {
this.studyRepository = studyRepository;
this.housekeepingRepository = housekeepingRepository;
this.diseaseTraitRepository = diseaseTraitRepository;
this.efoTraitRepository = efoTraitRepository;
this.curatorRepository = curatorRepository;
this.curationStatusRepository = curationStatusRepository;
this.associationRepository = associationRepository;
this.ethnicityRepository = ethnicityRepository;
this.defaultPubMedSearchService = defaultPubMedSearchService;
this.mailService = mailService;
}
/* All studies and various filtered lists */
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String allStudiesPage(Model model,
@RequestParam(required = false) Integer page,
@RequestParam(required = false) String pubmed,
@RequestParam(required = false) String author,
@RequestParam(required = false) String studyType,
@RequestParam(required = false) Long efoTraitId,
@RequestParam(required = false) String notesQuery,
@RequestParam(required = false) Long status,
@RequestParam(required = false) Long curator,
@RequestParam(required = false) String sortType) {
// Return all studies ordered by date if no page number given
if (page == null) {
// Find all studies ordered by study date and only display first page
return "redirect:/studies?page=1";
}
// This will be returned to view and store what curator has searched for
StudySearchFilter studySearchFilter = new StudySearchFilter();
// Store filters which will be need for pagination bar and to build URI passed back to view
String filters = "";
// Set sort object and sort string for URI
Sort sort = findSort(sortType);
String sortString = "";
if (sortType != null && !sortType.isEmpty()) {
sortString = "&sortType=" + sortType;
}
// This is the default study page will all studies
Page<Study> studyPage =
studyRepository.findAll(constructPageSpecification(page - 1, sort));
// Search by pubmed ID option available from landing page
if (pubmed != null && !pubmed.isEmpty()) {
studyPage =
studyRepository.findByPubmedId(pubmed, constructPageSpecification(page - 1, sort));
filters = filters + "&pubmed=" + pubmed;
}
// Search by author option available from landing page
if (author != null && !author.isEmpty()) {
studyPage = studyRepository.findByAuthorContainingIgnoreCase(author, constructPageSpecification(page - 1,
sort));
filters = filters + "&author=" + author;
}
// Search by study type
if (studyType != null && !studyType.isEmpty()) {
if (studyType.equals("GXE")) {
studyPage = studyRepository.findByGxe(true, constructPageSpecification(page - 1,
sort));
}
if (studyType.equals("GXG")) {
studyPage = studyRepository.findByGxg(true, constructPageSpecification(page - 1,
sort));
}
if (studyType.equals("CNV")) {
studyPage = studyRepository.findByCnv(true, constructPageSpecification(page - 1,
sort));
}
studySearchFilter.setStudyType(studyType);
filters = filters + "&studyType=" + studyType;
}
// Search by efo trait id
if (efoTraitId != null) {
studyPage = studyRepository.findByEfoTraitsId(efoTraitId, constructPageSpecification(page - 1,
sort));
studySearchFilter.setEfoTraitSearchFilterId(efoTraitId);
filters = filters + "&efoTraitId=" + efoTraitId;
}
// Search by notes for entered string
if (notesQuery != null && !notesQuery.isEmpty()) {
studyPage = studyRepository.findByHousekeepingNotesContainingIgnoreCase(notesQuery, constructPageSpecification(page - 1,
sort));
studySearchFilter.setNotesQuery(notesQuery);
filters = filters + "¬esQuery=" + notesQuery;
}
// If user entered a status
if (status != null) {
// If we have curator and status find by both
if (curator != null) {
studyPage = studyRepository.findByHousekeepingCurationStatusIdAndHousekeepingCuratorId(status,
curator,
constructPageSpecification(
page - 1,
sort));
filters = filters + "&status=" + status + "&curator=" + curator;
// Return these values so they appear in filter results
studySearchFilter.setCuratorSearchFilterId(curator);
studySearchFilter.setStatusSearchFilterId(status);
}
else {
studyPage = studyRepository.findByHousekeepingCurationStatusId(status, constructPageSpecification(
page - 1,
sort));
filters = filters + "&status=" + status;
// Return this value so it appears in filter result
studySearchFilter.setStatusSearchFilterId(status);
}
}
// If user entered curator
else {
if (curator != null) {
studyPage = studyRepository.findByHousekeepingCuratorId(curator, constructPageSpecification(
page - 1,
sort));
filters = filters + "&curator=" + curator;
// Return this value so it appears in filter result
studySearchFilter.setCuratorSearchFilterId(curator);
}
}
// Return URI, this will build thymeleaf links using by sort buttons.
// At present, do not add the current sort to the URI,
// just maintain any filter values (pubmed id, author etc) used by curator
String uri = "/studies?page=1";
if (!filters.isEmpty()) {
uri = uri + filters;
}
model.addAttribute("uri", uri);
// Return study page and filters,
// filters will be used by pagination bar
if (!filters.isEmpty()) {
if (!sortString.isEmpty()) {
filters = filters + sortString;
}
}
// If user has just sorted without any filter we need
// to pass this back to pagination bar
else {
if (!sortString.isEmpty()) {
filters = sortString;
}
}
model.addAttribute("filters", filters);
model.addAttribute("studies", studyPage);
//Pagination variables
long totalStudies = studyPage.getTotalElements();
int current = studyPage.getNumber() + 1;
int begin = Math.max(1, current - 5); // Returns the greater of two values
int end = Math.min(begin + 10, studyPage.getTotalPages()); // how many pages to display in the pagination bar
model.addAttribute("beginIndex", begin);
model.addAttribute("endIndex", end);
model.addAttribute("currentIndex", current);
model.addAttribute("totalStudies", totalStudies);
// Add studySearchFilter to model so user can filter table
model.addAttribute("studySearchFilter", studySearchFilter);
return "studies";
}
// Redirects from landing page and main page
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter,
Model model,
@RequestParam(required = true) String filters) {
// Get ids of objects searched for
Long status = studySearchFilter.getStatusSearchFilterId();
Long curator = studySearchFilter.getCuratorSearchFilterId();
String pubmedId = studySearchFilter.getPubmedId();
String author = studySearchFilter.getAuthor();
String studyType = studySearchFilter.getStudyType();
Long efoTraitId = studySearchFilter.getEfoTraitSearchFilterId();
String notesQuery = studySearchFilter.getNotesQuery();
// Search by pubmed ID option available from landing page
if (pubmedId != null && !pubmedId.isEmpty()) {
return "redirect:/studies?page=1&pubmed=" + pubmedId;
}
// Search by author option available from landing page
else if (author != null && !author.isEmpty()) {
return "redirect:/studies?page=1&author=" + author;
}
// Search by study type
else if (studyType != null && !studyType.isEmpty()) {
return "redirect:/studies?page=1&studyType=" + studyType;
}
// Search by efo trait
else if (efoTraitId != null) {
return "redirect:/studies?page=1&efoTraitId=" + efoTraitId;
}
// Search by string in notes
else if (notesQuery != null && !notesQuery.isEmpty()) {
return "redirect:/studies?page=1¬esQuery=" + notesQuery;
}
// If user entered a status
else if (status != null) {
// If we have curator and status find by both
if (curator != null) {
return "redirect:/studies?page=1&status=" + status + "&curator=" + curator;
}
else {
return "redirect:/studies?page=1&status=" + status;
}
}
// If user entered curator
else if (curator != null) {
return "redirect:/studies?page=1&curator=" + curator;
}
// If all else fails return all studies
else {
// Find all studies ordered by study date and only display first page
return "redirect:/studies?page=1";
}
}
/* New Study*/
// Add a new study
// Directs user to an empty form to which they can create a new study
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String newStudyForm(Model model) {
model.addAttribute("study", new Study());
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Save study found by Pubmed Id
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new/import", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String importStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport) throws PubmedImportException {
// Remove whitespace
String pubmedId = pubmedIdForImport.getPubmedId().trim();
// Check if there is an existing study with the same pubmed id
Collection<Study> existingStudies = studyRepository.findByPubmedId(pubmedId);
if (existingStudies.size() > 0) {
throw new PubmedImportException();
}
// Pass to importer
Study importedStudy = defaultPubMedSearchService.findPublicationSummary(pubmedId);
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
importedStudy.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(importedStudy);
// Save new study
studyRepository.save(importedStudy);
return "redirect:/studies/" + importedStudy.getId();
}
// Save newly added study details
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model) {
// If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix
if (bindingResult.hasErrors()) {
model.addAttribute("study", study);
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
study.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(study);
return "redirect:/studies/" + newStudy.getId();
}
/* Exitsing study*/
// View a study
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudy(Model model, @PathVariable Long studyId) {
Study studyToView = studyRepository.findOne(studyId);
model.addAttribute("study", studyToView);
return "study";
}
// Edit an existing study
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String updateStudy(@ModelAttribute Study study,
Model model,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Use id in URL to get study and then its associated housekeeping
Study existingStudy = studyRepository.findOne(studyId);
Housekeeping existingHousekeeping = existingStudy.getHousekeeping();
// Set the housekeeping of the study returned to one already linked to it in database
// Need to do this as we don't return housekeeping in form
study.setHousekeeping(existingHousekeeping);
// Saves the new information returned from form
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId();
}
// Delete an existing study
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyToDelete(Model model, @PathVariable Long studyId) {
Study studyToDelete = studyRepository.findOne(studyId);
// Check if it has any associations
Collection<Association> associations = associationRepository.findByStudyId(studyId);
// If so warn the curator
if (!associations.isEmpty()) {
return "delete_study_with_associations_warning";
}
else {
model.addAttribute("studyToDelete", studyToDelete);
return "delete_study";
}
}
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String deleteStudy(@PathVariable Long studyId) {
// Find our study based on the ID
Study studyToDelete = studyRepository.findOne(studyId);
// Before we delete the study get its associated housekeeping and ethnicity
Long housekeepingId = studyToDelete.getHousekeeping().getId();
Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId);
Collection<Ethnicity> ethnicitiesAttachedToStudy = ethnicityRepository.findByStudyId(studyId);
// Delete ethnicity information linked to this study
for (Ethnicity ethnicity : ethnicitiesAttachedToStudy) {
ethnicityRepository.delete(ethnicity);
}
// Delete study
studyRepository.delete(studyToDelete);
// Delete housekeeping
housekeepingRepository.delete(housekeepingAttachedToStudy);
return "redirect:/studies";
}
// Duplicate a study
@RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// Find study user wants to duplicate, based on the ID
Study studyToDuplicate = studyRepository.findOne(studyId);
// New study will be created by copying existing study details
Study duplicateStudy = copyStudy(studyToDuplicate);
// Create housekeeping object and add duplicate message
Housekeeping studyHousekeeping = createHousekeeping();
studyHousekeeping.setNotes(
"Duplicate of study: " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId());
duplicateStudy.setHousekeeping(studyHousekeeping);
// Save newly duplicated study
studyRepository.save(duplicateStudy);
// Copy existing ethnicity
Collection<Ethnicity> studyToDuplicateEthnicities = ethnicityRepository.findByStudyId(studyId);
for (Ethnicity studyToDuplicateEthnicity : studyToDuplicateEthnicities) {
Ethnicity duplicateEthnicity = copyEthnicity(studyToDuplicateEthnicity);
duplicateEthnicity.setStudy(duplicateStudy);
ethnicityRepository.save(duplicateEthnicity);
}
// Add duplicate message
String message =
"Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId();
redirectAttributes.addFlashAttribute("duplicateMessage", message);
return "redirect:/studies/" + duplicateStudy.getId();
}
/* Study housekeeping/curator information */
// Generate page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) {
// Find study
Study study = studyRepository.findOne(studyId);
// If we don't have a housekeeping object create one, this should not occur though as they are created when study is created
if (study.getHousekeeping() == null) {
model.addAttribute("studyHousekeeping", new Housekeeping());
}
else {
model.addAttribute("studyHousekeeping", study.getHousekeeping());
}
// Return the housekeeping object attached to study and return the study
model.addAttribute("study", study);
return "study_housekeeping";
}
// Update page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Establish linked study
Study study = studyRepository.findOne(studyId);
// Before we save housekeeping get the status in database so we can check for a change
CurationStatus statusInDatabase = housekeepingRepository.findOne(housekeeping.getId()).getCurationStatus();
// Save housekeeping returned from form straight away to save any curator entered details like notes etc
housekeepingRepository.save(housekeeping);
// For the study check all SNPs have been checked
Collection<Association> associations = associationRepository.findByStudyId(studyId);
int snpsNotChecked = 0;
for (Association association : associations) {
// If we have one that is not checked set value
if (association.getSnpChecked() == false) {
snpsNotChecked = 1;
}
}
// Establish whether user has set status to "Publish study" and "Send to NCBI"
// as corresponding dates will be set in housekeeping table
CurationStatus currentStatus = housekeeping.getCurationStatus();
// If the status has changed
if (currentStatus != statusInDatabase) {
if (currentStatus != null && currentStatus.getStatus().equals("Publish study")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before publishing";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date publishDate = new java.util.Date();
housekeeping.setPublishDate(publishDate);
}
}
//Set date and send email notification
if (currentStatus != null && currentStatus.getStatus().equals("Send to NCBI")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before sending to NCBI";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date sendToNCBIDate = new java.util.Date();
housekeeping.setSendToNCBIDate(sendToNCBIDate);
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Send notification email to curators
if (currentStatus != null && currentStatus.getStatus().equals("Level 1 curation done")) {
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
// Set study housekeeping
study.setHousekeeping(housekeeping);
// Save our study
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
/* General purpose methods */
private Housekeeping createHousekeeping() {
// Create housekeeping object and create the study added date
Housekeeping housekeeping = new Housekeeping();
java.util.Date studyAddedDate = new java.util.Date();
housekeeping.setStudyAddedDate(studyAddedDate);
// Set status
CurationStatus status = curationStatusRepository.findByStatus("Awaiting Curation");
housekeeping.setCurationStatus(status);
// Set curator
Curator curator = curatorRepository.findByLastName("Level 1 Curator");
housekeeping.setCurator(curator);
// Save housekeeping
housekeepingRepository.save(housekeeping);
// Save housekeeping
return housekeeping;
}
private Study copyStudy(Study studyToDuplicate) {
Study duplicateStudy = new Study();
duplicateStudy.setAuthor(studyToDuplicate.getAuthor() + " DUP");
duplicateStudy.setStudyDate(studyToDuplicate.getStudyDate());
duplicateStudy.setPublication(studyToDuplicate.getPublication());
duplicateStudy.setTitle(studyToDuplicate.getTitle());
duplicateStudy.setInitialSampleSize(studyToDuplicate.getInitialSampleSize());
duplicateStudy.setReplicateSampleSize(studyToDuplicate.getReplicateSampleSize());
duplicateStudy.setPlatform(studyToDuplicate.getPlatform());
duplicateStudy.setPubmedId(studyToDuplicate.getPubmedId());
duplicateStudy.setCnv(studyToDuplicate.getCnv());
duplicateStudy.setGxe(studyToDuplicate.getGxe());
duplicateStudy.setGxg(studyToDuplicate.getGxg());
duplicateStudy.setDiseaseTrait(studyToDuplicate.getDiseaseTrait());
// Deal with EFO traits
Collection<EfoTrait> efoTraits = studyToDuplicate.getEfoTraits();
Collection<EfoTrait> efoTraitsDuplicateStudy = new ArrayList<EfoTrait>();
if (efoTraits != null && !efoTraits.isEmpty()) {
efoTraitsDuplicateStudy.addAll(efoTraits);
duplicateStudy.setEfoTraits(efoTraitsDuplicateStudy);
}
return duplicateStudy;
}
private Ethnicity copyEthnicity(Ethnicity studyToDuplicateEthnicity) {
Ethnicity duplicateEthnicity = new Ethnicity();
duplicateEthnicity.setType(studyToDuplicateEthnicity.getType());
duplicateEthnicity.setNumberOfIndividuals(studyToDuplicateEthnicity.getNumberOfIndividuals());
duplicateEthnicity.setEthnicGroup(studyToDuplicateEthnicity.getEthnicGroup());
duplicateEthnicity.setCountryOfOrigin(studyToDuplicateEthnicity.getCountryOfOrigin());
duplicateEthnicity.setCountryOfRecruitment(studyToDuplicateEthnicity.getCountryOfRecruitment());
duplicateEthnicity.setDescription(studyToDuplicateEthnicity.getDescription());
duplicateEthnicity.setPreviouslyReported(studyToDuplicateEthnicity.getPreviouslyReported());
duplicateEthnicity.setSampleSizesMatch(studyToDuplicateEthnicity.getSampleSizesMatch());
duplicateEthnicity.setNotes(studyToDuplicateEthnicity.getNotes());
return duplicateEthnicity;
}
// Find correct sorting type and direction
private Sort findSort(String sortType) {
// Default sort by date
Sort sort = sortByStudyDateDesc();
Map<String, Sort> sortTypeMap = new HashMap<>();
sortTypeMap.put("authorsortasc", sortByAuthorAsc());
sortTypeMap.put("authorsortdesc", sortByAuthorDesc());
sortTypeMap.put("titlesortasc", sortByTitleAsc());
sortTypeMap.put("titlesortdesc", sortByTitleDesc());
sortTypeMap.put("studydatesortasc", sortByStudyDateAsc());
sortTypeMap.put("studydatesortdesc", sortByStudyDateDesc());
sortTypeMap.put("pubmedsortasc", sortByPubmedIdAsc());
sortTypeMap.put("pubmedsortdesc", sortByPubmedIdDesc());
sortTypeMap.put("publicationsortasc", sortByPublicationAsc());
sortTypeMap.put("publicationsortdesc", sortByPublicationDesc());
sortTypeMap.put("efotraitsortasc", sortByEfoTraitAsc());
sortTypeMap.put("efotraitsortdesc", sortByEfoTraitDesc());
sortTypeMap.put("diseasetraitsortasc", sortByDiseaseTraitAsc());
sortTypeMap.put("diseasetraitsortdesc", sortByDiseaseTraitDesc());
sortTypeMap.put("curatorsortasc", sortByCuratorAsc());
sortTypeMap.put("curatorsortdesc", sortByCuratorDesc());
sortTypeMap.put("curationstatussortasc", sortByCurationStatusAsc());
sortTypeMap.put("curationstatussortdesc", sortByCurationStatusDesc());
if (sortType != null && !sortType.isEmpty()) {
sort = sortTypeMap.get(sortType);
}
return sort;
}
/* Exception handling */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(PubmedLookupException.class)
public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) {
getLog().error("pubmed lookup exception", pubmedLookupException);
return "pubmed_lookup_warning";
}
@ExceptionHandler(PubmedImportException.class)
public String handlePubmedImportException(PubmedImportException pubmedImportException) {
getLog().error("pubmed import exception", pubmedImportException);
return "pubmed_import_warning";
}
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// Disease Traits
@ModelAttribute("diseaseTraits")
public List<DiseaseTrait> populateDiseaseTraits(Model model) {
return diseaseTraitRepository.findAll(sortByTraitAsc());
}
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEFOTraits(Model model) {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Curators
@ModelAttribute("curators")
public List<Curator> populateCurators(Model model) {
return curatorRepository.findAll();
}
// Curation statuses
@ModelAttribute("curationstatuses")
public List<CurationStatus> populateCurationStatuses(Model model) {
return curationStatusRepository.findAll();
}
// Study types
@ModelAttribute("studyTypes")
public List<String> populateStudyTypeOptions(Model model) {
List<String> studyTypesOptions = new ArrayList<String>();
studyTypesOptions.add("GXE");
studyTypesOptions.add("GXG");
studyTypesOptions.add("CNV");
return studyTypesOptions;
}
// Authors
@ModelAttribute("authors")
public List<String> populateAuthors(Model model) {
return studyRepository.findAllStudyAuthors();
}
/* Sorting options */
// Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
private Sort sortByStudyDateAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "studyDate"));}
private Sort sortByStudyDateDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "studyDate"));}
private Sort sortByAuthorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "author"));}
private Sort sortByAuthorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "author"));}
private Sort sortByTitleAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "title"));}
private Sort sortByTitleDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "title"));}
private Sort sortByPublicationAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "publication"));}
private Sort sortByPublicationDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "publication"));}
private Sort sortByPubmedIdAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "pubmedId"));}
private Sort sortByPubmedIdDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "pubmedId"));}
private Sort sortByDiseaseTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "diseaseTrait.trait").ignoreCase());}
private Sort sortByDiseaseTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "diseaseTrait.trait").ignoreCase());}
private Sort sortByEfoTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "efoTraits.trait").ignoreCase());}
private Sort sortByEfoTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "efoTraits.trait").ignoreCase());}
private Sort sortByCuratorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curator"));}
private Sort sortByCuratorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curator"));}
private Sort sortByCurationStatusAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC,
"housekeeping.curationStatus"));
}
private Sort sortByCurationStatusDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC,
"housekeeping.curationStatus"));
}
/* Pagination */
// Pagination, method passed page index and inlcudes max number of studies, sorted by study date, to return
private Pageable constructPageSpecification(int pageIndex, Sort sort) {
Pageable pageSpecification = new PageRequest(pageIndex, MAX_PAGE_ITEM_DISPLAY, sort);
return pageSpecification;
}
}
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/StudyController.java | package uk.ac.ebi.spot.goci.curation.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import uk.ac.ebi.spot.goci.curation.exception.PubmedImportException;
import uk.ac.ebi.spot.goci.curation.model.PubmedIdForImport;
import uk.ac.ebi.spot.goci.curation.model.StudySearchFilter;
import uk.ac.ebi.spot.goci.curation.service.MailService;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.CurationStatus;
import uk.ac.ebi.spot.goci.model.Curator;
import uk.ac.ebi.spot.goci.model.DiseaseTrait;
import uk.ac.ebi.spot.goci.model.EfoTrait;
import uk.ac.ebi.spot.goci.model.Ethnicity;
import uk.ac.ebi.spot.goci.model.Housekeeping;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.CurationStatusRepository;
import uk.ac.ebi.spot.goci.repository.CuratorRepository;
import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository;
import uk.ac.ebi.spot.goci.repository.EfoTraitRepository;
import uk.ac.ebi.spot.goci.repository.EthnicityRepository;
import uk.ac.ebi.spot.goci.repository.HousekeepingRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;
import uk.ac.ebi.spot.goci.service.DefaultPubMedSearchService;
import uk.ac.ebi.spot.goci.service.exception.PubmedLookupException;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by emma on 20/11/14.
*
* @author emma Study Controller interprets user input and transform it into a study model that is represented to the
* user by the associated HTML page.
*/
@Controller
@RequestMapping("/studies")
public class StudyController {
// Repositories allowing access to database objects associated with a study
private StudyRepository studyRepository;
private HousekeepingRepository housekeepingRepository;
private DiseaseTraitRepository diseaseTraitRepository;
private EfoTraitRepository efoTraitRepository;
private CuratorRepository curatorRepository;
private CurationStatusRepository curationStatusRepository;
private AssociationRepository associationRepository;
private EthnicityRepository ethnicityRepository;
// Pubmed ID lookup service
private DefaultPubMedSearchService defaultPubMedSearchService;
private MailService mailService;
public static final int MAX_PAGE_ITEM_DISPLAY = 10;
private Logger log = LoggerFactory.getLogger(getClass());
protected Logger getLog() {
return log;
}
@Autowired
public StudyController(StudyRepository studyRepository,
HousekeepingRepository housekeepingRepository,
DiseaseTraitRepository diseaseTraitRepository,
EfoTraitRepository efoTraitRepository,
CuratorRepository curatorRepository,
CurationStatusRepository curationStatusRepository,
AssociationRepository associationRepository,
EthnicityRepository ethnicityRepository,
DefaultPubMedSearchService defaultPubMedSearchService,
MailService mailService) {
this.studyRepository = studyRepository;
this.housekeepingRepository = housekeepingRepository;
this.diseaseTraitRepository = diseaseTraitRepository;
this.efoTraitRepository = efoTraitRepository;
this.curatorRepository = curatorRepository;
this.curationStatusRepository = curationStatusRepository;
this.associationRepository = associationRepository;
this.ethnicityRepository = ethnicityRepository;
this.defaultPubMedSearchService = defaultPubMedSearchService;
this.mailService = mailService;
}
/* All studies and various filtered lists */
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String allStudiesPage(Model model,
@RequestParam(required = false) Integer page,
@RequestParam(required = false) String pubmed,
@RequestParam(required = false) String author,
@RequestParam(required = false) String studyType,
@RequestParam(required = false) Long efoTraitId,
@RequestParam(required = false) String notesQuery,
@RequestParam(required = false) Long status,
@RequestParam(required = false) Long curator,
@RequestParam(required = false) String sortType) {
// Return all studies ordered by date if no page number given
if (page == null) {
// Find all studies ordered by study date and only display first page
return "redirect:/studies?page=1";
}
// This will be returned to view and store what curator has searched for
StudySearchFilter studySearchFilter = new StudySearchFilter();
// Store filters which will be need for pagination bar and to build URI passed back to view
String filters = "";
// Set sort object and sort string for URI
Sort sort = findSort(sortType);
String sortString = "";
if (sortType != null && !sortType.isEmpty()) {
sortString = "&sortType=" + sortType;
}
// This is the default study page will all studies
Page<Study> studyPage =
studyRepository.findAll(constructPageSpecification(page - 1, sort));
// Search by pubmed ID option available from landing page
if (pubmed != null && !pubmed.isEmpty()) {
studyPage =
studyRepository.findByPubmedId(pubmed, constructPageSpecification(page - 1, sort));
filters = filters + "&pubmed=" + pubmed;
}
// Search by author option available from landing page
if (author != null && !author.isEmpty()) {
studyPage = studyRepository.findByAuthorContainingIgnoreCase(author, constructPageSpecification(page - 1,
sort));
filters = filters + "&author=" + author;
}
// Search by study type
if (studyType != null && !studyType.isEmpty()) {
if (studyType.equals("GXE")) {
studyPage = studyRepository.findByGxe(true, constructPageSpecification(page - 1,
sort));
}
if (studyType.equals("GXG")) {
studyPage = studyRepository.findByGxg(true, constructPageSpecification(page - 1,
sort));
}
if (studyType.equals("CNV")) {
studyPage = studyRepository.findByCnv(true, constructPageSpecification(page - 1,
sort));
}
studySearchFilter.setStudyType(studyType);
filters = filters + "&studyType=" + studyType;
}
// Search by efo trait id
if (efoTraitId != null) {
studyPage = studyRepository.findByEfoTraitsId(efoTraitId, constructPageSpecification(page - 1,
sort));
studySearchFilter.setEfoTraitSearchFilterId(efoTraitId);
filters = filters + "&efoTraitId=" + efoTraitId;
}
// Search by notes for entered string
if (notesQuery != null && !notesQuery.isEmpty()) {
studyPage = studyRepository.findByHousekeepingNotesContainingIgnoreCase(notesQuery, constructPageSpecification(page - 1,
sort));
studySearchFilter.setNotesQuery(notesQuery);
filters = filters + "¬esQuery=" + notesQuery;
}
// If user entered a status
if (status != null) {
// If we have curator and status find by both
if (curator != null) {
studyPage = studyRepository.findByHousekeepingCurationStatusIdAndHousekeepingCuratorId(status,
curator,
constructPageSpecification(
page - 1,
sort));
filters = filters + "&status=" + status + "&curator=" + curator;
// Return these values so they appear in filter results
studySearchFilter.setCuratorSearchFilterId(curator);
studySearchFilter.setStatusSearchFilterId(status);
}
else {
studyPage = studyRepository.findByHousekeepingCurationStatusId(status, constructPageSpecification(
page - 1,
sort));
filters = filters + "&status=" + status;
// Return this value so it appears in filter result
studySearchFilter.setStatusSearchFilterId(status);
}
}
// If user entered curator
else {
if (curator != null) {
studyPage = studyRepository.findByHousekeepingCuratorId(curator, constructPageSpecification(
page - 1,
sort));
filters = filters + "&curator=" + curator;
// Return this value so it appears in filter result
studySearchFilter.setCuratorSearchFilterId(curator);
}
}
// Return URI, this will build thymeleaf links using by sort buttons.
// At present, do not add the current sort to the URI,
// just maintain any filter values (pubmed id, author etc) used by curator
String uri = "/studies?page=1";
if (!filters.isEmpty()) {
uri = uri + filters;
}
model.addAttribute("uri", uri);
// Return study page and filters,
// filters will be used by pagination bar
if (!filters.isEmpty()) {
if (!sortString.isEmpty()) {
filters = filters + sortString;
}
}
// If user has just sorted without any filter we need
// to pass this back to pagination bar
else {
if (!sortString.isEmpty()) {
filters = sortString;
}
}
model.addAttribute("filters", filters);
model.addAttribute("studies", studyPage);
//Pagination variables
long totalStudies = studyPage.getTotalElements();
int current = studyPage.getNumber() + 1;
int begin = Math.max(1, current - 5); // Returns the greater of two values
int end = Math.min(begin + 10, studyPage.getTotalPages()); // how many pages to display in the pagination bar
model.addAttribute("beginIndex", begin);
model.addAttribute("endIndex", end);
model.addAttribute("currentIndex", current);
model.addAttribute("totalStudies", totalStudies);
// Add studySearchFilter to model so user can filter table
model.addAttribute("studySearchFilter", studySearchFilter);
return "studies";
}
// Redirects from landing page and main page
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String searchForStudyByFilter(@ModelAttribute StudySearchFilter studySearchFilter,
Model model,
@RequestParam(required = true) String filters) {
// Get ids of objects searched for
Long status = studySearchFilter.getStatusSearchFilterId();
Long curator = studySearchFilter.getCuratorSearchFilterId();
String pubmedId = studySearchFilter.getPubmedId();
String author = studySearchFilter.getAuthor();
String studyType = studySearchFilter.getStudyType();
Long efoTraitId = studySearchFilter.getEfoTraitSearchFilterId();
String notesQuery = studySearchFilter.getNotesQuery();
// Search by pubmed ID option available from landing page
if (pubmedId != null && !pubmedId.isEmpty()) {
return "redirect:/studies?page=1&pubmed=" + pubmedId;
}
// Search by author option available from landing page
else if (author != null && !author.isEmpty()) {
return "redirect:/studies?page=1&author=" + author;
}
// Search by study type
else if (studyType != null && !studyType.isEmpty()) {
return "redirect:/studies?page=1&studyType=" + studyType;
}
// Search by efo trait
else if (efoTraitId != null) {
return "redirect:/studies?page=1&efoTraitId=" + efoTraitId;
}
else if (notesQuery != null && !notesQuery.isEmpty()) {
return "redirect:/studies?page=1¬esQuery=" + notesQuery;
}
// If user entered a status
else if (status != null) {
// If we have curator and status find by both
if (curator != null) {
return "redirect:/studies?page=1&status=" + status + "&curator=" + curator;
}
else {
return "redirect:/studies?page=1&status=" + status;
}
}
// If user entered curator
else if (curator != null) {
return "redirect:/studies?page=1&curator=" + curator;
}
// If all else fails return all studies
else {
// Find all studies ordered by study date and only display first page
return "redirect:/studies?page=1";
}
}
/* New Study*/
// Add a new study
// Directs user to an empty form to which they can create a new study
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String newStudyForm(Model model) {
model.addAttribute("study", new Study());
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Save study found by Pubmed Id
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new/import", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String importStudy(@ModelAttribute PubmedIdForImport pubmedIdForImport) throws PubmedImportException {
// Remove whitespace
String pubmedId = pubmedIdForImport.getPubmedId().trim();
// Check if there is an existing study with the same pubmed id
Collection<Study> existingStudies = studyRepository.findByPubmedId(pubmedId);
if (existingStudies.size() > 0) {
throw new PubmedImportException();
}
// Pass to importer
Study importedStudy = defaultPubMedSearchService.findPublicationSummary(pubmedId);
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
importedStudy.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(importedStudy);
// Save new study
studyRepository.save(importedStudy);
return "redirect:/studies/" + importedStudy.getId();
}
// Save newly added study details
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/new", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addStudy(@Valid @ModelAttribute Study study, BindingResult bindingResult, Model model) {
// If we have errors in the fields entered, i.e they are blank, then return these to form so user can fix
if (bindingResult.hasErrors()) {
model.addAttribute("study", study);
// Return an empty pubmedIdForImport object to store user entered pubmed id
model.addAttribute("pubmedIdForImport", new PubmedIdForImport());
return "add_study";
}
// Create housekeeping object
Housekeeping studyHousekeeping = createHousekeeping();
// Update and save study
study.setHousekeeping(studyHousekeeping);
Study newStudy = studyRepository.save(study);
return "redirect:/studies/" + newStudy.getId();
}
/* Exitsing study*/
// View a study
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudy(Model model, @PathVariable Long studyId) {
Study studyToView = studyRepository.findOne(studyId);
model.addAttribute("study", studyToView);
return "study";
}
// Edit an existing study
// @ModelAttribute is a reference to the object holding the data entered in the form
@RequestMapping(value = "/{studyId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String updateStudy(@ModelAttribute Study study,
Model model,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Use id in URL to get study and then its associated housekeeping
Study existingStudy = studyRepository.findOne(studyId);
Housekeeping existingHousekeeping = existingStudy.getHousekeeping();
// Set the housekeeping of the study returned to one already linked to it in database
// Need to do this as we don't return housekeeping in form
study.setHousekeeping(existingHousekeeping);
// Saves the new information returned from form
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId();
}
// Delete an existing study
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyToDelete(Model model, @PathVariable Long studyId) {
Study studyToDelete = studyRepository.findOne(studyId);
// Check if it has any associations
Collection<Association> associations = associationRepository.findByStudyId(studyId);
// If so warn the curator
if (!associations.isEmpty()) {
return "delete_study_with_associations_warning";
}
else {
model.addAttribute("studyToDelete", studyToDelete);
return "delete_study";
}
}
@RequestMapping(value = "/{studyId}/delete", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String deleteStudy(@PathVariable Long studyId) {
// Find our study based on the ID
Study studyToDelete = studyRepository.findOne(studyId);
// Before we delete the study get its associated housekeeping and ethnicity
Long housekeepingId = studyToDelete.getHousekeeping().getId();
Housekeeping housekeepingAttachedToStudy = housekeepingRepository.findOne(housekeepingId);
Collection<Ethnicity> ethnicitiesAttachedToStudy = ethnicityRepository.findByStudyId(studyId);
// Delete ethnicity information linked to this study
for (Ethnicity ethnicity : ethnicitiesAttachedToStudy) {
ethnicityRepository.delete(ethnicity);
}
// Delete study
studyRepository.delete(studyToDelete);
// Delete housekeeping
housekeepingRepository.delete(housekeepingAttachedToStudy);
return "redirect:/studies";
}
// Duplicate a study
@RequestMapping(value = "/{studyId}/duplicate", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String duplicateStudy(@PathVariable Long studyId, RedirectAttributes redirectAttributes) {
// Find study user wants to duplicate, based on the ID
Study studyToDuplicate = studyRepository.findOne(studyId);
// New study will be created by copying existing study details
Study duplicateStudy = copyStudy(studyToDuplicate);
// Create housekeeping object and add duplicate message
Housekeeping studyHousekeeping = createHousekeeping();
studyHousekeeping.setNotes(
"Duplicate of study: " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId());
duplicateStudy.setHousekeeping(studyHousekeeping);
// Save newly duplicated study
studyRepository.save(duplicateStudy);
// Copy existing ethnicity
Collection<Ethnicity> studyToDuplicateEthnicities = ethnicityRepository.findByStudyId(studyId);
for (Ethnicity studyToDuplicateEthnicity : studyToDuplicateEthnicities) {
Ethnicity duplicateEthnicity = copyEthnicity(studyToDuplicateEthnicity);
duplicateEthnicity.setStudy(duplicateStudy);
ethnicityRepository.save(duplicateEthnicity);
}
// Add duplicate message
String message =
"Study is a duplicate of " + studyToDuplicate.getAuthor() + ", PMID: " + studyToDuplicate.getPubmedId();
redirectAttributes.addFlashAttribute("duplicateMessage", message);
return "redirect:/studies/" + duplicateStudy.getId();
}
/* Study housekeeping/curator information */
// Generate page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
public String viewStudyHousekeeping(Model model, @PathVariable Long studyId) {
// Find study
Study study = studyRepository.findOne(studyId);
// If we don't have a housekeeping object create one, this should not occur though as they are created when study is created
if (study.getHousekeeping() == null) {
model.addAttribute("studyHousekeeping", new Housekeeping());
}
else {
model.addAttribute("studyHousekeeping", study.getHousekeeping());
}
// Return the housekeeping object attached to study and return the study
model.addAttribute("study", study);
return "study_housekeeping";
}
// Update page with housekeeping/curator information linked to a study
@RequestMapping(value = "/{studyId}/housekeeping",
produces = MediaType.TEXT_HTML_VALUE,
method = RequestMethod.POST)
public String updateStudyHousekeeping(@ModelAttribute Housekeeping housekeeping,
@PathVariable Long studyId,
RedirectAttributes redirectAttributes) {
// Establish linked study
Study study = studyRepository.findOne(studyId);
// Before we save housekeeping get the status in database so we can check for a change
CurationStatus statusInDatabase = housekeepingRepository.findOne(housekeeping.getId()).getCurationStatus();
// Save housekeeping returned from form straight away to save any curator entered details like notes etc
housekeepingRepository.save(housekeeping);
// For the study check all SNPs have been checked
Collection<Association> associations = associationRepository.findByStudyId(studyId);
int snpsNotChecked = 0;
for (Association association : associations) {
// If we have one that is not checked set value
if (association.getSnpChecked() == false) {
snpsNotChecked = 1;
}
}
// Establish whether user has set status to "Publish study" and "Send to NCBI"
// as corresponding dates will be set in housekeeping table
CurationStatus currentStatus = housekeeping.getCurationStatus();
// If the status has changed
if (currentStatus != statusInDatabase) {
if (currentStatus != null && currentStatus.getStatus().equals("Publish study")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before publishing";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date publishDate = new java.util.Date();
housekeeping.setPublishDate(publishDate);
}
}
//Set date and send email notification
if (currentStatus != null && currentStatus.getStatus().equals("Send to NCBI")) {
// If not checked redirect back to page and make no changes
if (snpsNotChecked == 1) {
// Restore old status
housekeeping.setCurationStatus(statusInDatabase);
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
String message =
"Some SNP associations have not been checked, please review before sending to NCBI";
redirectAttributes.addFlashAttribute("snpsNotChecked", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
else {
java.util.Date sendToNCBIDate = new java.util.Date();
housekeeping.setSendToNCBIDate(sendToNCBIDate);
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Send notification email to curators
if (currentStatus != null && currentStatus.getStatus().equals("Level 1 curation done")) {
mailService.sendEmailNotification(study, currentStatus.getStatus());
}
}
// Save any changes made to housekeeping
housekeepingRepository.save(housekeeping);
// Set study housekeeping
study.setHousekeeping(housekeeping);
// Save our study
studyRepository.save(study);
// Add save message
String message = "Changes saved successfully";
redirectAttributes.addFlashAttribute("changesSaved", message);
return "redirect:/studies/" + study.getId() + "/housekeeping";
}
/* General purpose methods */
private Housekeeping createHousekeeping() {
// Create housekeeping object and create the study added date
Housekeeping housekeeping = new Housekeeping();
java.util.Date studyAddedDate = new java.util.Date();
housekeeping.setStudyAddedDate(studyAddedDate);
// Set status
CurationStatus status = curationStatusRepository.findByStatus("Awaiting Curation");
housekeeping.setCurationStatus(status);
// Set curator
Curator curator = curatorRepository.findByLastName("Level 1 Curator");
housekeeping.setCurator(curator);
// Save housekeeping
housekeepingRepository.save(housekeeping);
// Save housekeeping
return housekeeping;
}
private Study copyStudy(Study studyToDuplicate) {
Study duplicateStudy = new Study();
duplicateStudy.setAuthor(studyToDuplicate.getAuthor() + " DUP");
duplicateStudy.setStudyDate(studyToDuplicate.getStudyDate());
duplicateStudy.setPublication(studyToDuplicate.getPublication());
duplicateStudy.setTitle(studyToDuplicate.getTitle());
duplicateStudy.setInitialSampleSize(studyToDuplicate.getInitialSampleSize());
duplicateStudy.setReplicateSampleSize(studyToDuplicate.getReplicateSampleSize());
duplicateStudy.setPlatform(studyToDuplicate.getPlatform());
duplicateStudy.setPubmedId(studyToDuplicate.getPubmedId());
duplicateStudy.setCnv(studyToDuplicate.getCnv());
duplicateStudy.setGxe(studyToDuplicate.getGxe());
duplicateStudy.setGxg(studyToDuplicate.getGxg());
duplicateStudy.setDiseaseTrait(studyToDuplicate.getDiseaseTrait());
// Deal with EFO traits
Collection<EfoTrait> efoTraits = studyToDuplicate.getEfoTraits();
Collection<EfoTrait> efoTraitsDuplicateStudy = new ArrayList<EfoTrait>();
if (efoTraits != null && !efoTraits.isEmpty()) {
efoTraitsDuplicateStudy.addAll(efoTraits);
duplicateStudy.setEfoTraits(efoTraitsDuplicateStudy);
}
return duplicateStudy;
}
private Ethnicity copyEthnicity(Ethnicity studyToDuplicateEthnicity) {
Ethnicity duplicateEthnicity = new Ethnicity();
duplicateEthnicity.setType(studyToDuplicateEthnicity.getType());
duplicateEthnicity.setNumberOfIndividuals(studyToDuplicateEthnicity.getNumberOfIndividuals());
duplicateEthnicity.setEthnicGroup(studyToDuplicateEthnicity.getEthnicGroup());
duplicateEthnicity.setCountryOfOrigin(studyToDuplicateEthnicity.getCountryOfOrigin());
duplicateEthnicity.setCountryOfRecruitment(studyToDuplicateEthnicity.getCountryOfRecruitment());
duplicateEthnicity.setDescription(studyToDuplicateEthnicity.getDescription());
duplicateEthnicity.setPreviouslyReported(studyToDuplicateEthnicity.getPreviouslyReported());
duplicateEthnicity.setSampleSizesMatch(studyToDuplicateEthnicity.getSampleSizesMatch());
duplicateEthnicity.setNotes(studyToDuplicateEthnicity.getNotes());
return duplicateEthnicity;
}
// Find correct sorting type and direction
private Sort findSort(String sortType) {
// Default sort by date
Sort sort = sortByStudyDateDesc();
Map<String, Sort> sortTypeMap = new HashMap<>();
sortTypeMap.put("authorsortasc", sortByAuthorAsc());
sortTypeMap.put("authorsortdesc", sortByAuthorDesc());
sortTypeMap.put("titlesortasc", sortByTitleAsc());
sortTypeMap.put("titlesortdesc", sortByTitleDesc());
sortTypeMap.put("studydatesortasc", sortByStudyDateAsc());
sortTypeMap.put("studydatesortdesc", sortByStudyDateDesc());
sortTypeMap.put("pubmedsortasc", sortByPubmedIdAsc());
sortTypeMap.put("pubmedsortdesc", sortByPubmedIdDesc());
sortTypeMap.put("publicationsortasc", sortByPublicationAsc());
sortTypeMap.put("publicationsortdesc", sortByPublicationDesc());
sortTypeMap.put("efotraitsortasc", sortByEfoTraitAsc());
sortTypeMap.put("efotraitsortdesc", sortByEfoTraitDesc());
sortTypeMap.put("diseasetraitsortasc", sortByDiseaseTraitAsc());
sortTypeMap.put("diseasetraitsortdesc", sortByDiseaseTraitDesc());
sortTypeMap.put("curatorsortasc", sortByCuratorAsc());
sortTypeMap.put("curatorsortdesc", sortByCuratorDesc());
sortTypeMap.put("curationstatussortasc", sortByCurationStatusAsc());
sortTypeMap.put("curationstatussortdesc", sortByCurationStatusDesc());
if (sortType != null && !sortType.isEmpty()) {
sort = sortTypeMap.get(sortType);
}
return sort;
}
/* Exception handling */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(PubmedLookupException.class)
public String handlePubmedLookupException(PubmedLookupException pubmedLookupException) {
getLog().error("pubmed lookup exception", pubmedLookupException);
return "pubmed_lookup_warning";
}
@ExceptionHandler(PubmedImportException.class)
public String handlePubmedImportException(PubmedImportException pubmedImportException) {
getLog().error("pubmed import exception", pubmedImportException);
return "pubmed_import_warning";
}
/* Model Attributes :
* Used for dropdowns in HTML forms
*/
// Disease Traits
@ModelAttribute("diseaseTraits")
public List<DiseaseTrait> populateDiseaseTraits(Model model) {
return diseaseTraitRepository.findAll(sortByTraitAsc());
}
// EFO traits
@ModelAttribute("efoTraits")
public List<EfoTrait> populateEFOTraits(Model model) {
return efoTraitRepository.findAll(sortByTraitAsc());
}
// Curators
@ModelAttribute("curators")
public List<Curator> populateCurators(Model model) {
return curatorRepository.findAll();
}
// Curation statuses
@ModelAttribute("curationstatuses")
public List<CurationStatus> populateCurationStatuses(Model model) {
return curationStatusRepository.findAll();
}
// Study types
@ModelAttribute("studyTypes")
public List<String> populateStudyTypeOptions(Model model) {
List<String> studyTypesOptions = new ArrayList<String>();
studyTypesOptions.add("GXE");
studyTypesOptions.add("GXG");
studyTypesOptions.add("CNV");
return studyTypesOptions;
}
/* Sorting options */
// Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case
private Sort sortByTraitAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC, "trait").ignoreCase());
}
private Sort sortByStudyDateAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "studyDate"));}
private Sort sortByStudyDateDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "studyDate"));}
private Sort sortByAuthorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "author"));}
private Sort sortByAuthorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "author"));}
private Sort sortByTitleAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "title"));}
private Sort sortByTitleDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "title"));}
private Sort sortByPublicationAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "publication"));}
private Sort sortByPublicationDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "publication"));}
private Sort sortByPubmedIdAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "pubmedId"));}
private Sort sortByPubmedIdDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "pubmedId"));}
private Sort sortByDiseaseTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "diseaseTrait.trait").ignoreCase());}
private Sort sortByDiseaseTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "diseaseTrait.trait").ignoreCase());}
private Sort sortByEfoTraitAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "efoTraits.trait").ignoreCase());}
private Sort sortByEfoTraitDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "efoTraits.trait").ignoreCase());}
private Sort sortByCuratorAsc() {return new Sort(new Sort.Order(Sort.Direction.ASC, "housekeeping.curator"));}
private Sort sortByCuratorDesc() {return new Sort(new Sort.Order(Sort.Direction.DESC, "housekeeping.curator"));}
private Sort sortByCurationStatusAsc() {
return new Sort(new Sort.Order(Sort.Direction.ASC,
"housekeeping.curationStatus"));
}
private Sort sortByCurationStatusDesc() {
return new Sort(new Sort.Order(Sort.Direction.DESC,
"housekeeping.curationStatus"));
}
/* Pagination */
// Pagination, method passed page index and inlcudes max number of studies, sorted by study date, to return
private Pageable constructPageSpecification(int pageIndex, Sort sort) {
Pageable pageSpecification = new PageRequest(pageIndex, MAX_PAGE_ITEM_DISPLAY, sort);
return pageSpecification;
}
}
| Added model attribute that stores list of all authors
| goci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/StudyController.java | Added model attribute that stores list of all authors | <ide><path>oci-interfaces/goci-curation/src/main/java/uk/ac/ebi/spot/goci/curation/controller/StudyController.java
<ide> return "redirect:/studies?page=1&efoTraitId=" + efoTraitId;
<ide> }
<ide>
<add> // Search by string in notes
<ide> else if (notesQuery != null && !notesQuery.isEmpty()) {
<ide> return "redirect:/studies?page=1¬esQuery=" + notesQuery;
<ide> }
<ide> return studyTypesOptions;
<ide> }
<ide>
<add> // Authors
<add> @ModelAttribute("authors")
<add> public List<String> populateAuthors(Model model) {
<add> return studyRepository.findAllStudyAuthors();
<add> }
<add>
<ide>
<ide> /* Sorting options */
<ide> |
|
Java | mit | 498ca59ed3325209be867a7d62751803e4660e40 | 0 | domisum/AuxiliumLib | package de.domisum.lib.auxilium.util;
import de.domisum.lib.auxilium.util.file.DirectoryCopy;
import de.domisum.lib.auxilium.util.file.FileFilter;
import de.domisum.lib.auxilium.util.java.ThreadUtil;
import de.domisum.lib.auxilium.util.java.annotations.API;
import de.domisum.lib.auxilium.util.java.exceptions.ShouldNeverHappenError;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Validate;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Stream;
@API
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class FileUtil
{
// CONSTANTS
@API
public static final Charset DEFAULT_STRING_ENCODING = StandardCharsets.UTF_8;
// TEMP
private static final Collection<File> temporaryDirectories = new ArrayList<>();
// STRING
@API
public static String readString(File file)
{
return readString(file, DEFAULT_STRING_ENCODING);
}
@API
public static String readString(File file, Charset encoding)
{
try
{
byte[] contentBytes = Files.readAllBytes(file.toPath());
return new String(contentBytes, encoding);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeString(File file, String toWrite)
{
writeString(file, toWrite, DEFAULT_STRING_ENCODING);
}
@API
public static void writeString(File file, String toWrite, Charset encoding)
{
try
{
createParentDirectory(file);
FileUtils.writeStringToFile(file, toWrite, encoding);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// RAW
@API
public static byte[] readRaw(File file)
{
try
{
return Files.readAllBytes(file.toPath());
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeRaw(File file, byte[] toWrite)
{
try
{
createParentDirectory(file);
Files.write(file.toPath(), toWrite);
}
catch(ClosedByInterruptException ignored)
{
// ignore this, because the thread was interrupted and no result is expected
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// STREAM
@API
public static void writeStream(File file, InputStream inputStream)
{
try
{
writeStreamUncaught(file, inputStream);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeStreamUncaught(File file, InputStream inputStream) throws IOException
{
createParentDirectory(file);
Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
// IMAGE
@API
public static BufferedImage readImage(File file)
{
try
{
return readImageUncaught(file);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static BufferedImage readImageUncaught(File file) throws IOException
{
if(!file.exists())
throw new FileNotFoundException("file doesn't exist: "+file);
return ImageIO.read(file);
}
@API
public static void writeImage(File file, BufferedImage image)
{
Validate.notNull(file, "file was null");
Validate.notNull(image, "image was null");
try
{
createParentDirectory(file);
ImageIO.write(image, getExtension(file), file);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// COPY
@API
public static void copyFile(File from, File to)
{
if(to.exists() && to.isDirectory())
throw new UncheckedIOException(new IOException("can't copy to file '"+to+"', it is a directory and already exists"));
try
{
createParentDirectory(to);
Files.copy(from.getAbsoluteFile().toPath(), to.getAbsoluteFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void copyDirectory(File sourceRootDirectory, File targetRootDirectory, FileFilter... filters)
{
DirectoryCopy.fromTo(sourceRootDirectory, targetRootDirectory, filters).copy();
}
// DIRECTORY
@API
public static void mkdirs(File dir)
{
if(dir.exists())
return;
dir.mkdirs();
if(!dir.exists())
throw new UncheckedIOException(new IOException("Failed to create directory '"+dir+"'"));
}
@API
public static File getFileInSameDirectory(File file, String otherName)
{
return new File(file.getAbsoluteFile().getParent(), otherName);
}
@API
public static void createParentDirectory(File file)
{
mkdirs(file.getAbsoluteFile().getParentFile());
}
@API
public static void deleteDirectory(File directory)
{
if(!directory.exists())
return;
validateIsNotFile(directory);
deleteDirectoryContents(directory);
deleteFile(directory);
}
@API
public static void deleteDirectoryContents(File directory)
{
if(!directory.exists())
return;
validateIsNotFile(directory);
for(File file : listFilesFlat(directory, FileType.FILE))
deleteFile(file);
for(File dir : listFilesFlat(directory, FileType.DIRECTORY))
deleteDirectory(dir);
}
private static void validateIsNotFile(File directory)
{
if(directory.isFile())
throw new IllegalArgumentException("given directory is file, not directory");
}
@API
public static Collection<File> listFilesFlat(File directory, FileType fileType)
{
return listFiles(directory, fileType, false);
}
@API
public static Collection<File> listFilesRecursively(File directory, FileType fileType)
{
return listFiles(directory, fileType, true);
}
private static Collection<File> listFiles(File directory, FileType fileType, boolean recursive)
{
validateIsNotFile(directory);
if(!directory.exists())
return Collections.emptySet();
Collection<File> directoryContents = new ConcurrentLinkedQueue<>();
try(Stream<Path> stream = Files.list(directory.toPath()))
{
stream.parallel().map(Path::toFile).forEach(f->
{
if(fileType.isOfType(f))
directoryContents.add(f);
if(recursive && f.isDirectory())
directoryContents.addAll(listFilesRecursively(f, fileType));
});
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
return directoryContents;
}
// TEMP
@API
public static File getNonExistentTemporaryFile(String extension)
{
File temporaryFile = createTemporaryFile(extension);
String path = temporaryFile.getPath();
deleteFile(temporaryFile);
return new File(path);
}
@API
public static File createTemporaryFile()
{
return createTemporaryFile(null);
}
@API
public static File createTemporaryFile(String extension)
{
String cleanedExtension = extension;
if(cleanedExtension == null)
cleanedExtension = ".tmp";
if(!cleanedExtension.startsWith("."))
cleanedExtension = "."+cleanedExtension;
try
{
File file = File.createTempFile("tempFile", cleanedExtension);
file.deleteOnExit();
return file;
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static File createTemporaryDirectory()
{
try
{
File directory = Files.createTempDirectory("tempDirectory").toFile();
deleteDirectoryOnShutdown(directory);
return directory;
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
private static synchronized void deleteDirectoryOnShutdown(File directory)
{
if(temporaryDirectories.isEmpty())
ThreadUtil.registerShutdownHook(()->temporaryDirectories.forEach(FileUtil::deleteDirectory));
temporaryDirectories.add(directory);
}
@API
public static File getTempDirectory()
{
return getNonExistentTemporaryFile("shouldBeDeletedInstantly").getAbsoluteFile().getParentFile();
}
// GENERAL FILE
@API
public static boolean createFile(File file)
{
try
{
return file.createNewFile();
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void delete(File file)
{
if(file.isDirectory())
deleteDirectory(file);
else
deleteFile(file);
}
@API
public static void deleteFile(File file)
{
try
{
if(file.exists())
Files.delete(file.toPath());
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static String getExtension(File file)
{
return getExtension(file.getName());
}
/**
* Returns the exension of the file without a preceding dot.
*
* @param fileName the name of the file of which to determine the extension
* @return file extension without dot
*/
@API
public static String getExtension(String fileName)
{
return FilenameUtils.getExtension(fileName);
}
@API
public static String getCompositeExtension(File file)
{
String fileName = file.getName();
if(!fileName.contains("."))
return "";
return fileName.substring(fileName.indexOf('.'));
}
@API
public static String getNameWithoutCompositeExtension(File file)
{
String compositeFileExtension = getCompositeExtension(file);
String fileName = file.getName();
String fileNameWithout = fileName.substring(0, fileName.length()-compositeFileExtension.length());
return fileNameWithout;
}
@API
public static String getFilePath(File file)
{
String path = file.getAbsoluteFile().getPath();
path = unifyDelimiters(path);
return path;
}
@API
public static String unifyDelimiters(String path)
{
return path.replaceAll(StringUtil.escapeStringForRegex("\\"), "/");
}
@API
public static Instant getContentLastModified(File file)
{
if(!file.isDirectory())
return getLastModified(file);
Collection<File> files = listFilesFlat(file, FileType.FILE_AND_DIRECTORY);
if(files.isEmpty())
return getLastModified(file);
Instant mostRecentModified = Instant.MIN;
for(File f : files)
{
Instant fLastModified = getContentLastModified(f);
if(fLastModified.compareTo(mostRecentModified) > 0)
mostRecentModified = fLastModified;
}
return mostRecentModified;
}
@API
public static Instant getLastModified(File file)
{
return Instant.ofEpochMilli(file.lastModified());
}
public enum FileType
{
FILE,
DIRECTORY,
FILE_AND_DIRECTORY;
public boolean isOfType(File file)
{
if(!file.exists())
throw new IllegalArgumentException("file does not exist: "+file);
if(this == FILE_AND_DIRECTORY)
return true;
else if(this == FILE)
return file.isFile();
else if(this == DIRECTORY)
return file.isDirectory();
throw new ShouldNeverHappenError("unknown file type: "+this);
}
}
}
| src/main/java/de/domisum/lib/auxilium/util/FileUtil.java | package de.domisum.lib.auxilium.util;
import de.domisum.lib.auxilium.util.file.DirectoryCopy;
import de.domisum.lib.auxilium.util.file.FileFilter;
import de.domisum.lib.auxilium.util.java.ThreadUtil;
import de.domisum.lib.auxilium.util.java.annotations.API;
import de.domisum.lib.auxilium.util.java.exceptions.ShouldNeverHappenError;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.Validate;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Stream;
@API
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class FileUtil
{
// CONSTANTS
@API
public static final Charset DEFAULT_STRING_ENCODING = StandardCharsets.UTF_8;
// TEMP
private static final Collection<File> temporaryDirectories = new ArrayList<>();
// STRING
@API
public static String readString(File file)
{
return readString(file, DEFAULT_STRING_ENCODING);
}
@API
public static String readString(File file, Charset encoding)
{
try
{
byte[] contentBytes = Files.readAllBytes(file.toPath());
return new String(contentBytes, encoding);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeString(File file, String toWrite)
{
writeString(file, toWrite, DEFAULT_STRING_ENCODING);
}
@API
public static void writeString(File file, String toWrite, Charset encoding)
{
try
{
createParentDirectory(file);
FileUtils.writeStringToFile(file, toWrite, encoding);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// RAW
@API
public static byte[] readRaw(File file)
{
try
{
return Files.readAllBytes(file.toPath());
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeRaw(File file, byte[] toWrite)
{
try
{
createParentDirectory(file);
Files.write(file.toPath(), toWrite);
}
catch(ClosedByInterruptException ignored)
{
// ignore this, because the thread was interrupted and no result is expected
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// STREAM
@API
public static void writeStream(File file, InputStream inputStream)
{
try
{
writeStreamUncaught(file, inputStream);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void writeStreamUncaught(File file, InputStream inputStream) throws IOException
{
createParentDirectory(file);
Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
// IMAGE
@API
public static BufferedImage readImage(File file)
{
try
{
return readImageUncaught(file);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static BufferedImage readImageUncaught(File file) throws IOException
{
if(!file.exists())
throw new FileNotFoundException("file doesn't exist: "+file);
return ImageIO.read(file);
}
@API
public static void writeImage(File file, BufferedImage image)
{
Validate.notNull(file, "file was null");
Validate.notNull(image, "image was null");
try
{
createParentDirectory(file);
ImageIO.write(image, getExtension(file), file);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
// COPY
@API
public static void copyFile(File from, File to)
{
if(to.exists() && to.isDirectory())
throw new UncheckedIOException(new IOException("can't copy to file '"+to+"', it is a directory and already exists"));
try
{
createParentDirectory(to);
Files.copy(from.getAbsoluteFile().toPath(), to.getAbsoluteFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void copyDirectory(File sourceRootDirectory, File targetRootDirectory, FileFilter... filters)
{
DirectoryCopy.fromTo(sourceRootDirectory, targetRootDirectory, filters).copy();
}
// DIRECTORY
@API
public static void mkdirs(File dir)
{
if(dir.exists())
return;
boolean success = dir.mkdirs();
if(!success)
throw new UncheckedIOException(new IOException(
"Failed to create directory (and possibly parent directories) of "+dir));
}
@API
public static File getFileInSameDirectory(File file, String otherName)
{
return new File(file.getAbsoluteFile().getParent(), otherName);
}
@API
public static void createParentDirectory(File file)
{
mkdirs(file.getAbsoluteFile().getParentFile());
}
@API
public static void deleteDirectory(File directory)
{
if(!directory.exists())
return;
validateIsNotFile(directory);
deleteDirectoryContents(directory);
deleteFile(directory);
}
@API
public static void deleteDirectoryContents(File directory)
{
if(!directory.exists())
return;
validateIsNotFile(directory);
for(File file : listFilesFlat(directory, FileType.FILE))
deleteFile(file);
for(File dir : listFilesFlat(directory, FileType.DIRECTORY))
deleteDirectory(dir);
}
private static void validateIsNotFile(File directory)
{
if(directory.isFile())
throw new IllegalArgumentException("given directory is file, not directory");
}
@API
public static Collection<File> listFilesFlat(File directory, FileType fileType)
{
return listFiles(directory, fileType, false);
}
@API
public static Collection<File> listFilesRecursively(File directory, FileType fileType)
{
return listFiles(directory, fileType, true);
}
private static Collection<File> listFiles(File directory, FileType fileType, boolean recursive)
{
validateIsNotFile(directory);
if(!directory.exists())
return Collections.emptySet();
Collection<File> directoryContents = new ConcurrentLinkedQueue<>();
try(Stream<Path> stream = Files.list(directory.toPath()))
{
stream.parallel().map(Path::toFile).forEach(f->
{
if(fileType.isOfType(f))
directoryContents.add(f);
if(recursive && f.isDirectory())
directoryContents.addAll(listFilesRecursively(f, fileType));
});
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
return directoryContents;
}
// TEMP
@API
public static File getNonExistentTemporaryFile(String extension)
{
File temporaryFile = createTemporaryFile(extension);
String path = temporaryFile.getPath();
deleteFile(temporaryFile);
return new File(path);
}
@API
public static File createTemporaryFile()
{
return createTemporaryFile(null);
}
@API
public static File createTemporaryFile(String extension)
{
String cleanedExtension = extension;
if(cleanedExtension == null)
cleanedExtension = ".tmp";
if(!cleanedExtension.startsWith("."))
cleanedExtension = "."+cleanedExtension;
try
{
File file = File.createTempFile("tempFile", cleanedExtension);
file.deleteOnExit();
return file;
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static File createTemporaryDirectory()
{
try
{
File directory = Files.createTempDirectory("tempDirectory").toFile();
deleteDirectoryOnShutdown(directory);
return directory;
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
private static synchronized void deleteDirectoryOnShutdown(File directory)
{
if(temporaryDirectories.isEmpty())
ThreadUtil.registerShutdownHook(()->temporaryDirectories.forEach(FileUtil::deleteDirectory));
temporaryDirectories.add(directory);
}
@API
public static File getTempDirectory()
{
return getNonExistentTemporaryFile("shouldBeDeletedInstantly").getAbsoluteFile().getParentFile();
}
// GENERAL FILE
@API
public static boolean createFile(File file)
{
try
{
return file.createNewFile();
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static void delete(File file)
{
if(file.isDirectory())
deleteDirectory(file);
else
deleteFile(file);
}
@API
public static void deleteFile(File file)
{
try
{
if(file.exists())
Files.delete(file.toPath());
}
catch(IOException e)
{
throw new UncheckedIOException(e);
}
}
@API
public static String getExtension(File file)
{
return getExtension(file.getName());
}
/**
* Returns the exension of the file without a preceding dot.
*
* @param fileName the name of the file of which to determine the extension
* @return file extension without dot
*/
@API
public static String getExtension(String fileName)
{
return FilenameUtils.getExtension(fileName);
}
@API
public static String getCompositeExtension(File file)
{
String fileName = file.getName();
if(!fileName.contains("."))
return "";
return fileName.substring(fileName.indexOf('.'));
}
@API
public static String getNameWithoutCompositeExtension(File file)
{
String compositeFileExtension = getCompositeExtension(file);
String fileName = file.getName();
String fileNameWithout = fileName.substring(0, fileName.length()-compositeFileExtension.length());
return fileNameWithout;
}
@API
public static String getFilePath(File file)
{
String path = file.getAbsoluteFile().getPath();
path = unifyDelimiters(path);
return path;
}
@API
public static String unifyDelimiters(String path)
{
return path.replaceAll(StringUtil.escapeStringForRegex("\\"), "/");
}
@API
public static Instant getContentLastModified(File file)
{
if(!file.isDirectory())
return getLastModified(file);
Collection<File> files = listFilesFlat(file, FileType.FILE_AND_DIRECTORY);
if(files.isEmpty())
return getLastModified(file);
Instant mostRecentModified = Instant.MIN;
for(File f : files)
{
Instant fLastModified = getContentLastModified(f);
if(fLastModified.compareTo(mostRecentModified) > 0)
mostRecentModified = fLastModified;
}
return mostRecentModified;
}
@API
public static Instant getLastModified(File file)
{
return Instant.ofEpochMilli(file.lastModified());
}
public enum FileType
{
FILE,
DIRECTORY,
FILE_AND_DIRECTORY;
public boolean isOfType(File file)
{
if(!file.exists())
throw new IllegalArgumentException("file does not exist: "+file);
if(this == FILE_AND_DIRECTORY)
return true;
else if(this == FILE)
return file.isFile();
else if(this == DIRECTORY)
return file.isDirectory();
throw new ShouldNeverHappenError("unknown file type: "+this);
}
}
}
| Changed mkdirs failure condition
| src/main/java/de/domisum/lib/auxilium/util/FileUtil.java | Changed mkdirs failure condition | <ide><path>rc/main/java/de/domisum/lib/auxilium/util/FileUtil.java
<ide> if(dir.exists())
<ide> return;
<ide>
<del> boolean success = dir.mkdirs();
<del> if(!success)
<del> throw new UncheckedIOException(new IOException(
<del> "Failed to create directory (and possibly parent directories) of "+dir));
<add> dir.mkdirs();
<add> if(!dir.exists())
<add> throw new UncheckedIOException(new IOException("Failed to create directory '"+dir+"'"));
<ide> }
<ide>
<ide> @API |
|
JavaScript | mit | 04c271964d6cc3269865c47aee95bfbd392a593c | 0 | simonfork/paranoid-auto-spacing,vinta/paranoid-auto-spacing,vinta/pangu.js,simonfork/paranoid-auto-spacing,vinta/pangu.js,vinta/paranoid-auto-spacing,7kfpun/paranoid-auto-spacing,7kfpun/paranoid-auto-spacing | (function(pangu) {
/*
1.
硬幹 contentEditable 元素的 child nodes 還是會被 spacing 的問題
因為 contentEditable 的值可能是 'true', 'false', 'inherit'
如果沒有顯式地指定 contentEditable 的值
一般都會是 'inherit' 而不是 'false'
2.
不要對特定 tag 裡的文字加空格
關於這個我還不是很確定
所以先註解掉
TODO:
太暴力了,應該有更好的解法
*/
function can_ignore_node(node) {
var parent_node = node.parentNode;
// var ignore_tags = /^(code|pre)$/i;
// var ignore_tags = /^(textarea)$/i;
while (parent_node) {
if (parent_node.contentEditable == 'true') {
return true;
}
// else if (parent_node.nodeName.search(ignore_tags) >= 0) {
// return true;
// }
else {
parent_node = parent_node.parentNode;
}
}
return false;
}
/*
nodeType: http://www.w3schools.com/dom/dom_nodetype.asp
1: ELEMENT_NODE
3: TEXT_NODE
8: COMMENT_NODE
*/
function is_first_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
// 只判斷第一個含有 text 的 node
for (var i = 0; i < child_nodes.length; i++) {
child_node = child_nodes[i];
if (child_node.nodeType != 8 && child_node.textContent) {
return child_node == target_node;
}
}
return false;
}
function is_last_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
// 只判斷倒數第一個含有 text 的 node
for (var i = child_nodes.length - 1; i > -1; i--) {
child_node = child_nodes[i];
if (child_node.nodeType != 8 && child_node.textContent) {
return child_node == target_node;
}
}
return false;
}
function insert_space(text) {
var old_text = text;
var new_text;
/*
~!@#$%^&*()_+`-=
[]\{}|
:;"'
<>?,./
3000−303F 中日韩符号和标点
3040−309F 日文平假名
30A0−30FF 日文片假名
3100−312F 注音字母
4E00−9FFF 中日韩统一表意文字
F900−FAFF 中日韩兼容表意文字
http://unicode-table.com/cn/
*/
// 前面"字"後面 >> 前面 "字" 後面
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])(["'#])/ig, '$1 $2');
text = text.replace(/(["'#])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
// 避免出現 '前面 " 字" 後面' 之類的不對稱的情況
text = text.replace(/(["'#]+)(\s*)(.*?)(\s*)(["'#]+)/ig, '$1$3$5');
// 1. 前面<字>後面 --> 前面 <字> 後面
old_text = text
new_text = old_text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<\[\{\(]+(.*?)[>\]\}\)]+)([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2 $4');
text = new_text
if (old_text == new_text) {
// 前面<後面 --> 前面 < 後面
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
}
// 避免出現 "前面 [ 字] 後面" 之類的不對稱的情況
text = text.replace(/([<\[\{\(]+)(\s*)(.*?)(\s*)([>\]\}\)]+)/ig, '$1$3$5');
// 2. 前面<字>後面 --> 前面 < 字 > 後面
// text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
// text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
// 中文在前
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([a-z0-9@&=`\|\$\%\^\*\-\+\/\\])/ig, '$1 $2');
// 中文在後
text = text.replace(/([a-z0-9!~&;=`\|\,\.\:\?\$\%\^\*\-\+\/\\])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
return text;
}
function spacing(xpath_query) {
// 是否加了空格
var had_spacing = false;
/*
因為 xpath_query 用的是 text(),所以這些 nodes 是 text 而不是 DOM element
https://developer.mozilla.org/en-US/docs/DOM/document.evaluate
http://www.w3cschool.cn/dom_xpathresult.html
snapshotLength 要配合 XPathResult.ORDERED_NODE_SNAPSHOT_TYPE 使用
*/
var text_nodes = document.evaluate(xpath_query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var nodes_length = text_nodes.snapshotLength;
var next_text_node;
// 從最下面、最裡面的節點開始
for (var i = nodes_length - 1; i > -1; --i) {
var current_text_node = text_nodes.snapshotItem(i);
// console.log('current_text_node: %O, nextSibling: %O', current_text_node.data, current_text_node.nextSibling);
// console.log('next_text_node: %O', next_text_node);
if (can_ignore_node(current_text_node)) {
next_text_node = current_text_node;
continue;
}
// http://www.w3school.com.cn/xmldom/dom_text.asp
var new_data = insert_space(current_text_node.data);
if (current_text_node.data != new_data) {
had_spacing = true;
current_text_node.data = new_data;
}
// 處理嵌套的 <tag> 中的文字
if (next_text_node) {
/*
TODO:
現在只是簡單地判斷相鄰的下一個 node 是不是 <br>
萬一遇上嵌套的標籤就不行了
*/
if (current_text_node.nextSibling) {
if (current_text_node.nextSibling.nodeName.search(/^(br|hr)$/i) >= 0) {
next_text_node = current_text_node;
continue;
}
}
// current_text_node 的最後一個字 + next_text_node 的第一個字
var text = current_text_node.data.toString().substr(-1) + next_text_node.data.toString().substr(0, 1);
var new_text = insert_space(text);
if (text != new_text) {
had_spacing = true;
/*
基本上
next_node 就是 next_text_node 的 parent node
current_node 就是 current_text_node 的 parent node
*/
// 不要把空格加在 <space_sensitive_tags> 裡的文字的開頭或結尾
var space_sensitive_tags = /^(a|del|pre|s|strike|u)$/i;
var block_tags = /^(div|h1|h2|h3|h4|h5|h6|p)$/i;
/*
往上找 next_text_node 的 parent node
直到遇到 space_sensitive_tags
而且 next_text_node 必須是第一個 text child
才能把空格加在 next_text_node 的前面
*/
var next_node = next_text_node;
while (next_node.parentNode
&& next_node.nodeName.search(space_sensitive_tags) == -1
&& is_first_text_child(next_node.parentNode, next_node)) {
next_node = next_node.parentNode;
}
// console.log('next_node: %O', next_node);
var current_node = current_text_node;
while (current_node.parentNode
&& current_node.nodeName.search(space_sensitive_tags) == -1
&& is_last_text_child(current_node.parentNode, current_node)) {
current_node = current_node.parentNode;
}
// console.log('current_node: %O, nextSibling: %O', current_node, current_node.nextSibling);
if (current_node.nodeName.search(block_tags) == -1) {
if (next_node.nodeName.search(space_sensitive_tags) == -1) {
if (next_node.nodeName.search(block_tags) == -1) {
// console.log('spacing 1: %O', next_text_node.data);
next_text_node.data = " " + next_text_node.data;
}
}
else if (current_node.nodeName.search(space_sensitive_tags) == -1) {
// console.log('spacing 2: %O', current_text_node.data);
current_text_node.data = current_text_node.data + " ";
}
else {
// console.log('spacing 3: %O', next_node.parentNode);
next_node.parentNode.insertBefore(document.createTextNode(" "), next_node);
}
}
}
}
next_text_node = current_text_node;
}
return had_spacing;
}
pangu.text_spacing = function(text) {
return insert_space(text);
};
pangu.page_spacing = function() {
// var p = 'page_spacing';
// console.profile(p);
// console.time(p);
// var start = new Date().getTime();
/*
// >> 任意位置的節點
. >> 當前節點
.. >> 父節點
[] >> 條件
text() >> 節點的文字內容,例如 hello 之於 <tag>hello</tag>
[@contenteditable]
帶有 contenteditable 屬性的節點
normalize-space(.)
當前節點的頭尾的空白字元都會被移除,大於兩個以上的空白字元會被置換成單一空白
https://developer.mozilla.org/en-US/docs/XPath/Functions/normalize-space
name(..)
父節點的名稱
https://developer.mozilla.org/en-US/docs/XPath/Functions/name
translate(string, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
將 string 轉換成小寫,因為 XML 是 case-sensitive 的
https://developer.mozilla.org/en-US/docs/XPath/Functions/translate
1. 處理 <title>
2. 處理 <body> 底下的節點
3. 略過 contentEditable 的節點
4. 略過特定節點,例如 <script> 和 <style>
注意,以下的 query 只會取出各節點的 text 內容!
*/
var title_query = '/html/head/title/text()';
spacing(title_query);
var body_query = '/html/body//*[not(@contenteditable)]/text()[normalize-space(.)]';
var body_query = '/html/body//*/text()[normalize-space(.)]';
['script', 'style', 'textarea'].forEach(function(tag) {
/*
理論上這幾個 tag 裡面不會包含其他 tag
所以可以直接用 .. 取父節點
ex: [translate(name(..), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") != "script"]
*/
body_query += '[translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="' + tag + '"]';
});
var had_spacing = spacing(body_query);
// console.profileEnd(p);
// console.timeEnd(p);
// var end = new Date().getTime();
// console.log(end - start);
return had_spacing;
};
pangu.element_spacing = function(selector_string) {
var xpath_query;
if (selector_string.indexOf('#') === 0) {
var target_id = selector_string.substr(1, selector_string.length - 1);
// ex: id("id_name")//text()
xpath_query = 'id("' + target_id + '")//text()';
}
else if (selector_string.indexOf('.') === 0) {
var target_class = selector_string.slice(1);
// ex: //*[contains(concat(' ', normalize-space(@class), ' '), ' class_name ')]/text()
xpath_query = '//*[contains(concat(" ", normalize-space(@class), " "), " ' + target_class + ' ")]/text()';
}
else {
var target_tag = selector_string;
// ex: //tag_name/text()
xpath_query = '//' + target_tag + '//text()';
}
var had_spacing = spacing(xpath_query);
return had_spacing;
};
}(window.pangu = window.pangu || {}));
| src/pangu.js | (function(pangu) {
/*
1.
硬幹 contentEditable 元素的 child nodes 還是會被 spacing 的問題
因為 contentEditable 的值可能是 'true', 'false', 'inherit'
如果沒有顯式地指定 contentEditable 的值
一般都會是 'inherit' 而不是 'false'
2.
不要對特定 tag 裡的文字加空格
關於這個我還不是很確定
所以先註解掉
TODO:
太暴力了,應該有更好的解法
*/
function can_ignore_node(node) {
var parent_node = node.parentNode;
// var ignore_tags = /^(code|pre)$/i;
// var ignore_tags = /^(textarea)$/i;
while (parent_node) {
if (parent_node.contentEditable == 'true') {
return true;
}
// else if (parent_node.nodeName.search(ignore_tags) >= 0) {
// return true;
// }
else {
parent_node = parent_node.parentNode;
}
}
return false;
}
/*
nodeType: http://www.w3schools.com/dom/dom_nodetype.asp
1: ELEMENT_NODE
3: TEXT_NODE
8: COMMENT_NODE
*/
function is_first_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
// 只判斷第一個含有 text 的 node
for (var i = 0; i < child_nodes.length; i++) {
child_node = child_nodes[i];
if (child_node.nodeType != 8 && child_node.textContent) {
return child_node == target_node;
}
}
return false;
}
function is_last_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
// 只判斷倒數第一個含有 text 的 node
for (var i = child_nodes.length - 1; i > -1; i--) {
child_node = child_nodes[i];
if (child_node.nodeType != 8 && child_node.textContent) {
return child_node == target_node;
}
}
return false;
}
function insert_space(text) {
var old_text = text;
var new_text;
/*
~!@#$%^&*()_+`-=
[]\{}|
:;"'
<>?,./
中文 ([\u4E00-\u9FFF])
日文 ([\u3040-\u30FF])
http://www.diybl.com/course/6_system/linux/Linuxjs/20090426/165435.html
*/
// 前面"字"後面 >> 前面 "字" 後面
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])(["'#](\S+))/ig, '$1 $2');
text = text.replace(/((\S+)["'#])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $3'); // $2 是 (\S+)
// 1. 前面<字>後面 --> 前面 <字> 後面
old_text = text
new_text = old_text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<\[\{\(]+(.*?)[>\]\}\)]+)([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2 $4');
text = new_text
if (old_text == new_text) {
// 前面<後面 --> 前面 < 後面
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
}
// 避免出現 "前面 [ 中文123] 後面" 之類的不對稱的情況
text = text.replace(/([<\[\{\(]+)(\s*)(.*?)(\s*)([>\]\}\)]+)/ig, '$1$3$5');
// // 2. 前面<字>後面 --> 前面 < 字 > 後面
// text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
// text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
// 中文在前
text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([a-z0-9@&=`\|\$\%\^\*\-\+\/\\])/ig, '$1 $2');
// 中文在後
text = text.replace(/([a-z0-9!~&;=`\|\,\.\:\?\$\%\^\*\-\+\/\\])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
return text;
}
function spacing(xpath_query) {
// 是否加了空格
var had_spacing = false;
/*
因為 xpath_query 用的是 text(),所以這些 nodes 是 text 而不是 DOM element
https://developer.mozilla.org/en-US/docs/DOM/document.evaluate
http://www.w3cschool.cn/dom_xpathresult.html
snapshotLength 要配合 XPathResult.ORDERED_NODE_SNAPSHOT_TYPE 使用
*/
var text_nodes = document.evaluate(xpath_query, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var nodes_length = text_nodes.snapshotLength;
var next_text_node;
// 從最下面、最裡面的節點開始
for (var i = nodes_length - 1; i > -1; --i) {
var current_text_node = text_nodes.snapshotItem(i);
// console.log('current_text_node: %O, nextSibling: %O', current_text_node.data, current_text_node.nextSibling);
// console.log('next_text_node: %O', next_text_node);
if (can_ignore_node(current_text_node)) {
next_text_node = current_text_node;
continue;
}
// http://www.w3school.com.cn/xmldom/dom_text.asp
var new_data = insert_space(current_text_node.data);
if (current_text_node.data != new_data) {
had_spacing = true;
current_text_node.data = new_data;
}
// 處理嵌套的 <tag> 中的文字
if (next_text_node) {
/*
TODO:
現在只是簡單地判斷相鄰的下一個 node 是不是 <br>
萬一遇上嵌套的標籤就不行了
*/
if (current_text_node.nextSibling) {
if (current_text_node.nextSibling.nodeName.search(/^(br|hr)$/i) >= 0) {
next_text_node = current_text_node;
continue;
}
}
// current_text_node 的最後一個字 + next_text_node 的第一個字
var text = current_text_node.data.toString().substr(-1) + next_text_node.data.toString().substr(0, 1);
var new_text = insert_space(text);
if (text != new_text) {
had_spacing = true;
/*
基本上
next_node 就是 next_text_node 的 parent node
current_node 就是 current_text_node 的 parent node
*/
// 不要把空格加在 <space_sensitive_tags> 裡的文字的開頭或結尾
var space_sensitive_tags = /^(a|del|pre|s|strike|u)$/i;
var block_tags = /^(div|h1|h2|h3|h4|h5|h6|p)$/i;
/*
往上找 next_text_node 的 parent node
直到遇到 space_sensitive_tags
而且 next_text_node 必須是第一個 text child
才能把空格加在 next_text_node 的前面
*/
var next_node = next_text_node;
while (next_node.parentNode
&& next_node.nodeName.search(space_sensitive_tags) == -1
&& is_first_text_child(next_node.parentNode, next_node)) {
next_node = next_node.parentNode;
}
// console.log('next_node: %O', next_node);
var current_node = current_text_node;
while (current_node.parentNode
&& current_node.nodeName.search(space_sensitive_tags) == -1
&& is_last_text_child(current_node.parentNode, current_node)) {
current_node = current_node.parentNode;
}
// console.log('current_node: %O, nextSibling: %O', current_node, current_node.nextSibling);
if (current_node.nodeName.search(block_tags) == -1) {
if (next_node.nodeName.search(space_sensitive_tags) == -1) {
if (next_node.nodeName.search(block_tags) == -1) {
// console.log('spacing 1: %O', next_text_node.data);
next_text_node.data = " " + next_text_node.data;
}
}
else if (current_node.nodeName.search(space_sensitive_tags) == -1) {
// console.log('spacing 2: %O', current_text_node.data);
current_text_node.data = current_text_node.data + " ";
}
else {
// console.log('spacing 3: %O', next_node.parentNode);
next_node.parentNode.insertBefore(document.createTextNode(" "), next_node);
}
}
}
}
next_text_node = current_text_node;
}
return had_spacing;
}
pangu.text_spacing = function(text) {
return insert_space(text);
};
pangu.page_spacing = function() {
// var p = 'page_spacing';
// console.profile(p);
// console.time(p);
// var start = new Date().getTime();
/*
// >> 任意位置的節點
. >> 當前節點
.. >> 父節點
[] >> 條件
text() >> 節點的文字內容,例如 hello 之於 <tag>hello</tag>
[@contenteditable]
帶有 contenteditable 屬性的節點
normalize-space(.)
當前節點的頭尾的空白字元都會被移除,大於兩個以上的空白字元會被置換成單一空白
https://developer.mozilla.org/en-US/docs/XPath/Functions/normalize-space
name(..)
父節點的名稱
https://developer.mozilla.org/en-US/docs/XPath/Functions/name
translate(string, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")
將 string 轉換成小寫,因為 XML 是 case-sensitive 的
https://developer.mozilla.org/en-US/docs/XPath/Functions/translate
1. 處理 <title>
2. 處理 <body> 底下的節點
3. 略過 contentEditable 的節點
4. 略過特定節點,例如 <script> 和 <style>
注意,以下的 query 只會取出各節點的 text 內容!
*/
var title_query = '/html/head/title/text()';
spacing(title_query);
var body_query = '/html/body//*[not(@contenteditable)]/text()[normalize-space(.)]';
var body_query = '/html/body//*/text()[normalize-space(.)]';
['script', 'style', 'textarea'].forEach(function(tag) {
/*
理論上這幾個 tag 裡面不會包含其他 tag
所以可以直接用 .. 取父節點
ex: [translate(name(..), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz") != "script"]
*/
body_query += '[translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="' + tag + '"]';
});
var had_spacing = spacing(body_query);
// console.profileEnd(p);
// console.timeEnd(p);
// var end = new Date().getTime();
// console.log(end - start);
return had_spacing;
};
pangu.element_spacing = function(selector_string) {
var xpath_query;
if (selector_string.indexOf('#') === 0) {
var target_id = selector_string.substr(1, selector_string.length - 1);
// ex: id("id_name")//text()
xpath_query = 'id("' + target_id + '")//text()';
}
else if (selector_string.indexOf('.') === 0) {
var target_class = selector_string.slice(1);
// ex: //*[contains(concat(' ', normalize-space(@class), ' '), ' class_name ')]/text()
xpath_query = '//*[contains(concat(" ", normalize-space(@class), " "), " ' + target_class + ' ")]/text()';
}
else {
var target_tag = selector_string;
// ex: //tag_name/text()
xpath_query = '//' + target_tag + '//text()';
}
var had_spacing = spacing(xpath_query);
return had_spacing;
};
}(window.pangu = window.pangu || {}));
| 鬼燈就在細節裡
| src/pangu.js | 鬼燈就在細節裡 | <ide><path>rc/pangu.js
<ide> :;"'
<ide> <>?,./
<ide>
<del> 中文 ([\u4E00-\u9FFF])
<del> 日文 ([\u3040-\u30FF])
<del> http://www.diybl.com/course/6_system/linux/Linuxjs/20090426/165435.html
<add> 3000−303F 中日韩符号和标点
<add> 3040−309F 日文平假名
<add> 30A0−30FF 日文片假名
<add> 3100−312F 注音字母
<add> 4E00−9FFF 中日韩统一表意文字
<add> F900−FAFF 中日韩兼容表意文字
<add> http://unicode-table.com/cn/
<ide> */
<ide>
<ide> // 前面"字"後面 >> 前面 "字" 後面
<del> text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])(["'#](\S+))/ig, '$1 $2');
<del> text = text.replace(/((\S+)["'#])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $3'); // $2 是 (\S+)
<add> text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])(["'#])/ig, '$1 $2');
<add> text = text.replace(/(["'#])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
<add>
<add> // 避免出現 '前面 " 字" 後面' 之類的不對稱的情況
<add> text = text.replace(/(["'#]+)(\s*)(.*?)(\s*)(["'#]+)/ig, '$1$3$5');
<ide>
<ide> // 1. 前面<字>後面 --> 前面 <字> 後面
<ide> old_text = text
<ide> text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
<ide> text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
<ide> }
<del> // 避免出現 "前面 [ 中文123] 後面" 之類的不對稱的情況
<add> // 避免出現 "前面 [ 字] 後面" 之類的不對稱的情況
<ide> text = text.replace(/([<\[\{\(]+)(\s*)(.*?)(\s*)([>\]\}\)]+)/ig, '$1$3$5');
<ide>
<del> // // 2. 前面<字>後面 --> 前面 < 字 > 後面
<add> // 2. 前面<字>後面 --> 前面 < 字 > 後面
<ide> // text = text.replace(/([\u4e00-\u9fa5\u3040-\u30FF])([<>\[\]\{\}\(\)])/ig, '$1 $2');
<ide> // text = text.replace(/([<>\[\]\{\}\(\)])([\u4e00-\u9fa5\u3040-\u30FF])/ig, '$1 $2');
<ide> |
|
JavaScript | mit | 9dd94d3b46a4d4d6a3c62b3af3f50d45a5c40702 | 0 | DesoGit/Tsunami_PS,Mystifi/Exiled,DarkSuicune/Pokemon-Showdown,azum4roll/Pokemon-Showdown,Sora-League/Sora,SolarisFox/Pokemon-Showdown,DesoGit/Tsunami_PS,AWailOfATail/Pokemon-Showdown,Mystifi/Exiled,Kokonoe-san/Glacia-PS,EienSeiryuu/Pokemon-Showdown,Sora-League/Sora,azum4roll/Pokemon-Showdown,xfix/Pokemon-Showdown,Enigami/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,cadaeic/Pokemon-Showdown,Enigami/Pokemon-Showdown,TbirdClanWish/Pokemon-Showdown,Git-Worm/City-PS,danpantry/Pokemon-Showdown,Pikachuun/Pokemon-Showdown,zek7rom/SpacialGaze,svivian/Pokemon-Showdown,zek7rom/SpacialGaze,AustinXII/Pokemon-Showdown,panpawn/Gold-Server,Guernouille/Pokemon-Showdown,HoeenCoder/SpacialGaze,aakashrajput/Pokemon-Showdown,AnaRitaTorres/Pokemon-Showdown,AWailOfATail/Pokemon-Showdown,Zarel/Pokemon-Showdown,svivian/Pokemon-Showdown,KewlStatics/Alliance,CreaturePhil/Showdown-Boilerplate,HoeenCoder/SpacialGaze,aakashrajput/Pokemon-Showdown,urkerab/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,svivian/Pokemon-Showdown,Guernouille/Pokemon-Showdown,panpawn/Gold-Server,CreaturePhil/Showdown-Boilerplate,panpawn/Pokemon-Showdown,jd4564/Pokemon-Showdown,xfix/Pokemon-Showdown,sirDonovan/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,xCrystal/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,danpantry/Pokemon-Showdown,KewlStatics/Shit,sirDonovan/Pokemon-Showdown,PS-Spectral/Spectral,QuiteQuiet/Pokemon-Showdown,QuiteQuiet/Pokemon-Showdown,Enigami/Pokemon-Showdown,xfix/Pokemon-Showdown,Mystifi/Exiled,xfix/Pokemon-Showdown,DarkSuicune/Pokemon-Showdown,svivian/Pokemon-Showdown,Volcos/SpacialGaze,Bryan-0/Pokemon-Showdown,SolarisFox/Pokemon-Showdown,Kokonoe-san/Glacia-PS,DesoGit/Tsunami_PS,Zarel/Pokemon-Showdown,panpawn/Pokemon-Showdown,Lord-Haji/SpacialGaze,jd4564/Pokemon-Showdown,xCrystal/Pokemon-Showdown,CreaturePhil/Showdown-Boilerplate,QuiteQuiet/Pokemon-Showdown,PS-Spectral/Spectral,xfix/Pokemon-Showdown,Lord-Haji/SpacialGaze,PS-Spectral/Spectral,Sora-League/Sora,AnaRitaTorres/Pokemon-Showdown,AustinXII/Pokemon-Showdown,HoeenCoder/SpacialGaze,Git-Worm/City-PS,urkerab/Pokemon-Showdown,jumbowhales/Pokemon-Showdown,Enigami/Pokemon-Showdown,Lord-Haji/SpacialGaze,xCrystal/Pokemon-Showdown,urkerab/Pokemon-Showdown,ShowdownHelper/Saffron,svivian/Pokemon-Showdown,KewlStatics/Alliance,AustinXII/Pokemon-Showdown,cadaeic/Pokemon-Showdown,panpawn/Gold-Server,ShowdownHelper/Saffron,HoeenCoder/SpacialGaze,ShowdownHelper/Saffron,TbirdClanWish/Pokemon-Showdown,EienSeiryuu/Pokemon-Showdown,Volcos/SpacialGaze,KewlStatics/Shit,aakashrajput/Pokemon-Showdown,Bryan-0/Pokemon-Showdown,Zarel/Pokemon-Showdown,Pikachuun/Pokemon-Showdown | 'use strict';
exports.BattleFormatsData = {
bulbasaur: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["sweetscent", "growth", "solarbeam", "synthesis"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "leechseed", "vinewhip"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "leechseed", "vinewhip"]},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"def": 31}, "isHidden": false, "moves":["falseswipe", "block", "frenzyplant", "weatherball"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "leechseed", "vinewhip", "poisonpowder"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "growl", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
ivysaur: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
tier: "Bank-NFE",
},
venusaur: {
randomBattleMoves: ["sunnyday", "sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
eventPokemon: [
{"generation": 6, "level": 100, "isHidden": true, "moves":["solarbeam", "frenzyplant", "synthesis", "grasspledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
venusaurmega: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "synthesis", "earthquake", "knockoff"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
requiredItem: "Venusaurite",
tier: "Bank",
},
charmander: {
randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast"],
randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "ember"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Naive", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Naughty", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "ember", "smokescreen"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"spe": 31}, "isHidden": false, "moves":["falseswipe", "block", "blastburn", "acrobatics"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "ember", "smokescreen", "dragonrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["scratch", "growl", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
charmeleon: {
randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast", "dragondance", "flareblitz", "shadowclaw", "dragonclaw"],
randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"],
tier: "Bank-NFE",
},
charizard: {
randomBattleMoves: ["fireblast", "airslash", "focusblast", "roost", "swordsdance", "flareblitz", "acrobatics", "earthquake"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "overheat", "dragonpulse", "roost", "tailwind", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["wingattack", "slash", "dragonrage", "firespin"]},
{"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "flameburst", "airslash", "inferno"], "pokeball": "cherishball"},
{"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "airslash", "dragonclaw", "dragonrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 36, "shiny": true, "gender": "M", "isHidden": false, "moves":["overheat", "solarbeam", "focusblast", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": true, "moves":["flareblitz", "blastburn", "scaryface", "firepledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
charizardmegax: {
randomBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "roost", "willowisp"],
randomDoubleBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "rockslide", "roost", "substitute"],
requiredItem: "Charizardite X",
tier: "Bank",
},
charizardmegay: {
randomBattleMoves: ["fireblast", "airslash", "roost", "solarbeam", "focusblast", "dragonpulse"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "roost", "solarbeam", "focusblast", "protect"],
requiredItem: "Charizardite Y",
tier: "Bank",
},
squirtle: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "tailwhip", "bubble", "withdraw"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "tailwhip", "bubble", "withdraw"]},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"hp": 31}, "isHidden": false, "moves":["falseswipe", "block", "hydrocannon", "followme"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tailwhip", "watergun", "withdraw", "bubble"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "tailwhip", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
wartortle: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"],
tier: "Bank-NFE",
},
blastoise: {
randomBattleMoves: ["icebeam", "rapidspin", "scald", "toxic", "dragontail", "roar"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect", "waterspout"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["protect", "raindance", "skullbash", "hydropump"]},
{"generation": 6, "level": 100, "isHidden": true, "moves":["hydropump", "hydrocannon", "irondefense", "waterpledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
blastoisemega: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "toxic", "dragontail", "darkpulse", "aurasphere"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "darkpulse", "aurasphere", "followme", "icywind", "protect"],
requiredItem: "Blastoisinite",
tier: "Bank",
},
caterpie: {
randomBattleMoves: ["bugbite", "snore", "tackle", "electroweb"],
tier: "LC",
},
metapod: {
randomBattleMoves: ["snore", "bugbite", "tackle", "electroweb"],
tier: "NFE",
},
butterfree: {
randomBattleMoves: ["sleeppowder", "quiverdance", "bugbuzz", "psychic", "gigadrain", "substitute"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "substitute", "sleeppowder", "psychic", "shadowball", "protect"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["morningsun", "psychic", "sleeppowder", "aerialace"]},
],
tier: "New",
},
weedle: {
randomBattleMoves: ["bugbite", "stringshot", "poisonsting", "electroweb"],
tier: "Bank-LC",
},
kakuna: {
randomBattleMoves: ["electroweb", "bugbite", "irondefense", "poisonsting"],
tier: "Bank-NFE",
},
beedrill: {
randomBattleMoves: ["toxicspikes", "tailwind", "uturn", "endeavor", "poisonjab", "knockoff"],
randomDoubleBattleMoves: ["xscissor", "uturn", "poisonjab", "drillrun", "brickbreak", "knockoff", "protect", "stringshot"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["batonpass", "sludgebomb", "twineedle", "swordsdance"]},
],
tier: "Bank",
},
beedrillmega: {
randomBattleMoves: ["xscissor", "swordsdance", "uturn", "poisonjab", "drillrun", "knockoff"],
randomDoubleBattleMoves: ["xscissor", "uturn", "substitute", "poisonjab", "drillrun", "knockoff", "protect"],
requiredItem: "Beedrillite",
tier: "Bank",
},
pidgey: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"],
tier: "Bank-LC",
},
pidgeotto: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"],
eventPokemon: [
{"generation": 3, "level": 30, "abilities":["keeneye"], "moves":["refresh", "wingattack", "steelwing", "featherdance"]},
],
tier: "Bank-NFE",
},
pidgeot: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "doubleedge", "uturn", "hurricane"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "doubleedge", "uturn", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 61, "gender": "M", "nature": "Naughty", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["keeneye"], "moves":["whirlwind", "wingattack", "skyattack", "mirrormove"], "pokeball": "cherishball"},
],
tier: "Bank",
},
pidgeotmega: {
randomBattleMoves: ["roost", "heatwave", "uturn", "hurricane", "defog"],
randomDoubleBattleMoves: ["tailwind", "heatwave", "uturn", "hurricane", "protect"],
requiredItem: "Pidgeotite",
tier: "Bank",
},
rattata: {
randomBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "thunderwave", "crunch", "revenge"],
randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "superfang", "crunch", "protect"],
tier: "Bank-LC",
},
rattataalola: {
tier: "LC",
},
raticate: {
randomBattleMoves: ["protect", "facade", "flamewheel", "suckerpunch", "uturn", "swordsdance"],
randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "crunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 34, "moves":["refresh", "superfang", "scaryface", "hyperfang"]},
],
tier: "Bank",
},
raticatealola: {
randomBattleMoves: ["swordsdance", "return", "suckerpunch", "crunch", "doubleedge"],
tier: "New",
},
spearow: {
randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "pursuit", "drillrun", "featherdance"],
randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"],
eventPokemon: [
{"generation": 3, "level": 22, "moves":["batonpass", "falseswipe", "leer", "aerialace"]},
],
tier: "LC",
},
fearow: {
randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "pursuit", "drillrun"],
randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"],
tier: "New",
},
ekans: {
randomBattleMoves: ["coil", "gunkshot", "glare", "suckerpunch", "earthquake", "rest"],
randomDoubleBattleMoves: ["gunkshot", "seedbomb", "suckerpunch", "aquatail", "earthquake", "rest", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 14, "gender": "F", "nature": "Docile", "ivs": {"hp": 26, "atk": 28, "def": 6, "spa": 14, "spd": 30, "spe": 11}, "abilities":["shedskin"], "moves":["leer", "wrap", "poisonsting", "bite"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "leer", "poisonsting"]},
],
tier: "Bank-LC",
},
arbok: {
randomBattleMoves: ["coil", "gunkshot", "suckerpunch", "aquatail", "earthquake", "rest"],
randomDoubleBattleMoves: ["gunkshot", "suckerpunch", "aquatail", "crunch", "earthquake", "rest", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 33, "moves":["refresh", "sludgebomb", "glare", "bite"]},
],
tier: "Bank",
},
pichu: {
randomBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "toxic", "thunderbolt"],
randomDoubleBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "protect", "thunderbolt"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "surf"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "teeterdance"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "followme"]},
{"generation": 4, "level": 1, "moves":["volttackle", "thunderbolt", "grassknot", "return"]},
{"generation": 4, "level": 30, "shiny": true, "gender": "M", "nature": "Jolly", "moves":["charge", "volttackle", "endeavor", "endure"], "pokeball": "cherishball"},
],
tier: "LC",
},
pichuspikyeared: {
eventPokemon: [
{"generation": 4, "level": 30, "gender": "F", "nature": "Naughty", "moves":["helpinghand", "volttackle", "swagger", "painsplit"]},
],
eventOnly: true,
gen: 4,
tier: "Illegal",
},
pikachu: {
randomBattleMoves: ["thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff", "protect", "discharge"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["thunderbolt", "agility", "thunder", "lightscreen"]},
{"generation": 3, "level": 10, "moves":["thundershock", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["fly", "tailwhip", "growl", "thunderwave"]},
{"generation": 3, "level": 5, "moves":["surf", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["fly", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["thundershock", "growl", "thunderwave", "surf"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "fly"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "surf"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "agility"]},
{"generation": 4, "level": 10, "gender": "F", "nature": "Hardy", "moves":["surf", "volttackle", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["thundershock", "growl", "tailwhip", "thunderwave"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["surf", "thunderbolt", "lightscreen", "quickattack"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Jolly", "moves":["grassknot", "thunderbolt", "flash", "doubleteam"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Modest", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["quickattack", "thundershock", "tailwhip", "present"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thunderwave", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lastresort", "present", "thunderbolt", "quickattack"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "gender": "M", "nature": "Relaxed", "moves":["rest", "sleeptalk", "yawn", "snore"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Docile", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["volttackle", "irontail", "quickattack", "thunderbolt"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["sing", "teeterdance", "encore", "electroball"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["fly", "irontail", "electroball", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "shiny": 1, "gender": "F", "isHidden": false, "moves":["thunder", "volttackle", "grassknot", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "gender": "F", "isHidden": false, "moves":["extremespeed", "thunderbolt", "grassknot", "brickbreak"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "isHidden": true, "moves":["fly", "thunderbolt", "grassknot", "protect"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["thundershock", "tailwhip", "thunderwave", "headbutt"]},
{"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["volttackle", "quickattack", "feint", "voltswitch"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "growl", "playnice", "quickattack"], "pokeball": "cherishball"},
{"generation": 6, "level": 22, "isHidden": false, "moves":["quickattack", "electroball", "doubleteam", "megakick"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["thunderbolt", "quickattack", "surf", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["thunderbolt", "quickattack", "heartstamp", "holdhands"], "pokeball": "healball"},
{"generation": 6, "level": 36, "shiny": true, "isHidden": true, "moves":["thunder", "substitute", "playnice", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["playnice", "charm", "nuzzle", "sweetkiss"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "gender": "M", "nature": "Naughty", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "shiny": true, "isHidden": false, "moves":["teeterdance", "playnice", "tailwhip", "nuzzle"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "perfectIVs": 2, "isHidden": true, "moves":["fakeout", "encore", "volttackle", "endeavor"], "pokeball": "cherishball"},
{"generation": 6, "level": 99, "isHidden": false, "moves":["happyhour", "playnice", "holdhands", "flash"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["fly", "surf", "agility", "celebrate"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["bestow", "holdhands", "return", "playnice"], "pokeball": "healball"},
],
tier: "NFE",
},
pikachucosplay: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "thundershock"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachurockstar: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "meteormash"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachubelle: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "iciclecrash"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachupopstar: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "drainingkiss"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachuphd: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "electricterrain"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachulibre: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "flyingpress"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
raichu: {
randomBattleMoves: ["nastyplot", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "voltswitch"],
randomDoubleBattleMoves: ["fakeout", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "substitute", "extremespeed", "knockoff", "protect"],
tier: "Bank",
},
raichualola: {
randomBattleMoves: ["nastyplot", "encore", "thunderbolt", "psyshock", "focusblast", "voltswitch"],
tier: "New",
},
sandshrew: {
randomBattleMoves: ["earthquake", "rockslide", "swordsdance", "rapidspin", "xscissor", "stealthrock", "toxic", "knockoff"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "swordsdance", "xscissor", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 12, "gender": "M", "nature": "Docile", "ivs": {"hp": 4, "atk": 23, "def": 8, "spa": 31, "spd": 1, "spe": 25}, "moves":["scratch", "defensecurl", "sandattack", "poisonsting"]},
],
tier: "Bank-LC",
},
sandshrewalola: {
tier: "LC",
},
sandslash: {
randomBattleMoves: ["earthquake", "swordsdance", "rapidspin", "toxic", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "stoneedge", "swordsdance", "xscissor", "knockoff", "protect"],
tier: "Bank",
},
sandslashalola: {
randomBattleMoves: ["substitute", "swordsdance", "iciclecrash", "ironhead", "earthquake", "rapidspin"],
tier: "New",
},
nidoranf: {
randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws"],
randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect"],
tier: "Bank-LC",
},
nidorina: {
randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws", "icebeam", "thunderbolt", "shadowclaw"],
randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect", "icebeam", "thunderbolt", "shadowclaw"],
tier: "Bank-NFE",
},
nidoqueen: {
randomBattleMoves: ["toxicspikes", "stealthrock", "fireblast", "icebeam", "earthpower", "sludgewave"],
randomDoubleBattleMoves: ["protect", "fireblast", "icebeam", "earthpower", "sludgebomb"],
eventPokemon: [
{"generation": 6, "level": 41, "perfectIVs": 2, "isHidden": false, "abilities":["poisonpoint"], "moves":["tailwhip", "doublekick", "poisonsting", "bodyslam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
nidoranm: {
randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"],
tier: "Bank-LC",
},
nidorino: {
randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"],
tier: "Bank-NFE",
},
nidoking: {
randomBattleMoves: ["substitute", "fireblast", "icebeam", "earthpower", "sludgewave", "superpower"],
randomDoubleBattleMoves: ["protect", "fireblast", "thunderbolt", "icebeam", "earthpower", "sludgebomb", "focusblast"],
tier: "Bank",
},
cleffa: {
randomBattleMoves: ["reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "protect"],
tier: "LC",
},
clefairy: {
randomBattleMoves: ["healingwish", "reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy", "stealthrock", "moonblast", "knockoff", "moonlight"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast"],
tier: "New",
},
clefable: {
randomBattleMoves: ["calmmind", "softboiled", "fireblast", "moonblast", "stealthrock", "thunderwave"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast", "dazzlinggleam", "softboiled"],
tier: "New",
},
vulpix: {
randomBattleMoves: ["flamethrower", "fireblast", "willowisp", "energyball", "substitute", "toxic", "hypnosis", "painsplit"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "energyball", "substitute", "protect"],
eventPokemon: [
{"generation": 3, "level": 18, "gender": "F", "nature": "Quirky", "ivs": {"hp": 15, "atk": 6, "def": 3, "spa": 25, "spd": 13, "spe": 22}, "moves":["tailwhip", "roar", "quickattack", "willowisp"]},
{"generation": 3, "level": 18, "moves":["charm", "heatwave", "ember", "dig"]},
],
tier: "Bank-LC",
},
vulpixalola: {
tier: "LC",
},
ninetales: {
randomBattleMoves: ["fireblast", "willowisp", "solarbeam", "nastyplot", "substitute", "hiddenpowerice"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "solarbeam", "substitute", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Bold", "ivs": {"def": 31}, "isHidden": true, "moves":["heatwave", "solarbeam", "psyshock", "willowisp"], "pokeball": "cherishball"},
],
tier: "Bank",
},
ninetalesalola: {
randomBattleMoves: ["nastyplot", "blizzard", "moonblast", "substitute", "hiddenpowerfire"],
tier: "New",
},
igglybuff: {
randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "protect"],
randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["sing", "charm", "defensecurl", "tickle"]},
],
tier: "LC",
},
jigglypuff: {
randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "stealthrock", "protect", "knockoff", "dazzlinggleam"],
randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect", "knockoff", "dazzlinggleam"],
tier: "NFE",
},
wigglytuff: {
randomBattleMoves: ["wish", "protect", "fireblast", "stealthrock", "dazzlinggleam", "hypervoice"],
randomDoubleBattleMoves: ["thunderwave", "reflect", "lightscreen", "protect", "knockoff", "dazzlinggleam", "fireblast", "icebeam", "hypervoice"],
tier: "New",
},
zubat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "whirlwind", "heatwave", "superfang"],
randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"],
tier: "LC",
},
golbat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "superfang", "uturn"],
randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"],
tier: "New",
},
crobat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "uturn", "superfang"],
randomDoubleBattleMoves: ["bravebird", "taunt", "tailwind", "crosspoison", "uturn", "protect", "superfang"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Timid", "moves":["heatwave", "airslash", "sludgebomb", "superfang"], "pokeball": "cherishball"},
],
tier: "New",
},
oddish: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
eventPokemon: [
{"generation": 3, "level": 26, "gender": "M", "nature": "Quirky", "ivs": {"hp": 23, "atk": 24, "def": 20, "spa": 21, "spd": 9, "spe": 16}, "moves":["poisonpowder", "stunspore", "sleeppowder", "acid"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["absorb", "leechseed"]},
],
tier: "Bank-LC",
},
gloom: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["sleeppowder", "acid", "moonlight", "petaldance"]},
],
tier: "Bank-NFE",
},
vileplume: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "hiddenpowerfire", "aromatherapy"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast", "dazzlinggleam"],
tier: "Bank",
},
bellossom: {
randomBattleMoves: ["gigadrain", "synthesis", "sleeppowder", "hiddenpowerfire", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast", "dazzlinggleam", "sunnyday", "solarbeam"],
tier: "Bank",
},
paras: {
randomBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "synthesis", "leechseed", "aromatherapy", "knockoff"],
randomDoubleBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 3, "level": 28, "abilities":["effectspore"], "moves":["refresh", "spore", "slash", "falseswipe"]},
],
tier: "LC",
},
parasect: {
randomBattleMoves: ["spore", "substitute", "xscissor", "seedbomb", "leechseed", "knockoff"],
randomDoubleBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"],
tier: "New",
},
venonat: {
randomBattleMoves: ["sleeppowder", "morningsun", "toxicspikes", "sludgebomb", "signalbeam", "stunspore", "psychic"],
randomDoubleBattleMoves: ["sleeppowder", "morningsun", "ragepowder", "sludgebomb", "signalbeam", "stunspore", "psychic", "protect"],
tier: "Bank-LC",
},
venomoth: {
randomBattleMoves: ["sleeppowder", "quiverdance", "batonpass", "bugbuzz", "sludgebomb", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "roost", "ragepowder", "quiverdance", "protect", "bugbuzz", "sludgebomb", "gigadrain", "substitute", "psychic"],
eventPokemon: [
{"generation": 3, "level": 32, "abilities":["shielddust"], "moves":["refresh", "silverwind", "substitute", "psychic"]},
],
tier: "Bank",
},
diglett: {
randomBattleMoves: ["earthquake", "rockslide", "stealthrock", "suckerpunch", "reversal", "substitute", "shadowclaw"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "shadowclaw"],
tier: "Bank-LC",
},
diglettalola: {
tier: "LC",
},
dugtrio: {
randomBattleMoves: ["earthquake", "stoneedge", "stealthrock", "suckerpunch", "reversal", "substitute"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "stoneedge"],
eventPokemon: [
{"generation": 3, "level": 40, "moves":["charm", "earthquake", "sandstorm", "triattack"]},
],
tier: "Bank",
},
dugtrioalola: {
randomBattleMoves: ["earthquake", "ironhead", "substitute", "reversal"],
tier: "New",
},
meowth: {
randomBattleMoves: ["fakeout", "uturn", "thief", "taunt", "return", "hypnosis"],
randomDoubleBattleMoves: ["fakeout", "uturn", "nightslash", "taunt", "return", "hypnosis", "feint", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["scratch", "growl", "petaldance"]},
{"generation": 3, "level": 5, "moves":["scratch", "growl"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "bite"]},
{"generation": 3, "level": 22, "moves":["sing", "slash", "payday", "bite"]},
{"generation": 4, "level": 21, "gender": "F", "nature": "Jolly", "abilities":["pickup"], "moves":["bite", "fakeout", "furyswipes", "screech"], "pokeball": "cherishball"},
{"generation": 4, "level": 10, "gender": "M", "nature": "Jolly", "abilities":["pickup"], "moves":["fakeout", "payday", "assist", "scratch"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pickup"], "moves":["furyswipes", "sing", "nastyplot", "snatch"], "pokeball": "cherishball"},
{"generation": 6, "level": 20, "isHidden": false, "abilities":["pickup"], "moves":["happyhour", "screech", "bite", "fakeout"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
meowthalola: {
tier: "LC",
},
persian: {
randomBattleMoves: ["fakeout", "uturn", "taunt", "return", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "uturn", "knockoff", "taunt", "return", "hypnosis", "feint", "protect"],
tier: "Bank",
},
persianalola: {
randomBattleMoves: ["nastyplot", "darkpulse", "powergem", "hypnosis", "hiddenpowerfighting"],
tier: "New",
},
psyduck: {
randomBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam"],
randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam", "surf", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 27, "gender": "M", "nature": "Lax", "ivs": {"hp": 31, "atk": 16, "def": 12, "spa": 29, "spd": 31, "spe": 14}, "abilities":["damp"], "moves":["tailwhip", "confusion", "disable", "screech"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["watersport", "scratch", "tailwhip", "mudsport"]},
],
tier: "LC",
},
golduck: {
randomBattleMoves: ["hydropump", "scald", "icebeam", "signalbeam", "encore", "calmmind", "substitute"],
randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "focusblast", "encore", "psychic", "surf", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 33, "moves":["charm", "waterfall", "psychup", "brickbreak"]},
],
tier: "New",
},
mankey: {
randomBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab"],
randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect"],
tier: "LC",
},
primeape: {
randomBattleMoves: ["closecombat", "uturn", "icepunch", "stoneedge", "encore", "earthquake", "gunkshot"],
randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect", "taunt", "stoneedge"],
eventPokemon: [
{"generation": 3, "level": 34, "abilities":["vitalspirit"], "moves":["helpinghand", "crosschop", "focusenergy", "reversal"]},
],
tier: "New",
},
growlithe: {
randomBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "morningsun", "willowisp", "toxic", "flamethrower"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "willowisp", "snarl", "heatwave", "helpinghand", "protect"],
eventPokemon: [
{"generation": 3, "level": 32, "gender": "F", "nature": "Quiet", "ivs": {"hp": 11, "atk": 24, "def": 28, "spa": 1, "spd": 20, "spe": 2}, "abilities":["intimidate"], "moves":["leer", "odorsleuth", "takedown", "flamewheel"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["bite", "roar", "ember"]},
{"generation": 3, "level": 28, "moves":["charm", "flamethrower", "bite", "takedown"]},
],
tier: "LC",
},
arcanine: {
randomBattleMoves: ["flareblitz", "wildcharge", "extremespeed", "closecombat", "morningsun", "willowisp", "toxic", "crunch", "roar"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "closecombat", "willowisp", "snarl", "protect", "extremespeed"],
eventPokemon: [
{"generation": 4, "level": 50, "abilities":["intimidate"], "moves":["flareblitz", "thunderfang", "crunch", "extremespeed"], "pokeball": "cherishball"},
],
tier: "New",
},
poliwag: {
randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "sweetkiss"]},
],
tier: "LC",
},
poliwhirl: {
randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return", "earthquake"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand", "earthquake"],
tier: "NFE",
},
poliwrath: {
randomBattleMoves: ["hydropump", "focusblast", "icebeam", "rest", "sleeptalk", "scald", "circlethrow", "raindance"],
randomDoubleBattleMoves: ["bellydrum", "encore", "waterfall", "protect", "icepunch", "earthquake", "brickbreak", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 42, "moves":["helpinghand", "hydropump", "raindance", "brickbreak"]},
],
tier: "New",
},
politoed: {
randomBattleMoves: ["scald", "toxic", "encore", "perishsong", "protect", "hypnosis", "rest"],
randomDoubleBattleMoves: ["scald", "hypnosis", "icywind", "encore", "helpinghand", "protect", "icebeam", "focusblast", "hydropump", "hiddenpowergrass"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Calm", "ivs": {"hp": 31, "atk": 13, "def": 31, "spa": 5, "spd": 31, "spe": 5}, "isHidden": true, "moves":["scald", "icebeam", "perishsong", "protect"], "pokeball": "cherishball"},
],
tier: "New",
},
abra: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
tier: "LC",
},
kadabra: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
tier: "New",
},
alakazam: {
randomBattleMoves: ["psyshock", "psychic", "focusblast", "shadowball", "hiddenpowerice", "hiddenpowerfire"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["futuresight", "calmmind", "psychic", "trick"]},
],
tier: "New",
},
alakazammega: {
randomBattleMoves: ["calmmind", "psyshock", "focusblast", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"],
requiredItem: "Alakazite",
tier: "New",
},
machop: {
randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "knockoff"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"],
tier: "LC",
},
machoke: {
randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "poweruppunch", "knockoff"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["lowsweep", "foresight", "seismictoss", "revenge"], "pokeball": "cherishball"},
],
tier: "New",
},
machamp: {
randomBattleMoves: ["dynamicpunch", "icepunch", "stoneedge", "bulletpunch", "knockoff", "substitute"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "stoneedge", "rockslide", "bulletpunch", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 3, "level": 38, "gender": "M", "nature": "Quiet", "ivs": {"hp": 9, "atk": 23, "def": 25, "spa": 20, "spd": 15, "spe": 10}, "abilities":["guts"], "moves":["seismictoss", "foresight", "revenge", "vitalthrow"]},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 31, "spd": 31, "spe": 31}, "isHidden": false, "abilities":["noguard"], "moves":["dynamicpunch", "stoneedge", "wideguard", "knockoff"], "pokeball": "cherishball"},
],
tier: "New",
},
bellsprout: {
randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["vinewhip", "teeterdance"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["vinewhip", "growth"]},
],
tier: "LC",
},
weepinbell: {
randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 32, "moves":["morningsun", "magicalleaf", "sludgebomb", "sweetscent"]},
],
tier: "NFE",
},
victreebel: {
randomBattleMoves: ["sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "knockoff", "swordsdance"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "protect", "knockoff"],
tier: "New",
},
tentacool: {
randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "toxic", "dazzlinggleam"],
randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"],
tier: "LC",
},
tentacruel: {
randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "acidspray", "knockoff"],
randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "acidspray", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"],
tier: "New",
},
geodude: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank-LC",
},
geodudealola: {
tier: "LC",
},
graveler: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank-NFE",
},
graveleralola: {
tier: "NFE",
},
golem: {
randomBattleMoves: ["stealthrock", "earthquake", "explosion", "suckerpunch", "toxic", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank",
},
golemalola: {
randomBattleMoves: ["stealthrock", "stoneedge", "thunderpunch", "earthquake", "suckerpunch", "toxic"],
tier: "New",
},
ponyta: {
randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "hypnosis", "flamecharge"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge"],
tier: "Bank-LC",
},
rapidash: {
randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "drillrun", "willowisp", "sunnyday", "solarbeam"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge", "megahorn", "drillrun", "willowisp"],
eventPokemon: [
{"generation": 3, "level": 40, "moves":["batonpass", "solarbeam", "sunnyday", "flamethrower"]},
],
tier: "Bank",
},
slowpoke: {
randomBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "toxic", "slackoff", "trickroom"],
randomDoubleBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "slackoff", "trickroom", "protect"],
eventPokemon: [
{"generation": 3, "level": 31, "gender": "F", "nature": "Naive", "ivs": {"hp": 17, "atk": 11, "def": 19, "spa": 20, "spd": 5, "spe": 10}, "abilities":["oblivious"], "moves":["watergun", "confusion", "disable", "headbutt"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["curse", "yawn", "tackle", "growl"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["confusion", "disable", "headbutt", "waterpulse"], "pokeball": "cherishball"},
],
tier: "LC",
},
slowbro: {
randomBattleMoves: ["scald", "toxic", "thunderwave", "psyshock", "foulplay", "fireblast", "icebeam", "slackoff"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
eventPokemon: [
{"generation": 6, "level": 100, "nature": "Quiet", "isHidden": false, "abilities":["oblivious"], "moves":["scald", "trickroom", "slackoff", "irontail"], "pokeball": "cherishball"},
],
tier: "New",
},
slowbromega: {
randomBattleMoves: ["calmmind", "scald", "psyshock", "slackoff", "fireblast", "psychic", "icebeam", "grassknot"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
requiredItem: "Slowbronite",
tier: "(OU)",
},
slowking: {
randomBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "toxic", "slackoff", "trickroom", "nastyplot", "dragontail", "psyshock"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
tier: "New",
},
magnemite: {
randomBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch"],
randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge"],
tier: "LC",
},
magneton: {
randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "chargebeam", "hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["refresh", "doubleedge", "raindance", "thunder"]},
],
tier: "New",
},
magnezone: {
randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "chargebeam", "hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"],
tier: "New",
},
farfetchd: {
randomBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "roost", "nightslash"],
randomDoubleBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "protect", "nightslash"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["yawn", "wish"]},
{"generation": 3, "level": 36, "moves":["batonpass", "slash", "swordsdance", "aerialace"]},
],
tier: "Bank",
},
doduo: {
randomBattleMoves: ["bravebird", "return", "doubleedge", "roost", "quickattack", "pursuit"],
randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "protect"],
tier: "Bank-LC",
},
dodrio: {
randomBattleMoves: ["bravebird", "return", "doubleedge", "roost", "quickattack", "knockoff"],
randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "protect"],
eventPokemon: [
{"generation": 3, "level": 34, "moves":["batonpass", "drillpeck", "agility", "triattack"]},
],
tier: "Bank",
},
seel: {
randomBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "drillrun"],
randomDoubleBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "fakeout", "drillrun", "icywind"],
eventPokemon: [
{"generation": 3, "level": 23, "abilities":["thickfat"], "moves":["helpinghand", "surf", "safeguard", "icebeam"]},
],
tier: "Bank-LC",
},
dewgong: {
randomBattleMoves: ["surf", "icebeam", "perishsong", "encore", "toxic", "protect"],
randomDoubleBattleMoves: ["surf", "icebeam", "protect", "perishsong", "fakeout", "encore", "toxic"],
tier: "Bank",
},
grimer: {
randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "painsplit", "icepunch", "firepunch", "memento"],
randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch"],
eventPokemon: [
{"generation": 3, "level": 23, "moves":["helpinghand", "sludgebomb", "shadowpunch", "minimize"]},
],
tier: "Bank-LC",
},
grimeralola: {
tier: "LC",
},
muk: {
randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "icepunch", "firepunch", "memento"],
randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch", "brickbreak"],
tier: "Bank",
},
mukalola: {
randomBattleMoves: ["curse", "gunkshot", "knockoff", "poisonjab", "shadowsneak", "stoneedge"],
tier: "New",
},
shellder: {
randomBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "rapidspin"],
randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"],
eventPokemon: [
{"generation": 3, "level": 24, "gender": "F", "nature": "Brave", "ivs": {"hp": 5, "atk": 19, "def": 18, "spa": 5, "spd": 11, "spe": 13}, "abilities":["shellarmor"], "moves":["withdraw", "iciclespear", "supersonic", "aurorabeam"]},
{"generation": 3, "level": 10, "gender": "M", "abilities":["shellarmor"], "moves":["tackle", "withdraw", "iciclespear"]},
{"generation": 3, "level": 29, "abilities":["shellarmor"], "moves":["refresh", "takedown", "surf", "aurorabeam"]},
],
tier: "LC",
},
cloyster: {
randomBattleMoves: ["shellsmash", "hydropump", "rockblast", "iciclespear", "iceshard", "rapidspin", "spikes", "toxicspikes"],
randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "M", "nature": "Naughty", "isHidden": false, "abilities":["skilllink"], "moves":["iciclespear", "rockblast", "hiddenpower", "razorshell"]},
],
tier: "New",
},
gastly: {
randomBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "painsplit", "hypnosis", "gigadrain", "trick", "dazzlinggleam"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"],
tier: "LC",
},
haunter: {
randomBattleMoves: ["shadowball", "sludgebomb", "dazzlinggleam", "substitute", "destinybond"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 5, "level": 30, "moves":["confuseray", "suckerpunch", "shadowpunch", "payback"], "pokeball": "cherishball"},
],
tier: "New",
},
gengar: {
randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "substitute", "disable", "painsplit", "willowisp"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 3, "level": 23, "gender": "F", "nature": "Hardy", "ivs": {"hp": 19, "atk": 14, "def": 0, "spa": 14, "spd": 17, "spe": 27}, "moves":["spite", "curse", "nightshade", "confuseray"]},
{"generation": 6, "level": 25, "nature": "Timid", "moves":["psychic", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "moves":["nightshade", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["shadowball", "sludgebomb", "willowisp", "destinybond"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "shiny": true, "moves":["shadowball", "sludgewave", "confuseray", "astonish"], "pokeball": "duskball"},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "New",
},
gengarmega: {
randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "taunt", "destinybond", "disable", "perishsong", "protect"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"],
requiredItem: "Gengarite",
tier: "Uber",
},
onix: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "dragontail", "curse"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "stoneedge", "rockslide", "protect", "explosion"],
tier: "Bank-LC",
},
steelix: {
randomBattleMoves: ["stealthrock", "earthquake", "ironhead", "roar", "toxic", "rockslide"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "ironhead", "rockslide", "protect", "explosion"],
tier: "Bank",
},
steelixmega: {
randomBattleMoves: ["stealthrock", "earthquake", "heavyslam", "roar", "toxic", "dragontail"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "heavyslam", "rockslide", "protect", "explosion"],
requiredItem: "Steelixite",
tier: "Bank",
},
drowzee: {
randomBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "toxic", "shadowball", "trickroom", "calmmind", "dazzlinggleam"],
randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "shadowball", "trickroom", "calmmind", "dazzlinggleam", "toxic"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["insomnia"], "moves":["bellydrum", "wish"]},
],
tier: "LC",
},
hypno: {
randomBattleMoves: ["psychic", "seismictoss", "foulplay", "wish", "protect", "thunderwave", "toxic"],
randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "trickroom", "dazzlinggleam", "foulplay"],
eventPokemon: [
{"generation": 3, "level": 34, "abilities":["insomnia"], "moves":["batonpass", "psychic", "meditate", "shadowball"]},
],
tier: "New",
},
krabby: {
randomBattleMoves: ["crabhammer", "swordsdance", "agility", "rockslide", "substitute", "xscissor", "superpower", "knockoff"],
randomDoubleBattleMoves: ["crabhammer", "swordsdance", "rockslide", "substitute", "xscissor", "superpower", "knockoff", "protect"],
tier: "Bank-LC",
},
kingler: {
randomBattleMoves: ["crabhammer", "xscissor", "rockslide", "swordsdance", "agility", "superpower", "knockoff"],
randomDoubleBattleMoves: ["crabhammer", "xscissor", "rockslide", "substitute", "superpower", "knockoff", "protect", "wideguard"],
tier: "Bank",
},
voltorb: {
randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 19, "moves":["refresh", "mirrorcoat", "spark", "swift"]},
],
tier: "Bank-LC",
},
electrode: {
randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowergrass", "signalbeam"],
randomDoubleBattleMoves: ["voltswitch", "discharge", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"],
tier: "Bank",
},
exeggcute: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "synthesis"],
randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "protect", "trickroom"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]},
],
tier: "LC",
},
exeggutor: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire", "protect", "trickroom", "psyshock"],
eventPokemon: [
{"generation": 3, "level": 46, "moves":["refresh", "psychic", "hypnosis", "ancientpower"]},
],
tier: "Bank",
},
exeggutoralola: {
randomBattleMoves: ["dracometeor", "leafstorm", "flamethrower", "psyshock"],
tier: "New",
},
cubone: {
randomBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake"],
randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect"],
tier: "LC",
},
marowak: {
randomBattleMoves: ["bonemerang", "earthquake", "knockoff", "doubleedge", "stoneedge", "stealthrock", "substitute"],
randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect", "swordsdance"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["sing", "earthquake", "swordsdance", "rockslide"]},
],
tier: "Bank",
},
marowakalola: {
randomBattleMoves: ["flamecharge", "shadowbone", "bonemerang", "doubleedge", "stoneedge"],
tier: "New",
},
tyrogue: {
randomBattleMoves: ["highjumpkick", "rapidspin", "fakeout", "bulletpunch", "machpunch", "toxic", "counter"],
randomDoubleBattleMoves: ["highjumpkick", "fakeout", "bulletpunch", "machpunch", "helpinghand", "protect"],
tier: "Bank-LC",
},
hitmonlee: {
randomBattleMoves: ["highjumpkick", "knockoff", "stoneedge", "rapidspin", "machpunch", "poisonjab", "fakeout"],
randomDoubleBattleMoves: ["knockoff", "rockslide", "machpunch", "fakeout", "highjumpkick", "earthquake", "blazekick", "wideguard", "protect"],
eventPokemon: [
{"generation": 3, "level": 38, "abilities":["limber"], "moves":["refresh", "highjumpkick", "mindreader", "megakick"]},
],
tier: "Bank",
},
hitmonchan: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "firepunch", "machpunch", "rapidspin"],
randomDoubleBattleMoves: ["fakeout", "drainpunch", "icepunch", "firepunch", "machpunch", "earthquake", "rockslide", "protect", "thunderpunch"],
eventPokemon: [
{"generation": 3, "level": 38, "abilities":["keeneye"], "moves":["helpinghand", "skyuppercut", "mindreader", "megapunch"]},
],
tier: "Bank",
},
hitmontop: {
randomBattleMoves: ["suckerpunch", "machpunch", "rapidspin", "closecombat", "toxic"],
randomDoubleBattleMoves: ["fakeout", "feint", "suckerpunch", "closecombat", "helpinghand", "machpunch", "wideguard"],
eventPokemon: [
{"generation": 5, "level": 55, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["intimidate"], "moves":["fakeout", "closecombat", "suckerpunch", "helpinghand"]},
],
tier: "Bank",
},
lickitung: {
randomBattleMoves: ["wish", "protect", "dragontail", "curse", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake", "toxic", "healbell"],
randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake", "toxic", "healbell"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["healbell", "wish"]},
{"generation": 3, "level": 38, "moves":["helpinghand", "doubleedge", "defensecurl", "rollout"]},
],
tier: "Bank-LC",
},
lickilicky: {
randomBattleMoves: ["wish", "protect", "bodyslam", "knockoff", "dragontail", "healbell", "swordsdance", "explosion", "earthquake", "powerwhip"],
randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "rockslide", "powerwhip", "earthquake", "toxic", "healbell", "explosion"],
tier: "Bank",
},
koffing: {
randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "toxic", "clearsmog", "rest", "sleeptalk", "thunderbolt"],
randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "rest", "sleeptalk", "thunderbolt"],
tier: "Bank-LC",
},
weezing: {
randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "protect", "toxicspikes"],
randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "painsplit", "thunderbolt", "explosion"],
tier: "Bank",
},
rhyhorn: {
randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"],
tier: "LC",
},
rhydon: {
randomBattleMoves: ["stealthrock", "earthquake", "rockblast", "roar", "swordsdance", "stoneedge", "megahorn", "rockpolish"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 46, "moves":["helpinghand", "megahorn", "scaryface", "earthquake"]},
],
tier: "New",
},
rhyperior: {
randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish", "dragontail"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "hammerarm", "megahorn", "stealthrock", "rockslide", "protect"],
tier: "New",
},
happiny: {
randomBattleMoves: ["aromatherapy", "toxic", "thunderwave", "counter", "endeavor", "lightscreen", "fireblast"],
randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "swagger", "lightscreen", "fireblast", "protect"],
tier: "LC",
},
chansey: {
randomBattleMoves: ["softboiled", "healbell", "stealthrock", "thunderwave", "toxic", "seismictoss", "wish", "protect", "counter"],
randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "softboiled", "lightscreen", "seismictoss", "protect", "wish"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]},
{"generation": 3, "level": 10, "moves":["pound", "growl", "tailwhip", "refresh"]},
{"generation": 3, "level": 39, "moves":["sweetkiss", "thunderbolt", "softboiled", "skillswap"]},
],
tier: "New",
},
blissey: {
randomBattleMoves: ["toxic", "flamethrower", "seismictoss", "softboiled", "wish", "healbell", "protect", "thunderwave", "stealthrock"],
randomDoubleBattleMoves: ["wish", "softboiled", "protect", "toxic", "aromatherapy", "seismictoss", "helpinghand", "thunderwave", "flamethrower", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 10, "isHidden": true, "moves":["pound", "growl", "tailwhip", "refresh"]},
],
tier: "New",
},
tangela: {
randomBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerfire", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "sludgebomb", "synthesis"],
randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerrock", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "stunspore", "protect", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 30, "abilities":["chlorophyll"], "moves":["morningsun", "solarbeam", "sunnyday", "ingrain"]},
],
tier: "Bank",
},
tangrowth: {
randomBattleMoves: ["gigadrain", "leafstorm", "knockoff", "earthquake", "hiddenpowerfire", "rockslide", "sleeppowder", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerice", "leechseed", "knockoff", "ragepowder", "focusblast", "protect", "powerwhip", "earthquake"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Brave", "moves":["sunnyday", "morningsun", "ancientpower", "naturalgift"], "pokeball": "cherishball"},
],
tier: "Bank",
},
kangaskhan: {
randomBattleMoves: ["return", "suckerpunch", "earthquake", "drainpunch", "crunch", "fakeout"],
randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "drainpunch", "crunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["earlybird"], "moves":["yawn", "wish"]},
{"generation": 3, "level": 10, "abilities":["earlybird"], "moves":["cometpunch", "leer", "bite"]},
{"generation": 3, "level": 35, "abilities":["earlybird"], "moves":["sing", "earthquake", "tailwhip", "dizzypunch"]},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["scrappy"], "moves":["fakeout", "return", "earthquake", "suckerpunch"], "pokeball": "cherishball"},
],
tier: "New",
},
kangaskhanmega: {
randomBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "poweruppunch", "crunch"],
randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "poweruppunch", "drainpunch", "crunch", "protect"],
requiredItem: "Kangaskhanite",
tier: "Uber",
},
horsea: {
randomBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance", "muddywater", "protect"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bubble"]},
],
tier: "Bank-LC",
},
seadra: {
randomBattleMoves: ["hydropump", "icebeam", "agility", "substitute", "hiddenpowergrass"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "agility", "muddywater", "protect"],
eventPokemon: [
{"generation": 3, "level": 45, "abilities":["poisonpoint"], "moves":["leer", "watergun", "twister", "agility"]},
],
tier: "Bank-NFE",
},
kingdra: {
randomBattleMoves: ["dragondance", "waterfall", "outrage", "ironhead", "substitute", "raindance", "hydropump", "dracometeor"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "focusenergy", "dracometeor", "dragonpulse", "muddywater", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "abilities":["swiftswim"], "moves":["leer", "watergun", "twister", "agility"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Timid", "ivs": {"hp": 31, "atk": 17, "def": 8, "spa": 31, "spd": 11, "spe": 31}, "isHidden": false, "abilities":["swiftswim"], "moves":["dracometeor", "muddywater", "dragonpulse", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
goldeen: {
randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam"],
randomDoubleBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam", "protect"],
tier: "LC",
},
seaking: {
randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "scald", "icebeam"],
randomDoubleBattleMoves: ["waterfall", "surf", "megahorn", "knockoff", "drillrun", "icebeam", "icywind", "protect"],
tier: "New",
},
staryu: {
randomBattleMoves: ["scald", "thunderbolt", "icebeam", "rapidspin", "recover", "dazzlinggleam", "hydropump"],
randomDoubleBattleMoves: ["scald", "thunderbolt", "icebeam", "protect", "recover", "dazzlinggleam", "hydropump"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["minimize", "lightscreen", "cosmicpower", "hydropump"]},
{"generation": 3, "level": 18, "nature": "Timid", "ivs": {"hp": 10, "atk": 3, "def": 22, "spa": 24, "spd": 3, "spe": 18}, "abilities":["illuminate"], "moves":["harden", "watergun", "rapidspin", "recover"]},
],
tier: "LC",
},
starmie: {
randomBattleMoves: ["thunderbolt", "icebeam", "rapidspin", "recover", "psyshock", "scald", "hydropump"],
randomDoubleBattleMoves: ["surf", "thunderbolt", "icebeam", "protect", "recover", "psychic", "psyshock", "scald", "hydropump"],
eventPokemon: [
{"generation": 3, "level": 41, "moves":["refresh", "waterfall", "icebeam", "recover"]},
],
tier: "New",
},
mimejr: {
randomBattleMoves: ["batonpass", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore"],
randomDoubleBattleMoves: ["fakeout", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore", "icywind", "protect"],
tier: "Bank-LC",
},
mrmime: {
randomBattleMoves: ["nastyplot", "psychic", "psyshock", "dazzlinggleam", "shadowball", "batonpass", "focusblast", "healingwish", "encore"],
randomDoubleBattleMoves: ["fakeout", "thunderwave", "hiddenpowerfighting", "teeterdance", "thunderbolt", "encore", "icywind", "protect", "wideguard", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 42, "abilities":["soundproof"], "moves":["followme", "psychic", "encore", "thunderpunch"]},
],
tier: "Bank",
},
scyther: {
randomBattleMoves: ["swordsdance", "roost", "bugbite", "quickattack", "brickbreak", "aerialace", "batonpass", "uturn", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "protect", "bugbite", "quickattack", "brickbreak", "aerialace", "feint", "uturn", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["swarm"], "moves":["quickattack", "leer", "focusenergy"]},
{"generation": 3, "level": 40, "abilities":["swarm"], "moves":["morningsun", "razorwind", "silverwind", "slash"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["agility", "wingattack", "furycutter", "slash"], "pokeball": "cherishball"},
],
tier: "New",
},
scizor: {
randomBattleMoves: ["swordsdance", "bulletpunch", "bugbite", "superpower", "uturn", "pursuit", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 50, "gender": "M", "abilities":["swarm"], "moves":["furycutter", "metalclaw", "swordsdance", "slash"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "abilities":["swarm"], "moves":["xscissor", "swordsdance", "irondefense", "agility"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "bugbite", "roost", "swordsdance"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "focusenergy", "pursuit", "steelwing"]},
{"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["xscissor", "nightslash", "doublehit", "ironhead"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "nature": "Adamant", "isHidden": false, "abilities":["technician"], "moves":["aerialace", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "isHidden": false, "moves":["metalclaw", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "swordsdance", "roost", "uturn"], "pokeball": "cherishball"},
],
tier: "New",
},
scizormega: {
randomBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "batonpass", "pursuit", "defog", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"],
requiredItem: "Scizorite",
tier: "New",
},
smoochum: {
randomBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot"],
randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot", "fakeout", "protect"],
tier: "Bank-LC",
},
jynx: {
randomBattleMoves: ["icebeam", "psychic", "focusblast", "trick", "nastyplot", "lovelykiss", "substitute", "psyshock"],
randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "shadowball", "protect", "lovelykiss", "substitute", "psyshock"],
tier: "Bank",
},
elekid: {
randomBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass"],
randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect"],
eventPokemon: [
{"generation": 3, "level": 20, "moves":["icepunch", "firepunch", "thunderpunch", "crosschop"]},
],
tier: "LC",
},
electabuzz: {
randomBattleMoves: ["thunderbolt", "voltswitch", "substitute", "hiddenpowerice", "hiddenpowergrass", "focusblast", "psychic"],
randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect", "focusblast", "discharge"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["quickattack", "leer", "thunderpunch"]},
{"generation": 3, "level": 43, "moves":["followme", "crosschop", "thunderwave", "thunderbolt"]},
{"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["lowkick", "swift", "shockwave", "lightscreen"], "pokeball": "cherishball"},
{"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"], "pokeball": "cherishball"},
],
tier: "NFE",
},
electivire: {
randomBattleMoves: ["wildcharge", "crosschop", "icepunch", "flamethrower", "earthquake", "voltswitch"],
randomDoubleBattleMoves: ["wildcharge", "crosschop", "icepunch", "substitute", "flamethrower", "earthquake", "protect", "followme"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["thunderpunch", "icepunch", "crosschop", "earthquake"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Serious", "moves":["lightscreen", "thunderpunch", "discharge", "thunderbolt"], "pokeball": "cherishball"},
],
tier: "New",
},
magby: {
randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "overheat"],
tier: "LC",
},
magmar: {
randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "focusblast"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["leer", "smog", "firepunch", "leer"]},
{"generation": 3, "level": 36, "moves":["followme", "fireblast", "crosschop", "thunderpunch"]},
{"generation": 4, "level": 30, "gender": "M", "nature": "Quiet", "moves":["smokescreen", "firespin", "confuseray", "firepunch"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["smokescreen", "feintattack", "firespin", "confuseray"], "pokeball": "cherishball"},
{"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["smokescreen", "firespin", "confuseray", "firepunch"], "pokeball": "cherishball"},
],
tier: "NFE",
},
magmortar: {
randomBattleMoves: ["fireblast", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "earthquake", "substitute"],
randomDoubleBattleMoves: ["fireblast", "taunt", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "heatwave", "willowisp", "protect", "followme"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "F", "nature": "Modest", "moves":["flamethrower", "psychic", "hyperbeam", "solarbeam"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["confuseray", "firepunch", "lavaplume", "flamethrower"], "pokeball": "cherishball"},
],
tier: "New",
},
pinsir: {
randomBattleMoves: ["earthquake", "xscissor", "closecombat", "stoneedge", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 35, "abilities":["hypercutter"], "moves":["helpinghand", "guillotine", "falseswipe", "submission"]},
{"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["xscissor", "earthquake", "stoneedge", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Jolly", "isHidden": true, "moves":["earthquake", "swordsdance", "feint", "quickattack"], "pokeball": "cherishball"},
],
tier: "New",
},
pinsirmega: {
randomBattleMoves: ["swordsdance", "earthquake", "closecombat", "quickattack", "return"],
randomDoubleBattleMoves: ["feint", "protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "quickattack", "return", "rockslide"],
requiredItem: "Pinsirite",
tier: "New",
},
tauros: {
randomBattleMoves: ["rockclimb", "earthquake", "zenheadbutt", "rockslide", "doubleedge"],
randomDoubleBattleMoves: ["return", "earthquake", "zenheadbutt", "rockslide", "stoneedge", "protect", "doubleedge"],
eventPokemon: [
{"generation": 3, "level": 25, "nature": "Docile", "ivs": {"hp": 14, "atk": 19, "def": 12, "spa": 17, "spd": 5, "spe": 26}, "abilities":["intimidate"], "moves":["rage", "hornattack", "scaryface", "pursuit"], "pokeball": "safariball"},
{"generation": 3, "level": 10, "abilities":["intimidate"], "moves":["tackle", "tailwhip", "rage", "hornattack"]},
{"generation": 3, "level": 46, "abilities":["intimidate"], "moves":["refresh", "earthquake", "tailwhip", "bodyslam"]},
],
tier: "New",
},
magikarp: {
randomBattleMoves: ["bounce", "flail", "tackle", "hydropump"],
eventPokemon: [
{"generation": 4, "level": 5, "gender": "M", "nature": "Relaxed", "moves":["splash"]},
{"generation": 4, "level": 6, "gender": "F", "nature": "Rash", "moves":["splash"]},
{"generation": 4, "level": 7, "gender": "F", "nature": "Hardy", "moves":["splash"]},
{"generation": 4, "level": 5, "gender": "F", "nature": "Lonely", "moves":["splash"]},
{"generation": 4, "level": 4, "gender": "M", "nature": "Modest", "moves":["splash"]},
{"generation": 5, "level": 99, "shiny": true, "gender": "M", "isHidden": false, "moves":["flail", "hydropump", "bounce", "splash"], "pokeball": "cherishball"},
{"generation": 6, "level": 1, "shiny": 1, "isHidden": false, "moves":["splash", "celebrate", "happyhour"], "pokeball": "cherishball"},
],
tier: "LC",
},
gyarados: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "rest", "sleeptalk", "dragontail", "stoneedge", "substitute"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": false, "moves":["waterfall", "earthquake", "icefang", "dragondance"], "pokeball": "cherishball"},
{"generation": 6, "level": 20, "shiny": true, "isHidden": false, "moves":["waterfall", "bite", "icefang", "ironhead"], "pokeball": "cherishball"},
],
tier: "New",
},
gyaradosmega: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "substitute", "icefang", "crunch"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang"],
requiredItem: "Gyaradosite",
tier: "New",
},
lapras: {
randomBattleMoves: ["icebeam", "thunderbolt", "healbell", "toxic", "hydropump", "substitute"],
randomDoubleBattleMoves: ["icebeam", "thunderbolt", "healbell", "hydropump", "surf", "substitute", "protect", "iceshard", "icywind"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["hydropump", "raindance", "blizzard", "healbell"]},
],
tier: "New",
},
ditto: {
randomBattleMoves: ["transform"],
tier: "New",
},
eevee: {
randomBattleMoves: ["quickattack", "return", "bite", "batonpass", "irontail", "yawn", "protect", "wish"],
randomDoubleBattleMoves: ["quickattack", "return", "bite", "helpinghand", "irontail", "yawn", "protect", "wish"],
eventPokemon: [
{"generation": 4, "level": 10, "gender": "F", "nature": "Lonely", "abilities":["adaptability"], "moves":["covet", "bite", "helpinghand", "attract"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Hardy", "abilities":["adaptability"], "moves":["irontail", "trumpcard", "flail", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "F", "nature": "Hardy", "isHidden": false, "abilities":["adaptability"], "moves":["sing", "return", "echoedvoice", "attract"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "sandattack", "babydolleyes", "swift"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "shiny": true, "isHidden": true, "moves":["swift", "quickattack", "babydolleyes", "helpinghand"], "pokeball": "cherishball"},
],
tier: "LC",
},
vaporeon: {
randomBattleMoves: ["wish", "protect", "scald", "roar", "icebeam", "healbell", "batonpass"],
randomDoubleBattleMoves: ["helpinghand", "wish", "protect", "scald", "muddywater", "icebeam", "toxic", "hydropump"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "watergun"], "pokeball": "cherishball"},
],
tier: "New",
},
jolteon: {
randomBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowerice", "batonpass", "substitute", "signalbeam"],
randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowergrass", "hiddenpowerice", "helpinghand", "protect", "substitute", "signalbeam"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "thundershock"], "pokeball": "cherishball"},
],
tier: "New",
},
flareon: {
randomBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "wish", "protect", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "ember"], "pokeball": "cherishball"},
],
tier: "New",
},
espeon: {
randomBattleMoves: ["psychic", "psyshock", "substitute", "shadowball", "calmmind", "morningsun", "batonpass", "dazzlinggleam"],
randomDoubleBattleMoves: ["psychic", "psyshock", "substitute", "wish", "shadowball", "hiddenpowerfighting", "helpinghand", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["psybeam", "psychup", "psychic", "morningsun"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "confusion"], "pokeball": "cherishball"},
],
tier: "New",
},
umbreon: {
randomBattleMoves: ["wish", "protect", "healbell", "toxic", "batonpass", "foulplay"],
randomDoubleBattleMoves: ["moonlight", "wish", "protect", "healbell", "snarl", "foulplay", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["feintattack", "meanlook", "screech", "moonlight"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "pursuit"], "pokeball": "cherishball"},
],
tier: "New",
},
leafeon: {
randomBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "synthesis", "batonpass", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "protect", "helpinghand", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "razorleaf"], "pokeball": "cherishball"},
],
tier: "New",
},
glaceon: {
randomBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "healbell", "wish", "protect", "toxic"],
randomDoubleBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "wish", "protect", "healbell", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "icywind"], "pokeball": "cherishball"},
],
tier: "New",
},
porygon: {
randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "discharge", "trick"],
eventPokemon: [
{"generation": 5, "level": 10, "isHidden": true, "moves":["tackle", "conversion", "sharpen", "psybeam"]},
],
tier: "LC",
},
porygon2: {
randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "thunderbolt"],
randomDoubleBattleMoves: ["triattack", "icebeam", "discharge", "shadowball", "protect", "recover"],
tier: "New",
},
porygonz: {
randomBattleMoves: ["triattack", "darkpulse", "icebeam", "thunderbolt", "agility", "trick", "nastyplot"],
randomDoubleBattleMoves: ["protect", "triattack", "darkpulse", "hiddenpowerfighting", "agility", "trick", "nastyplot"],
tier: "New",
},
omanyte: {
randomBattleMoves: ["shellsmash", "surf", "icebeam", "earthpower", "hiddenpowerelectric", "spikes", "toxicspikes", "stealthrock", "hydropump"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["swiftswim"], "moves":["bubblebeam", "supersonic", "withdraw", "bite"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
omastar: {
randomBattleMoves: ["shellsmash", "scald", "icebeam", "earthpower", "spikes", "stealthrock", "hydropump"],
randomDoubleBattleMoves: ["shellsmash", "muddywater", "icebeam", "earthpower", "hiddenpowerelectric", "protect", "hydropump"],
tier: "Bank",
},
kabuto: {
randomBattleMoves: ["aquajet", "rockslide", "rapidspin", "stealthrock", "honeclaws", "waterfall", "toxic"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["battlearmor"], "moves":["confuseray", "dig", "scratch", "harden"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
kabutops: {
randomBattleMoves: ["aquajet", "stoneedge", "rapidspin", "swordsdance", "waterfall", "knockoff"],
randomDoubleBattleMoves: ["aquajet", "stoneedge", "protect", "rockslide", "swordsdance", "waterfall", "superpower", "knockoff"],
tier: "Bank",
},
aerodactyl: {
randomBattleMoves: ["stealthrock", "taunt", "stoneedge", "earthquake", "defog", "roost", "doubleedge"],
randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "aquatail", "protect", "icefang", "skydrop", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pressure"], "moves":["steelwing", "icefang", "firefang", "thunderfang"], "pokeball": "cherishball"},
],
tier: "New",
},
aerodactylmega: {
randomBattleMoves: ["aquatail", "pursuit", "honeclaws", "stoneedge", "firefang", "aerialace", "roost"],
randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "ironhead", "aerialace", "protect", "icefang", "skydrop", "tailwind"],
requiredItem: "Aerodactylite",
tier: "New",
},
munchlax: {
randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "whirlwind", "toxic"],
eventPokemon: [
{"generation": 4, "level": 5, "moves":["metronome", "tackle", "defensecurl", "selfdestruct"]},
{"generation": 4, "level": 5, "gender": "F", "nature": "Relaxed", "abilities":["thickfat"], "moves":["metronome", "odorsleuth", "tackle", "curse"], "pokeball": "cherishball"},
],
tier: "LC",
},
snorlax: {
randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "crunch", "pursuit", "whirlwind"],
randomDoubleBattleMoves: ["curse", "protect", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "crunch", "selfdestruct"],
eventPokemon: [
{"generation": 3, "level": 43, "moves":["refresh", "fissure", "curse", "bodyslam"]},
],
tier: "New",
},
articuno: {
randomBattleMoves: ["icebeam", "roost", "freezedry", "toxic", "substitute", "hurricane"],
randomDoubleBattleMoves: ["freezedry", "roost", "protect", "substitute", "hurricane", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]},
{"generation": 3, "level": 70, "moves":["agility", "mindreader", "icebeam", "reflect"]},
{"generation": 3, "level": 50, "moves":["icebeam", "healbell", "extrasensory", "haze"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["agility", "icebeam", "reflect", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["icebeam", "reflect", "hail", "tailwind"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["freezedry", "icebeam", "hail", "reflect"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
zapdos: {
randomBattleMoves: ["thunderbolt", "heatwave", "hiddenpowerice", "roost", "toxic", "uturn", "defog"],
randomDoubleBattleMoves: ["thunderbolt", "heatwave", "hiddenpowergrass", "hiddenpowerice", "tailwind", "protect", "discharge"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]},
{"generation": 3, "level": 70, "moves":["agility", "detect", "drillpeck", "charge"]},
{"generation": 3, "level": 50, "moves":["thunderbolt", "extrasensory", "batonpass", "metalsound"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["charge", "agility", "discharge", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["agility", "discharge", "raindance", "lightscreen"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["discharge", "thundershock", "raindance", "agility"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
moltres: {
randomBattleMoves: ["fireblast", "hiddenpowergrass", "roost", "substitute", "toxic", "willowisp", "hurricane"],
randomDoubleBattleMoves: ["fireblast", "hiddenpowergrass", "airslash", "roost", "substitute", "protect", "uturn", "willowisp", "hurricane", "heatwave", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]},
{"generation": 3, "level": 70, "moves":["agility", "endure", "flamethrower", "safeguard"]},
{"generation": 3, "level": 50, "moves":["extrasensory", "morningsun", "willowisp", "flamethrower"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["flamethrower", "safeguard", "airslash", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["safeguard", "airslash", "sunnyday", "heatwave"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["skyattack", "heatwave", "sunnyday", "safeguard"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
dratini: {
randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"],
tier: "LC",
},
dragonair: {
randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"],
tier: "NFE",
},
dragonite: {
randomBattleMoves: ["dragondance", "outrage", "firepunch", "extremespeed", "earthquake", "roost"],
randomDoubleBattleMoves: ["dragondance", "firepunch", "extremespeed", "dragonclaw", "earthquake", "roost", "substitute", "superpower", "dracometeor", "protect", "skydrop"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["agility", "safeguard", "wingattack", "outrage"]},
{"generation": 3, "level": 55, "moves":["healbell", "hyperbeam", "dragondance", "earthquake"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Mild", "moves":["dracometeor", "thunderbolt", "outrage", "dragondance"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["extremespeed", "firepunch", "dragondance", "outrage"], "pokeball": "cherishball"},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "thunderpunch"]},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "extremespeed"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["fireblast", "safeguard", "outrage", "hyperbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 55, "gender": "M", "isHidden": true, "moves":["dragondance", "outrage", "hurricane", "extremespeed"], "pokeball": "cherishball"},
{"generation": 6, "level": 62, "gender": "M", "ivs": {"hp": 31, "def": 31, "spa": 31, "spd": 31}, "isHidden": false, "moves":["agility", "slam", "barrier", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "New",
},
mewtwo: {
randomBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "recover"],
randomDoubleBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "substitute", "recover", "thunderbolt", "willowisp", "taunt", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["swift", "recover", "safeguard", "psychic"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["psychocut", "amnesia", "powerswap", "guardswap"]},
{"generation": 5, "level": 70, "isHidden": false, "moves":["psystrike", "shadowball", "aurasphere", "electroball"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "nature": "Timid", "ivs": {"spa": 31, "spe": 31}, "isHidden": true, "moves":["psystrike", "icebeam", "healpulse", "hurricane"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "isHidden": false, "moves":["recover", "psychic", "barrier", "aurasphere"]},
{"generation": 6, "level": 100, "shiny": true, "isHidden": true, "moves":["psystrike", "psychic", "recover", "aurasphere"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
mewtwomegax: {
randomBattleMoves: ["bulkup", "drainpunch", "earthquake", "taunt", "stoneedge", "zenheadbutt", "icebeam"],
requiredItem: "Mewtwonite X",
tier: "Bank-Uber",
},
mewtwomegay: {
randomBattleMoves: ["psystrike", "aurasphere", "shadowball", "fireblast", "icebeam", "calmmind", "recover", "willowisp", "taunt"],
requiredItem: "Mewtwonite Y",
tier: "Bank-Uber",
},
mew: {
randomBattleMoves: ["defog", "roost", "willowisp", "knockoff", "taunt", "icebeam", "earthpower", "aurasphere", "stealthrock", "nastyplot", "psyshock", "batonpass"],
randomDoubleBattleMoves: ["taunt", "willowisp", "transform", "roost", "psyshock", "nastyplot", "aurasphere", "fireblast", "icebeam", "thunderbolt", "protect", "fakeout", "helpinghand", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 30, "shiny": 1, "moves":["pound", "transform", "megapunch", "metronome"]},
{"generation": 3, "level": 10, "moves":["pound", "transform"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["fakeout"]},
{"generation": 3, "level": 10, "moves":["fakeout"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["feintattack"]},
{"generation": 3, "level": 10, "moves":["feintattack"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["hypnosis"]},
{"generation": 3, "level": 10, "moves":["hypnosis"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["nightshade"]},
{"generation": 3, "level": 10, "moves":["nightshade"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["roleplay"]},
{"generation": 3, "level": 10, "moves":["roleplay"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["zapcannon"]},
{"generation": 3, "level": 10, "moves":["zapcannon"]},
{"generation": 4, "level": 50, "moves":["ancientpower", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["barrier", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["megapunch", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["amnesia", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["transform", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["psychic", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["synthesis", "return", "hypnosis", "teleport"], "pokeball": "cherishball"},
{"generation": 4, "level": 5, "moves":["pound"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["pound"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
chikorita: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "razorleaf"]},
{"generation": 3, "level": 5, "moves":["tackle", "growl", "ancientpower", "frenzyplant"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "growl"], "pokeball": "cherishball"},
],
tier: "LC",
},
bayleef: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"],
tier: "NFE",
},
meganium: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "leechseed", "toxic", "gigadrain", "synthesis", "dragontail"],
randomDoubleBattleMoves: ["reflect", "lightscreen", "aromatherapy", "leechseed", "petalblizzard", "gigadrain", "synthesis", "dragontail", "healpulse", "toxic", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": true, "moves":["solarbeam", "sunnyday", "synthesis", "bodyslam"]},
],
tier: "New",
},
cyndaquil: {
randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "leer", "smokescreen"]},
{"generation": 3, "level": 5, "moves":["tackle", "leer", "reversal", "blastburn"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "leer"], "pokeball": "cherishball"},
],
tier: "LC",
},
quilava: {
randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"],
tier: "NFE",
},
typhlosion: {
randomBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast"],
randomDoubleBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast", "heatwave", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["quickattack", "flamewheel", "swift", "flamethrower"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["overheat", "flamewheel", "flamecharge", "swift"]},
],
tier: "New",
},
totodile: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "rage"]},
{"generation": 3, "level": 5, "moves":["scratch", "leer", "crunch", "hydrocannon"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["scratch", "leer"], "pokeball": "cherishball"},
],
tier: "LC",
},
croconaw: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"],
tier: "NFE",
},
feraligatr: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake"],
randomDoubleBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": true, "moves":["icepunch", "crunch", "waterfall", "screech"]},
],
tier: "New",
},
sentret: {
randomBattleMoves: ["superfang", "trick", "toxic", "uturn", "knockoff"],
tier: "Bank-LC",
},
furret: {
randomBattleMoves: ["uturn", "trick", "aquatail", "firepunch", "knockoff", "doubleedge"],
randomDoubleBattleMoves: ["uturn", "suckerpunch", "icepunch", "firepunch", "knockoff", "doubleedge", "superfang", "followme", "helpinghand", "protect"],
tier: "Bank",
},
hoothoot: {
randomBattleMoves: ["reflect", "toxic", "roost", "whirlwind", "nightshade", "magiccoat"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "foresight"]},
],
tier: "Bank-LC",
},
noctowl: {
randomBattleMoves: ["roost", "whirlwind", "airslash", "nightshade", "toxic", "defog"],
randomDoubleBattleMoves: ["roost", "tailwind", "airslash", "hypervoice", "heatwave", "protect", "hypnosis"],
tier: "Bank",
},
ledyba: {
randomBattleMoves: ["roost", "agility", "lightscreen", "encore", "reflect", "knockoff", "swordsdance", "batonpass", "toxic"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["refresh", "psybeam", "aerialace", "supersonic"]},
],
tier: "LC",
},
ledian: {
randomBattleMoves: ["roost", "lightscreen", "encore", "reflect", "knockoff", "toxic", "uturn"],
randomDoubleBattleMoves: ["protect", "lightscreen", "encore", "reflect", "knockoff", "bugbuzz", "uturn", "tailwind"],
tier: "New",
},
spinarak: {
randomBattleMoves: ["agility", "toxic", "xscissor", "toxicspikes", "poisonjab", "batonpass", "stickyweb"],
eventPokemon: [
{"generation": 3, "level": 14, "moves":["refresh", "dig", "signalbeam", "nightshade"]},
],
tier: "LC",
},
ariados: {
randomBattleMoves: ["megahorn", "toxicspikes", "poisonjab", "suckerpunch", "stickyweb"],
randomDoubleBattleMoves: ["protect", "megahorn", "stringshot", "poisonjab", "stickyweb", "ragepowder"],
tier: "New",
},
chinchou: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "surf", "thunderwave", "scald", "discharge", "healbell"],
tier: "LC",
},
lanturn: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "thunderbolt", "healbell", "toxic"],
randomDoubleBattleMoves: ["thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "discharge", "protect", "surf"],
tier: "New",
},
togepi: {
randomBattleMoves: ["protect", "fireblast", "toxic", "thunderwave", "softboiled", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 20, "gender": "F", "abilities":["serenegrace"], "moves":["metronome", "charm", "sweetkiss", "yawn"]},
{"generation": 3, "level": 25, "moves":["triattack", "followme", "ancientpower", "helpinghand"]},
],
tier: "LC",
},
togetic: {
randomBattleMoves: ["nastyplot", "dazzlinggleam", "fireblast", "batonpass", "roost", "defog", "toxic", "thunderwave", "healbell"],
tier: "New",
},
togekiss: {
randomBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "aurasphere", "batonpass", "healbell", "defog"],
randomDoubleBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "followme", "dazzlinggleam", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["extremespeed", "aurasphere", "airslash", "present"]},
],
tier: "New",
},
natu: {
randomBattleMoves: ["thunderwave", "roost", "toxic", "reflect", "lightscreen", "uturn", "wish", "psychic", "nightshade"],
eventPokemon: [
{"generation": 3, "level": 22, "moves":["batonpass", "futuresight", "nightshade", "aerialace"]},
],
tier: "Bank-LC",
},
xatu: {
randomBattleMoves: ["thunderwave", "toxic", "roost", "psychic", "uturn", "reflect", "lightscreen", "nightshade", "heatwave"],
randomDoubleBattleMoves: ["thunderwave", "tailwind", "roost", "psychic", "uturn", "reflect", "lightscreen", "grassknot", "heatwave", "protect"],
tier: "Bank",
},
mareep: {
randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"],
eventPokemon: [
{"generation": 3, "level": 37, "gender": "F", "moves":["thunder", "thundershock", "thunderwave", "cottonspore"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "thundershock"]},
{"generation": 3, "level": 17, "moves":["healbell", "thundershock", "thunderwave", "bodyslam"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["holdback", "tackle", "thunderwave", "thundershock"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
flaaffy: {
randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"],
tier: "Bank-NFE",
},
ampharos: {
randomBattleMoves: ["voltswitch", "reflect", "lightscreen", "focusblast", "thunderbolt", "toxic", "healbell", "hiddenpowerice"],
randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"],
tier: "Bank",
},
ampharosmega: {
randomBattleMoves: ["voltswitch", "focusblast", "agility", "thunderbolt", "healbell", "dragonpulse"],
randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"],
requiredItem: "Ampharosite",
tier: "Bank",
},
azurill: {
randomBattleMoves: ["scald", "return", "bodyslam", "encore", "toxic", "protect", "knockoff"],
tier: "Bank-LC",
},
marill: {
randomBattleMoves: ["waterfall", "knockoff", "encore", "toxic", "aquajet", "superpower", "icepunch", "protect", "playrough", "poweruppunch"],
tier: "NFE",
},
azumarill: {
randomBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff", "protect"],
tier: "New",
},
bonsly: {
randomBattleMoves: ["rockslide", "brickbreak", "doubleedge", "toxic", "stealthrock", "suckerpunch", "explosion"],
tier: "LC",
},
sudowoodo: {
randomBattleMoves: ["stoneedge", "earthquake", "suckerpunch", "woodhammer", "toxic", "stealthrock"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "suckerpunch", "woodhammer", "explosion", "stealthrock", "rockslide", "helpinghand", "protect"],
tier: "New",
},
hoppip: {
randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"],
tier: "Bank-LC",
},
skiploom: {
randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"],
tier: "Bank-NFE",
},
jumpluff: {
randomBattleMoves: ["swordsdance", "sleeppowder", "uturn", "encore", "toxic", "acrobatics", "leechseed", "seedbomb", "substitute"],
randomDoubleBattleMoves: ["encore", "sleeppowder", "uturn", "helpinghand", "leechseed", "gigadrain", "ragepowder", "protect"],
eventPokemon: [
{"generation": 5, "level": 27, "gender": "M", "isHidden": true, "moves":["falseswipe", "sleeppowder", "bulletseed", "leechseed"]},
],
tier: "Bank",
},
aipom: {
randomBattleMoves: ["fakeout", "return", "brickbreak", "seedbomb", "knockoff", "uturn", "icepunch", "irontail"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "tailwhip", "sandattack"]},
],
tier: "Bank-LC",
},
ambipom: {
randomBattleMoves: ["fakeout", "return", "knockoff", "uturn", "switcheroo", "seedbomb", "acrobatics", "lowkick"],
randomDoubleBattleMoves: ["fakeout", "return", "knockoff", "uturn", "doublehit", "icepunch", "lowkick", "protect"],
tier: "Bank",
},
sunkern: {
randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "toxic", "earthpower", "leechseed"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["chlorophyll"], "moves":["absorb", "growth"]},
],
tier: "Bank-LC",
},
sunflora: {
randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "earthpower"],
randomDoubleBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "earthpower", "protect", "encore"],
tier: "Bank",
},
yanma: {
randomBattleMoves: ["bugbuzz", "airslash", "hiddenpowerground", "uturn", "protect", "gigadrain", "ancientpower"],
tier: "Bank",
},
yanmega: {
randomBattleMoves: ["bugbuzz", "airslash", "ancientpower", "uturn", "protect", "gigadrain"],
tier: "Bank",
},
wooper: {
randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "stockpile", "yawn", "protect"],
tier: "Bank-LC",
},
quagsire: {
randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "encore", "icebeam"],
randomDoubleBattleMoves: ["icywind", "earthquake", "waterfall", "scald", "rockslide", "curse", "yawn", "icepunch", "protect"],
tier: "Bank",
},
murkrow: {
randomBattleMoves: ["substitute", "suckerpunch", "bravebird", "heatwave", "roost", "darkpulse", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["insomnia"], "moves":["peck", "astonish"]},
],
tier: "LC Uber",
},
honchkrow: {
randomBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "pursuit"],
randomDoubleBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "protect"],
tier: "New",
},
misdreavus: {
randomBattleMoves: ["nastyplot", "thunderbolt", "dazzlinggleam", "willowisp", "shadowball", "taunt", "painsplit"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "psywave", "spite"]},
],
tier: "New",
},
mismagius: {
randomBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "painsplit", "destinybond"],
randomDoubleBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "protect"],
tier: "New",
},
unown: {
randomBattleMoves: ["hiddenpowerpsychic"],
tier: "Bank",
},
wynaut: {
randomBattleMoves: ["destinybond", "counter", "mirrorcoat", "encore"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["splash", "charm", "encore", "tickle"]},
],
tier: "Bank-LC",
},
wobbuffet: {
randomBattleMoves: ["counter", "mirrorcoat", "encore", "destinybond", "safeguard"],
eventPokemon: [
{"generation": 3, "level": 5, "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]},
{"generation": 6, "level": 10, "gender": "M", "isHidden": false, "moves":["counter"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "gender": "M", "isHidden": false, "moves":["counter", "mirrorcoat"], "pokeball": "cherishball"},
],
tier: "Bank",
},
girafarig: {
randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "batonpass", "substitute", "hypervoice"],
randomDoubleBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "protect", "agility", "hypervoice"],
tier: "Bank",
},
pineco: {
randomBattleMoves: ["rapidspin", "toxicspikes", "spikes", "bugbite", "stealthrock"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "protect", "selfdestruct"]},
{"generation": 3, "level": 20, "moves":["refresh", "pinmissile", "spikes", "counter"]},
],
tier: "Bank-LC",
},
forretress: {
randomBattleMoves: ["rapidspin", "toxic", "spikes", "voltswitch", "stealthrock", "gyroball"],
randomDoubleBattleMoves: ["rockslide", "drillrun", "toxic", "voltswitch", "stealthrock", "gyroball", "protect"],
tier: "Bank",
},
dunsparce: {
randomBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "roost"],
randomDoubleBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "protect"],
tier: "Bank",
},
gligar: {
randomBattleMoves: ["stealthrock", "toxic", "roost", "defog", "earthquake", "uturn", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["poisonsting", "sandattack"]},
],
tier: "Bank",
},
gliscor: {
randomBattleMoves: ["roost", "substitute", "taunt", "earthquake", "protect", "toxic", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["tailwind", "substitute", "taunt", "earthquake", "protect", "stoneedge", "knockoff"],
tier: "Bank",
},
snubbull: {
randomBattleMoves: ["thunderwave", "firepunch", "crunch", "closecombat", "icepunch", "earthquake", "playrough"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "scaryface", "tailwhip", "charm"]},
],
tier: "LC",
},
granbull: {
randomBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "healbell"],
randomDoubleBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "snarl", "rockslide", "protect"],
tier: "New",
},
qwilfish: {
randomBattleMoves: ["toxicspikes", "waterfall", "spikes", "painsplit", "thunderwave", "taunt", "destinybond"],
randomDoubleBattleMoves: ["poisonjab", "waterfall", "swordsdance", "protect", "thunderwave", "taunt", "destinybond"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "poisonsting", "harden", "minimize"]},
],
tier: "Bank",
},
shuckle: {
randomBattleMoves: ["toxic", "encore", "stealthrock", "knockoff", "stickyweb", "infestation"],
randomDoubleBattleMoves: ["encore", "stealthrock", "knockoff", "stickyweb", "guardsplit", "powersplit", "toxic", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["sturdy"], "moves":["constrict", "withdraw", "wrap"]},
{"generation": 3, "level": 20, "abilities":["sturdy"], "moves":["substitute", "toxic", "sludgebomb", "encore"]},
],
tier: "Bank",
},
heracross: {
randomBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake"],
randomDoubleBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["bulletseed", "pinmissile", "closecombat", "megahorn"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Adamant", "isHidden": false, "abilities":["guts"], "moves":["pinmissile", "bulletseed", "earthquake", "rockblast"], "pokeball": "cherishball"},
],
tier: "Bank",
},
heracrossmega: {
randomBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "substitute"],
randomDoubleBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "knockoff", "earthquake", "protect"],
requiredItem: "Heracronite",
tier: "Bank",
},
sneasel: {
randomBattleMoves: ["iceshard", "iciclecrash", "lowkick", "pursuit", "swordsdance", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "taunt", "quickattack"]},
],
tier: "New",
},
weavile: {
randomBattleMoves: ["iceshard", "iciclecrash", "knockoff", "pursuit", "swordsdance", "lowkick"],
randomDoubleBattleMoves: ["iceshard", "iciclecrash", "knockoff", "fakeout", "swordsdance", "lowkick", "taunt", "protect", "feint"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Jolly", "moves":["fakeout", "iceshard", "nightslash", "brickbreak"], "pokeball": "cherishball"},
{"generation": 6, "level": 48, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["nightslash", "icepunch", "brickbreak", "xscissor"], "pokeball": "cherishball"},
],
tier: "New",
},
teddiursa: {
randomBattleMoves: ["swordsdance", "protect", "facade", "closecombat", "firepunch", "crunch", "playrough", "gunkshot"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["pickup"], "moves":["scratch", "leer", "lick"]},
{"generation": 3, "level": 11, "abilities":["pickup"], "moves":["refresh", "metalclaw", "lick", "return"]},
],
tier: "Bank-LC",
},
ursaring: {
randomBattleMoves: ["swordsdance", "facade", "closecombat", "crunch", "protect"],
randomDoubleBattleMoves: ["swordsdance", "facade", "closecombat", "earthquake", "crunch", "protect"],
tier: "Bank",
},
slugma: {
randomBattleMoves: ["stockpile", "recover", "lavaplume", "willowisp", "toxic", "hiddenpowergrass", "earthpower", "memento"],
tier: "Bank-LC",
},
magcargo: {
randomBattleMoves: ["recover", "lavaplume", "toxic", "hiddenpowergrass", "stealthrock", "fireblast", "earthpower", "shellsmash", "ancientpower"],
randomDoubleBattleMoves: ["protect", "heatwave", "willowisp", "shellsmash", "hiddenpowergrass", "ancientpower", "stealthrock", "fireblast", "earthpower"],
eventPokemon: [
{"generation": 3, "level": 38, "moves":["refresh", "heatwave", "earthquake", "flamethrower"]},
],
tier: "Bank",
},
swinub: {
randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "superpower", "endeavor", "stealthrock"],
eventPokemon: [
{"generation": 3, "level": 22, "abilities":["oblivious"], "moves":["charm", "ancientpower", "mist", "mudshot"]},
],
tier: "LC",
},
piloswine: {
randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "superpower", "endeavor", "stealthrock"],
tier: "New",
},
mamoswine: {
randomBattleMoves: ["iceshard", "earthquake", "endeavor", "iciclecrash", "stealthrock", "superpower", "knockoff"],
randomDoubleBattleMoves: ["iceshard", "earthquake", "rockslide", "iciclecrash", "protect", "superpower", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 34, "gender": "M", "isHidden": true, "moves":["hail", "icefang", "takedown", "doublehit"]},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "isHidden": true, "moves":["iciclespear", "earthquake", "iciclecrash", "rockslide"]},
],
tier: "New",
},
corsola: {
randomBattleMoves: ["recover", "toxic", "powergem", "scald", "stealthrock"],
randomDoubleBattleMoves: ["protect", "icywind", "powergem", "scald", "stealthrock", "earthpower", "icebeam"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "mudsport"]},
],
tier: "New",
},
remoraid: {
randomBattleMoves: ["waterspout", "hydropump", "fireblast", "hiddenpowerground", "icebeam", "seedbomb", "rockblast"],
tier: "Bank-LC",
},
octillery: {
randomBattleMoves: ["hydropump", "fireblast", "icebeam", "energyball", "rockblast", "gunkshot", "scald"],
randomDoubleBattleMoves: ["hydropump", "surf", "fireblast", "icebeam", "energyball", "chargebeam", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "F", "nature": "Serious", "abilities":["suctioncups"], "moves":["octazooka", "icebeam", "signalbeam", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
delibird: {
randomBattleMoves: ["rapidspin", "iceshard", "icepunch", "aerialace", "spikes", "destinybond"],
randomDoubleBattleMoves: ["fakeout", "iceshard", "icepunch", "aerialace", "brickbreak", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["present"]},
{"generation": 6, "level": 10, "isHidden": false, "abilities":["vitalspirit"], "moves":["present", "happyhour"], "pokeball": "cherishball"},
],
tier: "New",
},
mantyke: {
randomBattleMoves: ["raindance", "hydropump", "scald", "airslash", "icebeam", "rest", "sleeptalk", "toxic"],
tier: "Bank-LC",
},
mantine: {
randomBattleMoves: ["scald", "airslash", "rest", "sleeptalk", "toxic", "defog"],
randomDoubleBattleMoves: ["raindance", "hydropump", "scald", "airslash", "icebeam", "tailwind", "wideguard", "helpinghand", "protect", "surf"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "bubble", "supersonic"]},
],
tier: "Bank",
},
skarmory: {
randomBattleMoves: ["whirlwind", "bravebird", "roost", "spikes", "stealthrock", "defog"],
randomDoubleBattleMoves: ["skydrop", "bravebird", "tailwind", "taunt", "feint", "protect", "ironhead"],
tier: "New",
},
houndour: {
randomBattleMoves: ["pursuit", "suckerpunch", "fireblast", "darkpulse", "hiddenpowerfighting", "nastyplot"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["leer", "ember", "howl"]},
{"generation": 3, "level": 17, "moves":["charm", "feintattack", "ember", "roar"]},
],
tier: "Bank-LC",
},
houndoom: {
randomBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "fireblast", "hiddenpowergrass"],
randomDoubleBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "heatwave", "hiddenpowerfighting", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["flashfire"], "moves":["flamethrower", "darkpulse", "solarbeam", "sludgebomb"], "pokeball": "cherishball"},
],
tier: "Bank",
},
houndoommega: {
randomBattleMoves: ["nastyplot", "darkpulse", "taunt", "fireblast", "hiddenpowergrass"],
randomDoubleBattleMoves: ["nastyplot", "darkpulse", "taunt", "heatwave", "hiddenpowergrass", "protect"],
requiredItem: "Houndoominite",
tier: "Bank",
},
phanpy: {
randomBattleMoves: ["stealthrock", "earthquake", "iceshard", "headsmash", "knockoff", "seedbomb", "superpower", "playrough"],
tier: "Bank-LC",
},
donphan: {
randomBattleMoves: ["stealthrock", "rapidspin", "iceshard", "earthquake", "knockoff", "stoneedge"],
randomDoubleBattleMoves: ["stealthrock", "knockoff", "iceshard", "earthquake", "rockslide", "protect"],
tier: "Bank",
},
stantler: {
randomBattleMoves: ["doubleedge", "megahorn", "jumpkick", "earthquake", "suckerpunch"],
randomDoubleBattleMoves: ["return", "megahorn", "jumpkick", "earthquake", "suckerpunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["intimidate"], "moves":["tackle", "leer"]},
],
tier: "Bank",
},
smeargle: {
randomBattleMoves: ["spore", "spikes", "stealthrock", "destinybond", "whirlwind", "stickyweb"],
randomDoubleBattleMoves: ["spore", "fakeout", "wideguard", "helpinghand", "followme", "tailwind", "kingsshield", "transform"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["owntempo"], "moves":["sketch"]},
{"generation": 5, "level": 50, "gender": "F", "nature": "Jolly", "ivs": {"atk": 31, "spe": 31}, "isHidden": false, "abilities":["technician"], "moves":["falseswipe", "spore", "odorsleuth", "meanlook"], "pokeball": "cherishball"},
],
tier: "New",
},
miltank: {
randomBattleMoves: ["milkdrink", "stealthrock", "bodyslam", "healbell", "curse", "earthquake", "toxic"],
randomDoubleBattleMoves: ["protect", "helpinghand", "bodyslam", "healbell", "curse", "earthquake", "thunderwave"],
eventPokemon: [
{"generation": 6, "level": 20, "perfectIVs": 3, "isHidden": false, "abilities":["scrappy"], "moves":["rollout", "attract", "stomp", "milkdrink"], "pokeball": "cherishball"},
],
tier: "New",
},
raikou: {
randomBattleMoves: ["thunderbolt", "hiddenpowerice", "aurasphere", "calmmind", "substitute", "voltswitch", "extrasensory"],
randomDoubleBattleMoves: ["thunderbolt", "hiddenpowerice", "extrasensory", "calmmind", "substitute", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["thundershock", "roar", "quickattack", "spark"]},
{"generation": 3, "level": 70, "moves":["quickattack", "spark", "reflect", "crunch"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "quickattack", "spark", "reflect"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Rash", "moves":["zapcannon", "aurasphere", "extremespeed", "weatherball"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["spark", "reflect", "crunch", "thunderfang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
entei: {
randomBattleMoves: ["extremespeed", "flareblitz", "bulldoze", "stoneedge", "sacredfire"],
randomDoubleBattleMoves: ["extremespeed", "flareblitz", "ironhead", "bulldoze", "stoneedge", "sacredfire", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["ember", "roar", "firespin", "stomp"]},
{"generation": 3, "level": 70, "moves":["firespin", "stomp", "flamethrower", "swagger"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "firespin", "stomp", "flamethrower"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Adamant", "moves":["flareblitz", "howl", "extremespeed", "crushclaw"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["stomp", "flamethrower", "swagger", "firefang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
suicune: {
randomBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "rest", "sleeptalk", "calmmind"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "snarl", "tailwind", "protect", "calmmind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["bubblebeam", "raindance", "gust", "aurorabeam"]},
{"generation": 3, "level": 70, "moves":["gust", "aurorabeam", "mist", "mirrorcoat"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["raindance", "gust", "aurorabeam", "mist"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Relaxed", "moves":["sheercold", "airslash", "extremespeed", "aquaring"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["aurorabeam", "mist", "mirrorcoat", "icefang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
larvitar: {
randomBattleMoves: ["earthquake", "stoneedge", "facade", "dragondance", "superpower", "crunch"],
eventPokemon: [
{"generation": 3, "level": 20, "moves":["sandstorm", "dragondance", "bite", "outrage"]},
{"generation": 5, "level": 5, "shiny": true, "gender": "M", "isHidden": false, "moves":["bite", "leer", "sandstorm", "superpower"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
pupitar: {
randomBattleMoves: ["earthquake", "stoneedge", "crunch", "dragondance", "superpower", "stealthrock"],
tier: "Bank-NFE",
},
tyranitar: {
randomBattleMoves: ["crunch", "stoneedge", "pursuit", "earthquake", "fireblast", "icebeam", "stealthrock"],
randomDoubleBattleMoves: ["crunch", "stoneedge", "rockslide", "earthquake", "firepunch", "icepunch", "stealthrock", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["thrash", "scaryface", "crunch", "earthquake"]},
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "icebeam", "stoneedge", "crunch"], "pokeball": "cherishball"},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["payback", "crunch", "earthquake", "seismictoss"]},
{"generation": 6, "level": 50, "isHidden": false, "moves":["stoneedge", "crunch", "earthquake", "icepunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Jolly", "isHidden": false, "moves":["rockslide", "earthquake", "crunch", "stoneedge"], "pokeball": "cherishball"},
{"generation": 6, "level": 55, "shiny": true, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 0}, "isHidden": false, "moves":["crunch", "rockslide", "lowkick", "protect"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": false, "moves":["rockslide", "crunch", "icepunch", "lowkick"], "pokeball": "cherishball"},
],
tier: "Bank",
},
tyranitarmega: {
randomBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance"],
randomDoubleBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance", "rockslide", "protect"],
requiredItem: "Tyranitarite",
tier: "Bank",
},
lugia: {
randomBattleMoves: ["toxic", "roost", "substitute", "whirlwind", "thunderwave", "dragontail", "aeroblast"],
randomDoubleBattleMoves: ["aeroblast", "roost", "substitute", "tailwind", "icebeam", "psychic", "calmmind", "skydrop", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "hydropump", "raindance", "swift"]},
{"generation": 3, "level": 50, "moves":["psychoboost", "earthquake", "hydropump", "featherdance"]},
{"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "raindance", "hydropump", "aeroblast"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["aeroblast", "punishment", "ancientpower", "safeguard"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["raindance", "hydropump", "aeroblast", "punishment"]},
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "moves":["aeroblast", "hydropump", "dragonrush", "icebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
hooh: {
randomBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "flamecharge"],
randomDoubleBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "tailwind", "skydrop", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "fireblast", "sunnyday", "swift"]},
{"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "sunnyday", "fireblast", "sacredfire"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["sacredfire", "punishment", "ancientpower", "safeguard"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["sunnyday", "fireblast", "sacredfire", "punishment"]},
{"generation": 6, "level": 50, "shiny": true, "isHidden": false, "moves":["sacredfire", "bravebird", "recover", "celebrate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
celebi: {
randomBattleMoves: ["nastyplot", "psychic", "gigadrain", "recover", "healbell", "batonpass", "earthpower", "hiddenpowerfire", "leafstorm", "uturn", "thunderwave"],
randomDoubleBattleMoves: ["protect", "psychic", "gigadrain", "leechseed", "recover", "earthpower", "hiddenpowerfire", "nastyplot", "leafstorm", "uturn", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["confusion", "recover", "healbell", "safeguard"]},
{"generation": 3, "level": 70, "moves":["ancientpower", "futuresight", "batonpass", "perishsong"]},
{"generation": 3, "level": 10, "moves":["leechseed", "recover", "healbell", "safeguard"]},
{"generation": 3, "level": 30, "moves":["healbell", "safeguard", "ancientpower", "futuresight"]},
{"generation": 4, "level": 50, "moves":["leafstorm", "recover", "nastyplot", "healingwish"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "moves":["recover", "healbell", "safeguard", "holdback"], "pokeball": "luxuryball"},
{"generation": 6, "level": 100, "moves":["confusion", "recover", "healbell", "safeguard"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
treecko: {
randomBattleMoves: ["substitute", "leechseed", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["pound", "leer", "absorb"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "leer", "absorb"]},
],
tier: "Bank-LC",
},
grovyle: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"],
tier: "Bank-NFE",
},
sceptile: {
randomBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerfire", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["leafstorm", "dragonpulse", "focusblast", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
sceptilemega: {
randomBattleMoves: ["substitute", "gigadrain", "dragonpulse", "focusblast", "swordsdance", "outrage", "leafblade", "earthquake", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "dragonpulse", "hiddenpowerfire", "protect"],
requiredItem: "Sceptilite",
tier: "Bank",
},
torchic: {
randomBattleMoves: ["protect", "batonpass", "substitute", "hiddenpowergrass", "swordsdance", "firepledge"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "focusenergy", "ember"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"]},
{"generation": 6, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
combusken: {
randomBattleMoves: ["flareblitz", "skyuppercut", "protect", "swordsdance", "substitute", "batonpass", "shadowclaw"],
tier: "Bank",
},
blaziken: {
randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["blazekick", "slash", "mirrormove", "skyuppercut"]},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["flareblitz", "highjumpkick", "thunderpunch", "stoneedge"], "pokeball": "cherishball"},
],
tier: "Bank-Uber",
},
blazikenmega: {
randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"],
requiredItem: "Blazikenite",
tier: "Bank-Uber",
},
mudkip: {
randomBattleMoves: ["hydropump", "earthpower", "hiddenpowerelectric", "icebeam", "sludgewave"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "mudslap", "watergun"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "mudslap", "watergun"]},
],
tier: "Bank-LC",
},
marshtomp: {
randomBattleMoves: ["waterfall", "earthquake", "superpower", "icepunch", "rockslide", "stealthrock"],
tier: "Bank-NFE",
},
swampert: {
randomBattleMoves: ["stealthrock", "earthquake", "scald", "icebeam", "roar", "toxic", "protect"],
randomDoubleBattleMoves: ["waterfall", "earthquake", "icebeam", "stealthrock", "wideguard", "scald", "rockslide", "muddywater", "protect", "icywind"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthquake", "icebeam", "hydropump", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
swampertmega: {
randomBattleMoves: ["raindance", "waterfall", "earthquake", "icepunch", "superpower"],
randomDoubleBattleMoves: ["waterfall", "earthquake", "raindance", "icepunch", "superpower", "protect"],
requiredItem: "Swampertite",
tier: "Bank",
},
poochyena: {
randomBattleMoves: ["superfang", "foulplay", "suckerpunch", "toxic", "crunch", "firefang", "icefang", "poisonfang"],
eventPokemon: [
{"generation": 3, "level": 10, "abilities":["runaway"], "moves":["healbell", "dig", "poisonfang", "howl"]},
],
tier: "Bank-LC",
},
mightyena: {
randomBattleMoves: ["crunch", "suckerpunch", "playrough", "firefang", "irontail"],
randomDoubleBattleMoves: ["suckerpunch", "crunch", "playrough", "firefang", "taunt", "protect"],
tier: "Bank",
},
zigzagoon: {
randomBattleMoves: ["trick", "thunderwave", "icebeam", "thunderbolt", "gunkshot", "lastresort"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": true, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip", "extremespeed"]},
],
tier: "Bank-LC",
},
linoone: {
randomBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "shadowclaw"],
randomDoubleBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "protect", "shadowclaw"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": false, "moves":["extremespeed", "helpinghand", "babydolleyes", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
wurmple: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-LC",
},
silcoon: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-NFE",
},
beautifly: {
randomBattleMoves: ["quiverdance", "bugbuzz", "aircutter", "psychic", "gigadrain", "hiddenpowerrock"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "gigadrain", "hiddenpowerrock", "aircutter", "tailwind", "stringshot", "protect"],
tier: "Bank",
},
cascoon: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-NFE",
},
dustox: {
randomBattleMoves: ["roost", "defog", "bugbuzz", "sludgebomb", "quiverdance", "uturn", "shadowball"],
randomDoubleBattleMoves: ["tailwind", "stringshot", "strugglebug", "bugbuzz", "protect", "sludgebomb", "quiverdance", "shadowball"],
tier: "Bank",
},
lotad: {
randomBattleMoves: ["gigadrain", "icebeam", "scald", "naturepower", "raindance"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "growl", "absorb"]},
],
tier: "Bank-LC",
},
lombre: {
randomBattleMoves: ["fakeout", "swordsdance", "waterfall", "seedbomb", "icepunch", "firepunch", "thunderpunch", "poweruppunch", "gigadrain", "icebeam"],
tier: "Bank-NFE",
},
ludicolo: {
randomBattleMoves: ["raindance", "hydropump", "scald", "gigadrain", "icebeam", "focusblast"],
randomDoubleBattleMoves: ["raindance", "hydropump", "surf", "gigadrain", "icebeam", "fakeout", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["swiftswim"], "moves":["fakeout", "hydropump", "icebeam", "gigadrain"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "M", "nature": "Calm", "isHidden": false, "abilities":["swiftswim"], "moves":["scald", "gigadrain", "icebeam", "sunnyday"]},
],
tier: "Bank",
},
seedot: {
randomBattleMoves: ["defog", "naturepower", "seedbomb", "explosion", "foulplay"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["bide", "harden", "growth"]},
{"generation": 3, "level": 17, "moves":["refresh", "gigadrain", "bulletseed", "secretpower"]},
],
tier: "Bank-LC",
},
nuzleaf: {
randomBattleMoves: ["naturepower", "seedbomb", "explosion", "swordsdance", "rockslide", "lowsweep"],
tier: "Bank-NFE",
},
shiftry: {
randomBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "defog", "lowkick", "knockoff"],
randomDoubleBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "knockoff", "lowkick", "fakeout", "protect"],
tier: "Bank",
},
taillow: {
randomBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "focusenergy", "featherdance"]},
],
tier: "Bank-LC",
},
swellow: {
randomBattleMoves: ["protect", "facade", "bravebird", "uturn", "quickattack"],
randomDoubleBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"],
eventPokemon: [
{"generation": 3, "level": 43, "moves":["batonpass", "skyattack", "agility", "facade"]},
],
tier: "Bank",
},
wingull: {
randomBattleMoves: ["scald", "icebeam", "tailwind", "uturn", "airslash", "knockoff", "defog"],
tier: "LC",
},
pelipper: {
randomBattleMoves: ["scald", "uturn", "hurricane", "toxic", "roost", "defog", "knockoff"],
randomDoubleBattleMoves: ["scald", "surf", "hurricane", "wideguard", "protect", "tailwind", "knockoff"],
tier: "New",
},
ralts: {
randomBattleMoves: ["trickroom", "destinybond", "psychic", "willowisp", "hypnosis", "dazzlinggleam", "substitute", "trick"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "charm"]},
{"generation": 3, "level": 20, "moves":["sing", "shockwave", "reflect", "confusion"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["growl", "encore"]},
],
tier: "Bank-LC",
},
kirlia: {
randomBattleMoves: ["trick", "dazzlinggleam", "psychic", "willowisp", "signalbeam", "thunderbolt", "destinybond", "substitute"],
tier: "Bank-NFE",
},
gardevoir: {
randomBattleMoves: ["psychic", "thunderbolt", "focusblast", "shadowball", "moonblast", "calmmind", "substitute", "willowisp"],
randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "moonblast", "taunt", "willowisp", "thunderbolt", "trickroom", "helpinghand", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["trace"], "moves":["hypnosis", "thunderbolt", "focusblast", "psychic"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": true, "gender": "F", "isHidden": false, "abilities":["synchronize"], "moves":["dazzlinggleam", "moonblast", "storedpower", "calmmind"], "pokeball": "cherishball"},
],
tier: "Bank",
},
gardevoirmega: {
randomBattleMoves: ["calmmind", "hypervoice", "psyshock", "focusblast", "substitute", "taunt", "willowisp"],
randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "calmmind", "thunderbolt", "hypervoice", "protect"],
requiredItem: "Gardevoirite",
tier: "Bank",
},
gallade: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "shadowsneak", "closecombat", "zenheadbutt", "knockoff", "trick"],
randomDoubleBattleMoves: ["closecombat", "trick", "stoneedge", "shadowsneak", "drainpunch", "icepunch", "zenheadbutt", "knockoff", "trickroom", "protect", "helpinghand"],
tier: "Bank",
},
gallademega: {
randomBattleMoves: ["swordsdance", "closecombat", "drainpunch", "knockoff", "zenheadbutt", "substitute"],
randomDoubleBattleMoves: ["closecombat", "stoneedge", "drainpunch", "icepunch", "zenheadbutt", "swordsdance", "knockoff", "protect"],
requiredItem: "Galladite",
tier: "Bank",
},
surskit: {
randomBattleMoves: ["hydropump", "signalbeam", "hiddenpowerfire", "stickyweb", "gigadrain", "powersplit"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "mudsport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["bubble", "quickattack"]},
],
tier: "LC",
},
masquerain: {
randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "hydropump", "roost", "batonpass", "stickyweb"],
randomDoubleBattleMoves: ["hydropump", "bugbuzz", "airslash", "quiverdance", "tailwind", "roost", "strugglebug", "protect"],
tier: "New",
},
shroomish: {
randomBattleMoves: ["spore", "substitute", "leechseed", "gigadrain", "protect", "toxic", "stunspore"],
eventPokemon: [
{"generation": 3, "level": 15, "abilities":["effectspore"], "moves":["refresh", "falseswipe", "megadrain", "stunspore"]},
],
tier: "Bank-LC",
},
breloom: {
randomBattleMoves: ["spore", "machpunch", "bulletseed", "rocktomb", "swordsdance"],
randomDoubleBattleMoves: ["spore", "helpinghand", "machpunch", "bulletseed", "rocktomb", "protect", "drainpunch"],
tier: "Bank",
},
slakoth: {
randomBattleMoves: ["doubleedge", "hammerarm", "firepunch", "counter", "retaliate", "toxic"],
tier: "LC",
},
vigoroth: {
randomBattleMoves: ["bulkup", "return", "earthquake", "firepunch", "suckerpunch", "slackoff", "icepunch", "lowkick"],
tier: "New",
},
slaking: {
randomBattleMoves: ["earthquake", "pursuit", "nightslash", "doubleedge", "retaliate"],
randomDoubleBattleMoves: ["earthquake", "nightslash", "doubleedge", "retaliate", "hammerarm", "rockslide"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["gigaimpact", "return", "shadowclaw", "aerialace"], "pokeball": "cherishball"},
],
tier: "New",
},
nincada: {
randomBattleMoves: ["xscissor", "dig", "aerialace", "nightslash"],
tier: "Bank-LC",
},
ninjask: {
randomBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "xscissor"],
randomDoubleBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "xscissor", "aerialace"],
tier: "Bank",
},
shedinja: {
randomBattleMoves: ["swordsdance", "willowisp", "xscissor", "shadowsneak", "shadowclaw", "batonpass"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["spite", "confuseray", "shadowball", "grudge"]},
{"generation": 3, "level": 20, "moves":["doubleteam", "furycutter", "screech"]},
{"generation": 3, "level": 25, "moves":["swordsdance"]},
{"generation": 3, "level": 31, "moves":["slash"]},
{"generation": 3, "level": 38, "moves":["agility"]},
{"generation": 3, "level": 45, "moves":["batonpass"]},
{"generation": 4, "level": 52, "moves":["xscissor"]},
],
tier: "Bank",
},
whismur: {
randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "extrasensory"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["pound", "uproar", "teeterdance"]},
],
tier: "Bank-LC",
},
loudred: {
randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "circlethrow", "bodyslam"],
tier: "Bank-NFE",
},
exploud: {
randomBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast"],
randomDoubleBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast", "protect", "hypervoice"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["roar", "rest", "sleeptalk", "hypervoice"]},
{"generation": 3, "level": 50, "moves":["stomp", "screech", "hyperbeam", "roar"]},
],
tier: "Bank",
},
makuhita: {
randomBattleMoves: ["crosschop", "bulletpunch", "closecombat", "icepunch", "bulkup", "fakeout", "earthquake"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["refresh", "brickbreak", "armthrust", "rocktomb"]},
],
tier: "LC",
},
hariyama: {
randomBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "fakeout", "knockoff", "helpinghand", "wideguard", "protect"],
tier: "New",
},
nosepass: {
randomBattleMoves: ["powergem", "thunderwave", "stealthrock", "painsplit", "explosion", "voltswitch"],
eventPokemon: [
{"generation": 3, "level": 26, "moves":["helpinghand", "thunderbolt", "thunderwave", "rockslide"]},
],
tier: "LC",
},
probopass: {
randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "flashcannon", "powergem", "voltswitch", "painsplit"],
randomDoubleBattleMoves: ["stealthrock", "thunderwave", "helpinghand", "earthpower", "powergem", "wideguard", "protect", "voltswitch"],
tier: "New",
},
skitty: {
randomBattleMoves: ["doubleedge", "zenheadbutt", "thunderwave", "fakeout", "playrough", "healbell"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["tackle", "growl", "tailwhip", "payday"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "rollout"]},
{"generation": 3, "level": 10, "gender": "M", "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "attract"]},
],
tier: "Bank-LC",
},
delcatty: {
randomBattleMoves: ["doubleedge", "suckerpunch", "wildcharge", "fakeout", "thunderwave", "healbell"],
randomDoubleBattleMoves: ["doubleedge", "suckerpunch", "playrough", "wildcharge", "fakeout", "thunderwave", "protect", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 18, "abilities":["cutecharm"], "moves":["sweetkiss", "secretpower", "attract", "shockwave"]},
],
tier: "Bank",
},
sableye: {
randomBattleMoves: ["recover", "willowisp", "taunt", "toxic", "knockoff", "foulplay"],
randomDoubleBattleMoves: ["recover", "willowisp", "taunt", "fakeout", "knockoff", "foulplay", "helpinghand", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["keeneye"], "moves":["leer", "scratch", "foresight", "nightshade"]},
{"generation": 3, "level": 33, "abilities":["keeneye"], "moves":["helpinghand", "shadowball", "feintattack", "recover"]},
{"generation": 5, "level": 50, "gender": "M", "isHidden": true, "moves":["foulplay", "octazooka", "tickle", "trick"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Relaxed", "ivs": {"hp": 31, "spa": 31}, "isHidden": true, "moves":["calmmind", "willowisp", "recover", "shadowball"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Bold", "isHidden": true, "moves":["willowisp", "recover", "taunt", "shockwave"], "pokeball": "cherishball"},
],
tier: "New",
},
sableyemega: {
randomBattleMoves: ["recover", "willowisp", "darkpulse", "calmmind", "shadowball"],
randomDoubleBattleMoves: ["fakeout", "knockoff", "darkpulse", "shadowball", "willowisp", "protect"],
requiredItem: "Sablenite",
tier: "New",
},
mawile: {
randomBattleMoves: ["swordsdance", "ironhead", "substitute", "playrough", "suckerpunch", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "faketears"]},
{"generation": 3, "level": 22, "moves":["sing", "falseswipe", "vicegrip", "irondefense"]},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["intimidate"], "moves":["ironhead", "playrough", "firefang", "suckerpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": false, "abilities":["intimidate"], "moves":["suckerpunch", "protect", "playrough", "ironhead"], "pokeball": "cherishball"},
],
tier: "Bank",
},
mawilemega: {
randomBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "focuspunch"],
randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"],
requiredItem: "Mawilite",
tier: "Bank",
},
aron: {
randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock", "endeavor"],
tier: "Bank-LC",
},
lairon: {
randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock"],
tier: "Bank-NFE",
},
aggron: {
randomBattleMoves: ["autotomize", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock"],
randomDoubleBattleMoves: ["rockslide", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["irontail", "protect", "metalsound", "doubleedge"]},
{"generation": 3, "level": 50, "moves":["takedown", "irontail", "protect", "metalsound"]},
{"generation": 6, "level": 50, "nature": "Brave", "isHidden": false, "abilities":["rockhead"], "moves":["ironhead", "earthquake", "headsmash", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
aggronmega: {
randomBattleMoves: ["earthquake", "heavyslam", "icepunch", "stealthrock", "thunderwave", "roar", "toxic"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "lowkick", "heavyslam", "aquatail", "protect"],
requiredItem: "Aggronite",
tier: "Bank",
},
meditite: {
randomBattleMoves: ["highjumpkick", "psychocut", "icepunch", "thunderpunch", "trick", "fakeout", "bulletpunch", "drainpunch", "zenheadbutt"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["bide", "meditate", "confusion"]},
{"generation": 3, "level": 20, "moves":["dynamicpunch", "confusion", "shadowball", "detect"]},
],
tier: "Bank",
},
medicham: {
randomBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch"],
randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"],
tier: "Bank",
},
medichammega: {
randomBattleMoves: ["highjumpkick", "drainpunch", "icepunch", "fakeout", "zenheadbutt"],
randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"],
requiredItem: "Medichamite",
tier: "Bank",
},
electrike: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "switcheroo", "flamethrower", "hiddenpowergrass"],
tier: "Bank-LC",
},
manectric: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["refresh", "thunder", "raindance", "bite"]},
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["lightningrod"], "moves":["overheat", "thunderbolt", "voltswitch", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
manectricmega: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"],
requiredItem: "Manectite",
tier: "Bank",
},
plusle: {
randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "mudsport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]},
],
tier: "Bank",
},
minun: {
randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "watersport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]},
],
tier: "Bank",
},
volbeat: {
randomBattleMoves: ["tailglow", "batonpass", "substitute", "bugbuzz", "thunderwave", "encore", "tailwind"],
randomDoubleBattleMoves: ["stringshot", "strugglebug", "helpinghand", "bugbuzz", "thunderwave", "encore", "tailwind", "protect"],
tier: "Bank",
},
illumise: {
randomBattleMoves: ["substitute", "batonpass", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn", "thunderwave"],
randomDoubleBattleMoves: ["protect", "helpinghand", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn"],
tier: "Bank",
},
budew: {
randomBattleMoves: ["spikes", "sludgebomb", "sleeppowder", "gigadrain", "stunspore", "rest"],
tier: "LC",
},
roselia: {
randomBattleMoves: ["spikes", "toxicspikes", "sleeppowder", "gigadrain", "stunspore", "rest", "sludgebomb", "synthesis"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["absorb", "growth", "poisonsting"]},
{"generation": 3, "level": 22, "moves":["sweetkiss", "magicalleaf", "leechseed", "grasswhistle"]},
],
tier: "New",
},
roserade: {
randomBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "spikes", "toxicspikes", "rest", "synthesis", "hiddenpowerfire"],
randomDoubleBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "protect", "hiddenpowerfire"],
tier: "New",
},
gulpin: {
randomBattleMoves: ["stockpile", "sludgebomb", "sludgewave", "icebeam", "toxic", "painsplit", "yawn", "encore"],
eventPokemon: [
{"generation": 3, "level": 17, "moves":["sing", "shockwave", "sludge", "toxic"]},
],
tier: "Bank-LC",
},
swalot: {
randomBattleMoves: ["sludgebomb", "icebeam", "toxic", "yawn", "encore", "painsplit", "earthquake"],
randomDoubleBattleMoves: ["sludgebomb", "icebeam", "protect", "yawn", "encore", "gunkshot", "earthquake"],
tier: "Bank",
},
carvanha: {
randomBattleMoves: ["protect", "hydropump", "icebeam", "waterfall", "crunch", "aquajet", "destinybond"],
eventPokemon: [
{"generation": 3, "level": 15, "moves":["refresh", "waterpulse", "bite", "scaryface"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["leer", "bite", "hydropump"]},
],
tier: "LC",
},
sharpedo: {
randomBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall", "destinybond"],
randomDoubleBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall", "destinybond"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "isHidden": true, "moves":["aquajet", "crunch", "icefang", "destinybond"], "pokeball": "cherishball"},
{"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["scaryface", "slash", "poisonfang", "crunch"], "pokeball": "cherishball"},
],
tier: "New",
},
sharpedomega: {
randomBattleMoves: ["protect", "icefang", "crunch", "earthquake", "waterfall", "zenheadbutt"],
requiredItem: "Sharpedonite",
tier: "New",
},
wailmer: {
randomBattleMoves: ["waterspout", "surf", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerelectric"],
tier: "LC",
},
wailord: {
randomBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire"],
randomDoubleBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["rest", "waterspout", "amnesia", "hydropump"]},
{"generation": 3, "level": 50, "moves":["waterpulse", "mist", "rest", "waterspout"]},
],
tier: "New",
},
numel: {
randomBattleMoves: ["curse", "earthquake", "rockslide", "fireblast", "flamecharge", "rest", "sleeptalk", "stockpile", "hiddenpowerelectric", "earthpower", "lavaplume"],
eventPokemon: [
{"generation": 3, "level": 14, "abilities":["oblivious"], "moves":["charm", "takedown", "dig", "ember"]},
{"generation": 6, "level": 1, "isHidden": false, "moves":["growl", "tackle", "ironhead"]},
],
tier: "Bank-LC",
},
camerupt: {
randomBattleMoves: ["rockpolish", "fireblast", "earthpower", "lavaplume", "stealthrock", "hiddenpowergrass", "roar", "stoneedge"],
randomDoubleBattleMoves: ["rockpolish", "fireblast", "earthpower", "heatwave", "eruption", "hiddenpowergrass", "protect"],
eventPokemon: [
{"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["solidrock"], "moves":["curse", "takedown", "rockslide", "yawn"], "pokeball": "cherishball"},
],
tier: "Bank",
},
cameruptmega: {
randomBattleMoves: ["stealthrock", "fireblast", "earthpower", "ancientpower", "willowisp", "toxic"],
randomDoubleBattleMoves: ["fireblast", "earthpower", "heatwave", "eruption", "rockslide", "protect"],
requiredItem: "Cameruptite",
tier: "Bank",
},
torkoal: {
randomBattleMoves: ["shellsmash", "fireblast", "earthpower", "hiddenpowergrass", "stealthrock", "rapidspin", "yawn", "lavaplume"],
randomDoubleBattleMoves: ["protect", "heatwave", "earthpower", "willowisp", "shellsmash", "fireblast", "hiddenpowergrass"],
tier: "New",
},
spoink: {
randomBattleMoves: ["psychic", "reflect", "lightscreen", "thunderwave", "trick", "healbell", "calmmind", "hiddenpowerfighting", "shadowball"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["owntempo"], "moves":["splash", "uproar"]},
],
tier: "Bank-LC",
},
grumpig: {
randomBattleMoves: ["psychic", "thunderwave", "healbell", "whirlwind", "toxic", "focusblast", "reflect", "lightscreen"],
randomDoubleBattleMoves: ["psychic", "psyshock", "thunderwave", "trickroom", "taunt", "protect", "focusblast", "reflect", "lightscreen"],
tier: "Bank",
},
spinda: {
randomBattleMoves: ["return", "superpower", "suckerpunch", "trickroom"],
randomDoubleBattleMoves: ["doubleedge", "return", "superpower", "suckerpunch", "trickroom", "fakeout", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "uproar", "sing"]},
],
tier: "New",
},
trapinch: {
randomBattleMoves: ["earthquake", "rockslide", "crunch", "quickattack", "superpower"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bite"]},
],
tier: "LC",
},
vibrava: {
randomBattleMoves: ["substitute", "earthquake", "outrage", "roost", "uturn", "superpower", "defog"],
tier: "NFE",
},
flygon: {
randomBattleMoves: ["earthquake", "outrage", "uturn", "roost", "stoneedge", "firepunch", "fireblast", "defog"],
randomDoubleBattleMoves: ["earthquake", "protect", "dragonclaw", "uturn", "rockslide", "firepunch", "fireblast", "tailwind", "feint"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["sandtomb", "crunch", "dragonbreath", "screech"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naive", "moves":["dracometeor", "uturn", "earthquake", "dragonclaw"], "pokeball": "cherishball"},
],
tier: "New",
},
cacnea: {
randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["poisonsting", "leer", "absorb", "encore"]},
],
tier: "Bank-LC",
},
cacturne: {
randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch", "substitute"],
randomDoubleBattleMoves: ["swordsdance", "spikyshield", "suckerpunch", "seedbomb", "drainpunch", "substitute"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["ingrain", "feintattack", "spikes", "needlearm"]},
],
tier: "Bank",
},
swablu: {
randomBattleMoves: ["roost", "toxic", "cottonguard", "pluck", "hypervoice", "return"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "falseswipe"]},
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["peck", "growl"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["peck", "growl", "hypervoice"]},
],
tier: "Bank-LC",
},
altaria: {
randomBattleMoves: ["dragondance", "dracometeor", "outrage", "dragonclaw", "earthquake", "roost", "fireblast", "healbell"],
randomDoubleBattleMoves: ["dragondance", "dracometeor", "protect", "dragonclaw", "earthquake", "fireblast", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["takedown", "dragonbreath", "dragondance", "refresh"]},
{"generation": 3, "level": 36, "moves":["healbell", "dragonbreath", "solarbeam", "aerialace"]},
{"generation": 5, "level": 35, "gender": "M", "isHidden": true, "moves":["takedown", "naturalgift", "dragonbreath", "falseswipe"]},
{"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["hypervoice", "fireblast", "protect", "agility"], "pokeball": "cherishball"},
],
tier: "Bank",
},
altariamega: {
randomBattleMoves: ["dragondance", "return", "hypervoice", "healbell", "earthquake", "roost", "dracometeor", "fireblast"],
randomDoubleBattleMoves: ["dragondance", "return", "doubleedge", "dragonclaw", "earthquake", "protect", "fireblast"],
requiredItem: "Altarianite",
tier: "Bank",
},
zangoose: {
randomBattleMoves: ["swordsdance", "closecombat", "knockoff", "quickattack", "facade"],
randomDoubleBattleMoves: ["protect", "closecombat", "knockoff", "quickattack", "facade"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["leer", "quickattack", "swordsdance", "furycutter"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "quickattack", "swordsdance"]},
{"generation": 3, "level": 28, "moves":["refresh", "brickbreak", "counter", "crushclaw"]},
],
tier: "Bank",
},
seviper: {
randomBattleMoves: ["flamethrower", "sludgewave", "gigadrain", "darkpulse", "switcheroo", "coil", "earthquake", "poisonjab", "suckerpunch"],
randomDoubleBattleMoves: ["flamethrower", "gigadrain", "earthquake", "suckerpunch", "aquatail", "protect", "glare", "poisonjab", "sludgebomb"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["wrap", "lick", "bite", "poisontail"]},
{"generation": 3, "level": 30, "moves":["poisontail", "screech", "glare", "crunch"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "lick", "bite"]},
],
tier: "Bank",
},
lunatone: {
randomBattleMoves: ["psychic", "earthpower", "stealthrock", "rockpolish", "batonpass", "calmmind", "icebeam", "ancientpower", "moonlight", "toxic"],
randomDoubleBattleMoves: ["psychic", "earthpower", "rockpolish", "calmmind", "helpinghand", "icebeam", "ancientpower", "moonlight", "trickroom", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]},
{"generation": 3, "level": 25, "moves":["batonpass", "psychic", "raindance", "rocktomb"]},
],
tier: "Bank",
},
solrock: {
randomBattleMoves: ["stealthrock", "explosion", "rockslide", "reflect", "lightscreen", "willowisp", "morningsun"],
randomDoubleBattleMoves: ["protect", "helpinghand", "stoneedge", "zenheadbutt", "willowisp", "trickroom", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]},
{"generation": 3, "level": 41, "moves":["batonpass", "psychic", "sunnyday", "cosmicpower"]},
],
tier: "Bank",
},
barboach: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "return", "bounce"],
tier: "LC",
},
whiscash: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt", "protect"],
eventPokemon: [
{"generation": 4, "level": 51, "gender": "F", "nature": "Gentle", "abilities":["oblivious"], "moves":["earthquake", "aquatail", "zenheadbutt", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "New",
},
corphish: {
randomBattleMoves: ["dragondance", "waterfall", "crunch", "superpower", "swordsdance", "knockoff", "aquajet"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "watersport"]},
],
tier: "Bank-LC",
},
crawdaunt: {
randomBattleMoves: ["dragondance", "crabhammer", "superpower", "swordsdance", "knockoff", "aquajet"],
randomDoubleBattleMoves: ["dragondance", "crabhammer", "crunch", "superpower", "swordsdance", "knockoff", "aquajet", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["taunt", "crabhammer", "swordsdance", "guillotine"]},
{"generation": 3, "level": 50, "moves":["knockoff", "taunt", "crabhammer", "swordsdance"]},
],
tier: "Bank",
},
baltoy: {
randomBattleMoves: ["stealthrock", "earthquake", "toxic", "psychic", "reflect", "lightscreen", "icebeam", "rapidspin"],
eventPokemon: [
{"generation": 3, "level": 17, "moves":["refresh", "rocktomb", "mudslap", "psybeam"]},
],
tier: "Bank-LC",
},
claydol: {
randomBattleMoves: ["stealthrock", "toxic", "psychic", "icebeam", "earthquake", "rapidspin"],
randomDoubleBattleMoves: ["earthpower", "trickroom", "psychic", "icebeam", "earthquake", "protect"],
tier: "Bank",
},
lileep: {
randomBattleMoves: ["stealthrock", "recover", "ancientpower", "hiddenpowerfire", "gigadrain", "stockpile"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["recover", "rockslide", "constrict", "acid"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
cradily: {
randomBattleMoves: ["stealthrock", "recover", "gigadrain", "toxic", "seedbomb", "rockslide", "curse"],
randomDoubleBattleMoves: ["protect", "recover", "seedbomb", "rockslide", "earthquake", "curse", "swordsdance"],
tier: "Bank",
},
anorith: {
randomBattleMoves: ["stealthrock", "brickbreak", "toxic", "xscissor", "rockslide", "swordsdance", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["harden", "mudsport", "watergun", "crosspoison"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
armaldo: {
randomBattleMoves: ["stealthrock", "stoneedge", "toxic", "xscissor", "swordsdance", "knockoff", "rapidspin"],
randomDoubleBattleMoves: ["rockslide", "stoneedge", "stringshot", "xscissor", "swordsdance", "knockoff", "protect"],
tier: "Bank",
},
feebas: {
randomBattleMoves: ["protect", "confuseray", "hypnosis", "scald", "toxic"],
eventPokemon: [
{"generation": 4, "level": 5, "gender": "F", "nature": "Calm", "moves":["splash", "mirrorcoat"], "pokeball": "cherishball"},
],
tier: "LC",
},
milotic: {
randomBattleMoves: ["recover", "scald", "toxic", "icebeam", "dragontail", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["recover", "scald", "hydropump", "icebeam", "dragontail", "hypnosis", "protect", "hiddenpowergrass"],
eventPokemon: [
{"generation": 3, "level": 35, "moves":["waterpulse", "twister", "recover", "raindance"]},
{"generation": 4, "level": 50, "gender": "F", "nature": "Bold", "moves":["recover", "raindance", "icebeam", "hydropump"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Timid", "moves":["raindance", "recover", "hydropump", "icywind"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["recover", "hydropump", "icebeam", "mirrorcoat"], "pokeball": "cherishball"},
{"generation": 5, "level": 58, "gender": "M", "nature": "Lax", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["recover", "surf", "icebeam", "toxic"], "pokeball": "cherishball"},
],
tier: "New",
},
castform: {
tier: "New",
},
castformsunny: {
randomBattleMoves: ["sunnyday", "weatherball", "solarbeam", "icebeam"],
battleOnly: true,
},
castformrainy: {
randomBattleMoves: ["raindance", "weatherball", "thunder", "hurricane"],
battleOnly: true,
},
castformsnowy: {
battleOnly: true,
},
kecleon: {
randomBattleMoves: ["fakeout", "knockoff", "drainpunch", "suckerpunch", "shadowsneak", "stealthrock", "recover"],
randomDoubleBattleMoves: ["knockoff", "fakeout", "trickroom", "recover", "drainpunch", "suckerpunch", "shadowsneak", "protect"],
tier: "Bank",
},
shuppet: {
randomBattleMoves: ["trickroom", "destinybond", "taunt", "shadowsneak", "suckerpunch", "willowisp"],
eventPokemon: [
{"generation": 3, "level": 45, "abilities":["insomnia"], "moves":["spite", "willowisp", "feintattack", "shadowball"]},
],
tier: "Bank-LC",
},
banette: {
randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff"],
randomDoubleBattleMoves: ["shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 37, "abilities":["insomnia"], "moves":["helpinghand", "feintattack", "shadowball", "curse"]},
{"generation": 5, "level": 37, "gender": "F", "isHidden": true, "moves":["feintattack", "hex", "shadowball", "cottonguard"]},
],
tier: "Bank",
},
banettemega: {
randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff"],
randomDoubleBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff", "protect"],
requiredItem: "Banettite",
tier: "Bank",
},
duskull: {
randomBattleMoves: ["willowisp", "shadowsneak", "painsplit", "substitute", "nightshade", "destinybond", "trickroom"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["pursuit", "curse", "willowisp", "meanlook"]},
{"generation": 3, "level": 19, "moves":["helpinghand", "shadowball", "astonish", "confuseray"]},
],
tier: "Bank-LC",
},
dusclops: {
randomBattleMoves: ["willowisp", "shadowsneak", "icebeam", "painsplit", "substitute", "seismictoss", "toxic", "trickroom"],
tier: "Bank-NFE",
},
dusknoir: {
randomBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "substitute", "earthquake", "focuspunch"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "protect", "earthquake", "helpinghand", "trickroom"],
tier: "Bank",
},
tropius: {
randomBattleMoves: ["leechseed", "substitute", "airslash", "gigadrain", "toxic", "protect"],
randomDoubleBattleMoves: ["leechseed", "protect", "airslash", "gigadrain", "earthquake", "hiddenpowerfire", "tailwind", "sunnyday", "roost"],
eventPokemon: [
{"generation": 4, "level": 53, "gender": "F", "nature": "Jolly", "abilities":["chlorophyll"], "moves":["airslash", "synthesis", "sunnyday", "solarbeam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
chingling: {
randomBattleMoves: ["hypnosis", "reflect", "lightscreen", "toxic", "recover", "psychic", "signalbeam", "healbell"],
tier: "Bank-LC",
},
chimecho: {
randomBattleMoves: ["psychic", "yawn", "recover", "calmmind", "shadowball", "healingwish", "healbell", "taunt"],
randomDoubleBattleMoves: ["protect", "psychic", "thunderwave", "recover", "shadowball", "dazzlinggleam", "trickroom", "helpinghand", "taunt"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "growl", "astonish"]},
],
tier: "Bank",
},
absol: {
randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "superpower", "pursuit", "playrough"],
randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "spite"]},
{"generation": 3, "level": 35, "abilities":["pressure"], "moves":["razorwind", "bite", "swordsdance", "spite"]},
{"generation": 3, "level": 70, "abilities":["pressure"], "moves":["doubleteam", "slash", "futuresight", "perishsong"]},
],
tier: "New",
},
absolmega: {
randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "pursuit", "playrough", "icebeam"],
randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"],
requiredItem: "Absolite",
tier: "New",
},
snorunt: {
randomBattleMoves: ["spikes", "icebeam", "iceshard", "shadowball", "toxic"],
eventPokemon: [
{"generation": 3, "level": 20, "abilities":["innerfocus"], "moves":["sing", "waterpulse", "bite", "icywind"]},
],
tier: "LC",
},
glalie: {
randomBattleMoves: ["spikes", "icebeam", "iceshard", "taunt", "earthquake", "explosion", "superfang"],
randomDoubleBattleMoves: ["icebeam", "iceshard", "taunt", "earthquake", "protect"],
tier: "New",
},
glaliemega: {
randomBattleMoves: ["freezedry", "iceshard", "earthquake", "explosion", "return", "spikes"],
randomDoubleBattleMoves: ["crunch", "iceshard", "freezedry", "earthquake", "explosion", "protect", "return"],
requiredItem: "Glalitite",
tier: "New",
},
froslass: {
randomBattleMoves: ["icebeam", "spikes", "destinybond", "shadowball", "taunt", "thunderwave"],
randomDoubleBattleMoves: ["icebeam", "protect", "destinybond", "shadowball", "taunt", "thunderwave"],
tier: "New",
},
spheal: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"],
eventPokemon: [
{"generation": 3, "level": 17, "abilities":["thickfat"], "moves":["charm", "aurorabeam", "watergun", "mudslap"]},
],
tier: "LC",
},
sealeo: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"],
tier: "NFE",
},
walrein: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "roar"],
randomDoubleBattleMoves: ["protect", "icywind", "surf", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 50, "isHidden": false, "abilities":["thickfat"], "moves":["icebeam", "brine", "hail", "sheercold"], "pokeball": "cherishball"},
],
tier: "New",
},
clamperl: {
randomBattleMoves: ["shellsmash", "icebeam", "surf", "hiddenpowergrass", "hiddenpowerelectric", "substitute"],
tier: "Bank-LC",
},
huntail: {
randomBattleMoves: ["shellsmash", "waterfall", "icebeam", "batonpass", "suckerpunch"],
randomDoubleBattleMoves: ["shellsmash", "waterfall", "icefang", "batonpass", "suckerpunch", "protect"],
tier: "Bank",
},
gorebyss: {
randomBattleMoves: ["shellsmash", "batonpass", "hydropump", "icebeam", "hiddenpowergrass", "substitute"],
randomDoubleBattleMoves: ["shellsmash", "batonpass", "surf", "icebeam", "hiddenpowergrass", "substitute", "protect"],
tier: "Bank",
},
relicanth: {
randomBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "stealthrock", "toxic"],
randomDoubleBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "rockslide", "protect"],
tier: "New",
},
luvdisc: {
randomBattleMoves: ["icebeam", "toxic", "sweetkiss", "protect", "scald"],
tier: "New",
},
bagon: {
randomBattleMoves: ["outrage", "dragondance", "firefang", "rockslide", "dragonclaw"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "irondefense"]},
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["rage"]},
{"generation": 6, "level": 1, "isHidden": false, "moves":["rage", "thrash"]},
],
tier: "LC",
},
shelgon: {
randomBattleMoves: ["outrage", "brickbreak", "dragonclaw", "dragondance", "crunch", "zenheadbutt"],
tier: "NFE",
},
salamence: {
randomBattleMoves: ["outrage", "fireblast", "earthquake", "dracometeor", "dragondance", "dragonclaw"],
randomDoubleBattleMoves: ["protect", "fireblast", "earthquake", "dracometeor", "tailwind", "dragondance", "dragonclaw", "hydropump", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["protect", "dragonbreath", "scaryface", "fly"]},
{"generation": 3, "level": 50, "moves":["refresh", "dragonclaw", "dragondance", "aerialace"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["hydropump", "stoneedge", "fireblast", "dragonclaw"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["dragondance", "dragonclaw", "outrage", "aerialace"], "pokeball": "cherishball"},
],
tier: "New",
},
salamencemega: {
randomBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "roost", "dragondance"],
randomDoubleBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "protect", "dragondance", "dragonclaw"],
requiredItem: "Salamencite",
tier: "Uber",
},
beldum: {
randomBattleMoves: ["ironhead", "zenheadbutt", "headbutt", "irondefense"],
eventPokemon: [
{"generation": 6, "level": 5, "shiny": true, "isHidden": false, "moves":["holdback", "ironhead", "zenheadbutt", "irondefense"], "pokeball": "cherishball"},
],
tier: "LC",
},
metang: {
randomBattleMoves: ["stealthrock", "meteormash", "toxic", "earthquake", "bulletpunch", "zenheadbutt"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["takedown", "confusion", "metalclaw", "refresh"]},
],
tier: "New",
},
metagross: {
randomBattleMoves: ["meteormash", "earthquake", "agility", "stealthrock", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch"],
randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch", "hammerarm"],
eventPokemon: [
{"generation": 4, "level": 62, "nature": "Brave", "moves":["bulletpunch", "meteormash", "hammerarm", "zenheadbutt"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["meteormash", "earthquake", "bulletpunch", "hammerarm"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "isHidden": false, "moves":["bulletpunch", "zenheadbutt", "hammerarm", "icepunch"], "pokeball": "cherishball"},
{"generation": 5, "level": 45, "isHidden": false, "moves":["earthquake", "zenheadbutt", "protect", "meteormash"]},
{"generation": 5, "level": 45, "isHidden": true, "moves":["irondefense", "agility", "hammerarm", "doubleedge"]},
{"generation": 5, "level": 45, "isHidden": true, "moves":["psychic", "meteormash", "hammerarm", "doubleedge"]},
{"generation": 5, "level": 58, "nature": "Serious", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["earthquake", "hyperbeam", "psychic", "meteormash"], "pokeball": "cherishball"},
],
tier: "New",
},
metagrossmega: {
randomBattleMoves: ["meteormash", "earthquake", "agility", "zenheadbutt", "hammerarm", "icepunch"],
randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "thunderpunch", "icepunch"],
requiredItem: "Metagrossite",
tier: "New",
},
regirock: {
randomBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rest", "rockslide", "toxic"],
randomDoubleBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["rockthrow", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "rockthrow", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["irondefense", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "irondefense"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["explosion", "icepunch", "stoneedge", "hammerarm"]},
],
eventOnly: true,
tier: "Bank",
},
regice: {
randomBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "rest", "sleeptalk", "focusblast", "rockpolish"],
randomDoubleBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "icywind", "protect", "focusblast", "rockpolish"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["icywind", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "icywind", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "amnesia"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["thunderbolt", "amnesia", "icebeam", "hail"]},
],
eventOnly: true,
tier: "Bank",
},
registeel: {
randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "protect", "seismictoss", "curse", "ironhead", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["stealthrock", "ironhead", "curse", "rest", "thunderwave", "protect", "seismictoss"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["metalclaw", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "metalclaw", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["curse", "ancientpower", "irondefense", "amnesia"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["ironhead", "rockslide", "gravity", "irondefense"]},
],
eventOnly: true,
tier: "Bank",
},
latias: {
randomBattleMoves: ["dracometeor", "psyshock", "hiddenpowerfire", "roost", "thunderbolt", "healingwish", "defog"],
randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "psychic"]},
{"generation": 3, "level": 50, "shiny": 1, "moves":["mistball", "psychic", "recover", "charm"]},
{"generation": 3, "level": 70, "moves":["mistball", "psychic", "recover", "charm"]},
{"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "watersport", "refresh", "mistball"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "zenheadbutt"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "charm", "psychic", "healpulse"]},
{"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "mistball", "psychoshift"]},
],
eventOnly: true,
tier: "Bank",
},
latiasmega: {
randomBattleMoves: ["calmmind", "dragonpulse", "surf", "dracometeor", "roost", "hiddenpowerfire", "substitute", "psyshock"],
randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"],
requiredItem: "Latiasite",
tier: "Bank",
},
latios: {
randomBattleMoves: ["dracometeor", "hiddenpowerfire", "surf", "thunderbolt", "psyshock", "roost", "trick", "defog"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "trick", "tailwind", "protect", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "psychic"]},
{"generation": 3, "level": 50, "shiny": 1, "moves":["lusterpurge", "psychic", "recover", "dragondance"]},
{"generation": 3, "level": 70, "moves":["lusterpurge", "psychic", "recover", "dragondance"]},
{"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "protect", "refresh", "lusterpurge"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "zenheadbutt"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "dragondance", "psychic", "healpulse"]},
{"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "lusterpurge", "psychoshift"]},
{"generation": 6, "level": 50, "nature": "Modest", "moves":["dragonpulse", "lusterpurge", "psychic", "healpulse"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
latiosmega: {
randomBattleMoves: ["calmmind", "dracometeor", "hiddenpowerfire", "psyshock", "roost", "memento", "defog"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "tailwind", "protect", "hiddenpowerfire"],
requiredItem: "Latiosite",
tier: "Bank",
},
kyogre: {
randomBattleMoves: ["waterspout", "originpulse", "scald", "thunder", "icebeam"],
randomDoubleBattleMoves: ["waterspout", "muddywater", "originpulse", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"],
eventPokemon: [
{"generation": 3, "level": 45, "shiny": 1, "moves":["bodyslam", "calmmind", "icebeam", "hydropump"]},
{"generation": 3, "level": 70, "shiny": 1, "moves":["hydropump", "rest", "sheercold", "doubleedge"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["aquaring", "icebeam", "ancientpower", "waterspout"]},
{"generation": 5, "level": 80, "shiny": 1, "moves":["icebeam", "ancientpower", "waterspout", "thunder"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["waterspout", "thunder", "icebeam", "sheercold"], "pokeball": "cherishball"},
{"generation": 6, "level": 45, "moves":["bodyslam", "aquaring", "icebeam", "originpulse"]},
{"generation": 6, "level": 100, "nature": "Timid", "moves":["waterspout", "thunder", "sheercold", "icebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
kyogreprimal: {
randomBattleMoves: ["calmmind", "waterspout", "originpulse", "scald", "thunder", "icebeam", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["waterspout", "originpulse", "muddywater", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"],
requiredItem: "Blue Orb",
},
groudon: {
randomBattleMoves: ["precipiceblades", "earthquake", "stealthrock", "lavaplume", "stoneedge", "dragontail", "roar", "toxic", "swordsdance", "rockpolish", "firepunch"],
randomDoubleBattleMoves: ["precipiceblades", "rockslide", "protect", "stoneedge", "swordsdance", "rockpolish", "dragonclaw", "firepunch"],
eventPokemon: [
{"generation": 3, "level": 45, "shiny": 1, "moves":["slash", "bulkup", "earthquake", "fireblast"]},
{"generation": 3, "level": 70, "shiny": 1, "moves":["fireblast", "rest", "fissure", "solarbeam"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "earthquake", "ancientpower", "eruption"]},
{"generation": 5, "level": 80, "shiny": 1, "moves":["earthquake", "ancientpower", "eruption", "solarbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["eruption", "hammerarm", "earthpower", "solarbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 45, "moves":["lavaplume", "rest", "earthquake", "precipiceblades"]},
{"generation": 6, "level": 100, "nature": "Adamant", "moves":["firepunch", "solarbeam", "hammerarm", "rockslide"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
groudonprimal: {
randomBattleMoves: ["stealthrock", "precipiceblades", "earthquake", "lavaplume", "stoneedge", "overheat", "rockpolish", "thunderwave"],
randomDoubleBattleMoves: ["precipiceblades", "lavaplume", "rockslide", "stoneedge", "swordsdance", "overheat", "rockpolish", "firepunch", "protect"],
requiredItem: "Red Orb",
},
rayquaza: {
randomBattleMoves: ["outrage", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw"],
randomDoubleBattleMoves: ["tailwind", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["fly", "rest", "extremespeed", "outrage"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "airslash", "ancientpower", "outrage"]},
{"generation": 5, "level": 70, "shiny": true, "moves":["dragonpulse", "ancientpower", "outrage", "dragondance"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["extremespeed", "hyperbeam", "dragonpulse", "vcreate"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "moves":["extremespeed", "dragonpulse", "dragondance", "dragonascent"]},
{"generation": 6, "level": 70, "shiny": true, "moves":["dragonpulse", "thunder", "twister", "extremespeed"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "shiny": true, "moves":["dragonascent", "dragonclaw", "extremespeed", "dragondance"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "shiny": true, "moves":["dragonascent", "dracometeor", "fly", "celebrate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
rayquazamega: {
randomBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance"],
randomDoubleBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance", "protect"],
requiredMove: "Dragon Ascent",
tier: "Bank",
},
jirachi: {
randomBattleMoves: ["ironhead", "uturn", "firepunch", "icepunch", "trick", "stealthrock", "bodyslam", "toxic", "wish", "substitute"],
randomDoubleBattleMoves: ["bodyslam", "ironhead", "icywind", "thunderwave", "helpinghand", "trickroom", "uturn", "followme", "zenheadbutt", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Bashful", "ivs": {"hp": 24, "atk": 3, "def": 30, "spa": 12, "spd": 16, "spe": 11}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Careful", "ivs": {"hp": 10, "atk": 0, "def": 10, "spa": 10, "spd": 26, "spe": 12}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Docile", "ivs": {"hp": 19, "atk": 7, "def": 10, "spa": 19, "spd": 10, "spe": 16}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Hasty", "ivs": {"hp": 3, "atk": 12, "def": 12, "spa": 7, "spd": 11, "spe": 9}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Jolly", "ivs": {"hp": 11, "atk": 8, "def": 6, "spa": 14, "spd": 5, "spe": 20}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Lonely", "ivs": {"hp": 31, "atk": 23, "def": 26, "spa": 29, "spd": 18, "spe": 5}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Naughty", "ivs": {"hp": 21, "atk": 31, "def": 31, "spa": 18, "spd": 24, "spe": 19}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Serious", "ivs": {"hp": 29, "atk": 10, "def": 31, "spa": 25, "spd": 23, "spe": 21}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Timid", "ivs": {"hp": 15, "atk": 28, "def": 29, "spa": 3, "spd": 0, "spe": 7}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 30, "moves":["helpinghand", "psychic", "refresh", "rest"]},
{"generation": 4, "level": 5, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"},
{"generation": 4, "level": 5, "moves":["wish", "confusion", "rest", "dracometeor"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["healingwish", "psychic", "swift", "meteormash"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["dracometeor", "meteormash", "wish", "followme"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["wish", "healingwish", "cosmicpower", "meteormash"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["wish", "healingwish", "swift", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "shiny": true, "moves":["wish", "swift", "healingwish", "moonblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "shiny": true, "moves":["wish", "confusion", "helpinghand", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["heartstamp", "playrough", "wish", "cosmicpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "shiny": true, "moves":["wish", "confusion", "swift", "happyhour"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
deoxys: {
randomBattleMoves: ["psychoboost", "stealthrock", "spikes", "firepunch", "superpower", "extremespeed", "knockoff", "taunt"],
randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff", "psyshock"],
eventPokemon: [
{"generation": 3, "level": 30, "shiny": 1, "moves":["taunt", "pursuit", "psychic", "superpower"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "spikes", "psychic", "snatch"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "pursuit", "psychic", "swift"]},
{"generation": 3, "level": 70, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "zapcannon", "irondefense", "extremespeed"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["psychoboost", "swift", "doubleteam", "extremespeed"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "detect", "counter", "mirrorcoat"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "meteormash", "superpower", "hyperbeam"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "leer", "wrap", "nightshade"]},
{"generation": 5, "level": 100, "moves":["nastyplot", "darkpulse", "recover", "psychoboost"], "pokeball": "duskball"},
{"generation": 6, "level": 80, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysattack: {
randomBattleMoves: ["psychoboost", "superpower", "icebeam", "knockoff", "extremespeed", "firepunch", "stealthrock"],
randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff"],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysdefense: {
randomBattleMoves: ["spikes", "stealthrock", "recover", "taunt", "toxic", "seismictoss", "knockoff"],
randomDoubleBattleMoves: ["protect", "stealthrock", "recover", "taunt", "reflect", "seismictoss", "lightscreen", "trickroom"],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysspeed: {
randomBattleMoves: ["spikes", "stealthrock", "superpower", "psychoboost", "taunt", "magiccoat", "knockoff"],
randomDoubleBattleMoves: ["superpower", "icebeam", "psychoboost", "taunt", "lightscreen", "reflect", "protect", "knockoff"],
eventOnly: true,
tier: "Bank-Uber",
},
turtwig: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb", "stockpile"]},
],
tier: "Bank-LC",
},
grotle: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"],
tier: "Bank-NFE",
},
torterra: {
randomBattleMoves: ["stealthrock", "earthquake", "woodhammer", "stoneedge", "synthesis", "rockpolish"],
randomDoubleBattleMoves: ["protect", "earthquake", "woodhammer", "stoneedge", "rockslide", "wideguard", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["woodhammer", "earthquake", "outrage", "stoneedge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
chimchar: {
randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "uturn", "gunkshot"],
eventPokemon: [
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "leer", "ember", "taunt"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "ember", "taunt", "fakeout"]},
],
tier: "Bank-LC",
},
monferno: {
randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "vacuumwave", "uturn", "gunkshot"],
tier: "Bank",
},
infernape: {
randomBattleMoves: ["stealthrock", "uturn", "swordsdance", "closecombat", "flareblitz", "thunderpunch", "machpunch", "nastyplot", "fireblast", "vacuumwave", "grassknot", "hiddenpowerice"],
randomDoubleBattleMoves: ["fakeout", "heatwave", "closecombat", "uturn", "grassknot", "stoneedge", "machpunch", "feint", "taunt", "flareblitz", "hiddenpowerice", "thunderpunch", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "closecombat", "uturn", "grassknot"], "pokeball": "cherishball"},
{"generation": 6, "level": 88, "isHidden": true, "moves":["fireblast", "closecombat", "firepunch", "focuspunch"], "pokeball": "cherishball"},
],
tier: "Bank",
},
piplup: {
randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble"]},
{"generation": 5, "level": 15, "shiny": 1, "isHidden": false, "moves":["hydropump", "featherdance", "watersport", "peck"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["sing", "round", "featherdance", "peck"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble", "featherdance"]},
{"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "return"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
prinplup: {
randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"],
tier: "Bank",
},
empoleon: {
randomBattleMoves: ["hydropump", "flashcannon", "grassknot", "hiddenpowerfire", "icebeam", "scald", "toxic", "roar", "stealthrock"],
randomDoubleBattleMoves: ["icywind", "scald", "surf", "icebeam", "hiddenpowerelectric", "protect", "grassknot", "flashcannon"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "aquajet", "grassknot"], "pokeball": "cherishball"},
],
tier: "Bank",
},
starly: {
randomBattleMoves: ["bravebird", "return", "uturn", "pursuit"],
eventPokemon: [
{"generation": 4, "level": 1, "gender": "M", "nature": "Mild", "moves":["tackle", "growl"]},
],
tier: "LC",
},
staravia: {
randomBattleMoves: ["bravebird", "return", "uturn", "pursuit", "defog"],
tier: "NFE",
},
staraptor: {
randomBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "roost", "doubleedge"],
randomDoubleBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "doubleedge", "tailwind", "protect"],
tier: "New",
},
bidoof: {
randomBattleMoves: ["return", "aquatail", "curse", "quickattack", "stealthrock", "superfang"],
eventPokemon: [
{"generation": 4, "level": 1, "gender": "M", "nature": "Lonely", "abilities":["simple"], "moves":["tackle"]},
],
tier: "Bank-LC",
},
bibarel: {
randomBattleMoves: ["return", "waterfall", "curse", "quickattack", "stealthrock", "rest"],
randomDoubleBattleMoves: ["return", "waterfall", "curse", "quickattack", "protect", "rest"],
tier: "Bank",
},
kricketot: {
randomBattleMoves: ["endeavor", "mudslap", "bugbite", "strugglebug"],
tier: "Bank-LC",
},
kricketune: {
randomBattleMoves: ["xscissor", "endeavor", "taunt", "toxic", "stickyweb", "knockoff"],
randomDoubleBattleMoves: ["bugbite", "protect", "taunt", "stickyweb", "knockoff"],
tier: "Bank",
},
shinx: {
randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"],
tier: "LC",
},
luxio: {
randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"],
tier: "NFE",
},
luxray: {
randomBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade"],
randomDoubleBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade", "protect"],
tier: "New",
},
cranidos: {
randomBattleMoves: ["headsmash", "rockslide", "earthquake", "zenheadbutt", "firepunch", "rockpolish", "crunch"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["pursuit", "takedown", "crunch", "headbutt"], "pokeball": "cherishball"},
],
tier: "LC",
},
rampardos: {
randomBattleMoves: ["headsmash", "earthquake", "rockpolish", "crunch", "rockslide", "firepunch"],
randomDoubleBattleMoves: ["headsmash", "earthquake", "zenheadbutt", "rockslide", "crunch", "stoneedge", "protect"],
tier: "New",
},
shieldon: {
randomBattleMoves: ["stealthrock", "metalburst", "fireblast", "icebeam", "protect", "toxic", "roar"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["metalsound", "takedown", "bodyslam", "protect"], "pokeball": "cherishball"},
],
tier: "LC",
},
bastiodon: {
randomBattleMoves: ["stealthrock", "rockblast", "metalburst", "protect", "toxic", "roar"],
randomDoubleBattleMoves: ["stealthrock", "stoneedge", "metalburst", "protect", "wideguard", "guardsplit"],
tier: "New",
},
burmy: {
randomBattleMoves: ["bugbite", "hiddenpowerice", "electroweb", "protect"],
tier: "Bank-LC",
},
wormadam: {
randomBattleMoves: ["gigadrain", "signalbeam", "protect", "toxic", "synthesis"],
randomDoubleBattleMoves: ["leafstorm", "gigadrain", "signalbeam", "hiddenpowerice", "hiddenpowerrock", "stringshot", "protect"],
tier: "Bank",
},
wormadamsandy: {
randomBattleMoves: ["earthquake", "toxic", "rockblast", "protect", "stealthrock"],
randomDoubleBattleMoves: ["earthquake", "suckerpunch", "rockblast", "protect", "stringshot"],
tier: "Bank",
},
wormadamtrash: {
randomBattleMoves: ["stealthrock", "toxic", "gyroball", "protect"],
randomDoubleBattleMoves: ["strugglebug", "stringshot", "gyroball", "protect"],
tier: "Bank",
},
mothim: {
randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "hiddenpowerground", "uturn"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "roost", "protect"],
tier: "Bank",
},
combee: {
randomBattleMoves: ["bugbuzz", "aircutter", "endeavor", "ominouswind", "tailwind"],
tier: "Bank-LC",
},
vespiquen: {
randomBattleMoves: ["substitute", "healorder", "toxic", "attackorder", "defendorder", "infestation"],
randomDoubleBattleMoves: ["tailwind", "healorder", "stringshot", "attackorder", "strugglebug", "protect"],
tier: "Bank",
},
pachirisu: {
randomBattleMoves: ["nuzzle", "thunderbolt", "superfang", "toxic", "uturn"],
randomDoubleBattleMoves: ["nuzzle", "thunderbolt", "superfang", "followme", "uturn", "helpinghand", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Impish", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 31}, "isHidden": true, "moves":["nuzzle", "superfang", "followme", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
buizel: {
randomBattleMoves: ["waterfall", "aquajet", "switcheroo", "brickbreak", "bulkup", "batonpass", "icepunch"],
tier: "Bank-LC",
},
floatzel: {
randomBattleMoves: ["bulkup", "batonpass", "waterfall", "icepunch", "substitute", "taunt", "aquajet", "brickbreak"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "switcheroo", "raindance", "protect", "icepunch", "crunch", "taunt"],
tier: "Bank",
},
cherubi: {
randomBattleMoves: ["sunnyday", "solarbeam", "weatherball", "hiddenpowerice", "aromatherapy", "dazzlinggleam"],
tier: "Bank-LC",
},
cherrim: {
randomBattleMoves: ["energyball", "dazzlinggleam", "hiddenpowerfire", "synthesis", "healingwish"],
randomDoubleBattleMoves: ["sunnyday", "solarbeam", "weatherball", "gigadrain", "protect"],
tier: "Bank",
},
cherrimsunshine: {
randomBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "hiddenpowerice"],
randomDoubleBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "protect"],
battleOnly: true,
},
shellos: {
randomBattleMoves: ["scald", "clearsmog", "recover", "toxic", "icebeam", "stockpile"],
tier: "LC",
},
gastrodon: {
randomBattleMoves: ["earthquake", "icebeam", "scald", "toxic", "recover", "clearsmog"],
randomDoubleBattleMoves: ["earthpower", "icebeam", "scald", "muddywater", "recover", "icywind", "protect"],
tier: "New",
},
drifloon: {
randomBattleMoves: ["shadowball", "substitute", "calmmind", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp"],
tier: "LC Uber",
},
drifblim: {
randomBattleMoves: ["acrobatics", "willowisp", "substitute", "destinybond", "shadowball"],
randomDoubleBattleMoves: ["shadowball", "substitute", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp", "protect"],
tier: "New",
},
buneary: {
randomBattleMoves: ["fakeout", "return", "switcheroo", "thunderpunch", "jumpkick", "firepunch", "icepunch", "healingwish"],
tier: "Bank-LC",
},
lopunny: {
randomBattleMoves: ["return", "switcheroo", "highjumpkick", "icepunch", "healingwish"],
randomDoubleBattleMoves: ["return", "switcheroo", "highjumpkick", "firepunch", "icepunch", "fakeout", "protect", "encore"],
tier: "Bank",
},
lopunnymega: {
randomBattleMoves: ["return", "highjumpkick", "substitute", "thunderpunch", "icepunch"],
randomDoubleBattleMoves: ["return", "highjumpkick", "protect", "fakeout", "icepunch", "encore"],
requiredItem: "Lopunnite",
tier: "Bank",
},
glameow: {
randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "hypnosis", "quickattack", "return", "foulplay"],
tier: "Bank-LC",
},
purugly: {
randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff", "protect"],
tier: "Bank",
},
stunky: {
randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "explosion", "taunt", "playrough", "defog"],
tier: "Bank-LC",
},
skuntank: {
randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "defog"],
randomDoubleBattleMoves: ["protect", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "playrough", "snarl"],
tier: "Bank",
},
bronzor: {
randomBattleMoves: ["stealthrock", "psychic", "toxic", "hypnosis", "reflect", "lightscreen", "trickroom", "trick"],
tier: "Bank-LC",
},
bronzong: {
randomBattleMoves: ["stealthrock", "earthquake", "toxic", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"],
randomDoubleBattleMoves: ["earthquake", "protect", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"],
tier: "Bank",
},
chatot: {
randomBattleMoves: ["nastyplot", "boomburst", "heatwave", "hiddenpowerground", "substitute", "chatter", "uturn"],
randomDoubleBattleMoves: ["nastyplot", "heatwave", "encore", "substitute", "chatter", "uturn", "protect", "hypervoice", "boomburst"],
eventPokemon: [
{"generation": 4, "level": 25, "gender": "M", "nature": "Jolly", "abilities":["keeneye"], "moves":["mirrormove", "furyattack", "chatter", "taunt"]},
],
tier: "Bank",
},
spiritomb: {
randomBattleMoves: ["shadowsneak", "suckerpunch", "pursuit", "willowisp", "darkpulse", "rest", "sleeptalk", "foulplay", "painsplit", "calmmind"],
randomDoubleBattleMoves: ["shadowsneak", "suckerpunch", "icywind", "willowisp", "snarl", "darkpulse", "protect", "foulplay", "painsplit"],
eventPokemon: [
{"generation": 5, "level": 61, "gender": "F", "nature": "Quiet", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["darkpulse", "psychic", "silverwind", "embargo"], "pokeball": "cherishball"},
],
tier: "Bank",
},
gible: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"],
tier: "LC",
},
gabite: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"],
tier: "New",
},
garchomp: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "stoneedge", "fireblast", "swordsdance", "stealthrock", "firefang"],
randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["outrage", "earthquake", "swordsdance", "stoneedge"], "pokeball": "cherishball"},
{"generation": 5, "level": 48, "gender": "M", "isHidden": true, "moves":["dragonclaw", "dig", "crunch", "outrage"]},
{"generation": 6, "level": 48, "gender": "M", "isHidden": false, "moves":["dracometeor", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["slash", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 66, "gender": "F", "perfectIVs": 3, "isHidden": false, "moves":["dragonrush", "earthquake", "brickbreak", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "New",
},
garchompmega: {
randomBattleMoves: ["outrage", "dracometeor", "earthquake", "stoneedge", "fireblast", "swordsdance"],
randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect", "fireblast"],
requiredItem: "Garchompite",
tier: "(OU)",
},
riolu: {
randomBattleMoves: ["crunch", "rockslide", "copycat", "drainpunch", "highjumpkick", "icepunch", "swordsdance"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Serious", "abilities":["steadfast"], "moves":["aurasphere", "shadowclaw", "bulletpunch", "drainpunch"]},
],
tier: "LC",
},
lucario: {
randomBattleMoves: ["swordsdance", "closecombat", "crunch", "extremespeed", "icepunch", "nastyplot", "aurasphere", "darkpulse", "vacuumwave", "flashcannon"],
randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Modest", "abilities":["steadfast"], "moves":["aurasphere", "darkpulse", "dragonpulse", "waterpulse"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "gender": "M", "nature": "Adamant", "abilities":["innerfocus"], "moves":["forcepalm", "bonerush", "sunnyday", "blazekick"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["detect", "metalclaw", "counter", "bulletpunch"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Naughty", "ivs": {"atk": 31}, "isHidden": true, "moves":["bulletpunch", "closecombat", "stoneedge", "shadowclaw"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Jolly", "isHidden": false, "abilities":["innerfocus"], "moves":["closecombat", "aurasphere", "flashcannon", "quickattack"], "pokeball": "cherishball"},
],
tier: "New",
},
lucariomega: {
randomBattleMoves: ["swordsdance", "closecombat", "crunch", "icepunch", "bulletpunch", "nastyplot", "aurasphere", "darkpulse", "flashcannon"],
randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"],
requiredItem: "Lucarionite",
tier: "Uber",
},
hippopotas: {
randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "protect", "toxic", "stockpile"],
tier: "Bank-LC",
},
hippowdon: {
randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "toxic", "stoneedge"],
randomDoubleBattleMoves: ["earthquake", "slackoff", "rockslide", "stealthrock", "protect", "stoneedge"],
tier: "Bank",
},
skorupi: {
randomBattleMoves: ["toxicspikes", "xscissor", "poisonjab", "knockoff", "pinmissile", "whirlwind"],
tier: "Bank-LC",
},
drapion: {
randomBattleMoves: ["knockoff", "taunt", "toxicspikes", "poisonjab", "whirlwind", "swordsdance", "aquatail", "earthquake"],
randomDoubleBattleMoves: ["snarl", "taunt", "protect", "earthquake", "aquatail", "swordsdance", "poisonjab", "knockoff"],
tier: "Bank",
},
croagunk: {
randomBattleMoves: ["fakeout", "vacuumwave", "suckerpunch", "drainpunch", "darkpulse", "knockoff", "gunkshot", "toxic"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["astonish", "mudslap", "poisonsting", "taunt"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["mudslap", "poisonsting", "taunt", "poisonjab"]},
],
tier: "Bank-LC",
},
toxicroak: {
randomBattleMoves: ["swordsdance", "gunkshot", "drainpunch", "suckerpunch", "icepunch", "substitute"],
randomDoubleBattleMoves: ["suckerpunch", "drainpunch", "substitute", "swordsdance", "knockoff", "icepunch", "gunkshot", "fakeout", "protect"],
tier: "Bank",
},
carnivine: {
randomBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "leechseed", "knockoff", "ragepowder", "protect"],
tier: "Bank",
},
finneon: {
randomBattleMoves: ["surf", "uturn", "icebeam", "hiddenpowerelectric", "hiddenpowergrass"],
tier: "LC",
},
lumineon: {
randomBattleMoves: ["scald", "waterfall", "icebeam", "uturn", "toxic", "defog"],
randomDoubleBattleMoves: ["surf", "uturn", "icebeam", "toxic", "raindance", "tailwind", "protect"],
tier: "New",
},
snover: {
randomBattleMoves: ["blizzard", "iceshard", "gigadrain", "leechseed", "substitute", "woodhammer"],
tier: "Bank-LC",
},
abomasnow: {
randomBattleMoves: ["woodhammer", "iceshard", "blizzard", "gigadrain", "leechseed", "substitute", "focuspunch", "earthquake"],
randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"],
tier: "Bank",
},
abomasnowmega: {
randomBattleMoves: ["blizzard", "gigadrain", "woodhammer", "earthquake", "iceshard", "hiddenpowerfire"],
randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"],
requiredItem: "Abomasite",
tier: "Bank",
},
rotom: {
randomBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp"],
randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp", "electroweb", "protect"],
eventPokemon: [
{"generation": 5, "level": 10, "nature": "Naughty", "moves":["uproar", "astonish", "trick", "thundershock"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "nature": "Quirky", "moves":["shockwave", "astonish", "trick", "thunderwave"], "pokeball": "cherishball"},
],
tier: "Bank",
},
rotomheat: {
randomBattleMoves: ["overheat", "thunderbolt", "voltswitch", "hiddenpowerice", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["overheat", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
rotomwash: {
randomBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerice", "willowisp", "trick"],
randomDoubleBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect", "hiddenpowergrass"],
tier: "Bank",
},
rotomfrost: {
randomBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
rotomfan: {
randomBattleMoves: ["airslash", "thunderbolt", "voltswitch", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["airslash", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "electroweb", "discharge", "protect"],
tier: "Bank",
},
rotommow: {
randomBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerfire", "willowisp", "trick"],
randomDoubleBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerfire", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
uxie: {
randomBattleMoves: ["stealthrock", "thunderwave", "psychic", "uturn", "healbell", "knockoff", "yawn"],
randomDoubleBattleMoves: ["uturn", "psyshock", "yawn", "healbell", "stealthrock", "thunderbolt", "protect", "helpinghand", "thunderwave", "skillswap"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "yawn", "futuresight", "amnesia"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "yawn", "futuresight", "amnesia"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["futuresight", "amnesia", "extrasensory", "flail"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["yawn", "futuresight", "amnesia", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
mesprit: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "energyball", "signalbeam", "hiddenpowerfire", "icebeam", "healingwish", "stealthrock", "uturn"],
randomDoubleBattleMoves: ["calmmind", "psychic", "thunderbolt", "icebeam", "substitute", "uturn", "trick", "protect", "knockoff", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "luckychant", "futuresight", "charm"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "luckychant", "futuresight", "charm"]},
{"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "charm", "extrasensory", "copycat"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["luckychant", "futuresight", "charm", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
azelf: {
randomBattleMoves: ["nastyplot", "psyshock", "fireblast", "dazzlinggleam", "stealthrock", "knockoff", "taunt", "explosion"],
randomDoubleBattleMoves: ["nastyplot", "psychic", "fireblast", "thunderbolt", "icepunch", "knockoff", "zenheadbutt", "uturn", "trick", "taunt", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "uproar", "futuresight", "nastyplot"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "uproar", "futuresight", "nastyplot"]},
{"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "nastyplot", "extrasensory", "lastresort"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["uproar", "futuresight", "nastyplot", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
dialga: {
randomBattleMoves: ["stealthrock", "toxic", "dracometeor", "fireblast", "flashcannon", "roar", "thunderbolt"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "protect", "thunderbolt", "flashcannon", "earthpower", "fireblast", "aurasphere"],
eventPokemon: [
{"generation": 4, "level": 47, "shiny": 1, "moves":["metalclaw", "ancientpower", "dragonclaw", "roaroftime"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["roaroftime", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dracometeor", "aurasphere", "roaroftime"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "irontail", "roaroftime", "flashcannon"]},
{"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["metalburst", "overheat", "roaroftime", "flashcannon"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
palkia: {
randomBattleMoves: ["spacialrend", "dracometeor", "hydropump", "thunderwave", "dragontail", "fireblast"],
randomDoubleBattleMoves: ["spacialrend", "dracometeor", "surf", "hydropump", "thunderbolt", "fireblast", "protect"],
eventPokemon: [
{"generation": 4, "level": 47, "shiny": 1, "moves":["waterpulse", "ancientpower", "dragonclaw", "spacialrend"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["spacialrend", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["hydropump", "dracometeor", "spacialrend", "aurasphere"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"]},
{"generation": 6, "level": 100, "nature": "Timid", "isHidden": true, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
heatran: {
randomBattleMoves: ["fireblast", "lavaplume", "stealthrock", "earthpower", "flashcannon", "protect", "toxic", "roar"],
randomDoubleBattleMoves: ["heatwave", "substitute", "earthpower", "protect", "eruption", "willowisp"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]},
{"generation": 4, "level": 50, "nature": "Quiet", "moves":["eruption", "magmastorm", "earthpower", "ancientpower"]},
{"generation": 5, "level": 68, "shiny": 1, "isHidden": false, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
regigigas: {
randomBattleMoves: ["thunderwave", "confuseray", "substitute", "return", "knockoff", "drainpunch"],
randomDoubleBattleMoves: ["thunderwave", "substitute", "return", "icywind", "rockslide", "earthquake", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["confuseray", "stomp", "superpower", "zenheadbutt"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dizzypunch", "knockoff", "foresight", "confuseray"]},
{"generation": 4, "level": 100, "moves":["ironhead", "rockslide", "icywind", "crushgrip"], "pokeball": "cherishball"},
{"generation": 5, "level": 68, "shiny": 1, "moves":["revenge", "wideguard", "zenheadbutt", "payback"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["foresight", "revenge", "wideguard", "zenheadbutt"]},
],
eventOnly: true,
tier: "Bank",
},
giratina: {
randomBattleMoves: ["rest", "sleeptalk", "dragontail", "roar", "willowisp", "shadowball", "dragonpulse"],
randomDoubleBattleMoves: ["tailwind", "icywind", "protect", "dragontail", "willowisp", "calmmind", "dragonpulse", "shadowball"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["shadowforce", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 47, "shiny": 1, "moves":["ominouswind", "ancientpower", "dragonclaw", "shadowforce"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dragonclaw", "aurasphere", "shadowforce"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "shadowclaw", "shadowforce", "hex"]},
{"generation": 6, "level": 100, "nature": "Brave", "isHidden": true, "moves":["aurasphere", "dracometeor", "shadowforce", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
giratinaorigin: {
randomBattleMoves: ["dracometeor", "shadowsneak", "dragontail", "willowisp", "defog", "toxic", "shadowball", "earthquake"],
randomDoubleBattleMoves: ["dracometeor", "shadowsneak", "tailwind", "hiddenpowerfire", "willowisp", "calmmind", "substitute", "dragonpulse", "shadowball", "aurasphere", "protect", "earthquake"],
eventOnly: true,
requiredItem: "Griseous Orb",
tier: "Bank-Uber",
},
cresselia: {
randomBattleMoves: ["moonlight", "psychic", "icebeam", "thunderwave", "toxic", "substitute", "psyshock", "moonblast", "calmmind"],
randomDoubleBattleMoves: ["psyshock", "icywind", "thunderwave", "trickroom", "moonblast", "moonlight", "skillswap", "reflect", "lightscreen", "icebeam", "protect", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["futuresight", "slash", "moonlight", "psychocut"]},
{"generation": 5, "level": 68, "nature": "Modest", "moves":["icebeam", "psyshock", "energyball", "hiddenpower"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]},
],
eventOnly: true,
tier: "Bank",
},
phione: {
randomBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam"],
randomDoubleBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam", "helpinghand", "icywind", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "moves":["grassknot", "raindance", "rest", "surf"], "pokeball": "cherishball"},
],
tier: "Bank",
},
manaphy: {
randomBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "psychic"],
randomDoubleBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "protect", "scald", "icywind", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 5, "moves":["tailglow", "bubble", "watersport"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["tailglow", "bubble", "watersport"]},
{"generation": 4, "level": 50, "moves":["heartswap", "waterpulse", "whirlpool", "acidarmor"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "nature": "Impish", "moves":["aquaring", "waterpulse", "watersport", "heartswap"], "pokeball": "cherishball"},
{"generation": 6, "level": 1, "moves":["tailglow", "bubble", "watersport", "heartswap"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["tailglow", "bubble", "watersport"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
darkrai: {
randomBattleMoves: ["hypnosis", "darkpulse", "focusblast", "nastyplot", "substitute", "sludgebomb"],
randomDoubleBattleMoves: ["darkpulse", "focusblast", "nastyplot", "substitute", "snarl", "protect"],
eventPokemon: [
{"generation": 4, "level": 40, "shiny": 1, "moves":["quickattack", "hypnosis", "pursuit", "nightmare"]},
{"generation": 4, "level": 50, "moves":["roaroftime", "spacialrend", "nightmare", "hypnosis"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["darkvoid", "darkpulse", "shadowball", "doubleteam"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["hypnosis", "feintattack", "nightmare", "doubleteam"]},
{"generation": 5, "level": 50, "moves":["darkvoid", "ominouswind", "feintattack", "nightmare"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["darkvoid", "darkpulse", "phantomforce", "dreameater"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["darkvoid", "ominouswind", "nightmare", "feintattack"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
shaymin: {
randomBattleMoves: ["seedflare", "earthpower", "airslash", "psychic", "rest", "substitute", "leechseed"],
randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "shiny": 1, "moves":["growth", "magicalleaf", "leechseed", "synthesis"]},
{"generation": 5, "level": 50, "moves":["seedflare", "leechseed", "synthesis", "sweetscent"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["growth", "magicalleaf", "seedflare", "airslash"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
shayminsky: {
randomBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "substitute", "leechseed", "healingwish"],
randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect", "hiddenpowerice"],
eventOnly: true,
tier: "Bank-Uber",
},
arceus: {
randomBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover"],
randomDoubleBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover", "protect"],
eventPokemon: [
{"generation": 4, "level": 100, "moves":["judgment", "roaroftime", "spacialrend", "shadowforce"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["recover", "hyperbeam", "perishsong", "judgment"]},
{"generation": 6, "level": 100, "shiny": 1, "moves":["judgment", "blastburn", "hydrocannon", "earthpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["judgment", "perishsong", "hyperbeam", "recover"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
arceusbug: {
randomBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead"],
randomDoubleBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead", "protect"],
eventOnly: true,
requiredItems: ["Insect Plate", "Buginium Z"],
},
arceusdark: {
randomBattleMoves: ["calmmind", "judgment", "recover", "fireblast", "thunderbolt"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "focusblast", "safeguard", "snarl", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Dread Plate", "Darkinium Z"],
},
arceusdragon: {
randomBattleMoves: ["swordsdance", "outrage", "extremespeed", "earthquake", "recover", "calmmind", "judgment", "fireblast", "earthpower"],
randomDoubleBattleMoves: ["swordsdance", "dragonclaw", "extremespeed", "earthquake", "recover", "protect"],
eventOnly: true,
requiredItems: ["Draco Plate", "Dragonium Z"],
},
arceuselectric: {
randomBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "grassknot", "fireblast", "willowisp"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "protect"],
eventOnly: true,
requiredItems: ["Zap Plate", "Electrium Z"],
},
arceusfairy: {
randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "defog", "thunderbolt", "toxic", "fireblast"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "protect", "earthpower", "thunderbolt"],
eventOnly: true,
requiredItems: ["Pixie Plate", "Fairium Z"],
},
arceusfighting: {
randomBattleMoves: ["calmmind", "judgment", "stoneedge", "shadowball", "recover", "toxic", "defog"],
randomDoubleBattleMoves: ["calmmind", "judgment", "icebeam", "shadowball", "recover", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Fist Plate", "Fightinium Z"],
},
arceusfire: {
randomBattleMoves: ["calmmind", "judgment", "grassknot", "thunderbolt", "icebeam", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "recover", "heatwave", "protect", "willowisp"],
eventOnly: true,
requiredItems: ["Flame Plate", "Firium Z"],
},
arceusflying: {
randomBattleMoves: ["calmmind", "judgment", "earthpower", "fireblast", "substitute", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "safeguard", "recover", "substitute", "tailwind", "protect"],
eventOnly: true,
requiredItems: ["Sky Plate", "Flyinium Z"],
},
arceusghost: {
randomBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "roar", "defog"],
randomDoubleBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Spooky Plate", "Ghostium Z"],
},
arceusgrass: {
randomBattleMoves: ["judgment", "recover", "calmmind", "icebeam", "fireblast"],
randomDoubleBattleMoves: ["calmmind", "icebeam", "judgment", "earthpower", "recover", "safeguard", "thunderwave", "protect"],
eventOnly: true,
requiredItems: ["Meadow Plate", "Grassium Z"],
},
arceusground: {
randomBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "extremespeed", "icebeam"],
randomDoubleBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "calmmind", "judgment", "icebeam", "rockslide", "protect"],
eventOnly: true,
requiredItems: ["Earth Plate", "Groundium Z"],
},
arceusice: {
randomBattleMoves: ["calmmind", "judgment", "thunderbolt", "fireblast", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "focusblast", "recover", "protect", "icywind"],
eventOnly: true,
requiredItems: ["Icicle Plate", "Icium Z"],
},
arceuspoison: {
randomBattleMoves: ["calmmind", "sludgebomb", "fireblast", "recover", "willowisp", "defog", "thunderwave"],
randomDoubleBattleMoves: ["calmmind", "judgment", "sludgebomb", "heatwave", "recover", "willowisp", "protect", "earthpower"],
eventOnly: true,
requiredItems: ["Toxic Plate", "Poisonium Z"],
},
arceuspsychic: {
randomBattleMoves: ["judgment", "calmmind", "focusblast", "recover", "defog", "thunderbolt", "willowisp"],
randomDoubleBattleMoves: ["calmmind", "psyshock", "focusblast", "recover", "willowisp", "judgment", "protect"],
eventOnly: true,
requiredItems: ["Mind Plate", "Psychium Z"],
},
arceusrock: {
randomBattleMoves: ["recover", "swordsdance", "earthquake", "stoneedge", "extremespeed"],
randomDoubleBattleMoves: ["swordsdance", "stoneedge", "recover", "rockslide", "earthquake", "protect"],
eventOnly: true,
requiredItems: ["Stone Plate", "Rockium Z"],
},
arceussteel: {
randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "thunderbolt", "swordsdance", "ironhead", "earthquake", "stoneedge"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "protect", "willowisp"],
eventOnly: true,
requiredItems: ["Iron Plate", "Steelium Z"],
},
arceuswater: {
randomBattleMoves: ["recover", "calmmind", "judgment", "substitute", "willowisp", "thunderbolt"],
randomDoubleBattleMoves: ["recover", "calmmind", "judgment", "icebeam", "fireblast", "icywind", "surf", "protect"],
eventOnly: true,
requiredItems: ["Splash Plate", "Waterium Z"],
},
victini: {
randomBattleMoves: ["vcreate", "boltstrike", "uturn", "zenheadbutt", "grassknot", "focusblast", "blueflare"],
randomDoubleBattleMoves: ["vcreate", "boltstrike", "uturn", "psychic", "focusblast", "blueflare", "protect"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["quickattack", "incinerate", "confusion", "endure"]},
{"generation": 5, "level": 50, "moves":["vcreate", "fusionflare", "fusionbolt", "searingshot"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["vcreate", "blueflare", "boltstrike", "glaciate"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["confusion", "quickattack", "vcreate", "searingshot"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["incinerate", "quickattack", "endure", "confusion"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["quickattack", "swagger", "vcreate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
snivy: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"],
eventPokemon: [
{"generation": 5, "level": 5, "gender": "M", "nature": "Hardy", "isHidden": false, "moves":["growth", "synthesis", "energyball", "aromatherapy"], "pokeball": "cherishball"},
],
tier: "LC",
},
servine: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"],
tier: "NFE",
},
serperior: {
randomBattleMoves: ["leafstorm", "dragonpulse", "hiddenpowerfire", "substitute", "leechseed", "glare"],
randomDoubleBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "taunt", "dragonpulse", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["leafstorm", "substitute", "gigadrain", "leechseed"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["leafstorm", "holdback", "wringout", "gigadrain"], "pokeball": "cherishball"},
],
tier: "New",
},
tepig: {
randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"],
tier: "LC",
},
pignite: {
randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"],
tier: "NFE",
},
emboar: {
randomBattleMoves: ["flareblitz", "superpower", "wildcharge", "stoneedge", "fireblast", "grassknot", "suckerpunch"],
randomDoubleBattleMoves: ["flareblitz", "superpower", "flamecharge", "wildcharge", "headsmash", "protect", "heatwave", "rockslide"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["flareblitz", "hammerarm", "wildcharge", "headsmash"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["flareblitz", "holdback", "headsmash", "takedown"], "pokeball": "cherishball"},
],
tier: "New",
},
oshawott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"],
tier: "LC",
},
dewott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"],
tier: "NFE",
},
samurott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "megahorn", "superpower", "hydropump", "icebeam", "grassknot"],
randomDoubleBattleMoves: ["hydropump", "aquajet", "icebeam", "scald", "hiddenpowergrass", "taunt", "helpinghand", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "megahorn", "superpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["razorshell", "holdback", "confide", "hydropump"], "pokeball": "cherishball"},
],
tier: "New",
},
patrat: {
randomBattleMoves: ["swordsdance", "batonpass", "substitute", "hypnosis", "return", "superfang"],
tier: "Bank-LC",
},
watchog: {
randomBattleMoves: ["hypnosis", "substitute", "batonpass", "superfang", "swordsdance", "return", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "knockoff", "substitute", "hypnosis", "return", "superfang", "protect"],
tier: "Bank",
},
lillipup: {
randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"],
tier: "LC",
},
herdier: {
randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"],
tier: "NFE",
},
stoutland: {
randomBattleMoves: ["return", "crunch", "wildcharge", "superpower", "icefang"],
randomDoubleBattleMoves: ["return", "wildcharge", "superpower", "crunch", "icefang", "protect"],
tier: "New",
},
purrloin: {
randomBattleMoves: ["encore", "taunt", "uturn", "knockoff", "thunderwave"],
tier: "Bank-LC",
},
liepard: {
randomBattleMoves: ["knockoff", "encore", "suckerpunch", "thunderwave", "uturn", "substitute", "nastyplot", "darkpulse", "copycat"],
randomDoubleBattleMoves: ["encore", "thunderwave", "substitute", "knockoff", "playrough", "uturn", "suckerpunch", "fakeout", "protect"],
eventPokemon: [
{"generation": 5, "level": 20, "gender": "F", "nature": "Jolly", "isHidden": true, "moves":["fakeout", "foulplay", "encore", "swagger"]},
],
tier: "Bank",
},
pansage: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "nastyplot", "substitute", "leechseed"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Brave", "ivs": {"spa": 31}, "isHidden": false, "moves":["bulletseed", "bite", "solarbeam", "dig"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "vinewhip", "leafstorm"]},
{"generation": 5, "level": 30, "gender": "M", "nature": "Serious", "isHidden": false, "moves":["seedbomb", "solarbeam", "rocktomb", "dig"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
simisage: {
randomBattleMoves: ["nastyplot", "gigadrain", "focusblast", "hiddenpowerice", "substitute", "leafstorm", "knockoff", "superpower"],
randomDoubleBattleMoves: ["nastyplot", "leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "focusblast", "substitute", "taunt", "synthesis", "helpinghand", "protect"],
tier: "Bank",
},
pansear: {
randomBattleMoves: ["nastyplot", "fireblast", "hiddenpowerelectric", "hiddenpowerground", "sunnyday", "solarbeam", "overheat"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "incinerate", "heatwave"]},
],
tier: "Bank-LC",
},
simisear: {
randomBattleMoves: ["substitute", "nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerrock"],
randomDoubleBattleMoves: ["nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerground", "substitute", "heatwave", "taunt", "protect"],
eventPokemon: [
{"generation": 6, "level": 5, "perfectIVs": 2, "isHidden": false, "moves":["workup", "honeclaws", "poweruppunch", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "Bank",
},
panpour: {
randomBattleMoves: ["nastyplot", "hydropump", "hiddenpowergrass", "substitute", "surf", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "watergun", "hydropump"]},
],
tier: "Bank-LC",
},
simipour: {
randomBattleMoves: ["substitute", "nastyplot", "hydropump", "icebeam", "focusblast"],
randomDoubleBattleMoves: ["nastyplot", "hydropump", "icebeam", "substitute", "surf", "taunt", "helpinghand", "protect"],
tier: "Bank",
},
munna: {
randomBattleMoves: ["psychic", "hiddenpowerfighting", "hypnosis", "calmmind", "moonlight", "thunderwave", "batonpass", "psyshock", "healbell", "signalbeam"],
tier: "Bank-LC",
},
musharna: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "signalbeam", "batonpass", "moonlight", "healbell", "thunderwave"],
randomDoubleBattleMoves: ["trickroom", "thunderwave", "moonlight", "psychic", "hiddenpowerfighting", "helpinghand", "psyshock", "healbell", "signalbeam", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "isHidden": true, "moves":["defensecurl", "luckychant", "psybeam", "hypnosis"]},
],
tier: "Bank",
},
pidove: {
randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "F", "nature": "Hardy", "ivs": {"atk": 31}, "isHidden": false, "abilities":["superluck"], "moves":["gust", "quickattack", "aircutter"]},
],
tier: "Bank-LC",
},
tranquill: {
randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"],
tier: "Bank-NFE",
},
unfezant: {
randomBattleMoves: ["return", "pluck", "hypnosis", "tailwind", "uturn", "roost", "nightslash"],
randomDoubleBattleMoves: ["pluck", "uturn", "return", "protect", "tailwind", "taunt", "roost", "nightslash"],
tier: "Bank",
},
blitzle: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "wildcharge", "mefirst"],
tier: "Bank-LC",
},
zebstrika: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "thunderbolt"],
randomDoubleBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "protect"],
tier: "Bank",
},
roggenrola: {
randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"],
tier: "LC",
},
boldore: {
randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"],
tier: "NFE",
},
gigalith: {
randomBattleMoves: ["stealthrock", "rockblast", "earthquake", "explosion", "stoneedge", "superpower"],
randomDoubleBattleMoves: ["stealthrock", "rockslide", "earthquake", "explosion", "stoneedge", "autotomize", "superpower", "wideguard", "protect"],
tier: "New",
},
woobat: {
randomBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "roost", "heatwave", "storedpower"],
tier: "Bank-LC",
},
swoobat: {
randomBattleMoves: ["substitute", "calmmind", "storedpower", "heatwave", "psychic", "airslash", "roost"],
randomDoubleBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "protect", "heatwave", "tailwind"],
tier: "Bank",
},
drilbur: {
randomBattleMoves: ["swordsdance", "rapidspin", "earthquake", "rockslide", "shadowclaw", "return", "xscissor"],
tier: "Bank-LC",
},
excadrill: {
randomBattleMoves: ["swordsdance", "earthquake", "ironhead", "rockslide", "rapidspin"],
randomDoubleBattleMoves: ["swordsdance", "drillrun", "earthquake", "rockslide", "ironhead", "substitute", "protect"],
tier: "Bank",
},
audino: {
randomBattleMoves: ["wish", "protect", "healbell", "toxic", "thunderwave", "reflect", "lightscreen", "doubleedge"],
randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "reflect", "lightscreen", "doubleedge", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "F", "nature": "Calm", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "doubleslap"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "F", "nature": "Serious", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "present"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Relaxed", "isHidden": false, "abilities":["regenerator"], "moves":["trickroom", "healpulse", "simplebeam", "thunderbolt"], "pokeball": "cherishball"},
],
tier: "Bank",
},
audinomega: {
randomBattleMoves: ["wish", "calmmind", "healbell", "dazzlinggleam", "hypervoice", "protect"],
randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "hypervoice", "helpinghand", "dazzlinggleam"],
requiredItem: "Audinite",
tier: "Bank",
},
timburr: {
randomBattleMoves: ["machpunch", "bulkup", "drainpunch", "icepunch", "knockoff"],
tier: "LC",
},
gurdurr: {
randomBattleMoves: ["bulkup", "machpunch", "drainpunch", "icepunch", "knockoff"],
tier: "New",
},
conkeldurr: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "knockoff", "machpunch"],
randomDoubleBattleMoves: ["wideguard", "machpunch", "drainpunch", "icepunch", "knockoff", "protect"],
tier: "New",
},
tympole: {
randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric"],
tier: "Bank-LC",
},
palpitoad: {
randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric", "stealthrock"],
tier: "Bank-NFE",
},
seismitoad: {
randomBattleMoves: ["hydropump", "scald", "sludgewave", "earthquake", "knockoff", "stealthrock", "toxic", "raindance"],
randomDoubleBattleMoves: ["hydropump", "muddywater", "sludgebomb", "earthquake", "hiddenpowerelectric", "icywind", "protect"],
tier: "Bank",
},
throh: {
randomBattleMoves: ["bulkup", "circlethrow", "icepunch", "stormthrow", "rest", "sleeptalk", "knockoff"],
randomDoubleBattleMoves: ["helpinghand", "circlethrow", "icepunch", "stormthrow", "wideguard", "knockoff", "protect"],
tier: "Bank",
},
sawk: {
randomBattleMoves: ["closecombat", "earthquake", "icepunch", "poisonjab", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["closecombat", "knockoff", "icepunch", "rockslide", "protect"],
tier: "Bank",
},
sewaddle: {
randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash"],
tier: "LC",
},
swadloon: {
randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash", "stickyweb"],
tier: "NFE",
},
leavanny: {
randomBattleMoves: ["stickyweb", "swordsdance", "leafblade", "xscissor", "knockoff", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "leafblade", "xscissor", "protect", "stickyweb", "poisonjab"],
tier: "New",
},
venipede: {
randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"],
tier: "LC",
},
whirlipede: {
randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"],
tier: "NFE",
},
scolipede: {
randomBattleMoves: ["substitute", "spikes", "toxicspikes", "megahorn", "rockslide", "earthquake", "swordsdance", "batonpass", "poisonjab"],
randomDoubleBattleMoves: ["substitute", "protect", "megahorn", "rockslide", "poisonjab", "swordsdance", "batonpass", "aquatail", "superpower"],
tier: "New",
},
cottonee: {
randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "toxic", "stunspore"],
tier: "LC",
},
whimsicott: {
randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "toxic", "stunspore", "memento", "tailwind", "moonblast"],
randomDoubleBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "helpinghand", "stunspore", "moonblast", "tailwind", "dazzlinggleam", "gigadrain", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "ivs": {"spe": 31}, "isHidden": false, "abilities":["prankster"], "moves":["swagger", "gigadrain", "beatup", "helpinghand"], "pokeball": "cherishball"},
],
tier: "New",
},
petilil: {
randomBattleMoves: ["sunnyday", "sleeppowder", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "healingwish"],
tier: "LC",
},
lilligant: {
randomBattleMoves: ["sleeppowder", "quiverdance", "petaldance", "gigadrain", "hiddenpowerfire", "hiddenpowerrock"],
randomDoubleBattleMoves: ["quiverdance", "gigadrain", "sleeppowder", "hiddenpowerice", "hiddenpowerfire", "hiddenpowerrock", "petaldance", "helpinghand", "protect"],
tier: "New",
},
basculin: {
randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "zenheadbutt"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"],
tier: "Bank",
},
basculinbluestriped: {
randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "zenheadbutt"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"],
tier: "Bank",
},
sandile: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"],
tier: "LC",
},
krokorok: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"],
tier: "NFE",
},
krookodile: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "knockoff", "stealthrock", "superpower"],
randomDoubleBattleMoves: ["earthquake", "stoneedge", "protect", "knockoff", "superpower"],
tier: "New",
},
darumaka: {
randomBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "superpower"],
tier: "Bank-LC",
},
darmanitan: {
randomBattleMoves: ["uturn", "flareblitz", "rockslide", "earthquake", "superpower"],
randomDoubleBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "earthquake", "superpower", "protect"],
eventPokemon: [
{"generation": 5, "level": 35, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"]},
{"generation": 6, "level": 35, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
darmanitanzen: {
requiredAbility: "Zen Mode",
battleOnly: true,
},
maractus: {
randomBattleMoves: ["spikes", "gigadrain", "leechseed", "hiddenpowerfire", "toxic", "suckerpunch", "spikyshield"],
randomDoubleBattleMoves: ["grassyterrain", "gigadrain", "leechseed", "hiddenpowerfire", "helpinghand", "suckerpunch", "spikyshield"],
tier: "Bank",
},
dwebble: {
randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"],
tier: "Bank-LC",
},
crustle: {
randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"],
randomDoubleBattleMoves: ["protect", "shellsmash", "earthquake", "rockslide", "xscissor", "stoneedge"],
tier: "Bank",
},
scraggy: {
randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "crunch", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 1, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moxie"], "moves":["headbutt", "leer", "highjumpkick", "lowkick"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
scrafty: {
randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "drainpunch", "knockoff", "icepunch", "stoneedge", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "abilities":["moxie"], "moves":["firepunch", "payback", "drainpunch", "substitute"], "pokeball": "cherishball"},
],
tier: "Bank",
},
sigilyph: {
randomBattleMoves: ["cosmicpower", "roost", "storedpower", "psychoshift"],
randomDoubleBattleMoves: ["psyshock", "heatwave", "icebeam", "airslash", "energyball", "shadowball", "tailwind", "protect"],
tier: "Bank",
},
yamask: {
randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "rest", "sleeptalk", "painsplit"],
tier: "Bank-LC",
},
cofagrigus: {
randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "painsplit"],
randomDoubleBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "protect", "painsplit"],
tier: "Bank",
},
tirtouga: {
randomBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "stealthrock"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["sturdy"], "moves":["bite", "protect", "aquajet", "bodyslam"], "pokeball": "cherishball"},
],
tier: "LC",
},
carracosta: {
randomBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "stealthrock"],
randomDoubleBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "protect", "wideguard", "rockslide"],
tier: "New",
},
archen: {
randomBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "pluck", "headsmash"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "moves":["headsmash", "wingattack", "doubleteam", "scaryface"], "pokeball": "cherishball"},
],
tier: "LC",
},
archeops: {
randomBattleMoves: ["headsmash", "acrobatics", "stoneedge", "earthquake", "aquatail", "uturn", "tailwind"],
randomDoubleBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "acrobatics", "tailwind", "taunt", "protect"],
tier: "New",
},
trubbish: {
randomBattleMoves: ["clearsmog", "toxicspikes", "spikes", "gunkshot", "painsplit", "toxic"],
tier: "LC",
},
garbodor: {
randomBattleMoves: ["spikes", "toxicspikes", "gunkshot", "haze", "painsplit", "toxic", "rockblast"],
randomDoubleBattleMoves: ["protect", "painsplit", "gunkshot", "seedbomb", "drainpunch", "explosion", "rockblast"],
tier: "New",
},
zorua: {
randomBattleMoves: ["suckerpunch", "extrasensory", "darkpulse", "hiddenpowerfighting", "uturn", "knockoff"],
tier: "Bank-LC",
},
zoroark: {
randomBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "trick"],
randomDoubleBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Quirky", "moves":["agility", "embargo", "punishment", "snarl"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["sludgebomb", "darkpulse", "flamethrower", "suckerpunch"], "pokeball": "ultraball"},
],
tier: "Bank",
},
minccino: {
randomBattleMoves: ["return", "tailslap", "wakeupslap", "uturn", "aquatail"],
tier: "Bank-LC",
},
cinccino: {
randomBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast"],
randomDoubleBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast", "protect"],
tier: "Bank",
},
gothita: {
randomBattleMoves: ["psychic", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"],
tier: "LC",
},
gothorita: {
randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"],
eventPokemon: [
{"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "mirrorcoat"]},
{"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "imprison"]},
],
tier: "NFE",
},
gothitelle: {
randomBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfire", "hiddenpowerfighting", "substitute", "calmmind", "trick", "psyshock"],
randomDoubleBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfighting", "reflect", "lightscreen", "psyshock", "energyball", "trickroom", "taunt", "healpulse", "protect"],
tier: "New",
},
solosis: {
randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"],
tier: "LC",
},
duosion: {
randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"],
tier: "NFE",
},
reuniclus: {
randomBattleMoves: ["calmmind", "recover", "psychic", "focusblast", "shadowball", "trickroom", "psyshock"],
randomDoubleBattleMoves: ["energyball", "helpinghand", "psychic", "focusblast", "shadowball", "trickroom", "psyshock", "hiddenpowerfire", "protect"],
tier: "New",
},
ducklett: {
randomBattleMoves: ["scald", "airslash", "roost", "hurricane", "icebeam", "hiddenpowergrass", "bravebird", "defog"],
tier: "Bank-LC",
},
swanna: {
randomBattleMoves: ["airslash", "roost", "hurricane", "surf", "icebeam", "raindance", "defog", "scald"],
randomDoubleBattleMoves: ["airslash", "roost", "hurricane", "surf", "icebeam", "raindance", "tailwind", "scald", "protect"],
tier: "Bank",
},
vanillite: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"],
tier: "LC",
},
vanillish: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"],
tier: "NFE",
},
vanilluxe: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerground", "flashcannon", "autotomize", "freezedry"],
randomDoubleBattleMoves: ["icebeam", "taunt", "hiddenpowerground", "flashcannon", "autotomize", "protect", "freezedry"],
tier: "New",
},
deerling: {
randomBattleMoves: ["agility", "batonpass", "seedbomb", "jumpkick", "synthesis", "return", "thunderwave"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["feintattack", "takedown", "jumpkick", "aromatherapy"]},
],
tier: "Bank-LC",
},
sawsbuck: {
randomBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "synthesis", "protect"],
tier: "Bank",
},
emolga: {
randomBattleMoves: ["encore", "chargebeam", "batonpass", "substitute", "thunderbolt", "airslash", "roost"],
randomDoubleBattleMoves: ["helpinghand", "tailwind", "encore", "substitute", "thunderbolt", "airslash", "roost", "protect"],
tier: "New",
},
karrablast: {
randomBattleMoves: ["swordsdance", "megahorn", "return", "substitute"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["furyattack", "headbutt", "falseswipe", "bugbuzz"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["megahorn", "takedown", "xscissor", "flail"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
escavalier: {
randomBattleMoves: ["megahorn", "pursuit", "ironhead", "knockoff", "swordsdance", "drillrun"],
randomDoubleBattleMoves: ["megahorn", "protect", "ironhead", "knockoff", "swordsdance", "drillrun"],
tier: "Bank",
},
foongus: {
randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb"],
tier: "Bank-LC",
},
amoonguss: {
randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb", "foulplay"],
randomDoubleBattleMoves: ["spore", "stunspore", "gigadrain", "ragepowder", "hiddenpowerfire", "synthesis", "sludgebomb", "protect"],
tier: "Bank",
},
frillish: {
randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "taunt"],
tier: "Bank-LC",
},
jellicent: {
randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "icebeam", "taunt"],
randomDoubleBattleMoves: ["scald", "willowisp", "recover", "trickroom", "shadowball", "icebeam", "waterspout", "icywind", "protect"],
eventPokemon: [
{"generation": 5, "level": 40, "isHidden": true, "moves":["waterpulse", "ominouswind", "brine", "raindance"]},
],
tier: "Bank",
},
alomomola: {
randomBattleMoves: ["wish", "protect", "knockoff", "toxic", "scald"],
randomDoubleBattleMoves: ["wish", "protect", "knockoff", "icywind", "scald", "helpinghand", "wideguard"],
tier: "New",
},
joltik: {
randomBattleMoves: ["thunderbolt", "bugbuzz", "hiddenpowerice", "gigadrain", "voltswitch"],
tier: "Bank-LC",
},
galvantula: {
randomBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb"],
randomDoubleBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb", "protect"],
tier: "Bank",
},
ferroseed: {
randomBattleMoves: ["spikes", "stealthrock", "leechseed", "seedbomb", "protect", "thunderwave", "gyroball"],
tier: "Bank",
},
ferrothorn: {
randomBattleMoves: ["spikes", "stealthrock", "leechseed", "powerwhip", "thunderwave", "protect", "knockoff", "gyroball"],
randomDoubleBattleMoves: ["gyroball", "stealthrock", "leechseed", "powerwhip", "thunderwave", "protect"],
tier: "Bank",
},
klink: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
tier: "LC",
},
klang: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
tier: "NFE",
},
klinklang: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
randomDoubleBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "protect"],
tier: "New",
},
tynamo: {
randomBattleMoves: ["spark", "chargebeam", "thunderwave", "tackle"],
tier: "LC",
},
eelektrik: {
randomBattleMoves: ["uturn", "voltswitch", "acidspray", "wildcharge", "thunderbolt", "gigadrain", "aquatail", "coil"],
tier: "NFE",
},
eelektross: {
randomBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "acidspray", "gigadrain", "knockoff", "superpower", "aquatail"],
randomDoubleBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "knockoff", "gigadrain", "protect"],
tier: "New",
},
elgyem: {
randomBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trickroom", "signalbeam"],
tier: "Bank-LC",
},
beheeyem: {
randomBattleMoves: ["nastyplot", "psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "trick", "trickroom", "signalbeam"],
randomDoubleBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trick", "trickroom", "signalbeam", "protect"],
tier: "Bank",
},
litwick: {
randomBattleMoves: ["shadowball", "energyball", "fireblast", "hiddenpowerground", "trickroom", "substitute", "painsplit"],
tier: "LC",
},
lampent: {
randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "substitute", "painsplit"],
tier: "NFE",
},
chandelure: {
randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "trick", "substitute", "painsplit"],
randomDoubleBattleMoves: ["shadowball", "energyball", "overheat", "heatwave", "hiddenpowerice", "trick", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "F", "nature": "Modest", "ivs": {"spa": 31}, "isHidden": false, "abilities":["flashfire"], "moves":["heatwave", "shadowball", "energyball", "psychic"], "pokeball": "cherishball"},
],
tier: "New",
},
axew: {
randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "swordsdance", "aquatail", "superpower", "poisonjab", "taunt", "substitute"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Naive", "ivs": {"spe": 31}, "isHidden": false, "abilities":["moldbreaker"], "moves":["scratch", "dragonrage"]},
{"generation": 5, "level": 10, "gender": "F", "isHidden": false, "abilities":["moldbreaker"], "moves":["dragonrage", "return", "endure", "dragonclaw"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "M", "nature": "Naive", "isHidden": false, "abilities":["rivalry"], "moves":["dragonrage", "scratch", "outrage", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "LC",
},
fraxure: {
randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "aquatail", "superpower", "poisonjab", "taunt", "substitute"],
tier: "NFE",
},
haxorus: {
randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"],
randomDoubleBattleMoves: ["dragondance", "swordsdance", "protect", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"],
eventPokemon: [
{"generation": 5, "level": 59, "gender": "F", "nature": "Naive", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["moldbreaker"], "moves":["earthquake", "dualchop", "xscissor", "dragondance"], "pokeball": "cherishball"},
],
tier: "New",
},
cubchoo: {
randomBattleMoves: ["icebeam", "surf", "hiddenpowergrass", "superpower"],
eventPokemon: [
{"generation": 5, "level": 15, "isHidden": false, "moves":["powdersnow", "growl", "bide", "icywind"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
beartic: {
randomBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet"],
randomDoubleBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet", "protect"],
tier: "Bank",
},
cryogonal: {
randomBattleMoves: ["icebeam", "recover", "toxic", "rapidspin", "haze", "freezedry", "hiddenpowerground"],
randomDoubleBattleMoves: ["icebeam", "recover", "icywind", "protect", "reflect", "freezedry", "hiddenpowerground"],
tier: "Bank",
},
shelmet: {
randomBattleMoves: ["spikes", "yawn", "substitute", "acidarmor", "batonpass", "recover", "toxic", "bugbuzz", "infestation"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["strugglebug", "megadrain", "yawn", "protect"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["encore", "gigadrain", "bodyslam", "bugbuzz"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
accelgor: {
randomBattleMoves: ["spikes", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore"],
randomDoubleBattleMoves: ["protect", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore", "sludgebomb"],
tier: "Bank",
},
stunfisk: {
randomBattleMoves: ["discharge", "earthpower", "scald", "toxic", "rest", "sleeptalk", "stealthrock"],
randomDoubleBattleMoves: ["discharge", "earthpower", "scald", "electroweb", "protect", "stealthrock"],
tier: "Bank",
},
mienfoo: {
randomBattleMoves: ["uturn", "drainpunch", "stoneedge", "swordsdance", "batonpass", "highjumpkick", "fakeout", "knockoff"],
tier: "Bank-LC",
},
mienshao: {
randomBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "substitute", "swordsdance", "batonpass", "knockoff"],
randomDoubleBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "drainpunch", "swordsdance", "wideguard", "knockoff", "feint", "protect"],
tier: "Bank",
},
druddigon: {
randomBattleMoves: ["outrage", "earthquake", "suckerpunch", "dragonclaw", "dragontail", "substitute", "glare", "stealthrock", "firepunch", "gunkshot"],
randomDoubleBattleMoves: ["superpower", "earthquake", "suckerpunch", "dragonclaw", "glare", "protect", "firepunch", "thunderpunch"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["leer", "scratch"]},
],
tier: "Bank",
},
golett: {
randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"],
tier: "Bank-LC",
},
golurk: {
randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"],
randomDoubleBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stoneedge", "protect", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": true, "isHidden": false, "abilities":["ironfist"], "moves":["shadowpunch", "hyperbeam", "gyroball", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
pawniard: {
randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"],
tier: "Bank",
},
bisharp: {
randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff", "protect"],
tier: "Bank",
},
bouffalant: {
randomBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower"],
randomDoubleBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": true, "moves":["headcharge", "facade", "earthquake", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
rufflet: {
randomBattleMoves: ["bravebird", "rockslide", "return", "uturn", "substitute", "bulkup", "roost"],
tier: "LC",
},
braviary: {
randomBattleMoves: ["bravebird", "superpower", "return", "uturn", "substitute", "rockslide", "bulkup", "roost"],
randomDoubleBattleMoves: ["bravebird", "superpower", "return", "uturn", "tailwind", "rockslide", "bulkup", "roost", "skydrop", "protect"],
eventPokemon: [
{"generation": 5, "level": 25, "gender": "M", "isHidden": true, "moves":["wingattack", "honeclaws", "scaryface", "aerialace"]},
],
tier: "New",
},
vullaby: {
randomBattleMoves: ["knockoff", "roost", "taunt", "whirlwind", "toxic", "defog", "uturn", "bravebird"],
tier: "New",
},
mandibuzz: {
randomBattleMoves: ["foulplay", "knockoff", "roost", "taunt", "whirlwind", "toxic", "uturn", "bravebird", "defog"],
randomDoubleBattleMoves: ["knockoff", "roost", "taunt", "tailwind", "snarl", "uturn", "bravebird", "protect"],
eventPokemon: [
{"generation": 5, "level": 25, "gender": "F", "isHidden": true, "moves":["pluck", "nastyplot", "flatter", "feintattack"]},
],
tier: "New",
},
heatmor: {
randomBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "knockoff"],
randomDoubleBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "heatwave", "protect"],
tier: "Bank",
},
durant: {
randomBattleMoves: ["honeclaws", "ironhead", "xscissor", "stoneedge", "batonpass", "superpower"],
randomDoubleBattleMoves: ["honeclaws", "ironhead", "xscissor", "rockslide", "protect", "superpower"],
tier: "Bank",
},
deino: {
randomBattleMoves: ["outrage", "crunch", "firefang", "dragontail", "thunderwave", "superpower"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "moves":["tackle", "dragonrage"]},
],
tier: "LC",
},
zweilous: {
randomBattleMoves: ["outrage", "crunch", "headsmash", "dragontail", "superpower", "rest", "sleeptalk"],
tier: "NFE",
},
hydreigon: {
randomBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower"],
randomDoubleBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": true, "gender": "M", "moves":["hypervoice", "dragonbreath", "flamethrower", "focusblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 52, "gender": "M", "perfectIVs": 2, "moves":["dragonrush", "crunch", "rockslide", "frustration"], "pokeball": "cherishball"},
],
tier: "New",
},
larvesta: {
randomBattleMoves: ["flareblitz", "uturn", "wildcharge", "zenheadbutt", "morningsun", "willowisp"],
tier: "Bank-LC",
},
volcarona: {
randomBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "hiddenpowerground"],
randomDoubleBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "heatwave", "willowisp", "ragepowder", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 35, "isHidden": false, "moves":["stringshot", "leechlife", "gust", "firespin"]},
{"generation": 5, "level": 77, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["bugbuzz", "overheat", "hyperbeam", "quiverdance"], "pokeball": "cherishball"},
],
tier: "Bank",
},
cobalion: {
randomBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "voltswitch", "hiddenpowerice", "taunt", "stealthrock"],
randomDoubleBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "thunderwave", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "ironhead", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
terrakion: {
randomBattleMoves: ["stoneedge", "closecombat", "swordsdance", "substitute", "stealthrock", "earthquake"],
randomDoubleBattleMoves: ["stoneedge", "closecombat", "substitute", "rockslide", "earthquake", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "rockslide", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
virizion: {
randomBattleMoves: ["swordsdance", "closecombat", "leafblade", "stoneedge", "calmmind", "focusblast", "gigadrain", "hiddenpowerice", "substitute"],
randomDoubleBattleMoves: ["taunt", "closecombat", "stoneedge", "leafblade", "swordsdance", "synthesis", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "gigadrain", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
tornadus: {
randomBattleMoves: ["bulkup", "acrobatics", "knockoff", "substitute", "hurricane", "heatwave", "superpower", "uturn", "taunt", "tailwind"],
randomDoubleBattleMoves: ["hurricane", "airslash", "uturn", "superpower", "focusblast", "taunt", "substitute", "heatwave", "tailwind", "protect", "skydrop"],
eventPokemon: [
{"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "aircutter", "extrasensory", "agility"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "gust"], "pokeball": "dreamball"},
{"generation": 5, "level": 70, "isHidden": false, "moves":["hurricane", "hammerarm", "airslash", "hiddenpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["extrasensory", "agility", "airslash", "crunch"]},
],
eventOnly: true,
tier: "Bank",
},
tornadustherian: {
randomBattleMoves: ["hurricane", "airslash", "heatwave", "knockoff", "superpower", "uturn", "taunt"],
randomDoubleBattleMoves: ["hurricane", "airslash", "focusblast", "uturn", "heatwave", "skydrop", "tailwind", "taunt", "protect"],
eventOnly: true,
tier: "Bank",
},
thundurus: {
randomBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt"],
randomDoubleBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt", "protect"],
eventPokemon: [
{"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "shockwave", "healblock", "agility"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "thundershock"], "pokeball": "dreamball"},
{"generation": 5, "level": 70, "isHidden": false, "moves":["thunder", "hammerarm", "focusblast", "wildcharge"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["healblock", "agility", "discharge", "crunch"]},
],
eventOnly: true,
tier: "Bank",
},
thundurustherian: {
randomBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch", "protect"],
eventOnly: true,
tier: "Bank",
},
reshiram: {
randomBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "toxic", "flamecharge", "stoneedge", "roost"],
randomDoubleBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "heatwave", "flamecharge", "roost", "protect", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]},
{"generation": 5, "level": 70, "moves":["extrasensory", "fusionflare", "dragonpulse", "imprison"]},
{"generation": 5, "level": 100, "moves":["blueflare", "fusionflare", "mist", "dracometeor"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
zekrom: {
randomBattleMoves: ["boltstrike", "outrage", "dragonclaw", "dracometeor", "voltswitch", "honeclaws", "substitute", "roost"],
randomDoubleBattleMoves: ["voltswitch", "protect", "dragonclaw", "boltstrike", "honeclaws", "substitute", "dracometeor", "fusionbolt", "roost", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]},
{"generation": 5, "level": 70, "moves":["zenheadbutt", "fusionbolt", "dragonclaw", "imprison"]},
{"generation": 5, "level": 100, "moves":["boltstrike", "fusionbolt", "haze", "outrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
landorus: {
randomBattleMoves: ["calmmind", "rockpolish", "earthpower", "focusblast", "psychic", "sludgewave", "stealthrock", "knockoff", "rockslide"],
randomDoubleBattleMoves: ["earthpower", "focusblast", "hiddenpowerice", "psychic", "sludgebomb", "rockslide", "protect"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": 1, "isHidden": false, "moves":["rockslide", "earthquake", "sandstorm", "fissure"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["block", "mudshot", "rocktomb"], "pokeball": "dreamball"},
{"generation": 6, "level": 65, "shiny": 1, "isHidden": false, "moves":["extrasensory", "swordsdance", "earthpower", "rockslide"]},
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 1, "spd": 31, "spe": 24}, "isHidden": false, "moves":["earthquake", "knockoff", "uturn", "rocktomb"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
landorustherian: {
randomBattleMoves: ["swordsdance", "rockpolish", "earthquake", "stoneedge", "uturn", "superpower", "stealthrock"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "uturn", "superpower", "knockoff", "protect"],
eventOnly: true,
tier: "Bank",
},
kyurem: {
randomBattleMoves: ["dracometeor", "icebeam", "earthpower", "outrage", "substitute", "dragonpulse", "focusblast", "roost"],
randomDoubleBattleMoves: ["substitute", "icebeam", "dracometeor", "dragonpulse", "focusblast", "glaciate", "earthpower", "roost", "protect"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["glaciate", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["scaryface", "glaciate", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "scaryface", "glaciate"]},
{"generation": 6, "level": 100, "moves":["glaciate", "scaryface", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
kyuremblack: {
randomBattleMoves: ["outrage", "fusionbolt", "icebeam", "roost", "substitute", "earthpower", "dragonclaw"],
randomDoubleBattleMoves: ["protect", "fusionbolt", "icebeam", "roost", "substitute", "honeclaws", "earthpower", "dragonclaw"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["freezeshock", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["fusionbolt", "freezeshock", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionbolt", "freezeshock"]},
{"generation": 6, "level": 100, "moves":["freezeshock", "fusionbolt", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
kyuremwhite: {
randomBattleMoves: ["dracometeor", "icebeam", "fusionflare", "earthpower", "focusblast", "dragonpulse", "substitute", "roost", "toxic"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "icebeam", "fusionflare", "earthpower", "focusblast", "roost", "protect"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["iceburn", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["fusionflare", "iceburn", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionflare", "iceburn"]},
{"generation": 6, "level": 100, "moves":["iceburn", "fusionflare", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
keldeo: {
randomBattleMoves: ["hydropump", "secretsword", "calmmind", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "scald", "icywind"],
randomDoubleBattleMoves: ["hydropump", "secretsword", "protect", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "surf", "icywind", "taunt"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["sacredsword", "hydropump", "aquajet", "swordsdance"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["aquajet", "leer", "doublekick", "hydropump"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
keldeoresolute: {
eventOnly: true,
requiredMove: "Secret Sword",
},
meloetta: {
randomBattleMoves: ["uturn", "calmmind", "psyshock", "hypervoice", "shadowball", "focusblast"],
randomDoubleBattleMoves: ["calmmind", "psyshock", "thunderbolt", "hypervoice", "shadowball", "focusblast", "protect"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["quickattack", "confusion", "round"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["round", "teeterdance", "psychic", "closecombat"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
meloettapirouette: {
randomBattleMoves: ["relicsong", "closecombat", "knockoff", "return"],
randomDoubleBattleMoves: ["relicsong", "closecombat", "knockoff", "return", "protect"],
requiredMove: "Relic Song",
battleOnly: true,
},
genesect: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "shiny": true, "nature": "Hasty", "ivs": {"atk": 31, "spe": 31}, "moves":["extremespeed", "technoblast", "blazekick", "shiftgear"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
genesectburn: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Burn Drive",
},
genesectchill: {
randomBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Chill Drive",
},
genesectdouse: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Douse Drive",
},
genesectshock: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Shock Drive",
},
chespin: {
randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"],
tier: "Bank-LC",
},
quilladin: {
randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"],
tier: "Bank-NFE",
},
chesnaught: {
randomBattleMoves: ["leechseed", "synthesis", "spikes", "drainpunch", "spikyshield", "woodhammer"],
randomDoubleBattleMoves: ["leechseed", "synthesis", "hammerarm", "spikyshield", "stoneedge", "woodhammer", "rockslide"],
tier: "Bank",
},
fennekin: {
randomBattleMoves: ["fireblast", "psychic", "psyshock", "grassknot", "willowisp", "hypnosis", "hiddenpowerrock", "flamecharge"],
eventPokemon: [
{"generation": 6, "level": 15, "gender": "F", "nature": "Hardy", "isHidden": false, "moves":["scratch", "flamethrower", "hiddenpower"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
braixen: {
randomBattleMoves: ["fireblast", "flamethrower", "psychic", "psyshock", "grassknot", "willowisp", "hiddenpowerrock"],
tier: "Bank-NFE",
},
delphox: {
randomBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball"],
randomDoubleBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball", "heatwave", "dazzlinggleam", "protect"],
tier: "Bank",
},
froakie: {
randomBattleMoves: ["quickattack", "hydropump", "icebeam", "waterfall", "toxicspikes", "poweruppunch", "uturn"],
eventPokemon: [
{"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "bubble", "return"], "pokeball": "cherishball"},
],
tier: "LC",
},
frogadier: {
randomBattleMoves: ["hydropump", "surf", "icebeam", "uturn", "taunt", "toxicspikes"],
tier: "NFE",
},
greninja: {
randomBattleMoves: ["hydropump", "icebeam", "darkpulse", "gunkshot", "uturn", "spikes", "toxicspikes", "taunt"],
randomDoubleBattleMoves: ["hydropump", "uturn", "surf", "icebeam", "matblock", "taunt", "darkpulse", "protect"],
eventPokemon: [
{"generation": 6, "level": 36, "ivs": {"spe": 31}, "isHidden": true, "moves":["watershuriken", "shadowsneak", "hydropump", "substitute"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": true, "moves":["hydrocannon", "gunkshot", "matblock", "happyhour"], "pokeball": "cherishball"},
],
tier: "New",
},
greninjaash: {
gen: 7,
requiredAbility: "Battle Bond",
battleOnly: true,
},
bunnelby: {
randomBattleMoves: ["agility", "earthquake", "return", "quickattack", "uturn", "stoneedge", "spikes", "bounce"],
tier: "Bank-LC",
},
diggersby: {
randomBattleMoves: ["earthquake", "return", "wildcharge", "uturn", "swordsdance", "quickattack", "knockoff", "agility"],
randomDoubleBattleMoves: ["earthquake", "uturn", "return", "wildcharge", "protect", "quickattack"],
tier: "Bank",
},
fletchling: {
randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind"],
tier: "LC",
},
fletchinder: {
randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind", "acrobatics"],
tier: "New",
},
talonflame: {
randomBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind"],
randomDoubleBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind", "taunt", "protect"],
tier: "New",
},
scatterbug: {
randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"],
tier: "Bank-LC",
},
spewpa: {
randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"],
tier: "Bank-NFE",
},
vivillon: {
randomBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "roost", "protect"],
tier: "Bank",
},
vivillonfancy: {
eventPokemon: [
{"generation": 6, "level": 12, "isHidden": false, "moves":["gust", "lightscreen", "strugglebug", "holdhands"], "pokeball": "cherishball"},
],
eventOnly: true,
},
vivillonpokeball: {
eventPokemon: [
{"generation": 6, "level": 12, "isHidden": false, "moves":["stunspore", "gust", "lightscreen", "strugglebug"]},
],
eventOnly: true,
},
litleo: {
randomBattleMoves: ["hypervoice", "fireblast", "willowisp", "bulldoze", "yawn"],
tier: "Bank-LC",
},
pyroar: {
randomBattleMoves: ["sunnyday", "fireblast", "hypervoice", "solarbeam", "willowisp", "darkpulse"],
randomDoubleBattleMoves: ["hypervoice", "fireblast", "willowisp", "protect", "sunnyday", "solarbeam"],
eventPokemon: [
{"generation": 6, "level": 49, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["unnerve"], "moves":["hypervoice", "fireblast", "darkpulse"], "pokeball": "cherishball"},
],
tier: "Bank",
},
flabebe: {
randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank-LC",
},
floette: {
randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank-NFE",
},
floetteeternal: {
randomBattleMoves: ["lightofruin", "psychic", "hiddenpowerfire", "hiddenpowerground", "moonblast"],
randomDoubleBattleMoves: ["lightofruin", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
isUnreleased: true,
tier: "Unreleased",
},
florges: {
randomBattleMoves: ["calmmind", "moonblast", "synthesis", "aromatherapy", "wish", "toxic", "protect"],
randomDoubleBattleMoves: ["moonblast", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank",
},
skiddo: {
randomBattleMoves: ["hornleech", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide"],
tier: "Bank-LC",
},
gogoat: {
randomBattleMoves: ["bulkup", "hornleech", "earthquake", "rockslide", "substitute", "leechseed", "milkdrink"],
randomDoubleBattleMoves: ["hornleech", "earthquake", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide", "protect"],
tier: "Bank",
},
pancham: {
randomBattleMoves: ["partingshot", "skyuppercut", "crunch", "stoneedge", "bulldoze", "shadowclaw", "bulkup"],
eventPokemon: [
{"generation": 6, "level": 30, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moldbreaker"], "moves":["armthrust", "stoneedge", "darkpulse"], "pokeball": "cherishball"},
],
tier: "LC",
},
pangoro: {
randomBattleMoves: ["knockoff", "superpower", "gunkshot", "icepunch", "partingshot", "drainpunch"],
randomDoubleBattleMoves: ["partingshot", "hammerarm", "crunch", "circlethrow", "icepunch", "earthquake", "poisonjab", "protect"],
tier: "New",
},
furfrou: {
randomBattleMoves: ["return", "cottonguard", "thunderwave", "substitute", "toxic", "suckerpunch", "uturn", "rest"],
randomDoubleBattleMoves: ["return", "cottonguard", "uturn", "thunderwave", "suckerpunch", "snarl", "wildcharge", "protect"],
tier: "Bank",
},
espurr: {
randomBattleMoves: ["fakeout", "yawn", "thunderwave", "psychic", "trick", "darkpulse"],
tier: "Bank-LC",
},
meowstic: {
randomBattleMoves: ["toxic", "yawn", "thunderwave", "psychic", "reflect", "lightscreen", "healbell"],
randomDoubleBattleMoves: ["fakeout", "thunderwave", "psychic", "reflect", "lightscreen", "safeguard", "protect"],
tier: "Bank",
},
meowsticf: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "shadowball", "energyball", "thunderbolt"],
randomDoubleBattleMoves: ["psyshock", "darkpulse", "fakeout", "energyball", "signalbeam", "thunderbolt", "protect", "helpinghand"],
tier: "Bank",
},
honedge: {
randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "rockslide", "aerialace", "destinybond"],
tier: "LC",
},
doublade: {
randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword"],
randomDoubleBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword", "rockslide", "protect"],
tier: "New",
},
aegislash: {
randomBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "hiddenpowerice", "shadowball", "flashcannon"],
randomDoubleBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "wideguard", "hiddenpowerice", "shadowball", "flashcannon"],
eventPokemon: [
{"generation": 6, "level": 50, "gender": "F", "nature": "Quiet", "moves":["wideguard", "kingsshield", "shadowball", "flashcannon"], "pokeball": "cherishball"},
],
tier: "New",
},
aegislashblade: {
battleOnly: true,
},
spritzee: {
randomBattleMoves: ["calmmind", "drainingkiss", "moonblast", "psychic", "aromatherapy", "wish", "trickroom", "thunderbolt"],
tier: "Bank-LC",
},
aromatisse: {
randomBattleMoves: ["wish", "protect", "moonblast", "aromatherapy", "reflect", "lightscreen"],
randomDoubleBattleMoves: ["moonblast", "aromatherapy", "wish", "trickroom", "thunderbolt", "protect", "healpulse"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Relaxed", "isHidden": true, "moves":["trickroom", "healpulse", "disable", "moonblast"], "pokeball": "cherishball"},
],
tier: "Bank",
},
swirlix: {
randomBattleMoves: ["calmmind", "drainingkiss", "dazzlinggleam", "surf", "psychic", "flamethrower", "bellydrum", "thunderbolt", "return", "thief", "cottonguard"],
tier: "Bank",
},
slurpuff: {
randomBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "calmmind", "drainingkiss", "dazzlinggleam", "flamethrower", "surf"],
randomDoubleBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "dazzlinggleam", "surf", "psychic", "flamethrower", "protect"],
tier: "Bank",
},
inkay: {
randomBattleMoves: ["topsyturvy", "switcheroo", "superpower", "psychocut", "flamethrower", "rockslide", "trickroom"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": false, "moves":["happyhour", "foulplay", "hypnosis", "topsyturvy"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
malamar: {
randomBattleMoves: ["superpower", "knockoff", "psychocut", "rockslide", "substitute", "trickroom"],
randomDoubleBattleMoves: ["superpower", "psychocut", "rockslide", "trickroom", "knockoff", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": false, "abilities":["contrary"], "moves":["superpower", "knockoff", "facade", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
binacle: {
randomBattleMoves: ["shellsmash", "razorshell", "stoneedge", "earthquake", "crosschop", "poisonjab", "xscissor", "rockslide"],
tier: "Bank-LC",
},
barbaracle: {
randomBattleMoves: ["shellsmash", "stoneedge", "razorshell", "earthquake", "crosschop", "stealthrock"],
randomDoubleBattleMoves: ["shellsmash", "razorshell", "earthquake", "crosschop", "rockslide", "protect"],
tier: "Bank",
},
skrelp: {
randomBattleMoves: ["scald", "sludgebomb", "thunderbolt", "shadowball", "toxicspikes", "hydropump"],
tier: "Bank-LC",
},
dragalge: {
randomBattleMoves: ["dracometeor", "sludgewave", "focusblast", "scald", "hiddenpowerfire", "toxicspikes", "dragonpulse"],
randomDoubleBattleMoves: ["dracometeor", "sludgebomb", "focusblast", "scald", "hiddenpowerfire", "protect", "dragonpulse"],
tier: "Bank",
},
clauncher: {
randomBattleMoves: ["waterpulse", "flashcannon", "uturn", "crabhammer", "aquajet", "sludgebomb"],
tier: "Bank-LC",
},
clawitzer: {
randomBattleMoves: ["scald", "waterpulse", "darkpulse", "aurasphere", "icebeam", "uturn"],
randomDoubleBattleMoves: ["waterpulse", "icebeam", "uturn", "darkpulse", "aurasphere", "muddywater", "helpinghand", "protect"],
tier: "Bank",
},
helioptile: {
randomBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt"],
tier: "Bank-LC",
},
heliolisk: {
randomBattleMoves: ["raindance", "thunder", "hypervoice", "surf", "darkpulse", "hiddenpowerice", "voltswitch", "thunderbolt"],
randomDoubleBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt", "electricterrain", "protect"],
tier: "Bank",
},
tyrunt: {
randomBattleMoves: ["stealthrock", "dragondance", "stoneedge", "dragonclaw", "earthquake", "icefang", "firefang"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": true, "moves":["tailwhip", "tackle", "roar", "stomp"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
tyrantrum: {
randomBattleMoves: ["stealthrock", "dragondance", "dragonclaw", "earthquake", "superpower", "outrage", "headsmash"],
randomDoubleBattleMoves: ["rockslide", "dragondance", "headsmash", "dragonclaw", "earthquake", "icefang", "firefang", "protect"],
tier: "Bank",
},
amaura: {
randomBattleMoves: ["naturepower", "hypervoice", "ancientpower", "thunderbolt", "darkpulse", "thunderwave", "dragontail", "flashcannon"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": true, "moves":["growl", "powdersnow", "thunderwave", "rockthrow"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
aurorus: {
randomBattleMoves: ["ancientpower", "thunderbolt", "encore", "thunderwave", "earthpower", "freezedry", "hypervoice", "stealthrock"],
randomDoubleBattleMoves: ["hypervoice", "ancientpower", "thunderbolt", "encore", "thunderwave", "flashcannon", "freezedry", "icywind", "protect"],
tier: "Bank",
},
sylveon: {
randomBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "batonpass", "shadowball"],
randomDoubleBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "helpinghand", "shadowball", "hiddenpowerground"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "helpinghand", "sandattack", "fairywind"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["disarmingvoice", "babydolleyes", "quickattack", "drainingkiss"], "pokeball": "cherishball"},
],
tier: "New",
},
hawlucha: {
randomBattleMoves: ["substitute", "swordsdance", "highjumpkick", "acrobatics", "roost", "stoneedge"],
randomDoubleBattleMoves: ["swordsdance", "highjumpkick", "uturn", "stoneedge", "skydrop", "encore", "protect"],
tier: "Bank",
},
dedenne: {
randomBattleMoves: ["substitute", "recycle", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "toxic"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "uturn", "helpinghand", "protect"],
tier: "Bank",
},
carbink: {
randomBattleMoves: ["stealthrock", "lightscreen", "reflect", "explosion", "powergem", "moonblast"],
randomDoubleBattleMoves: ["trickroom", "lightscreen", "reflect", "explosion", "powergem", "moonblast", "protect"],
tier: "New",
},
goomy: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation"],
tier: "LC",
},
sliggoo: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation", "icebeam"],
tier: "NFE",
},
goodra: {
randomBattleMoves: ["dracometeor", "dragonpulse", "fireblast", "sludgebomb", "thunderbolt", "earthquake", "dragontail"],
randomDoubleBattleMoves: ["thunderbolt", "icebeam", "dragonpulse", "fireblast", "muddywater", "dracometeor", "focusblast", "protect"],
tier: "New",
},
klefki: {
randomBattleMoves: ["reflect", "lightscreen", "spikes", "magnetrise", "playrough", "thunderwave", "foulplay", "toxic"],
randomDoubleBattleMoves: ["reflect", "lightscreen", "safeguard", "playrough", "substitute", "thunderwave", "protect", "flashcannon", "dazzlinggleam"],
tier: "New",
},
phantump: {
randomBattleMoves: ["hornleech", "leechseed", "phantomforce", "substitute", "willowisp", "rest"],
tier: "LC",
},
trevenant: {
randomBattleMoves: ["hornleech", "shadowclaw", "leechseed", "willowisp", "rest", "substitute", "phantomforce"],
randomDoubleBattleMoves: ["hornleech", "woodhammer", "leechseed", "shadowclaw", "willowisp", "trickroom", "earthquake", "rockslide", "protect"],
tier: "New",
},
pumpkaboo: {
randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb", "leechseed"],
tier: "Bank-LC",
},
pumpkaboosmall: {
randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb"],
unreleasedHidden: true,
tier: "Bank-LC",
},
pumpkaboolarge: {
randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"],
unreleasedHidden: true,
tier: "Bank-LC",
},
pumpkaboosuper: {
randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["trickortreat", "astonish", "scaryface", "shadowsneak"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
gourgeist: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"],
tier: "Bank",
},
gourgeistsmall: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"],
unreleasedHidden: true,
tier: "Bank",
},
gourgeistlarge: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"],
unreleasedHidden: true,
tier: "Bank",
},
gourgeistsuper: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"],
tier: "Bank",
},
bergmite: {
randomBattleMoves: ["avalanche", "recover", "stoneedge", "curse", "gyroball", "rapidspin"],
tier: "Bank-LC",
},
avalugg: {
randomBattleMoves: ["avalanche", "recover", "toxic", "rapidspin", "roar", "earthquake"],
randomDoubleBattleMoves: ["avalanche", "recover", "earthquake", "protect"],
tier: "Bank",
},
noibat: {
randomBattleMoves: ["airslash", "hurricane", "dracometeor", "uturn", "roost", "switcheroo"],
tier: "Bank-LC",
},
noivern: {
randomBattleMoves: ["dracometeor", "hurricane", "airslash", "flamethrower", "boomburst", "switcheroo", "uturn", "roost", "taunt"],
randomDoubleBattleMoves: ["airslash", "hurricane", "dragonpulse", "dracometeor", "focusblast", "flamethrower", "uturn", "roost", "boomburst", "switcheroo", "tailwind", "taunt", "protect"],
tier: "Bank",
},
xerneas: {
randomBattleMoves: ["geomancy", "moonblast", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat"],
randomDoubleBattleMoves: ["geomancy", "dazzlinggleam", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["gravity", "geomancy", "moonblast", "megahorn"]},
{"generation": 6, "level": 100, "shiny": true, "moves":["geomancy", "moonblast", "aromatherapy", "focusblast"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
yveltal: {
randomBattleMoves: ["darkpulse", "hurricane", "foulplay", "oblivionwing", "uturn", "suckerpunch", "taunt", "toxic", "roost"],
randomDoubleBattleMoves: ["darkpulse", "oblivionwing", "taunt", "focusblast", "hurricane", "roost", "suckerpunch", "snarl", "skydrop", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["snarl", "oblivionwing", "disable", "darkpulse"]},
{"generation": 6, "level": 100, "shiny": true, "moves":["oblivionwing", "suckerpunch", "darkpulse", "foulplay"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
zygarde: {
randomBattleMoves: ["dragondance", "earthquake", "outrage", "extremespeed", "stoneedge"],
randomDoubleBattleMoves: ["dragondance", "landswrath", "extremespeed", "rockslide", "coil", "stoneedge", "glare", "protect"],
eventPokemon: [
{"generation": 6, "level": 70, "moves":["crunch", "earthquake", "camouflage", "dragonpulse"]},
{"generation": 6, "level": 100, "moves":["landswrath", "extremespeed", "glare", "outrage"], "pokeball": "cherishball"},
{"generation": 7, "level": 50, "moves":["bind", "landswrath", "sandstorm", "haze"]},
],
eventOnly: true,
tier: "New",
},
zygarde10: {
randomBattleMoves: ["dragondance", "thousandarrows", "outrage", "extremespeed", "irontail", "substitute"],
eventPokemon: [
{"generation": 7, "level": 30, "moves":["safeguard", "dig", "bind", "landswrath"]},
],
eventOnly: true,
gen: 7,
tier: "New",
},
zygardecomplete: {
gen: 7,
requiredAbility: "Power Construct",
battleOnly: true,
},
diancie: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "diamondstorm", "moonblast", "hiddenpowerfire"],
randomDoubleBattleMoves: ["diamondstorm", "moonblast", "reflect", "lightscreen", "safeguard", "substitute", "calmmind", "psychic", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["diamondstorm", "reflect", "return", "moonblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": true, "moves":["diamondstorm", "moonblast", "reflect", "return"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
dianciemega: {
randomBattleMoves: ["calmmind", "moonblast", "earthpower", "hiddenpowerfire", "psyshock", "diamondstorm"],
randomDoubleBattleMoves: ["diamondstorm", "moonblast", "calmmind", "psyshock", "earthpower", "hiddenpowerfire", "dazzlinggleam", "protect"],
requiredItem: "Diancite",
tier: "Bank",
},
hoopa: {
randomBattleMoves: ["nastyplot", "psyshock", "shadowball", "focusblast", "trick"],
randomDoubleBattleMoves: ["hyperspacehole", "shadowball", "focusblast", "protect", "psychic", "trickroom"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["hyperspacehole", "nastyplot", "psychic", "astonish"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
hoopaunbound: {
randomBattleMoves: ["nastyplot", "substitute", "psyshock", "psychic", "darkpulse", "focusblast", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot", "knockoff", "trick"],
randomDoubleBattleMoves: ["psychic", "darkpulse", "focusblast", "protect", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot"],
eventOnly: true,
tier: "Bank",
},
volcanion: {
randomBattleMoves: ["substitute", "steameruption", "fireblast", "sludgewave", "hiddenpowerice", "earthpower", "superpower"],
randomDoubleBattleMoves: ["substitute", "steameruption", "heatwave", "sludgebomb", "rockslide", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 70, "moves":["steameruption", "overheat", "hydropump", "mist"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "moves":["steameruption", "flamethrower", "hydropump", "explosion"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
rowlet: {
unreleasedHidden: true,
tier: "LC",
},
dartrix: {
unreleasedHidden: true,
tier: "NFE",
},
decidueye: {
randomBattleMoves: ["spiritshackle", "uturn", "leafblade", "roost", "swordsdance", "suckerpunch"],
unreleasedHidden: true,
tier: "New",
},
litten: {
unreleasedHidden: true,
tier: "LC",
},
torracat: {
unreleasedHidden: true,
tier: "NFE",
},
incineroar: {
randomBattleMoves: ["fakeout", "darkestlariat", "flareblitz", "uturn", "earthquake"],
unreleasedHidden: true,
tier: "New",
},
popplio: {
unreleasedHidden: true,
tier: "LC",
},
brionne: {
unreleasedHidden: true,
tier: "NFE",
},
primarina: {
randomBattleMoves: ["hypervoice", "moonblast", "icebeam", "encore", "reflect", "lightscreen", "scald"],
unreleasedHidden: true,
tier: "New",
},
pikipek: {
tier: "LC",
},
trumbeak: {
tier: "NFE",
},
toucannon: {
randomBattleMoves: ["substitute", "beakblast", "swordsdance", "roost", "brickbreak"],
tier: "New",
},
yungoos: {
tier: "LC",
},
gumshoos: {
randomBattleMoves: ["uturn", "return", "crunch", "earthquake"],
tier: "New",
},
grubbin: {
tier: "LC",
},
charjabug: {
tier: "NFE",
},
vikavolt: {
randomBattleMoves: ["agility", "bugbuzz", "thunderbolt", "voltswitch", "energyball"],
tier: "New",
},
crabrawler: {
tier: "LC",
},
crabominable: {
randomBattleMoves: ["icehammer", "closecombat", "earthquake", "stoneedge"],
tier: "New",
},
oricorio: {
randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"],
tier: "New",
},
oricoriopompom: {
tier: "New",
},
oricoriopau: {
tier: "New",
},
oricoriosensu: {
tier: "New",
},
cutiefly: {
tier: "LC",
},
ribombee: {
randomBattleMoves: ["quiverdance", "bugbuzz", "moonblast", "hiddenpowerfire", "roost", "batonpass"],
tier: "New",
},
rockruff: {
tier: "LC",
},
lycanroc: {
randomBattleMoves: ["swordsdance", "accelerock", "stoneedge", "crunch", "firefang"],
tier: "New",
},
lycanrocmidnight: {
randomBattleMoves: ["bulkup", "stoneedge", "stealthrock", "suckerpunch", "swordsdance", "firefang", "rockclimb"],
tier: "New",
},
wishiwashi: {
randomBattleMoves: ["scald", "hydropump", "icebeam", "hiddenpowergrass", "earthquake"],
tier: "New",
},
wishiwashischool: {
battleOnly: true,
},
mareanie: {
tier: "LC",
},
toxapex: {
randomBattleMoves: ["toxicspikes", "banefulbunker", "recover", "liquidation", "venoshock"],
tier: "New",
},
mudbray: {
tier: "LC",
},
mudsdale: {
randomBattleMoves: ["earthquake", "closecombat", "payback", "rockslide"],
tier: "New",
},
dewpider: {
tier: "LC",
},
araquanid: {
randomBattleMoves: ["liquidation", "lunge", "infestation", "mirrorcoat"],
tier: "New",
},
fomantis: {
tier: "LC",
},
lurantis: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "gigadrain", "substitute"],
tier: "New",
},
morelull: {
tier: "LC",
},
shiinotic: {
randomBattleMoves: ["spore", "strengthsap", "moonblast", "substitute", "leechseed"],
tier: "New",
},
salandit: {
tier: "LC",
},
salazzle: {
randomBattleMoves: ["nastyplot", "fireblast", "sludgewave", "hiddenpowerground"],
tier: "New",
},
stufful: {
tier: "LC",
},
bewear: {
randomBattleMoves: ["hammerarm", "icepunch", "swordsdance", "painsplit", "substitute"],
tier: "New",
},
bounsweet: {
tier: "LC",
},
steenee: {
tier: "NFE",
},
tsareena: {
randomBattleMoves: ["highjumpkick", "tropkick", "playrough", "uturn"],
tier: "New",
},
comfey: {
randomBattleMoves: ["sweetkiss", "aromatherapy", "drainingkiss", "toxic", "synthesis"],
tier: "New",
},
oranguru: {
randomBattleMoves: ["nastyplot", "psyshock", "focusblast", "thunderbolt"],
tier: "New",
},
passimian: {
randomBattleMoves: ["rocktomb", "closecombat", "earthquake", "ironhead"],
tier: "New",
},
wimpod: {
tier: "LC",
},
golisopod: {
randomBattleMoves: ["spikes", "firstimpression", "liquidation", "suckerpunch", "aquajet", "toxic"],
tier: "New",
},
sandygast: {
tier: "LC",
},
palossand: {
randomBattleMoves: ["shoreup", "earthpower", "shadowball", "protect", "toxic"],
tier: "New",
},
pyukumuku: {
randomBattleMoves: ["curse", "batonpass", "recover", "counter", "reflect", "lightscreen"],
tier: "New",
},
typenull: {
eventPokemon: [
{"generation": 7, "level": 40, "moves":["crushclaw", "scaryface", "xscissor", "takedown"]},
],
eventOnly: true,
tier: "NFE",
},
silvally: {
randomBattleMoves: ["swordsdance", "return", "doubleedge", "crunch", "flamecharge", "flamethrower", "icebeam", "uturn", "ironhead"],
tier: "New",
},
silvallybug: {
tier: "New",
requiredItem: "Bug Memory",
},
silvallydark: {
randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "ironhead"],
tier: "New",
requiredItem: "Dark Memory",
},
silvallydragon: {
tier: "New",
requiredItem: "Dragon Memory",
},
silvallyelectric: {
randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"],
tier: "New",
requiredItem: "Electric Memory",
},
silvallyfairy: {
tier: "New",
requiredItem: "Fairy Memory",
},
silvallyfighting: {
tier: "New",
requiredItem: "Fighting Memory",
},
silvallyfire: {
tier: "New",
requiredItem: "Fire Memory",
},
silvallyflying: {
tier: "New",
requiredItem: "Flying Memory",
},
silvallyghost: {
randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"],
tier: "New",
requiredItem: "Ghost Memory",
},
silvallygrass: {
tier: "New",
requiredItem: "Grass Memory",
},
silvallyground: {
randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "rockslide"],
tier: "New",
requiredItem: "Ground Memory",
},
silvallyice: {
tier: "New",
requiredItem: "Ice Memory",
},
silvallypoison: {
tier: "New",
requiredItem: "Poison Memory",
},
silvallypsychic: {
tier: "New",
requiredItem: "Psychic Memory",
},
silvallyrock: {
tier: "New",
requiredItem: "Rock Memory",
},
silvallysteel: {
tier: "New",
requiredItem: "Steel Memory",
},
silvallywater: {
tier: "New",
requiredItem: "Water Memory",
},
minior: {
randomBattleMoves: ["shellsmash", "powergem", "acrobatics", "earthquake"],
tier: "New",
},
miniormeteor: {
battleOnly: true,
},
komala: {
randomBattleMoves: ["return", "suckerpunch", "woodhammer", "earthquake", "playrough", "uturn"],
tier: "New",
},
turtonator: {
randomBattleMoves: ["overheat", "shelltrap", "earthquake", "dragontail", "explosion"],
tier: "New",
},
togedemaru: {
randomBattleMoves: ["spikyshield", "zingzap", "nuzzle", "uturn", "wish"],
tier: "New",
},
mimikyu: {
randomBattleMoves: ["swordsdance", "shadowsneak", "playrough", "woodhammer", "shadowclaw"],
tier: "New",
},
mimikyubusted: {
battleOnly: true,
},
bruxish: {
randomBattleMoves: ["psychicfangs", "crunch", "waterfall", "icefang", "aquajet", "swordsdance"],
tier: "New",
},
drampa: {
randomBattleMoves: ["dracometeor", "dragonpulse", "hypervoice", "fireblast", "thunderbolt", "glare", "substitute", "roost"],
tier: "New",
},
dhelmise: {
randomBattleMoves: ["swordsdance", "powerwhip", "phantomforce", "anchorshot", "switcheroo", "earthquake"],
tier: "New",
},
jangmoo: {
tier: "LC",
},
hakamoo: {
tier: "NFE",
},
kommoo: {
randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "skyuppercut", "poisonjab"],
tier: "New",
},
tapukoko: {
randomBattleMoves: ["wildcharge", "voltswitch", "naturesmadness", "bravebird", "uturn"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "discharge", "agility", "electroball"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapulele: {
randomBattleMoves: ["moonblast", "psyshock", "calmmind", "focusblast", "aromatherapy"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "extrasensory", "flatter", "moonblast"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapubulu: {
randomBattleMoves: ["woodhammer", "naturesmadness", "rocktomb", "superpower", "megahorn"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "zenheadbutt", "megahorn", "skullbash"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapufini: {
randomBattleMoves: ["calmmind", "moonblast", "scald", "substitute", "icebeam"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "muddywater", "aquaring", "hydropump"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
cosmog: {
eventPokemon: [
{"generation": 7, "level": 5, "moves":["splash"]},
],
eventOnly: true,
tier: "LC",
},
cosmoem: {
tier: "NFE",
},
solgaleo: {
randomBattleMoves: ["sunsteelstrike", "zenheadbutt", "flareblitz", "morningsun", "stoneedge", "earthquake"],
eventPokemon: [
{"generation": 7, "level": 55, "moves":["sunsteelstrike", "cosmicpower", "crunch", "zenheadbutt"]},
],
tier: "Uber",
},
lunala: {
randomBattleMoves: ["moongeistbeam", "psyshock", "calmmind", "focusblast", "moonlight"],
eventPokemon: [
{"generation": 7, "level": 55, "moves":["moongeistbeam", "cosmicpower", "nightdaze", "shadowball"]},
],
tier: "Uber",
},
nihilego: {
randomBattleMoves: ["stealthrock", "acidspray", "powergem", "toxicspikes"],
tier: "New",
},
buzzwole: {
randomBattleMoves: ["lunge", "substitute", "focuspunch", "thunderpunch"],
tier: "New",
},
pheromosa: {
randomBattleMoves: ["highjumpkick", "uturn", "icebeam", "poisonjab", "bugbuzz"],
tier: "New",
},
xurkitree: {
randomBattleMoves: ["thunderbolt", "voltswitch", "energyball", "dazzlinggleam", "hiddenpowerice"],
tier: "New",
},
celesteela: {
randomBattleMoves: ["autotomize", "flashcannon", "airslash", "fireblast", "energyball"],
tier: "New",
},
kartana: {
randomBattleMoves: ["leafblade", "sacredsword", "smartstrike", "psychocut", "swordsdance"],
tier: "New",
},
guzzlord: {
randomBattleMoves: ["dracometeor", "hammerarm", "crunch", "earthquake", "fireblast"],
tier: "New",
},
necrozma: {
randomBattleMoves: ["autotomize", "swordsdance", "stoneedge", "psychocut", "earthquake", "psyshock"],
tier: "New",
},
magearna: {
randomBattleMoves: ["shiftgear", "flashcannon", "aurasphere", "fleurcannon", "ironhead", "thunderbolt", "icebeam"],
eventPokemon: [
{"generation": 7, "level": 50, "moves":["fleurcannon", "flashcannon", "luckychant", "helpinghand"]},
],
eventOnly: true,
tier: "New",
},
marshadow: {
randomBattleMoves: ["spectralthief", "closecombat", "stoneedge", "shadowsneak", "icepunch"],
isUnreleased: true,
tier: "Unreleased",
},
missingno: {
randomBattleMoves: ["watergun", "skyattack", "doubleedge", "metronome"],
isNonstandard: true,
tier: "Illegal",
},
tomohawk: {
randomBattleMoves: ["aurasphere", "roost", "stealthrock", "rapidspin", "hurricane", "airslash", "taunt", "substitute", "toxic", "naturepower", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
necturna: {
randomBattleMoves: ["powerwhip", "hornleech", "willowisp", "shadowsneak", "stoneedge", "sacredfire", "boltstrike", "vcreate", "extremespeed", "closecombat", "shellsmash", "spore", "milkdrink", "batonpass", "stickyweb"],
isNonstandard: true,
tier: "CAP",
},
mollux: {
randomBattleMoves: ["fireblast", "thunderbolt", "sludgebomb", "thunderwave", "willowisp", "recover", "rapidspin", "trick", "stealthrock", "toxicspikes", "lavaplume"],
isNonstandard: true,
tier: "CAP",
},
aurumoth: {
randomBattleMoves: ["dragondance", "quiverdance", "closecombat", "bugbuzz", "hydropump", "megahorn", "psychic", "blizzard", "thunder", "focusblast", "zenheadbutt"],
isNonstandard: true,
tier: "CAP",
},
malaconda: {
randomBattleMoves: ["powerwhip", "glare", "toxic", "suckerpunch", "rest", "substitute", "uturn", "synthesis", "rapidspin", "knockoff"],
isNonstandard: true,
tier: "CAP",
},
cawmodore: {
randomBattleMoves: ["bellydrum", "bulletpunch", "drainpunch", "acrobatics", "drillpeck", "substitute", "ironhead", "quickattack"],
isNonstandard: true,
tier: "CAP",
},
volkraken: {
randomBattleMoves: ["scald", "powergem", "hydropump", "memento", "hiddenpowerice", "fireblast", "willowisp", "uturn", "substitute", "flashcannon", "surf"],
isNonstandard: true,
tier: "CAP",
},
plasmanta: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "substitute", "hiddenpowerice", "psyshock", "dazzlinggleam", "flashcannon"],
isNonstandard: true,
tier: "CAP",
},
naviathan: {
randomBattleMoves: ["dragondance", "waterfall", "ironhead", "iciclecrash"],
isNonstandard: true,
tier: "CAP",
},
crucibelle: {
randomBattleMoves: ["headsmash", "gunkshot", "coil", "lowkick", "uturn", "stealthrock"],
isNonstandard: true,
tier: "CAP",
},
crucibellemega: {
randomBattleMoves: ["headsmash", "gunkshot", "coil", "woodhammer", "lowkick", "uturn"],
requiredItem: "Crucibellite",
isNonstandard: true,
tier: "CAP",
},
kerfluffle: {
randomBattleMoves: ["aurasphere", "moonblast", "taunt", "partingshot", "gigadrain", "yawn"],
isNonstandard: true,
eventPokemon: [
{"generation": 6, "level": 16, "isHidden": false, "abilities":["naturalcure"], "moves":["celebrate", "holdhands", "fly", "metronome"], "pokeball": "cherishball"},
],
tier: "CAP",
},
syclant: {
randomBattleMoves: ["bugbuzz", "icebeam", "blizzard", "earthpower", "spikes", "superpower", "tailglow", "uturn", "focusblast"],
isNonstandard: true,
tier: "CAP",
},
revenankh: {
randomBattleMoves: ["bulkup", "shadowsneak", "drainpunch", "rest", "moonlight", "icepunch", "glare"],
isNonstandard: true,
tier: "CAP",
},
pyroak: {
randomBattleMoves: ["leechseed", "lavaplume", "substitute", "protect", "gigadrain"],
isNonstandard: true,
tier: "CAP",
},
fidgit: {
randomBattleMoves: ["spikes", "stealthrock", "toxicspikes", "wish", "rapidspin", "encore", "uturn", "sludgebomb", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
stratagem: {
randomBattleMoves: ["paleowave", "earthpower", "fireblast", "gigadrain", "calmmind", "substitute"],
isNonstandard: true,
tier: "CAP",
},
arghonaut: {
randomBattleMoves: ["recover", "bulkup", "waterfall", "drainpunch", "crosschop", "stoneedge", "thunderpunch", "aquajet", "machpunch"],
isNonstandard: true,
tier: "CAP",
},
kitsunoh: {
randomBattleMoves: ["shadowstrike", "earthquake", "superpower", "meteormash", "uturn", "icepunch", "trick", "willowisp"],
isNonstandard: true,
tier: "CAP",
},
cyclohm: {
randomBattleMoves: ["slackoff", "dracometeor", "dragonpulse", "fireblast", "thunderbolt", "hydropump", "discharge", "healbell"],
isNonstandard: true,
tier: "CAP",
},
colossoil: {
randomBattleMoves: ["earthquake", "crunch", "suckerpunch", "uturn", "rapidspin", "encore", "pursuit", "knockoff"],
isNonstandard: true,
tier: "CAP",
},
krilowatt: {
randomBattleMoves: ["surf", "thunderbolt", "icebeam", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
voodoom: {
randomBattleMoves: ["aurasphere", "darkpulse", "taunt", "painsplit", "substitute", "hiddenpowerice", "vacuumwave"],
isNonstandard: true,
tier: "CAP",
},
};
| data/formats-data.js | 'use strict';
exports.BattleFormatsData = {
bulbasaur: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["sweetscent", "growth", "solarbeam", "synthesis"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "leechseed", "vinewhip"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "leechseed", "vinewhip"]},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"def": 31}, "isHidden": false, "moves":["falseswipe", "block", "frenzyplant", "weatherball"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "leechseed", "vinewhip", "poisonpowder"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "growl", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
ivysaur: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
tier: "Bank-NFE",
},
venusaur: {
randomBattleMoves: ["sunnyday", "sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
eventPokemon: [
{"generation": 6, "level": 100, "isHidden": true, "moves":["solarbeam", "frenzyplant", "synthesis", "grasspledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
venusaurmega: {
randomBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "sludgebomb", "leechseed", "synthesis", "earthquake", "knockoff"],
randomDoubleBattleMoves: ["sleeppowder", "gigadrain", "hiddenpowerfire", "hiddenpowerice", "sludgebomb", "powerwhip", "protect"],
requiredItem: "Venusaurite",
tier: "Bank",
},
charmander: {
randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast"],
randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "ember"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Naive", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Naughty", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "ember", "smokescreen"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["return", "hiddenpower", "quickattack", "howl"], "pokeball": "cherishball"},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"spe": 31}, "isHidden": false, "moves":["falseswipe", "block", "blastburn", "acrobatics"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["growl", "ember", "smokescreen", "dragonrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["scratch", "growl", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
charmeleon: {
randomBattleMoves: ["flamethrower", "overheat", "dragonpulse", "hiddenpowergrass", "fireblast", "dragondance", "flareblitz", "shadowclaw", "dragonclaw"],
randomDoubleBattleMoves: ["heatwave", "dragonpulse", "hiddenpowergrass", "fireblast", "protect"],
tier: "Bank-NFE",
},
charizard: {
randomBattleMoves: ["fireblast", "airslash", "focusblast", "roost", "swordsdance", "flareblitz", "acrobatics", "earthquake"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "overheat", "dragonpulse", "roost", "tailwind", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["wingattack", "slash", "dragonrage", "firespin"]},
{"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "flameburst", "airslash", "inferno"], "pokeball": "cherishball"},
{"generation": 6, "level": 36, "gender": "M", "isHidden": false, "moves":["firefang", "airslash", "dragonclaw", "dragonrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 36, "shiny": true, "gender": "M", "isHidden": false, "moves":["overheat", "solarbeam", "focusblast", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": true, "moves":["flareblitz", "blastburn", "scaryface", "firepledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
charizardmegax: {
randomBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "roost", "willowisp"],
randomDoubleBattleMoves: ["dragondance", "flareblitz", "dragonclaw", "earthquake", "rockslide", "roost", "substitute"],
requiredItem: "Charizardite X",
tier: "Bank",
},
charizardmegay: {
randomBattleMoves: ["fireblast", "airslash", "roost", "solarbeam", "focusblast", "dragonpulse"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "airslash", "roost", "solarbeam", "focusblast", "protect"],
requiredItem: "Charizardite Y",
tier: "Bank",
},
squirtle: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "tailwhip", "bubble", "withdraw"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "tailwhip", "bubble", "withdraw"]},
{"generation": 5, "level": 1, "shiny": 1, "ivs": {"hp": 31}, "isHidden": false, "moves":["falseswipe", "block", "hydrocannon", "followme"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tailwhip", "watergun", "withdraw", "bubble"], "pokeball": "cherishball"},
{"generation": 6, "level": 5, "isHidden": true, "moves":["tackle", "tailwhip", "celebrate"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
wartortle: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "aquajet", "toxic"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect"],
tier: "Bank-NFE",
},
blastoise: {
randomBattleMoves: ["icebeam", "rapidspin", "scald", "toxic", "dragontail", "roar"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "followme", "icywind", "protect", "waterspout"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["protect", "raindance", "skullbash", "hydropump"]},
{"generation": 6, "level": 100, "isHidden": true, "moves":["hydropump", "hydrocannon", "irondefense", "waterpledge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
blastoisemega: {
randomBattleMoves: ["icebeam", "hydropump", "rapidspin", "scald", "toxic", "dragontail", "darkpulse", "aurasphere"],
randomDoubleBattleMoves: ["muddywater", "icebeam", "hydropump", "fakeout", "scald", "darkpulse", "aurasphere", "followme", "icywind", "protect"],
requiredItem: "Blastoisinite",
tier: "Bank",
},
caterpie: {
randomBattleMoves: ["bugbite", "snore", "tackle", "electroweb"],
tier: "LC",
},
metapod: {
randomBattleMoves: ["snore", "bugbite", "tackle", "electroweb"],
tier: "NFE",
},
butterfree: {
randomBattleMoves: ["sleeppowder", "quiverdance", "bugbuzz", "psychic", "gigadrain", "substitute"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "substitute", "sleeppowder", "psychic", "shadowball", "protect"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["morningsun", "psychic", "sleeppowder", "aerialace"]},
],
tier: "New",
},
weedle: {
randomBattleMoves: ["bugbite", "stringshot", "poisonsting", "electroweb"],
tier: "Bank-LC",
},
kakuna: {
randomBattleMoves: ["electroweb", "bugbite", "irondefense", "poisonsting"],
tier: "Bank-NFE",
},
beedrill: {
randomBattleMoves: ["toxicspikes", "tailwind", "uturn", "endeavor", "poisonjab", "knockoff"],
randomDoubleBattleMoves: ["xscissor", "uturn", "poisonjab", "drillrun", "brickbreak", "knockoff", "protect", "stringshot"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["batonpass", "sludgebomb", "twineedle", "swordsdance"]},
],
tier: "Bank",
},
beedrillmega: {
randomBattleMoves: ["xscissor", "swordsdance", "uturn", "poisonjab", "drillrun", "knockoff"],
randomDoubleBattleMoves: ["xscissor", "uturn", "substitute", "poisonjab", "drillrun", "knockoff", "protect"],
requiredItem: "Beedrillite",
tier: "Bank",
},
pidgey: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"],
tier: "Bank-LC",
},
pidgeotto: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "workup", "uturn", "thief"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "uturn", "tailwind", "protect"],
eventPokemon: [
{"generation": 3, "level": 30, "abilities":["keeneye"], "moves":["refresh", "wingattack", "steelwing", "featherdance"]},
],
tier: "Bank-NFE",
},
pidgeot: {
randomBattleMoves: ["roost", "bravebird", "heatwave", "return", "doubleedge", "uturn", "hurricane"],
randomDoubleBattleMoves: ["bravebird", "heatwave", "return", "doubleedge", "uturn", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 61, "gender": "M", "nature": "Naughty", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["keeneye"], "moves":["whirlwind", "wingattack", "skyattack", "mirrormove"], "pokeball": "cherishball"},
],
tier: "Bank",
},
pidgeotmega: {
randomBattleMoves: ["roost", "heatwave", "uturn", "hurricane", "defog"],
randomDoubleBattleMoves: ["tailwind", "heatwave", "uturn", "hurricane", "protect"],
requiredItem: "Pidgeotite",
tier: "Bank",
},
rattata: {
randomBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "thunderwave", "crunch", "revenge"],
randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "wildcharge", "superfang", "crunch", "protect"],
tier: "Bank-LC",
},
rattataalola: {
tier: "LC",
},
raticate: {
randomBattleMoves: ["protect", "facade", "flamewheel", "suckerpunch", "uturn", "swordsdance"],
randomDoubleBattleMoves: ["facade", "flamewheel", "suckerpunch", "uturn", "crunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 34, "moves":["refresh", "superfang", "scaryface", "hyperfang"]},
],
tier: "Bank",
},
raticatealola: {
randomBattleMoves: ["swordsdance", "return", "suckerpunch", "crunch", "doubleedge"],
tier: "New",
},
spearow: {
randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "pursuit", "drillrun", "featherdance"],
randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"],
eventPokemon: [
{"generation": 3, "level": 22, "moves":["batonpass", "falseswipe", "leer", "aerialace"]},
],
tier: "LC",
},
fearow: {
randomBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "pursuit", "drillrun"],
randomDoubleBattleMoves: ["return", "drillpeck", "doubleedge", "uturn", "quickattack", "drillrun", "protect"],
tier: "New",
},
ekans: {
randomBattleMoves: ["coil", "gunkshot", "glare", "suckerpunch", "earthquake", "rest"],
randomDoubleBattleMoves: ["gunkshot", "seedbomb", "suckerpunch", "aquatail", "earthquake", "rest", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 14, "gender": "F", "nature": "Docile", "ivs": {"hp": 26, "atk": 28, "def": 6, "spa": 14, "spd": 30, "spe": 11}, "abilities":["shedskin"], "moves":["leer", "wrap", "poisonsting", "bite"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "leer", "poisonsting"]},
],
tier: "Bank-LC",
},
arbok: {
randomBattleMoves: ["coil", "gunkshot", "suckerpunch", "aquatail", "earthquake", "rest"],
randomDoubleBattleMoves: ["gunkshot", "suckerpunch", "aquatail", "crunch", "earthquake", "rest", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 33, "moves":["refresh", "sludgebomb", "glare", "bite"]},
],
tier: "Bank",
},
pichu: {
randomBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "toxic", "thunderbolt"],
randomDoubleBattleMoves: ["fakeout", "volttackle", "encore", "irontail", "protect", "thunderbolt"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "surf"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "teeterdance"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["thundershock", "charm", "followme"]},
{"generation": 4, "level": 1, "moves":["volttackle", "thunderbolt", "grassknot", "return"]},
{"generation": 4, "level": 30, "shiny": true, "gender": "M", "nature": "Jolly", "moves":["charge", "volttackle", "endeavor", "endure"], "pokeball": "cherishball"},
],
tier: "LC",
},
pichuspikyeared: {
eventPokemon: [
{"generation": 4, "level": 30, "gender": "F", "nature": "Naughty", "moves":["helpinghand", "volttackle", "swagger", "painsplit"]},
],
eventOnly: true,
gen: 4,
tier: "Illegal",
},
pikachu: {
randomBattleMoves: ["thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "thunderbolt", "volttackle", "voltswitch", "grassknot", "hiddenpowerice", "brickbreak", "extremespeed", "encore", "substitute", "knockoff", "protect", "discharge"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["thunderbolt", "agility", "thunder", "lightscreen"]},
{"generation": 3, "level": 10, "moves":["thundershock", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["fly", "tailwhip", "growl", "thunderwave"]},
{"generation": 3, "level": 5, "moves":["surf", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["fly", "growl", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "moves":["thundershock", "growl", "thunderwave", "surf"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "fly"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "surf"]},
{"generation": 3, "level": 70, "moves":["thunderbolt", "thunder", "lightscreen", "agility"]},
{"generation": 4, "level": 10, "gender": "F", "nature": "Hardy", "moves":["surf", "volttackle", "tailwhip", "thunderwave"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["thundershock", "growl", "tailwhip", "thunderwave"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["surf", "thunderbolt", "lightscreen", "quickattack"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Jolly", "moves":["grassknot", "thunderbolt", "flash", "doubleteam"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Modest", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["quickattack", "thundershock", "tailwhip", "present"], "pokeball": "cherishball"},
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["surf", "thunder", "protect"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "F", "nature": "Bashful", "moves":["present", "quickattack", "thunderwave", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lastresort", "present", "thunderbolt", "quickattack"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "gender": "M", "nature": "Relaxed", "moves":["rest", "sleeptalk", "yawn", "snore"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Docile", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["volttackle", "irontail", "quickattack", "thunderbolt"], "pokeball": "cherishball"},
{"generation": 4, "level": 20, "gender": "M", "nature": "Bashful", "moves":["present", "quickattack", "thundershock", "tailwhip"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["sing", "teeterdance", "encore", "electroball"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["fly", "irontail", "electroball", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "shiny": 1, "gender": "F", "isHidden": false, "moves":["thunder", "volttackle", "grassknot", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "gender": "F", "isHidden": false, "moves":["extremespeed", "thunderbolt", "grassknot", "brickbreak"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "isHidden": true, "moves":["fly", "thunderbolt", "grassknot", "protect"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["thundershock", "tailwhip", "thunderwave", "headbutt"]},
{"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["volttackle", "quickattack", "feint", "voltswitch"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "growl", "playnice", "quickattack"], "pokeball": "cherishball"},
{"generation": 6, "level": 22, "isHidden": false, "moves":["quickattack", "electroball", "doubleteam", "megakick"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["thunderbolt", "quickattack", "surf", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["thunderbolt", "quickattack", "heartstamp", "holdhands"], "pokeball": "healball"},
{"generation": 6, "level": 36, "shiny": true, "isHidden": true, "moves":["thunder", "substitute", "playnice", "holdhands"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["playnice", "charm", "nuzzle", "sweetkiss"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "gender": "M", "nature": "Naughty", "isHidden": false, "moves":["thunderbolt", "quickattack", "irontail", "electroball"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "shiny": true, "isHidden": false, "moves":["teeterdance", "playnice", "tailwhip", "nuzzle"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "perfectIVs": 2, "isHidden": true, "moves":["fakeout", "encore", "volttackle", "endeavor"], "pokeball": "cherishball"},
{"generation": 6, "level": 99, "isHidden": false, "moves":["happyhour", "playnice", "holdhands", "flash"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["fly", "surf", "agility", "celebrate"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["bestow", "holdhands", "return", "playnice"], "pokeball": "healball"},
],
tier: "NFE",
},
pikachucosplay: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "thundershock"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachurockstar: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "meteormash"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachubelle: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "iciclecrash"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachupopstar: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "drainingkiss"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachuphd: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "electricterrain"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
pikachulibre: {
eventPokemon: [
{"generation": 6, "level": 20, "moves":["quickattack", "electroball", "thunderwave", "flyingpress"]},
],
eventOnly: true,
gen: 6,
tier: "Illegal",
},
raichu: {
randomBattleMoves: ["nastyplot", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "voltswitch"],
randomDoubleBattleMoves: ["fakeout", "encore", "thunderbolt", "grassknot", "hiddenpowerice", "focusblast", "substitute", "extremespeed", "knockoff", "protect"],
tier: "Bank",
},
raichualola: {
randomBattleMoves: ["nastyplot", "encore", "thunderbolt", "psyshock", "focusblast", "voltswitch"],
tier: "New",
},
sandshrew: {
randomBattleMoves: ["earthquake", "rockslide", "swordsdance", "rapidspin", "xscissor", "stealthrock", "toxic", "knockoff"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "swordsdance", "xscissor", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 12, "gender": "M", "nature": "Docile", "ivs": {"hp": 4, "atk": 23, "def": 8, "spa": 31, "spd": 1, "spe": 25}, "moves":["scratch", "defensecurl", "sandattack", "poisonsting"]},
],
tier: "Bank-LC",
},
sandshrewalola: {
tier: "LC",
},
sandslash: {
randomBattleMoves: ["earthquake", "swordsdance", "rapidspin", "toxic", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "stoneedge", "swordsdance", "xscissor", "knockoff", "protect"],
tier: "Bank",
},
sandslashalola: {
randomBattleMoves: ["substitute", "swordsdance", "iciclecrash", "ironhead", "earthquake", "rapidspin"],
tier: "New",
},
nidoranf: {
randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws"],
randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect"],
tier: "Bank-LC",
},
nidorina: {
randomBattleMoves: ["toxicspikes", "crunch", "poisonjab", "honeclaws", "icebeam", "thunderbolt", "shadowclaw"],
randomDoubleBattleMoves: ["helpinghand", "crunch", "poisonjab", "protect", "icebeam", "thunderbolt", "shadowclaw"],
tier: "Bank-NFE",
},
nidoqueen: {
randomBattleMoves: ["toxicspikes", "stealthrock", "fireblast", "icebeam", "earthpower", "sludgewave"],
randomDoubleBattleMoves: ["protect", "fireblast", "icebeam", "earthpower", "sludgebomb"],
eventPokemon: [
{"generation": 6, "level": 41, "perfectIVs": 2, "isHidden": false, "abilities":["poisonpoint"], "moves":["tailwhip", "doublekick", "poisonsting", "bodyslam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
nidoranm: {
randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"],
tier: "Bank-LC",
},
nidorino: {
randomBattleMoves: ["suckerpunch", "poisonjab", "headsmash", "honeclaws", "shadowclaw"],
randomDoubleBattleMoves: ["suckerpunch", "poisonjab", "shadowclaw", "helpinghand", "protect"],
tier: "Bank-NFE",
},
nidoking: {
randomBattleMoves: ["substitute", "fireblast", "icebeam", "earthpower", "sludgewave", "superpower"],
randomDoubleBattleMoves: ["protect", "fireblast", "thunderbolt", "icebeam", "earthpower", "sludgebomb", "focusblast"],
tier: "Bank",
},
cleffa: {
randomBattleMoves: ["reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "protect"],
tier: "LC",
},
clefairy: {
randomBattleMoves: ["healingwish", "reflect", "thunderwave", "lightscreen", "toxic", "fireblast", "encore", "wish", "protect", "aromatherapy", "stealthrock", "moonblast", "knockoff", "moonlight"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast"],
tier: "New",
},
clefable: {
randomBattleMoves: ["calmmind", "softboiled", "fireblast", "moonblast", "stealthrock", "thunderwave"],
randomDoubleBattleMoves: ["reflect", "thunderwave", "lightscreen", "safeguard", "fireblast", "followme", "protect", "moonblast", "dazzlinggleam", "softboiled"],
tier: "New",
},
vulpix: {
randomBattleMoves: ["flamethrower", "fireblast", "willowisp", "energyball", "substitute", "toxic", "hypnosis", "painsplit"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "energyball", "substitute", "protect"],
eventPokemon: [
{"generation": 3, "level": 18, "gender": "F", "nature": "Quirky", "ivs": {"hp": 15, "atk": 6, "def": 3, "spa": 25, "spd": 13, "spe": 22}, "moves":["tailwhip", "roar", "quickattack", "willowisp"]},
{"generation": 3, "level": 18, "moves":["charm", "heatwave", "ember", "dig"]},
],
tier: "Bank-LC",
},
vulpixalola: {
tier: "LC",
},
ninetales: {
randomBattleMoves: ["fireblast", "willowisp", "solarbeam", "nastyplot", "substitute", "hiddenpowerice"],
randomDoubleBattleMoves: ["heatwave", "fireblast", "willowisp", "solarbeam", "substitute", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Bold", "ivs": {"def": 31}, "isHidden": true, "moves":["heatwave", "solarbeam", "psyshock", "willowisp"], "pokeball": "cherishball"},
],
tier: "Bank",
},
ninetalesalola: {
randomBattleMoves: ["nastyplot", "blizzard", "moonblast", "substitute", "hiddenpowerfire"],
tier: "New",
},
igglybuff: {
randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "protect"],
randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["sing", "charm", "defensecurl", "tickle"]},
],
tier: "LC",
},
jigglypuff: {
randomBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "healbell", "seismictoss", "counter", "stealthrock", "protect", "knockoff", "dazzlinggleam"],
randomDoubleBattleMoves: ["wish", "thunderwave", "reflect", "lightscreen", "seismictoss", "protect", "knockoff", "dazzlinggleam"],
tier: "NFE",
},
wigglytuff: {
randomBattleMoves: ["wish", "protect", "fireblast", "stealthrock", "dazzlinggleam", "hypervoice"],
randomDoubleBattleMoves: ["thunderwave", "reflect", "lightscreen", "protect", "knockoff", "dazzlinggleam", "fireblast", "icebeam", "hypervoice"],
tier: "New",
},
zubat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "whirlwind", "heatwave", "superfang"],
randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"],
tier: "LC",
},
golbat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "superfang", "uturn"],
randomDoubleBattleMoves: ["bravebird", "taunt", "nastyplot", "gigadrain", "sludgebomb", "airslash", "uturn", "protect", "heatwave", "superfang"],
tier: "New",
},
crobat: {
randomBattleMoves: ["bravebird", "roost", "toxic", "taunt", "defog", "uturn", "superfang"],
randomDoubleBattleMoves: ["bravebird", "taunt", "tailwind", "crosspoison", "uturn", "protect", "superfang"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Timid", "moves":["heatwave", "airslash", "sludgebomb", "superfang"], "pokeball": "cherishball"},
],
tier: "New",
},
oddish: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
eventPokemon: [
{"generation": 3, "level": 26, "gender": "M", "nature": "Quirky", "ivs": {"hp": 23, "atk": 24, "def": 20, "spa": 21, "spd": 9, "spe": 16}, "moves":["poisonpowder", "stunspore", "sleeppowder", "acid"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["absorb", "leechseed"]},
],
tier: "Bank-LC",
},
gloom: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "stunspore", "toxic", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "leechseed", "dazzlinggleam", "sunnyday"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["sleeppowder", "acid", "moonlight", "petaldance"]},
],
tier: "Bank-NFE",
},
vileplume: {
randomBattleMoves: ["gigadrain", "sludgebomb", "synthesis", "sleeppowder", "hiddenpowerfire", "aromatherapy"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast", "dazzlinggleam"],
tier: "Bank",
},
bellossom: {
randomBattleMoves: ["gigadrain", "synthesis", "sleeppowder", "hiddenpowerfire", "sunnyday"],
randomDoubleBattleMoves: ["gigadrain", "sludgebomb", "sleeppowder", "stunspore", "protect", "hiddenpowerfire", "moonblast", "dazzlinggleam", "sunnyday", "solarbeam"],
tier: "Bank",
},
paras: {
randomBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "synthesis", "leechseed", "aromatherapy", "knockoff"],
randomDoubleBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 3, "level": 28, "abilities":["effectspore"], "moves":["refresh", "spore", "slash", "falseswipe"]},
],
tier: "LC",
},
parasect: {
randomBattleMoves: ["spore", "substitute", "xscissor", "seedbomb", "leechseed", "knockoff"],
randomDoubleBattleMoves: ["spore", "stunspore", "xscissor", "seedbomb", "ragepowder", "leechseed", "protect", "knockoff", "wideguard"],
tier: "New",
},
venonat: {
randomBattleMoves: ["sleeppowder", "morningsun", "toxicspikes", "sludgebomb", "signalbeam", "stunspore", "psychic"],
randomDoubleBattleMoves: ["sleeppowder", "morningsun", "ragepowder", "sludgebomb", "signalbeam", "stunspore", "psychic", "protect"],
tier: "Bank-LC",
},
venomoth: {
randomBattleMoves: ["sleeppowder", "quiverdance", "batonpass", "bugbuzz", "sludgebomb", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "roost", "ragepowder", "quiverdance", "protect", "bugbuzz", "sludgebomb", "gigadrain", "substitute", "psychic"],
eventPokemon: [
{"generation": 3, "level": 32, "abilities":["shielddust"], "moves":["refresh", "silverwind", "substitute", "psychic"]},
],
tier: "Bank",
},
diglett: {
randomBattleMoves: ["earthquake", "rockslide", "stealthrock", "suckerpunch", "reversal", "substitute", "shadowclaw"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "shadowclaw"],
tier: "Bank-LC",
},
diglettalola: {
tier: "LC",
},
dugtrio: {
randomBattleMoves: ["earthquake", "stoneedge", "stealthrock", "suckerpunch", "reversal", "substitute"],
randomDoubleBattleMoves: ["earthquake", "rockslide", "protect", "suckerpunch", "stoneedge"],
eventPokemon: [
{"generation": 3, "level": 40, "moves":["charm", "earthquake", "sandstorm", "triattack"]},
],
tier: "Bank",
},
dugtrioalola: {
randomBattleMoves: ["earthquake", "ironhead", "substitute", "reversal"],
tier: "New",
},
meowth: {
randomBattleMoves: ["fakeout", "uturn", "thief", "taunt", "return", "hypnosis"],
randomDoubleBattleMoves: ["fakeout", "uturn", "nightslash", "taunt", "return", "hypnosis", "feint", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["scratch", "growl", "petaldance"]},
{"generation": 3, "level": 5, "moves":["scratch", "growl"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "bite"]},
{"generation": 3, "level": 22, "moves":["sing", "slash", "payday", "bite"]},
{"generation": 4, "level": 21, "gender": "F", "nature": "Jolly", "abilities":["pickup"], "moves":["bite", "fakeout", "furyswipes", "screech"], "pokeball": "cherishball"},
{"generation": 4, "level": 10, "gender": "M", "nature": "Jolly", "abilities":["pickup"], "moves":["fakeout", "payday", "assist", "scratch"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pickup"], "moves":["furyswipes", "sing", "nastyplot", "snatch"], "pokeball": "cherishball"},
{"generation": 6, "level": 20, "isHidden": false, "abilities":["pickup"], "moves":["happyhour", "screech", "bite", "fakeout"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
meowthalola: {
tier: "LC",
},
persian: {
randomBattleMoves: ["fakeout", "uturn", "taunt", "return", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "uturn", "knockoff", "taunt", "return", "hypnosis", "feint", "protect"],
tier: "Bank",
},
persianalola: {
randomBattleMoves: ["nastyplot", "darkpulse", "powergem", "hypnosis", "hiddenpowerfighting"],
tier: "New",
},
psyduck: {
randomBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam"],
randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "crosschop", "encore", "psychic", "signalbeam", "surf", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 27, "gender": "M", "nature": "Lax", "ivs": {"hp": 31, "atk": 16, "def": 12, "spa": 29, "spd": 31, "spe": 14}, "abilities":["damp"], "moves":["tailwhip", "confusion", "disable", "screech"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["watersport", "scratch", "tailwhip", "mudsport"]},
],
tier: "LC",
},
golduck: {
randomBattleMoves: ["hydropump", "scald", "icebeam", "signalbeam", "encore", "calmmind", "substitute"],
randomDoubleBattleMoves: ["hydropump", "scald", "icebeam", "hiddenpowergrass", "focusblast", "encore", "psychic", "surf", "icywind", "protect"],
eventPokemon: [
{"generation": 3, "level": 33, "moves":["charm", "waterfall", "psychup", "brickbreak"]},
],
tier: "New",
},
mankey: {
randomBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab"],
randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect"],
tier: "LC",
},
primeape: {
randomBattleMoves: ["closecombat", "uturn", "icepunch", "stoneedge", "encore", "earthquake", "gunkshot"],
randomDoubleBattleMoves: ["closecombat", "uturn", "icepunch", "rockslide", "punishment", "earthquake", "poisonjab", "protect", "taunt", "stoneedge"],
eventPokemon: [
{"generation": 3, "level": 34, "abilities":["vitalspirit"], "moves":["helpinghand", "crosschop", "focusenergy", "reversal"]},
],
tier: "New",
},
growlithe: {
randomBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "morningsun", "willowisp", "toxic", "flamethrower"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "hiddenpowergrass", "closecombat", "willowisp", "snarl", "heatwave", "helpinghand", "protect"],
eventPokemon: [
{"generation": 3, "level": 32, "gender": "F", "nature": "Quiet", "ivs": {"hp": 11, "atk": 24, "def": 28, "spa": 1, "spd": 20, "spe": 2}, "abilities":["intimidate"], "moves":["leer", "odorsleuth", "takedown", "flamewheel"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["bite", "roar", "ember"]},
{"generation": 3, "level": 28, "moves":["charm", "flamethrower", "bite", "takedown"]},
],
tier: "LC",
},
arcanine: {
randomBattleMoves: ["flareblitz", "wildcharge", "extremespeed", "closecombat", "morningsun", "willowisp", "toxic", "crunch", "roar"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "closecombat", "willowisp", "snarl", "protect", "extremespeed"],
eventPokemon: [
{"generation": 4, "level": 50, "abilities":["intimidate"], "moves":["flareblitz", "thunderfang", "crunch", "extremespeed"], "pokeball": "cherishball"},
],
tier: "New",
},
poliwag: {
randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "sweetkiss"]},
],
tier: "LC",
},
poliwhirl: {
randomBattleMoves: ["hydropump", "icebeam", "encore", "bellydrum", "hypnosis", "waterfall", "return", "earthquake"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "encore", "icywind", "hypnosis", "waterfall", "return", "protect", "helpinghand", "earthquake"],
tier: "NFE",
},
poliwrath: {
randomBattleMoves: ["hydropump", "focusblast", "icebeam", "rest", "sleeptalk", "scald", "circlethrow", "raindance"],
randomDoubleBattleMoves: ["bellydrum", "encore", "waterfall", "protect", "icepunch", "earthquake", "brickbreak", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 42, "moves":["helpinghand", "hydropump", "raindance", "brickbreak"]},
],
tier: "New",
},
politoed: {
randomBattleMoves: ["scald", "toxic", "encore", "perishsong", "protect", "hypnosis", "rest"],
randomDoubleBattleMoves: ["scald", "hypnosis", "icywind", "encore", "helpinghand", "protect", "icebeam", "focusblast", "hydropump", "hiddenpowergrass"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Calm", "ivs": {"hp": 31, "atk": 13, "def": 31, "spa": 5, "spd": 31, "spe": 5}, "isHidden": true, "moves":["scald", "icebeam", "perishsong", "protect"], "pokeball": "cherishball"},
],
tier: "New",
},
abra: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
tier: "LC",
},
kadabra: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "hiddenpowerfighting", "shadowball", "encore", "substitute"],
tier: "New",
},
alakazam: {
randomBattleMoves: ["psyshock", "psychic", "focusblast", "shadowball", "hiddenpowerice", "hiddenpowerfire"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["futuresight", "calmmind", "psychic", "trick"]},
],
tier: "New",
},
alakazammega: {
randomBattleMoves: ["calmmind", "psyshock", "focusblast", "shadowball", "encore", "substitute"],
randomDoubleBattleMoves: ["protect", "psychic", "psyshock", "focusblast", "shadowball", "encore", "substitute", "dazzlinggleam"],
requiredItem: "Alakazite",
tier: "New",
},
machop: {
randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "knockoff"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"],
tier: "LC",
},
machoke: {
randomBattleMoves: ["dynamicpunch", "bulkup", "icepunch", "rockslide", "bulletpunch", "poweruppunch", "knockoff"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "rockslide", "bulletpunch", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["lowsweep", "foresight", "seismictoss", "revenge"], "pokeball": "cherishball"},
],
tier: "New",
},
machamp: {
randomBattleMoves: ["dynamicpunch", "icepunch", "stoneedge", "bulletpunch", "knockoff", "substitute"],
randomDoubleBattleMoves: ["dynamicpunch", "protect", "icepunch", "stoneedge", "rockslide", "bulletpunch", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 3, "level": 38, "gender": "M", "nature": "Quiet", "ivs": {"hp": 9, "atk": 23, "def": 25, "spa": 20, "spd": 15, "spe": 10}, "abilities":["guts"], "moves":["seismictoss", "foresight", "revenge", "vitalthrow"]},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 31, "spd": 31, "spe": 31}, "isHidden": false, "abilities":["noguard"], "moves":["dynamicpunch", "stoneedge", "wideguard", "knockoff"], "pokeball": "cherishball"},
],
tier: "New",
},
bellsprout: {
randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["vinewhip", "teeterdance"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["vinewhip", "growth"]},
],
tier: "LC",
},
weepinbell: {
randomBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "seedbomb", "protect", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 32, "moves":["morningsun", "magicalleaf", "sludgebomb", "sweetscent"]},
],
tier: "NFE",
},
victreebel: {
randomBattleMoves: ["sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "knockoff", "swordsdance"],
randomDoubleBattleMoves: ["swordsdance", "sleeppowder", "sunnyday", "growth", "solarbeam", "gigadrain", "sludgebomb", "weatherball", "suckerpunch", "powerwhip", "protect", "knockoff"],
tier: "New",
},
tentacool: {
randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "toxic", "dazzlinggleam"],
randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"],
tier: "LC",
},
tentacruel: {
randomBattleMoves: ["toxicspikes", "rapidspin", "scald", "sludgebomb", "acidspray", "knockoff"],
randomDoubleBattleMoves: ["muddywater", "scald", "sludgebomb", "acidspray", "icebeam", "knockoff", "gigadrain", "protect", "dazzlinggleam"],
tier: "New",
},
geodude: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank-LC",
},
geodudealola: {
tier: "LC",
},
graveler: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank-NFE",
},
graveleralola: {
tier: "NFE",
},
golem: {
randomBattleMoves: ["stealthrock", "earthquake", "explosion", "suckerpunch", "toxic", "rockblast"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "suckerpunch", "hammerarm", "firepunch", "protect"],
tier: "Bank",
},
golemalola: {
randomBattleMoves: ["stealthrock", "stoneedge", "thunderpunch", "earthquake", "suckerpunch", "toxic"],
tier: "New",
},
ponyta: {
randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "hypnosis", "flamecharge"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge"],
tier: "Bank-LC",
},
rapidash: {
randomBattleMoves: ["flareblitz", "wildcharge", "morningsun", "drillrun", "willowisp", "sunnyday", "solarbeam"],
randomDoubleBattleMoves: ["flareblitz", "wildcharge", "protect", "hypnosis", "flamecharge", "megahorn", "drillrun", "willowisp"],
eventPokemon: [
{"generation": 3, "level": 40, "moves":["batonpass", "solarbeam", "sunnyday", "flamethrower"]},
],
tier: "Bank",
},
slowpoke: {
randomBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "toxic", "slackoff", "trickroom"],
randomDoubleBattleMoves: ["scald", "aquatail", "zenheadbutt", "thunderwave", "slackoff", "trickroom", "protect"],
eventPokemon: [
{"generation": 3, "level": 31, "gender": "F", "nature": "Naive", "ivs": {"hp": 17, "atk": 11, "def": 19, "spa": 20, "spd": 5, "spe": 10}, "abilities":["oblivious"], "moves":["watergun", "confusion", "disable", "headbutt"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["curse", "yawn", "tackle", "growl"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["confusion", "disable", "headbutt", "waterpulse"], "pokeball": "cherishball"},
],
tier: "LC",
},
slowbro: {
randomBattleMoves: ["scald", "toxic", "thunderwave", "psyshock", "foulplay", "fireblast", "icebeam", "slackoff"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
eventPokemon: [
{"generation": 6, "level": 100, "nature": "Quiet", "isHidden": false, "abilities":["oblivious"], "moves":["scald", "trickroom", "slackoff", "irontail"], "pokeball": "cherishball"},
],
tier: "New",
},
slowbromega: {
randomBattleMoves: ["calmmind", "scald", "psyshock", "slackoff", "fireblast", "psychic", "icebeam", "grassknot"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
requiredItem: "Slowbronite",
tier: "(OU)",
},
slowking: {
randomBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "toxic", "slackoff", "trickroom", "nastyplot", "dragontail", "psyshock"],
randomDoubleBattleMoves: ["scald", "fireblast", "icebeam", "psychic", "grassknot", "thunderwave", "slackoff", "trickroom", "protect", "psyshock"],
tier: "New",
},
magnemite: {
randomBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch"],
randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge"],
tier: "LC",
},
magneton: {
randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "chargebeam", "hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt", "thunderwave", "magnetrise", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["refresh", "doubleedge", "raindance", "thunder"]},
],
tier: "New",
},
magnezone: {
randomBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "chargebeam", "hiddenpowerfire"],
randomDoubleBattleMoves: ["thunderbolt", "substitute", "flashcannon", "hiddenpowerice", "voltswitch", "protect", "electroweb", "discharge", "hiddenpowerfire"],
tier: "New",
},
farfetchd: {
randomBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "roost", "nightslash"],
randomDoubleBattleMoves: ["bravebird", "swordsdance", "return", "leafblade", "protect", "nightslash"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["yawn", "wish"]},
{"generation": 3, "level": 36, "moves":["batonpass", "slash", "swordsdance", "aerialace"]},
],
tier: "Bank",
},
doduo: {
randomBattleMoves: ["bravebird", "return", "doubleedge", "roost", "quickattack", "pursuit"],
randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "protect"],
tier: "Bank-LC",
},
dodrio: {
randomBattleMoves: ["bravebird", "return", "doubleedge", "roost", "quickattack", "knockoff"],
randomDoubleBattleMoves: ["bravebird", "return", "doubleedge", "quickattack", "protect"],
eventPokemon: [
{"generation": 3, "level": 34, "moves":["batonpass", "drillpeck", "agility", "triattack"]},
],
tier: "Bank",
},
seel: {
randomBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "drillrun"],
randomDoubleBattleMoves: ["surf", "icebeam", "aquajet", "protect", "rest", "toxic", "fakeout", "drillrun", "icywind"],
eventPokemon: [
{"generation": 3, "level": 23, "abilities":["thickfat"], "moves":["helpinghand", "surf", "safeguard", "icebeam"]},
],
tier: "Bank-LC",
},
dewgong: {
randomBattleMoves: ["surf", "icebeam", "perishsong", "encore", "toxic", "protect"],
randomDoubleBattleMoves: ["surf", "icebeam", "protect", "perishsong", "fakeout", "encore", "toxic"],
tier: "Bank",
},
grimer: {
randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "painsplit", "icepunch", "firepunch", "memento"],
randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch"],
eventPokemon: [
{"generation": 3, "level": 23, "moves":["helpinghand", "sludgebomb", "shadowpunch", "minimize"]},
],
tier: "Bank-LC",
},
grimeralola: {
tier: "LC",
},
muk: {
randomBattleMoves: ["curse", "gunkshot", "poisonjab", "shadowsneak", "icepunch", "firepunch", "memento"],
randomDoubleBattleMoves: ["gunkshot", "poisonjab", "shadowsneak", "protect", "icepunch", "firepunch", "brickbreak"],
tier: "Bank",
},
mukalola: {
randomBattleMoves: ["curse", "gunkshot", "knockoff", "poisonjab", "shadowsneak", "stoneedge"],
tier: "New",
},
shellder: {
randomBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "rapidspin"],
randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"],
eventPokemon: [
{"generation": 3, "level": 24, "gender": "F", "nature": "Brave", "ivs": {"hp": 5, "atk": 19, "def": 18, "spa": 5, "spd": 11, "spe": 13}, "abilities":["shellarmor"], "moves":["withdraw", "iciclespear", "supersonic", "aurorabeam"]},
{"generation": 3, "level": 10, "gender": "M", "abilities":["shellarmor"], "moves":["tackle", "withdraw", "iciclespear"]},
{"generation": 3, "level": 29, "abilities":["shellarmor"], "moves":["refresh", "takedown", "surf", "aurorabeam"]},
],
tier: "LC",
},
cloyster: {
randomBattleMoves: ["shellsmash", "hydropump", "rockblast", "iciclespear", "iceshard", "rapidspin", "spikes", "toxicspikes"],
randomDoubleBattleMoves: ["shellsmash", "hydropump", "razorshell", "rockblast", "iciclespear", "protect"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "M", "nature": "Naughty", "isHidden": false, "abilities":["skilllink"], "moves":["iciclespear", "rockblast", "hiddenpower", "razorshell"]},
],
tier: "New",
},
gastly: {
randomBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "painsplit", "hypnosis", "gigadrain", "trick", "dazzlinggleam"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"],
tier: "LC",
},
haunter: {
randomBattleMoves: ["shadowball", "sludgebomb", "dazzlinggleam", "substitute", "destinybond"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "hiddenpowerfighting", "thunderbolt", "substitute", "disable", "taunt", "hypnosis", "gigadrain", "trick", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 5, "level": 30, "moves":["confuseray", "suckerpunch", "shadowpunch", "payback"], "pokeball": "cherishball"},
],
tier: "New",
},
gengar: {
randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "substitute", "disable", "painsplit", "willowisp"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 3, "level": 23, "gender": "F", "nature": "Hardy", "ivs": {"hp": 19, "atk": 14, "def": 0, "spa": 14, "spd": 17, "spe": 27}, "moves":["spite", "curse", "nightshade", "confuseray"]},
{"generation": 6, "level": 25, "nature": "Timid", "moves":["psychic", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "moves":["nightshade", "confuseray", "suckerpunch", "shadowpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["shadowball", "sludgebomb", "willowisp", "destinybond"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "shiny": true, "moves":["shadowball", "sludgewave", "confuseray", "astonish"], "pokeball": "duskball"},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["meanlook", "hypnosis", "psychic", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "New",
},
gengarmega: {
randomBattleMoves: ["shadowball", "sludgewave", "focusblast", "taunt", "destinybond", "disable", "perishsong", "protect"],
randomDoubleBattleMoves: ["shadowball", "sludgebomb", "focusblast", "substitute", "disable", "taunt", "hypnosis", "willowisp", "dazzlinggleam", "protect"],
requiredItem: "Gengarite",
tier: "Uber",
},
onix: {
randomBattleMoves: ["stealthrock", "earthquake", "stoneedge", "dragontail", "curse"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "stoneedge", "rockslide", "protect", "explosion"],
tier: "Bank-LC",
},
steelix: {
randomBattleMoves: ["stealthrock", "earthquake", "ironhead", "roar", "toxic", "rockslide"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "ironhead", "rockslide", "protect", "explosion"],
tier: "Bank",
},
steelixmega: {
randomBattleMoves: ["stealthrock", "earthquake", "heavyslam", "roar", "toxic", "dragontail"],
randomDoubleBattleMoves: ["stealthrock", "earthquake", "heavyslam", "rockslide", "protect", "explosion"],
requiredItem: "Steelixite",
tier: "Bank",
},
drowzee: {
randomBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "toxic", "shadowball", "trickroom", "calmmind", "dazzlinggleam"],
randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "shadowball", "trickroom", "calmmind", "dazzlinggleam", "toxic"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["insomnia"], "moves":["bellydrum", "wish"]},
],
tier: "LC",
},
hypno: {
randomBattleMoves: ["psychic", "seismictoss", "foulplay", "wish", "protect", "thunderwave", "toxic"],
randomDoubleBattleMoves: ["psychic", "seismictoss", "thunderwave", "wish", "protect", "hypnosis", "trickroom", "dazzlinggleam", "foulplay"],
eventPokemon: [
{"generation": 3, "level": 34, "abilities":["insomnia"], "moves":["batonpass", "psychic", "meditate", "shadowball"]},
],
tier: "New",
},
krabby: {
randomBattleMoves: ["crabhammer", "swordsdance", "agility", "rockslide", "substitute", "xscissor", "superpower", "knockoff"],
randomDoubleBattleMoves: ["crabhammer", "swordsdance", "rockslide", "substitute", "xscissor", "superpower", "knockoff", "protect"],
tier: "Bank-LC",
},
kingler: {
randomBattleMoves: ["crabhammer", "xscissor", "rockslide", "swordsdance", "agility", "superpower", "knockoff"],
randomDoubleBattleMoves: ["crabhammer", "xscissor", "rockslide", "substitute", "superpower", "knockoff", "protect", "wideguard"],
tier: "Bank",
},
voltorb: {
randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 19, "moves":["refresh", "mirrorcoat", "spark", "swift"]},
],
tier: "Bank-LC",
},
electrode: {
randomBattleMoves: ["voltswitch", "thunderbolt", "taunt", "foulplay", "hiddenpowergrass", "signalbeam"],
randomDoubleBattleMoves: ["voltswitch", "discharge", "taunt", "foulplay", "hiddenpowerice", "protect", "thunderwave"],
tier: "Bank",
},
exeggcute: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "synthesis"],
randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "stunspore", "hiddenpowerfire", "protect", "trickroom"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]},
],
tier: "LC",
},
exeggutor: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "leechseed", "gigadrain", "psychic", "sleeppowder", "hiddenpowerfire", "protect", "trickroom", "psyshock"],
eventPokemon: [
{"generation": 3, "level": 46, "moves":["refresh", "psychic", "hypnosis", "ancientpower"]},
],
tier: "Bank",
},
exeggutoralola: {
randomBattleMoves: ["dracometeor", "leafstorm", "flamethrower", "psyshock"],
tier: "New",
},
cubone: {
randomBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake"],
randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect"],
tier: "LC",
},
marowak: {
randomBattleMoves: ["bonemerang", "earthquake", "knockoff", "doubleedge", "stoneedge", "stealthrock", "substitute"],
randomDoubleBattleMoves: ["substitute", "bonemerang", "doubleedge", "rockslide", "firepunch", "earthquake", "protect", "swordsdance"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["sing", "earthquake", "swordsdance", "rockslide"]},
],
tier: "Bank",
},
marowakalola: {
randomBattleMoves: ["flamecharge", "shadowbone", "bonemerang", "doubleedge", "stoneedge"],
tier: "New",
},
tyrogue: {
randomBattleMoves: ["highjumpkick", "rapidspin", "fakeout", "bulletpunch", "machpunch", "toxic", "counter"],
randomDoubleBattleMoves: ["highjumpkick", "fakeout", "bulletpunch", "machpunch", "helpinghand", "protect"],
tier: "Bank-LC",
},
hitmonlee: {
randomBattleMoves: ["highjumpkick", "knockoff", "stoneedge", "rapidspin", "machpunch", "poisonjab", "fakeout"],
randomDoubleBattleMoves: ["knockoff", "rockslide", "machpunch", "fakeout", "highjumpkick", "earthquake", "blazekick", "wideguard", "protect"],
eventPokemon: [
{"generation": 3, "level": 38, "abilities":["limber"], "moves":["refresh", "highjumpkick", "mindreader", "megakick"]},
],
tier: "Bank",
},
hitmonchan: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "firepunch", "machpunch", "rapidspin"],
randomDoubleBattleMoves: ["fakeout", "drainpunch", "icepunch", "firepunch", "machpunch", "earthquake", "rockslide", "protect", "thunderpunch"],
eventPokemon: [
{"generation": 3, "level": 38, "abilities":["keeneye"], "moves":["helpinghand", "skyuppercut", "mindreader", "megapunch"]},
],
tier: "Bank",
},
hitmontop: {
randomBattleMoves: ["suckerpunch", "machpunch", "rapidspin", "closecombat", "toxic"],
randomDoubleBattleMoves: ["fakeout", "feint", "suckerpunch", "closecombat", "helpinghand", "machpunch", "wideguard"],
eventPokemon: [
{"generation": 5, "level": 55, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["intimidate"], "moves":["fakeout", "closecombat", "suckerpunch", "helpinghand"]},
],
tier: "Bank",
},
lickitung: {
randomBattleMoves: ["wish", "protect", "dragontail", "curse", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake", "toxic", "healbell"],
randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "return", "powerwhip", "swordsdance", "earthquake", "toxic", "healbell"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["healbell", "wish"]},
{"generation": 3, "level": 38, "moves":["helpinghand", "doubleedge", "defensecurl", "rollout"]},
],
tier: "Bank-LC",
},
lickilicky: {
randomBattleMoves: ["wish", "protect", "bodyslam", "knockoff", "dragontail", "healbell", "swordsdance", "explosion", "earthquake", "powerwhip"],
randomDoubleBattleMoves: ["wish", "protect", "dragontail", "knockoff", "bodyslam", "rockslide", "powerwhip", "earthquake", "toxic", "healbell", "explosion"],
tier: "Bank",
},
koffing: {
randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "toxic", "clearsmog", "rest", "sleeptalk", "thunderbolt"],
randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "rest", "sleeptalk", "thunderbolt"],
tier: "Bank-LC",
},
weezing: {
randomBattleMoves: ["painsplit", "sludgebomb", "willowisp", "fireblast", "protect", "toxicspikes"],
randomDoubleBattleMoves: ["protect", "sludgebomb", "willowisp", "fireblast", "toxic", "painsplit", "thunderbolt", "explosion"],
tier: "Bank",
},
rhyhorn: {
randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"],
tier: "LC",
},
rhydon: {
randomBattleMoves: ["stealthrock", "earthquake", "rockblast", "roar", "swordsdance", "stoneedge", "megahorn", "rockpolish"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 46, "moves":["helpinghand", "megahorn", "scaryface", "earthquake"]},
],
tier: "New",
},
rhyperior: {
randomBattleMoves: ["stoneedge", "earthquake", "aquatail", "megahorn", "stealthrock", "rockblast", "rockpolish", "dragontail"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "hammerarm", "megahorn", "stealthrock", "rockslide", "protect"],
tier: "New",
},
happiny: {
randomBattleMoves: ["aromatherapy", "toxic", "thunderwave", "counter", "endeavor", "lightscreen", "fireblast"],
randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "swagger", "lightscreen", "fireblast", "protect"],
tier: "LC",
},
chansey: {
randomBattleMoves: ["softboiled", "healbell", "stealthrock", "thunderwave", "toxic", "seismictoss", "wish", "protect", "counter"],
randomDoubleBattleMoves: ["aromatherapy", "toxic", "thunderwave", "helpinghand", "softboiled", "lightscreen", "seismictoss", "protect", "wish"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["sweetscent", "wish"]},
{"generation": 3, "level": 10, "moves":["pound", "growl", "tailwhip", "refresh"]},
{"generation": 3, "level": 39, "moves":["sweetkiss", "thunderbolt", "softboiled", "skillswap"]},
],
tier: "New",
},
blissey: {
randomBattleMoves: ["toxic", "flamethrower", "seismictoss", "softboiled", "wish", "healbell", "protect", "thunderwave", "stealthrock"],
randomDoubleBattleMoves: ["wish", "softboiled", "protect", "toxic", "aromatherapy", "seismictoss", "helpinghand", "thunderwave", "flamethrower", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 10, "isHidden": true, "moves":["pound", "growl", "tailwhip", "refresh"]},
],
tier: "New",
},
tangela: {
randomBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerfire", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "sludgebomb", "synthesis"],
randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerrock", "hiddenpowerice", "leechseed", "knockoff", "leafstorm", "stunspore", "protect", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 30, "abilities":["chlorophyll"], "moves":["morningsun", "solarbeam", "sunnyday", "ingrain"]},
],
tier: "Bank",
},
tangrowth: {
randomBattleMoves: ["gigadrain", "leafstorm", "knockoff", "earthquake", "hiddenpowerfire", "rockslide", "sleeppowder", "leechseed", "synthesis"],
randomDoubleBattleMoves: ["gigadrain", "sleeppowder", "hiddenpowerice", "leechseed", "knockoff", "ragepowder", "focusblast", "protect", "powerwhip", "earthquake"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Brave", "moves":["sunnyday", "morningsun", "ancientpower", "naturalgift"], "pokeball": "cherishball"},
],
tier: "Bank",
},
kangaskhan: {
randomBattleMoves: ["return", "suckerpunch", "earthquake", "drainpunch", "crunch", "fakeout"],
randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "drainpunch", "crunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["earlybird"], "moves":["yawn", "wish"]},
{"generation": 3, "level": 10, "abilities":["earlybird"], "moves":["cometpunch", "leer", "bite"]},
{"generation": 3, "level": 35, "abilities":["earlybird"], "moves":["sing", "earthquake", "tailwhip", "dizzypunch"]},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["scrappy"], "moves":["fakeout", "return", "earthquake", "suckerpunch"], "pokeball": "cherishball"},
],
tier: "New",
},
kangaskhanmega: {
randomBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "poweruppunch", "crunch"],
randomDoubleBattleMoves: ["fakeout", "return", "suckerpunch", "earthquake", "doubleedge", "poweruppunch", "drainpunch", "crunch", "protect"],
requiredItem: "Kangaskhanite",
tier: "Uber",
},
horsea: {
randomBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "raindance", "muddywater", "protect"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bubble"]},
],
tier: "Bank-LC",
},
seadra: {
randomBattleMoves: ["hydropump", "icebeam", "agility", "substitute", "hiddenpowergrass"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "substitute", "hiddenpowergrass", "agility", "muddywater", "protect"],
eventPokemon: [
{"generation": 3, "level": 45, "abilities":["poisonpoint"], "moves":["leer", "watergun", "twister", "agility"]},
],
tier: "Bank-NFE",
},
kingdra: {
randomBattleMoves: ["dragondance", "waterfall", "outrage", "ironhead", "substitute", "raindance", "hydropump", "dracometeor"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "focusenergy", "dracometeor", "dragonpulse", "muddywater", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "abilities":["swiftswim"], "moves":["leer", "watergun", "twister", "agility"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Timid", "ivs": {"hp": 31, "atk": 17, "def": 8, "spa": 31, "spd": 11, "spe": 31}, "isHidden": false, "abilities":["swiftswim"], "moves":["dracometeor", "muddywater", "dragonpulse", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
goldeen: {
randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam"],
randomDoubleBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "icebeam", "protect"],
tier: "LC",
},
seaking: {
randomBattleMoves: ["waterfall", "megahorn", "knockoff", "drillrun", "scald", "icebeam"],
randomDoubleBattleMoves: ["waterfall", "surf", "megahorn", "knockoff", "drillrun", "icebeam", "icywind", "protect"],
tier: "New",
},
staryu: {
randomBattleMoves: ["scald", "thunderbolt", "icebeam", "rapidspin", "recover", "dazzlinggleam", "hydropump"],
randomDoubleBattleMoves: ["scald", "thunderbolt", "icebeam", "protect", "recover", "dazzlinggleam", "hydropump"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["minimize", "lightscreen", "cosmicpower", "hydropump"]},
{"generation": 3, "level": 18, "nature": "Timid", "ivs": {"hp": 10, "atk": 3, "def": 22, "spa": 24, "spd": 3, "spe": 18}, "abilities":["illuminate"], "moves":["harden", "watergun", "rapidspin", "recover"]},
],
tier: "LC",
},
starmie: {
randomBattleMoves: ["thunderbolt", "icebeam", "rapidspin", "recover", "psyshock", "scald", "hydropump"],
randomDoubleBattleMoves: ["surf", "thunderbolt", "icebeam", "protect", "recover", "psychic", "psyshock", "scald", "hydropump"],
eventPokemon: [
{"generation": 3, "level": 41, "moves":["refresh", "waterfall", "icebeam", "recover"]},
],
tier: "New",
},
mimejr: {
randomBattleMoves: ["batonpass", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore"],
randomDoubleBattleMoves: ["fakeout", "psychic", "thunderwave", "hiddenpowerfighting", "healingwish", "nastyplot", "thunderbolt", "encore", "icywind", "protect"],
tier: "Bank-LC",
},
mrmime: {
randomBattleMoves: ["nastyplot", "psychic", "psyshock", "dazzlinggleam", "shadowball", "batonpass", "focusblast", "healingwish", "encore"],
randomDoubleBattleMoves: ["fakeout", "thunderwave", "hiddenpowerfighting", "teeterdance", "thunderbolt", "encore", "icywind", "protect", "wideguard", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 42, "abilities":["soundproof"], "moves":["followme", "psychic", "encore", "thunderpunch"]},
],
tier: "Bank",
},
scyther: {
randomBattleMoves: ["swordsdance", "roost", "bugbite", "quickattack", "brickbreak", "aerialace", "batonpass", "uturn", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "protect", "bugbite", "quickattack", "brickbreak", "aerialace", "feint", "uturn", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["swarm"], "moves":["quickattack", "leer", "focusenergy"]},
{"generation": 3, "level": 40, "abilities":["swarm"], "moves":["morningsun", "razorwind", "silverwind", "slash"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["agility", "wingattack", "furycutter", "slash"], "pokeball": "cherishball"},
],
tier: "New",
},
scizor: {
randomBattleMoves: ["swordsdance", "bulletpunch", "bugbite", "superpower", "uturn", "pursuit", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 50, "gender": "M", "abilities":["swarm"], "moves":["furycutter", "metalclaw", "swordsdance", "slash"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "abilities":["swarm"], "moves":["xscissor", "swordsdance", "irondefense", "agility"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "bugbite", "roost", "swordsdance"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "focusenergy", "pursuit", "steelwing"]},
{"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["xscissor", "nightslash", "doublehit", "ironhead"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "nature": "Adamant", "isHidden": false, "abilities":["technician"], "moves":["aerialace", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "isHidden": false, "moves":["metalclaw", "falseswipe", "agility", "furycutter"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["technician"], "moves":["bulletpunch", "swordsdance", "roost", "uturn"], "pokeball": "cherishball"},
],
tier: "New",
},
scizormega: {
randomBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "batonpass", "pursuit", "defog", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "roost", "bulletpunch", "bugbite", "superpower", "uturn", "protect", "feint", "knockoff"],
requiredItem: "Scizorite",
tier: "New",
},
smoochum: {
randomBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot"],
randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "trick", "shadowball", "grassknot", "fakeout", "protect"],
tier: "Bank-LC",
},
jynx: {
randomBattleMoves: ["icebeam", "psychic", "focusblast", "trick", "nastyplot", "lovelykiss", "substitute", "psyshock"],
randomDoubleBattleMoves: ["icebeam", "psychic", "hiddenpowerfighting", "shadowball", "protect", "lovelykiss", "substitute", "psyshock"],
tier: "Bank",
},
elekid: {
randomBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass"],
randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect"],
eventPokemon: [
{"generation": 3, "level": 20, "moves":["icepunch", "firepunch", "thunderpunch", "crosschop"]},
],
tier: "LC",
},
electabuzz: {
randomBattleMoves: ["thunderbolt", "voltswitch", "substitute", "hiddenpowerice", "hiddenpowergrass", "focusblast", "psychic"],
randomDoubleBattleMoves: ["thunderbolt", "crosschop", "voltswitch", "substitute", "icepunch", "psychic", "hiddenpowergrass", "protect", "focusblast", "discharge"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["quickattack", "leer", "thunderpunch"]},
{"generation": 3, "level": 43, "moves":["followme", "crosschop", "thunderwave", "thunderbolt"]},
{"generation": 4, "level": 30, "gender": "M", "nature": "Naughty", "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["lowkick", "swift", "shockwave", "lightscreen"], "pokeball": "cherishball"},
{"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["lowkick", "shockwave", "lightscreen", "thunderpunch"], "pokeball": "cherishball"},
],
tier: "NFE",
},
electivire: {
randomBattleMoves: ["wildcharge", "crosschop", "icepunch", "flamethrower", "earthquake", "voltswitch"],
randomDoubleBattleMoves: ["wildcharge", "crosschop", "icepunch", "substitute", "flamethrower", "earthquake", "protect", "followme"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["thunderpunch", "icepunch", "crosschop", "earthquake"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Serious", "moves":["lightscreen", "thunderpunch", "discharge", "thunderbolt"], "pokeball": "cherishball"},
],
tier: "New",
},
magby: {
randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "overheat"],
tier: "LC",
},
magmar: {
randomBattleMoves: ["flareblitz", "substitute", "fireblast", "hiddenpowergrass", "hiddenpowerice", "crosschop", "thunderpunch", "focusblast"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["leer", "smog", "firepunch", "leer"]},
{"generation": 3, "level": 36, "moves":["followme", "fireblast", "crosschop", "thunderpunch"]},
{"generation": 4, "level": 30, "gender": "M", "nature": "Quiet", "moves":["smokescreen", "firespin", "confuseray", "firepunch"]},
{"generation": 5, "level": 30, "isHidden": false, "moves":["smokescreen", "feintattack", "firespin", "confuseray"], "pokeball": "cherishball"},
{"generation": 6, "level": 30, "gender": "M", "isHidden": true, "moves":["smokescreen", "firespin", "confuseray", "firepunch"], "pokeball": "cherishball"},
],
tier: "NFE",
},
magmortar: {
randomBattleMoves: ["fireblast", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "earthquake", "substitute"],
randomDoubleBattleMoves: ["fireblast", "taunt", "focusblast", "hiddenpowergrass", "hiddenpowerice", "thunderbolt", "heatwave", "willowisp", "protect", "followme"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "F", "nature": "Modest", "moves":["flamethrower", "psychic", "hyperbeam", "solarbeam"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Hardy", "moves":["confuseray", "firepunch", "lavaplume", "flamethrower"], "pokeball": "cherishball"},
],
tier: "New",
},
pinsir: {
randomBattleMoves: ["earthquake", "xscissor", "closecombat", "stoneedge", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 35, "abilities":["hypercutter"], "moves":["helpinghand", "guillotine", "falseswipe", "submission"]},
{"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["xscissor", "earthquake", "stoneedge", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Jolly", "isHidden": true, "moves":["earthquake", "swordsdance", "feint", "quickattack"], "pokeball": "cherishball"},
],
tier: "New",
},
pinsirmega: {
randomBattleMoves: ["swordsdance", "earthquake", "closecombat", "quickattack", "return"],
randomDoubleBattleMoves: ["feint", "protect", "swordsdance", "xscissor", "earthquake", "closecombat", "substitute", "quickattack", "return", "rockslide"],
requiredItem: "Pinsirite",
tier: "New",
},
tauros: {
randomBattleMoves: ["rockclimb", "earthquake", "zenheadbutt", "rockslide", "doubleedge"],
randomDoubleBattleMoves: ["return", "earthquake", "zenheadbutt", "rockslide", "stoneedge", "protect", "doubleedge"],
eventPokemon: [
{"generation": 3, "level": 25, "nature": "Docile", "ivs": {"hp": 14, "atk": 19, "def": 12, "spa": 17, "spd": 5, "spe": 26}, "abilities":["intimidate"], "moves":["rage", "hornattack", "scaryface", "pursuit"], "pokeball": "safariball"},
{"generation": 3, "level": 10, "abilities":["intimidate"], "moves":["tackle", "tailwhip", "rage", "hornattack"]},
{"generation": 3, "level": 46, "abilities":["intimidate"], "moves":["refresh", "earthquake", "tailwhip", "bodyslam"]},
],
tier: "New",
},
magikarp: {
randomBattleMoves: ["bounce", "flail", "tackle", "hydropump"],
eventPokemon: [
{"generation": 4, "level": 5, "gender": "M", "nature": "Relaxed", "moves":["splash"]},
{"generation": 4, "level": 6, "gender": "F", "nature": "Rash", "moves":["splash"]},
{"generation": 4, "level": 7, "gender": "F", "nature": "Hardy", "moves":["splash"]},
{"generation": 4, "level": 5, "gender": "F", "nature": "Lonely", "moves":["splash"]},
{"generation": 4, "level": 4, "gender": "M", "nature": "Modest", "moves":["splash"]},
{"generation": 5, "level": 99, "shiny": true, "gender": "M", "isHidden": false, "moves":["flail", "hydropump", "bounce", "splash"], "pokeball": "cherishball"},
{"generation": 6, "level": 1, "shiny": 1, "isHidden": false, "moves":["splash", "celebrate", "happyhour"], "pokeball": "cherishball"},
],
tier: "LC",
},
gyarados: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "rest", "sleeptalk", "dragontail", "stoneedge", "substitute"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": false, "moves":["waterfall", "earthquake", "icefang", "dragondance"], "pokeball": "cherishball"},
{"generation": 6, "level": 20, "shiny": true, "isHidden": false, "moves":["waterfall", "bite", "icefang", "ironhead"], "pokeball": "cherishball"},
],
tier: "New",
},
gyaradosmega: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "substitute", "icefang", "crunch"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "bounce", "taunt", "protect", "thunderwave", "stoneedge", "substitute", "icefang"],
requiredItem: "Gyaradosite",
tier: "New",
},
lapras: {
randomBattleMoves: ["icebeam", "thunderbolt", "healbell", "toxic", "hydropump", "substitute"],
randomDoubleBattleMoves: ["icebeam", "thunderbolt", "healbell", "hydropump", "surf", "substitute", "protect", "iceshard", "icywind"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["hydropump", "raindance", "blizzard", "healbell"]},
],
tier: "New",
},
ditto: {
randomBattleMoves: ["transform"],
tier: "New",
},
eevee: {
randomBattleMoves: ["quickattack", "return", "bite", "batonpass", "irontail", "yawn", "protect", "wish"],
randomDoubleBattleMoves: ["quickattack", "return", "bite", "helpinghand", "irontail", "yawn", "protect", "wish"],
eventPokemon: [
{"generation": 4, "level": 10, "gender": "F", "nature": "Lonely", "abilities":["adaptability"], "moves":["covet", "bite", "helpinghand", "attract"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Hardy", "abilities":["adaptability"], "moves":["irontail", "trumpcard", "flail", "quickattack"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "gender": "F", "nature": "Hardy", "isHidden": false, "abilities":["adaptability"], "moves":["sing", "return", "echoedvoice", "attract"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "sandattack", "babydolleyes", "swift"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "shiny": true, "isHidden": true, "moves":["swift", "quickattack", "babydolleyes", "helpinghand"], "pokeball": "cherishball"},
],
tier: "LC",
},
vaporeon: {
randomBattleMoves: ["wish", "protect", "scald", "roar", "icebeam", "healbell", "batonpass"],
randomDoubleBattleMoves: ["helpinghand", "wish", "protect", "scald", "muddywater", "icebeam", "toxic", "hydropump"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "watergun"], "pokeball": "cherishball"},
],
tier: "New",
},
jolteon: {
randomBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowerice", "batonpass", "substitute", "signalbeam"],
randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "hiddenpowergrass", "hiddenpowerice", "helpinghand", "protect", "substitute", "signalbeam"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "thundershock"], "pokeball": "cherishball"},
],
tier: "New",
},
flareon: {
randomBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["flamecharge", "facade", "flareblitz", "superpower", "wish", "protect", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "ember"], "pokeball": "cherishball"},
],
tier: "New",
},
espeon: {
randomBattleMoves: ["psychic", "psyshock", "substitute", "shadowball", "calmmind", "morningsun", "batonpass", "dazzlinggleam"],
randomDoubleBattleMoves: ["psychic", "psyshock", "substitute", "wish", "shadowball", "hiddenpowerfighting", "helpinghand", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["psybeam", "psychup", "psychic", "morningsun"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "confusion"], "pokeball": "cherishball"},
],
tier: "New",
},
umbreon: {
randomBattleMoves: ["wish", "protect", "healbell", "toxic", "batonpass", "foulplay"],
randomDoubleBattleMoves: ["moonlight", "wish", "protect", "healbell", "snarl", "foulplay", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["feintattack", "meanlook", "screech", "moonlight"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "pursuit"], "pokeball": "cherishball"},
],
tier: "New",
},
leafeon: {
randomBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "synthesis", "batonpass", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "leafblade", "substitute", "xscissor", "protect", "helpinghand", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "razorleaf"], "pokeball": "cherishball"},
],
tier: "New",
},
glaceon: {
randomBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "healbell", "wish", "protect", "toxic"],
randomDoubleBattleMoves: ["icebeam", "hiddenpowerground", "shadowball", "wish", "protect", "healbell", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tailwhip", "tackle", "helpinghand", "sandattack"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "tailwhip", "sandattack", "icywind"], "pokeball": "cherishball"},
],
tier: "New",
},
porygon: {
randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "discharge", "trick"],
eventPokemon: [
{"generation": 5, "level": 10, "isHidden": true, "moves":["tackle", "conversion", "sharpen", "psybeam"]},
],
tier: "LC",
},
porygon2: {
randomBattleMoves: ["triattack", "icebeam", "recover", "toxic", "thunderwave", "thunderbolt"],
randomDoubleBattleMoves: ["triattack", "icebeam", "discharge", "shadowball", "protect", "recover"],
tier: "New",
},
porygonz: {
randomBattleMoves: ["triattack", "darkpulse", "icebeam", "thunderbolt", "agility", "trick", "nastyplot"],
randomDoubleBattleMoves: ["protect", "triattack", "darkpulse", "hiddenpowerfighting", "agility", "trick", "nastyplot"],
tier: "New",
},
omanyte: {
randomBattleMoves: ["shellsmash", "surf", "icebeam", "earthpower", "hiddenpowerelectric", "spikes", "toxicspikes", "stealthrock", "hydropump"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["swiftswim"], "moves":["bubblebeam", "supersonic", "withdraw", "bite"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
omastar: {
randomBattleMoves: ["shellsmash", "scald", "icebeam", "earthpower", "spikes", "stealthrock", "hydropump"],
randomDoubleBattleMoves: ["shellsmash", "muddywater", "icebeam", "earthpower", "hiddenpowerelectric", "protect", "hydropump"],
tier: "Bank",
},
kabuto: {
randomBattleMoves: ["aquajet", "rockslide", "rapidspin", "stealthrock", "honeclaws", "waterfall", "toxic"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["battlearmor"], "moves":["confuseray", "dig", "scratch", "harden"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
kabutops: {
randomBattleMoves: ["aquajet", "stoneedge", "rapidspin", "swordsdance", "waterfall", "knockoff"],
randomDoubleBattleMoves: ["aquajet", "stoneedge", "protect", "rockslide", "swordsdance", "waterfall", "superpower", "knockoff"],
tier: "Bank",
},
aerodactyl: {
randomBattleMoves: ["stealthrock", "taunt", "stoneedge", "earthquake", "defog", "roost", "doubleedge"],
randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "aquatail", "protect", "icefang", "skydrop", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["pressure"], "moves":["steelwing", "icefang", "firefang", "thunderfang"], "pokeball": "cherishball"},
],
tier: "New",
},
aerodactylmega: {
randomBattleMoves: ["aquatail", "pursuit", "honeclaws", "stoneedge", "firefang", "aerialace", "roost"],
randomDoubleBattleMoves: ["wideguard", "taunt", "stoneedge", "rockslide", "earthquake", "ironhead", "aerialace", "protect", "icefang", "skydrop", "tailwind"],
requiredItem: "Aerodactylite",
tier: "New",
},
munchlax: {
randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "whirlwind", "toxic"],
eventPokemon: [
{"generation": 4, "level": 5, "moves":["metronome", "tackle", "defensecurl", "selfdestruct"]},
{"generation": 4, "level": 5, "gender": "F", "nature": "Relaxed", "abilities":["thickfat"], "moves":["metronome", "odorsleuth", "tackle", "curse"], "pokeball": "cherishball"},
],
tier: "LC",
},
snorlax: {
randomBattleMoves: ["rest", "curse", "sleeptalk", "bodyslam", "earthquake", "return", "firepunch", "crunch", "pursuit", "whirlwind"],
randomDoubleBattleMoves: ["curse", "protect", "bodyslam", "earthquake", "return", "firepunch", "icepunch", "crunch", "selfdestruct"],
eventPokemon: [
{"generation": 3, "level": 43, "moves":["refresh", "fissure", "curse", "bodyslam"]},
],
tier: "New",
},
articuno: {
randomBattleMoves: ["icebeam", "roost", "freezedry", "toxic", "substitute", "hurricane"],
randomDoubleBattleMoves: ["freezedry", "roost", "protect", "substitute", "hurricane", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]},
{"generation": 3, "level": 70, "moves":["agility", "mindreader", "icebeam", "reflect"]},
{"generation": 3, "level": 50, "moves":["icebeam", "healbell", "extrasensory", "haze"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["agility", "icebeam", "reflect", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "agility", "mindreader", "icebeam"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["icebeam", "reflect", "hail", "tailwind"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["freezedry", "icebeam", "hail", "reflect"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
zapdos: {
randomBattleMoves: ["thunderbolt", "heatwave", "hiddenpowerice", "roost", "toxic", "uturn", "defog"],
randomDoubleBattleMoves: ["thunderbolt", "heatwave", "hiddenpowergrass", "hiddenpowerice", "tailwind", "protect", "discharge"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]},
{"generation": 3, "level": 70, "moves":["agility", "detect", "drillpeck", "charge"]},
{"generation": 3, "level": 50, "moves":["thunderbolt", "extrasensory", "batonpass", "metalsound"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["charge", "agility", "discharge", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["thunderwave", "agility", "detect", "drillpeck"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["agility", "discharge", "raindance", "lightscreen"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["discharge", "thundershock", "raindance", "agility"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
moltres: {
randomBattleMoves: ["fireblast", "hiddenpowergrass", "roost", "substitute", "toxic", "willowisp", "hurricane"],
randomDoubleBattleMoves: ["fireblast", "hiddenpowergrass", "airslash", "roost", "substitute", "protect", "uturn", "willowisp", "hurricane", "heatwave", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]},
{"generation": 3, "level": 70, "moves":["agility", "endure", "flamethrower", "safeguard"]},
{"generation": 3, "level": 50, "moves":["extrasensory", "morningsun", "willowisp", "flamethrower"]},
{"generation": 4, "level": 60, "shiny": 1, "moves":["flamethrower", "safeguard", "airslash", "roost"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["firespin", "agility", "endure", "flamethrower"]},
{"generation": 6, "level": 70, "isHidden": false, "moves":["safeguard", "airslash", "sunnyday", "heatwave"]},
{"generation": 6, "level": 70, "isHidden": true, "moves":["skyattack", "heatwave", "sunnyday", "safeguard"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
dratini: {
randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"],
tier: "LC",
},
dragonair: {
randomBattleMoves: ["dragondance", "outrage", "waterfall", "fireblast", "extremespeed", "dracometeor", "substitute"],
tier: "NFE",
},
dragonite: {
randomBattleMoves: ["dragondance", "outrage", "firepunch", "extremespeed", "earthquake", "roost"],
randomDoubleBattleMoves: ["dragondance", "firepunch", "extremespeed", "dragonclaw", "earthquake", "roost", "substitute", "superpower", "dracometeor", "protect", "skydrop"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["agility", "safeguard", "wingattack", "outrage"]},
{"generation": 3, "level": 55, "moves":["healbell", "hyperbeam", "dragondance", "earthquake"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Mild", "moves":["dracometeor", "thunderbolt", "outrage", "dragondance"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "gender": "M", "isHidden": true, "moves":["extremespeed", "firepunch", "dragondance", "outrage"], "pokeball": "cherishball"},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "thunderpunch"]},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["dragonrush", "safeguard", "wingattack", "extremespeed"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["fireblast", "safeguard", "outrage", "hyperbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 55, "gender": "M", "isHidden": true, "moves":["dragondance", "outrage", "hurricane", "extremespeed"], "pokeball": "cherishball"},
{"generation": 6, "level": 62, "gender": "M", "ivs": {"hp": 31, "def": 31, "spa": 31, "spd": 31}, "isHidden": false, "moves":["agility", "slam", "barrier", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "New",
},
mewtwo: {
randomBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "recover"],
randomDoubleBattleMoves: ["psystrike", "aurasphere", "fireblast", "icebeam", "calmmind", "substitute", "recover", "thunderbolt", "willowisp", "taunt", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["swift", "recover", "safeguard", "psychic"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["psychocut", "amnesia", "powerswap", "guardswap"]},
{"generation": 5, "level": 70, "isHidden": false, "moves":["psystrike", "shadowball", "aurasphere", "electroball"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "nature": "Timid", "ivs": {"spa": 31, "spe": 31}, "isHidden": true, "moves":["psystrike", "icebeam", "healpulse", "hurricane"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "isHidden": false, "moves":["recover", "psychic", "barrier", "aurasphere"]},
{"generation": 6, "level": 100, "shiny": true, "isHidden": true, "moves":["psystrike", "psychic", "recover", "aurasphere"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
mewtwomegax: {
randomBattleMoves: ["bulkup", "drainpunch", "earthquake", "taunt", "stoneedge", "zenheadbutt", "icebeam"],
requiredItem: "Mewtwonite X",
tier: "Bank-Uber",
},
mewtwomegay: {
randomBattleMoves: ["psystrike", "aurasphere", "shadowball", "fireblast", "icebeam", "calmmind", "recover", "willowisp", "taunt"],
requiredItem: "Mewtwonite Y",
tier: "Bank-Uber",
},
mew: {
randomBattleMoves: ["defog", "roost", "willowisp", "knockoff", "taunt", "icebeam", "earthpower", "aurasphere", "stealthrock", "nastyplot", "psyshock", "batonpass"],
randomDoubleBattleMoves: ["taunt", "willowisp", "transform", "roost", "psyshock", "nastyplot", "aurasphere", "fireblast", "icebeam", "thunderbolt", "protect", "fakeout", "helpinghand", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 30, "shiny": 1, "moves":["pound", "transform", "megapunch", "metronome"]},
{"generation": 3, "level": 10, "moves":["pound", "transform"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["fakeout"]},
{"generation": 3, "level": 10, "moves":["fakeout"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["feintattack"]},
{"generation": 3, "level": 10, "moves":["feintattack"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["hypnosis"]},
{"generation": 3, "level": 10, "moves":["hypnosis"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["nightshade"]},
{"generation": 3, "level": 10, "moves":["nightshade"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["roleplay"]},
{"generation": 3, "level": 10, "moves":["roleplay"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["zapcannon"]},
{"generation": 3, "level": 10, "moves":["zapcannon"]},
{"generation": 4, "level": 50, "moves":["ancientpower", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["barrier", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["megapunch", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["amnesia", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["transform", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["psychic", "metronome", "teleport", "aurasphere"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["synthesis", "return", "hypnosis", "teleport"], "pokeball": "cherishball"},
{"generation": 4, "level": 5, "moves":["pound"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["pound"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
chikorita: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "razorleaf"]},
{"generation": 3, "level": 5, "moves":["tackle", "growl", "ancientpower", "frenzyplant"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "growl"], "pokeball": "cherishball"},
],
tier: "LC",
},
bayleef: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "grasswhistle", "leechseed", "toxic", "gigadrain", "synthesis"],
tier: "NFE",
},
meganium: {
randomBattleMoves: ["reflect", "lightscreen", "aromatherapy", "leechseed", "toxic", "gigadrain", "synthesis", "dragontail"],
randomDoubleBattleMoves: ["reflect", "lightscreen", "aromatherapy", "leechseed", "petalblizzard", "gigadrain", "synthesis", "dragontail", "healpulse", "toxic", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": true, "moves":["solarbeam", "sunnyday", "synthesis", "bodyslam"]},
],
tier: "New",
},
cyndaquil: {
randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "leer", "smokescreen"]},
{"generation": 3, "level": 5, "moves":["tackle", "leer", "reversal", "blastburn"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["tackle", "leer"], "pokeball": "cherishball"},
],
tier: "LC",
},
quilava: {
randomBattleMoves: ["eruption", "fireblast", "flamethrower", "hiddenpowergrass", "hiddenpowerice"],
tier: "NFE",
},
typhlosion: {
randomBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast"],
randomDoubleBattleMoves: ["eruption", "fireblast", "hiddenpowergrass", "extrasensory", "focusblast", "heatwave", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["quickattack", "flamewheel", "swift", "flamethrower"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["overheat", "flamewheel", "flamecharge", "swift"]},
],
tier: "New",
},
totodile: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "rage"]},
{"generation": 3, "level": 5, "moves":["scratch", "leer", "crunch", "hydrocannon"]},
{"generation": 6, "level": 5, "isHidden": false, "moves":["scratch", "leer"], "pokeball": "cherishball"},
],
tier: "LC",
},
croconaw: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "superpower", "dragondance", "swordsdance"],
tier: "NFE",
},
feraligatr: {
randomBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake"],
randomDoubleBattleMoves: ["aquajet", "waterfall", "crunch", "icepunch", "dragondance", "swordsdance", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": true, "moves":["icepunch", "crunch", "waterfall", "screech"]},
],
tier: "New",
},
sentret: {
randomBattleMoves: ["superfang", "trick", "toxic", "uturn", "knockoff"],
tier: "Bank-LC",
},
furret: {
randomBattleMoves: ["uturn", "trick", "aquatail", "firepunch", "knockoff", "doubleedge"],
randomDoubleBattleMoves: ["uturn", "suckerpunch", "icepunch", "firepunch", "knockoff", "doubleedge", "superfang", "followme", "helpinghand", "protect"],
tier: "Bank",
},
hoothoot: {
randomBattleMoves: ["reflect", "toxic", "roost", "whirlwind", "nightshade", "magiccoat"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "foresight"]},
],
tier: "Bank-LC",
},
noctowl: {
randomBattleMoves: ["roost", "whirlwind", "airslash", "nightshade", "toxic", "defog"],
randomDoubleBattleMoves: ["roost", "tailwind", "airslash", "hypervoice", "heatwave", "protect", "hypnosis"],
tier: "Bank",
},
ledyba: {
randomBattleMoves: ["roost", "agility", "lightscreen", "encore", "reflect", "knockoff", "swordsdance", "batonpass", "toxic"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["refresh", "psybeam", "aerialace", "supersonic"]},
],
tier: "LC",
},
ledian: {
randomBattleMoves: ["roost", "lightscreen", "encore", "reflect", "knockoff", "toxic", "uturn"],
randomDoubleBattleMoves: ["protect", "lightscreen", "encore", "reflect", "knockoff", "bugbuzz", "uturn", "tailwind"],
tier: "New",
},
spinarak: {
randomBattleMoves: ["agility", "toxic", "xscissor", "toxicspikes", "poisonjab", "batonpass", "stickyweb"],
eventPokemon: [
{"generation": 3, "level": 14, "moves":["refresh", "dig", "signalbeam", "nightshade"]},
],
tier: "LC",
},
ariados: {
randomBattleMoves: ["megahorn", "toxicspikes", "poisonjab", "suckerpunch", "stickyweb"],
randomDoubleBattleMoves: ["protect", "megahorn", "stringshot", "poisonjab", "stickyweb", "ragepowder"],
tier: "New",
},
chinchou: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "surf", "thunderwave", "scald", "discharge", "healbell"],
tier: "LC",
},
lanturn: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "thunderbolt", "healbell", "toxic"],
randomDoubleBattleMoves: ["thunderbolt", "hiddenpowergrass", "hydropump", "icebeam", "thunderwave", "scald", "discharge", "protect", "surf"],
tier: "New",
},
togepi: {
randomBattleMoves: ["protect", "fireblast", "toxic", "thunderwave", "softboiled", "dazzlinggleam"],
eventPokemon: [
{"generation": 3, "level": 20, "gender": "F", "abilities":["serenegrace"], "moves":["metronome", "charm", "sweetkiss", "yawn"]},
{"generation": 3, "level": 25, "moves":["triattack", "followme", "ancientpower", "helpinghand"]},
],
tier: "LC",
},
togetic: {
randomBattleMoves: ["nastyplot", "dazzlinggleam", "fireblast", "batonpass", "roost", "defog", "toxic", "thunderwave", "healbell"],
tier: "New",
},
togekiss: {
randomBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "aurasphere", "batonpass", "healbell", "defog"],
randomDoubleBattleMoves: ["roost", "thunderwave", "nastyplot", "airslash", "followme", "dazzlinggleam", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["extremespeed", "aurasphere", "airslash", "present"]},
],
tier: "New",
},
natu: {
randomBattleMoves: ["thunderwave", "roost", "toxic", "reflect", "lightscreen", "uturn", "wish", "psychic", "nightshade"],
eventPokemon: [
{"generation": 3, "level": 22, "moves":["batonpass", "futuresight", "nightshade", "aerialace"]},
],
tier: "Bank-LC",
},
xatu: {
randomBattleMoves: ["thunderwave", "toxic", "roost", "psychic", "uturn", "reflect", "lightscreen", "nightshade", "heatwave"],
randomDoubleBattleMoves: ["thunderwave", "tailwind", "roost", "psychic", "uturn", "reflect", "lightscreen", "grassknot", "heatwave", "protect"],
tier: "Bank",
},
mareep: {
randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"],
eventPokemon: [
{"generation": 3, "level": 37, "gender": "F", "moves":["thunder", "thundershock", "thunderwave", "cottonspore"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "thundershock"]},
{"generation": 3, "level": 17, "moves":["healbell", "thundershock", "thunderwave", "bodyslam"]},
{"generation": 6, "level": 10, "isHidden": false, "moves":["holdback", "tackle", "thunderwave", "thundershock"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
flaaffy: {
randomBattleMoves: ["reflect", "lightscreen", "thunderbolt", "discharge", "thunderwave", "toxic", "hiddenpowerice", "cottonguard", "powergem"],
tier: "Bank-NFE",
},
ampharos: {
randomBattleMoves: ["voltswitch", "reflect", "lightscreen", "focusblast", "thunderbolt", "toxic", "healbell", "hiddenpowerice"],
randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"],
tier: "Bank",
},
ampharosmega: {
randomBattleMoves: ["voltswitch", "focusblast", "agility", "thunderbolt", "healbell", "dragonpulse"],
randomDoubleBattleMoves: ["focusblast", "hiddenpowerice", "hiddenpowergrass", "thunderbolt", "discharge", "dragonpulse", "protect"],
requiredItem: "Ampharosite",
tier: "Bank",
},
azurill: {
randomBattleMoves: ["scald", "return", "bodyslam", "encore", "toxic", "protect", "knockoff"],
tier: "Bank-LC",
},
marill: {
randomBattleMoves: ["waterfall", "knockoff", "encore", "toxic", "aquajet", "superpower", "icepunch", "protect", "playrough", "poweruppunch"],
tier: "NFE",
},
azumarill: {
randomBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "playrough", "superpower", "bellydrum", "knockoff", "protect"],
tier: "New",
},
bonsly: {
randomBattleMoves: ["rockslide", "brickbreak", "doubleedge", "toxic", "stealthrock", "suckerpunch", "explosion"],
tier: "LC",
},
sudowoodo: {
randomBattleMoves: ["stoneedge", "earthquake", "suckerpunch", "woodhammer", "toxic", "stealthrock"],
randomDoubleBattleMoves: ["stoneedge", "earthquake", "suckerpunch", "woodhammer", "explosion", "stealthrock", "rockslide", "helpinghand", "protect"],
tier: "New",
},
hoppip: {
randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"],
tier: "Bank-LC",
},
skiploom: {
randomBattleMoves: ["encore", "sleeppowder", "uturn", "toxic", "leechseed", "substitute", "protect"],
tier: "Bank-NFE",
},
jumpluff: {
randomBattleMoves: ["swordsdance", "sleeppowder", "uturn", "encore", "toxic", "acrobatics", "leechseed", "seedbomb", "substitute"],
randomDoubleBattleMoves: ["encore", "sleeppowder", "uturn", "helpinghand", "leechseed", "gigadrain", "ragepowder", "protect"],
eventPokemon: [
{"generation": 5, "level": 27, "gender": "M", "isHidden": true, "moves":["falseswipe", "sleeppowder", "bulletseed", "leechseed"]},
],
tier: "Bank",
},
aipom: {
randomBattleMoves: ["fakeout", "return", "brickbreak", "seedbomb", "knockoff", "uturn", "icepunch", "irontail"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "tailwhip", "sandattack"]},
],
tier: "Bank-LC",
},
ambipom: {
randomBattleMoves: ["fakeout", "return", "knockoff", "uturn", "switcheroo", "seedbomb", "acrobatics", "lowkick"],
randomDoubleBattleMoves: ["fakeout", "return", "knockoff", "uturn", "doublehit", "icepunch", "lowkick", "protect"],
tier: "Bank",
},
sunkern: {
randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "toxic", "earthpower", "leechseed"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["chlorophyll"], "moves":["absorb", "growth"]},
],
tier: "Bank-LC",
},
sunflora: {
randomBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "earthpower"],
randomDoubleBattleMoves: ["sunnyday", "gigadrain", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "earthpower", "protect", "encore"],
tier: "Bank",
},
yanma: {
randomBattleMoves: ["bugbuzz", "airslash", "hiddenpowerground", "uturn", "protect", "gigadrain", "ancientpower"],
tier: "Bank",
},
yanmega: {
randomBattleMoves: ["bugbuzz", "airslash", "ancientpower", "uturn", "protect", "gigadrain"],
tier: "Bank",
},
wooper: {
randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "stockpile", "yawn", "protect"],
tier: "Bank-LC",
},
quagsire: {
randomBattleMoves: ["recover", "earthquake", "scald", "toxic", "encore", "icebeam"],
randomDoubleBattleMoves: ["icywind", "earthquake", "waterfall", "scald", "rockslide", "curse", "yawn", "icepunch", "protect"],
tier: "Bank",
},
murkrow: {
randomBattleMoves: ["substitute", "suckerpunch", "bravebird", "heatwave", "roost", "darkpulse", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["insomnia"], "moves":["peck", "astonish"]},
],
tier: "LC Uber",
},
honchkrow: {
randomBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "pursuit"],
randomDoubleBattleMoves: ["substitute", "superpower", "suckerpunch", "bravebird", "roost", "heatwave", "protect"],
tier: "New",
},
misdreavus: {
randomBattleMoves: ["nastyplot", "thunderbolt", "dazzlinggleam", "willowisp", "shadowball", "taunt", "painsplit"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "psywave", "spite"]},
],
tier: "New",
},
mismagius: {
randomBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "painsplit", "destinybond"],
randomDoubleBattleMoves: ["nastyplot", "substitute", "willowisp", "shadowball", "thunderbolt", "dazzlinggleam", "taunt", "protect"],
tier: "New",
},
unown: {
randomBattleMoves: ["hiddenpowerpsychic"],
tier: "Bank",
},
wynaut: {
randomBattleMoves: ["destinybond", "counter", "mirrorcoat", "encore"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["splash", "charm", "encore", "tickle"]},
],
tier: "Bank-LC",
},
wobbuffet: {
randomBattleMoves: ["counter", "mirrorcoat", "encore", "destinybond", "safeguard"],
eventPokemon: [
{"generation": 3, "level": 5, "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["counter", "mirrorcoat", "safeguard", "destinybond"]},
{"generation": 6, "level": 10, "gender": "M", "isHidden": false, "moves":["counter"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "gender": "M", "isHidden": false, "moves":["counter", "mirrorcoat"], "pokeball": "cherishball"},
],
tier: "Bank",
},
girafarig: {
randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "batonpass", "substitute", "hypervoice"],
randomDoubleBattleMoves: ["psychic", "psyshock", "thunderbolt", "nastyplot", "protect", "agility", "hypervoice"],
tier: "Bank",
},
pineco: {
randomBattleMoves: ["rapidspin", "toxicspikes", "spikes", "bugbite", "stealthrock"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "protect", "selfdestruct"]},
{"generation": 3, "level": 20, "moves":["refresh", "pinmissile", "spikes", "counter"]},
],
tier: "Bank-LC",
},
forretress: {
randomBattleMoves: ["rapidspin", "toxic", "spikes", "voltswitch", "stealthrock", "gyroball"],
randomDoubleBattleMoves: ["rockslide", "drillrun", "toxic", "voltswitch", "stealthrock", "gyroball", "protect"],
tier: "Bank",
},
dunsparce: {
randomBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "roost"],
randomDoubleBattleMoves: ["coil", "rockslide", "bite", "headbutt", "glare", "bodyslam", "protect"],
tier: "Bank",
},
gligar: {
randomBattleMoves: ["stealthrock", "toxic", "roost", "defog", "earthquake", "uturn", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["poisonsting", "sandattack"]},
],
tier: "Bank",
},
gliscor: {
randomBattleMoves: ["roost", "substitute", "taunt", "earthquake", "protect", "toxic", "stealthrock", "knockoff"],
randomDoubleBattleMoves: ["tailwind", "substitute", "taunt", "earthquake", "protect", "stoneedge", "knockoff"],
tier: "Bank",
},
snubbull: {
randomBattleMoves: ["thunderwave", "firepunch", "crunch", "closecombat", "icepunch", "earthquake", "playrough"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "scaryface", "tailwhip", "charm"]},
],
tier: "LC",
},
granbull: {
randomBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "healbell"],
randomDoubleBattleMoves: ["thunderwave", "playrough", "crunch", "earthquake", "snarl", "rockslide", "protect"],
tier: "New",
},
qwilfish: {
randomBattleMoves: ["toxicspikes", "waterfall", "spikes", "painsplit", "thunderwave", "taunt", "destinybond"],
randomDoubleBattleMoves: ["poisonjab", "waterfall", "swordsdance", "protect", "thunderwave", "taunt", "destinybond"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "poisonsting", "harden", "minimize"]},
],
tier: "Bank",
},
shuckle: {
randomBattleMoves: ["toxic", "encore", "stealthrock", "knockoff", "stickyweb", "infestation"],
randomDoubleBattleMoves: ["encore", "stealthrock", "knockoff", "stickyweb", "guardsplit", "powersplit", "toxic", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["sturdy"], "moves":["constrict", "withdraw", "wrap"]},
{"generation": 3, "level": 20, "abilities":["sturdy"], "moves":["substitute", "toxic", "sludgebomb", "encore"]},
],
tier: "Bank",
},
heracross: {
randomBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake"],
randomDoubleBattleMoves: ["closecombat", "megahorn", "stoneedge", "swordsdance", "knockoff", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "gender": "F", "nature": "Adamant", "isHidden": false, "moves":["bulletseed", "pinmissile", "closecombat", "megahorn"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Adamant", "isHidden": false, "abilities":["guts"], "moves":["pinmissile", "bulletseed", "earthquake", "rockblast"], "pokeball": "cherishball"},
],
tier: "Bank",
},
heracrossmega: {
randomBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "substitute"],
randomDoubleBattleMoves: ["closecombat", "pinmissile", "rockblast", "swordsdance", "bulletseed", "knockoff", "earthquake", "protect"],
requiredItem: "Heracronite",
tier: "Bank",
},
sneasel: {
randomBattleMoves: ["iceshard", "iciclecrash", "lowkick", "pursuit", "swordsdance", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "taunt", "quickattack"]},
],
tier: "New",
},
weavile: {
randomBattleMoves: ["iceshard", "iciclecrash", "knockoff", "pursuit", "swordsdance", "lowkick"],
randomDoubleBattleMoves: ["iceshard", "iciclecrash", "knockoff", "fakeout", "swordsdance", "lowkick", "taunt", "protect", "feint"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Jolly", "moves":["fakeout", "iceshard", "nightslash", "brickbreak"], "pokeball": "cherishball"},
{"generation": 6, "level": 48, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["nightslash", "icepunch", "brickbreak", "xscissor"], "pokeball": "cherishball"},
],
tier: "New",
},
teddiursa: {
randomBattleMoves: ["swordsdance", "protect", "facade", "closecombat", "firepunch", "crunch", "playrough", "gunkshot"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["pickup"], "moves":["scratch", "leer", "lick"]},
{"generation": 3, "level": 11, "abilities":["pickup"], "moves":["refresh", "metalclaw", "lick", "return"]},
],
tier: "Bank-LC",
},
ursaring: {
randomBattleMoves: ["swordsdance", "facade", "closecombat", "crunch", "protect"],
randomDoubleBattleMoves: ["swordsdance", "facade", "closecombat", "earthquake", "crunch", "protect"],
tier: "Bank",
},
slugma: {
randomBattleMoves: ["stockpile", "recover", "lavaplume", "willowisp", "toxic", "hiddenpowergrass", "earthpower", "memento"],
tier: "Bank-LC",
},
magcargo: {
randomBattleMoves: ["recover", "lavaplume", "toxic", "hiddenpowergrass", "stealthrock", "fireblast", "earthpower", "shellsmash", "ancientpower"],
randomDoubleBattleMoves: ["protect", "heatwave", "willowisp", "shellsmash", "hiddenpowergrass", "ancientpower", "stealthrock", "fireblast", "earthpower"],
eventPokemon: [
{"generation": 3, "level": 38, "moves":["refresh", "heatwave", "earthquake", "flamethrower"]},
],
tier: "Bank",
},
swinub: {
randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "superpower", "endeavor", "stealthrock"],
eventPokemon: [
{"generation": 3, "level": 22, "abilities":["oblivious"], "moves":["charm", "ancientpower", "mist", "mudshot"]},
],
tier: "LC",
},
piloswine: {
randomBattleMoves: ["earthquake", "iciclecrash", "iceshard", "superpower", "endeavor", "stealthrock"],
tier: "New",
},
mamoswine: {
randomBattleMoves: ["iceshard", "earthquake", "endeavor", "iciclecrash", "stealthrock", "superpower", "knockoff"],
randomDoubleBattleMoves: ["iceshard", "earthquake", "rockslide", "iciclecrash", "protect", "superpower", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 34, "gender": "M", "isHidden": true, "moves":["hail", "icefang", "takedown", "doublehit"]},
{"generation": 6, "level": 50, "shiny": true, "gender": "M", "nature": "Adamant", "isHidden": true, "moves":["iciclespear", "earthquake", "iciclecrash", "rockslide"]},
],
tier: "New",
},
corsola: {
randomBattleMoves: ["recover", "toxic", "powergem", "scald", "stealthrock"],
randomDoubleBattleMoves: ["protect", "icywind", "powergem", "scald", "stealthrock", "earthpower", "icebeam"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "mudsport"]},
],
tier: "New",
},
remoraid: {
randomBattleMoves: ["waterspout", "hydropump", "fireblast", "hiddenpowerground", "icebeam", "seedbomb", "rockblast"],
tier: "Bank-LC",
},
octillery: {
randomBattleMoves: ["hydropump", "fireblast", "icebeam", "energyball", "rockblast", "gunkshot", "scald"],
randomDoubleBattleMoves: ["hydropump", "surf", "fireblast", "icebeam", "energyball", "chargebeam", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "F", "nature": "Serious", "abilities":["suctioncups"], "moves":["octazooka", "icebeam", "signalbeam", "hyperbeam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
delibird: {
randomBattleMoves: ["rapidspin", "iceshard", "icepunch", "aerialace", "spikes", "destinybond"],
randomDoubleBattleMoves: ["fakeout", "iceshard", "icepunch", "aerialace", "brickbreak", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["present"]},
{"generation": 6, "level": 10, "isHidden": false, "abilities":["vitalspirit"], "moves":["present", "happyhour"], "pokeball": "cherishball"},
],
tier: "New",
},
mantyke: {
randomBattleMoves: ["raindance", "hydropump", "scald", "airslash", "icebeam", "rest", "sleeptalk", "toxic"],
tier: "Bank-LC",
},
mantine: {
randomBattleMoves: ["scald", "airslash", "rest", "sleeptalk", "toxic", "defog"],
randomDoubleBattleMoves: ["raindance", "hydropump", "scald", "airslash", "icebeam", "tailwind", "wideguard", "helpinghand", "protect", "surf"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "bubble", "supersonic"]},
],
tier: "Bank",
},
skarmory: {
randomBattleMoves: ["whirlwind", "bravebird", "roost", "spikes", "stealthrock", "defog"],
randomDoubleBattleMoves: ["skydrop", "bravebird", "tailwind", "taunt", "feint", "protect", "ironhead"],
tier: "New",
},
houndour: {
randomBattleMoves: ["pursuit", "suckerpunch", "fireblast", "darkpulse", "hiddenpowerfighting", "nastyplot"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["leer", "ember", "howl"]},
{"generation": 3, "level": 17, "moves":["charm", "feintattack", "ember", "roar"]},
],
tier: "Bank-LC",
},
houndoom: {
randomBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "fireblast", "hiddenpowergrass"],
randomDoubleBattleMoves: ["nastyplot", "darkpulse", "suckerpunch", "heatwave", "hiddenpowerfighting", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["flashfire"], "moves":["flamethrower", "darkpulse", "solarbeam", "sludgebomb"], "pokeball": "cherishball"},
],
tier: "Bank",
},
houndoommega: {
randomBattleMoves: ["nastyplot", "darkpulse", "taunt", "fireblast", "hiddenpowergrass"],
randomDoubleBattleMoves: ["nastyplot", "darkpulse", "taunt", "heatwave", "hiddenpowergrass", "protect"],
requiredItem: "Houndoominite",
tier: "Bank",
},
phanpy: {
randomBattleMoves: ["stealthrock", "earthquake", "iceshard", "headsmash", "knockoff", "seedbomb", "superpower", "playrough"],
tier: "Bank-LC",
},
donphan: {
randomBattleMoves: ["stealthrock", "rapidspin", "iceshard", "earthquake", "knockoff", "stoneedge"],
randomDoubleBattleMoves: ["stealthrock", "knockoff", "iceshard", "earthquake", "rockslide", "protect"],
tier: "Bank",
},
stantler: {
randomBattleMoves: ["doubleedge", "megahorn", "jumpkick", "earthquake", "suckerpunch"],
randomDoubleBattleMoves: ["return", "megahorn", "jumpkick", "earthquake", "suckerpunch", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["intimidate"], "moves":["tackle", "leer"]},
],
tier: "Bank",
},
smeargle: {
randomBattleMoves: ["spore", "spikes", "stealthrock", "destinybond", "whirlwind", "stickyweb"],
randomDoubleBattleMoves: ["spore", "fakeout", "wideguard", "helpinghand", "followme", "tailwind", "kingsshield", "transform"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["owntempo"], "moves":["sketch"]},
{"generation": 5, "level": 50, "gender": "F", "nature": "Jolly", "ivs": {"atk": 31, "spe": 31}, "isHidden": false, "abilities":["technician"], "moves":["falseswipe", "spore", "odorsleuth", "meanlook"], "pokeball": "cherishball"},
],
tier: "New",
},
miltank: {
randomBattleMoves: ["milkdrink", "stealthrock", "bodyslam", "healbell", "curse", "earthquake", "toxic"],
randomDoubleBattleMoves: ["protect", "helpinghand", "bodyslam", "healbell", "curse", "earthquake", "thunderwave"],
eventPokemon: [
{"generation": 6, "level": 20, "perfectIVs": 3, "isHidden": false, "abilities":["scrappy"], "moves":["rollout", "attract", "stomp", "milkdrink"], "pokeball": "cherishball"},
],
tier: "New",
},
raikou: {
randomBattleMoves: ["thunderbolt", "hiddenpowerice", "aurasphere", "calmmind", "substitute", "voltswitch", "extrasensory"],
randomDoubleBattleMoves: ["thunderbolt", "hiddenpowerice", "extrasensory", "calmmind", "substitute", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["thundershock", "roar", "quickattack", "spark"]},
{"generation": 3, "level": 70, "moves":["quickattack", "spark", "reflect", "crunch"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "quickattack", "spark", "reflect"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Rash", "moves":["zapcannon", "aurasphere", "extremespeed", "weatherball"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["spark", "reflect", "crunch", "thunderfang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
entei: {
randomBattleMoves: ["extremespeed", "flareblitz", "bulldoze", "stoneedge", "sacredfire"],
randomDoubleBattleMoves: ["extremespeed", "flareblitz", "ironhead", "bulldoze", "stoneedge", "sacredfire", "protect"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["ember", "roar", "firespin", "stomp"]},
{"generation": 3, "level": 70, "moves":["firespin", "stomp", "flamethrower", "swagger"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["roar", "firespin", "stomp", "flamethrower"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Adamant", "moves":["flareblitz", "howl", "extremespeed", "crushclaw"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["stomp", "flamethrower", "swagger", "firefang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
suicune: {
randomBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "rest", "sleeptalk", "calmmind"],
randomDoubleBattleMoves: ["hydropump", "icebeam", "scald", "hiddenpowergrass", "snarl", "tailwind", "protect", "calmmind"],
eventPokemon: [
{"generation": 3, "level": 50, "shiny": 1, "moves":["bubblebeam", "raindance", "gust", "aurorabeam"]},
{"generation": 3, "level": 70, "moves":["gust", "aurorabeam", "mist", "mirrorcoat"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["raindance", "gust", "aurorabeam", "mist"]},
{"generation": 4, "level": 30, "shiny": true, "nature": "Relaxed", "moves":["sheercold", "airslash", "extremespeed", "aquaring"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["aurorabeam", "mist", "mirrorcoat", "icefang"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
larvitar: {
randomBattleMoves: ["earthquake", "stoneedge", "facade", "dragondance", "superpower", "crunch"],
eventPokemon: [
{"generation": 3, "level": 20, "moves":["sandstorm", "dragondance", "bite", "outrage"]},
{"generation": 5, "level": 5, "shiny": true, "gender": "M", "isHidden": false, "moves":["bite", "leer", "sandstorm", "superpower"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
pupitar: {
randomBattleMoves: ["earthquake", "stoneedge", "crunch", "dragondance", "superpower", "stealthrock"],
tier: "Bank-NFE",
},
tyranitar: {
randomBattleMoves: ["crunch", "stoneedge", "pursuit", "earthquake", "fireblast", "icebeam", "stealthrock"],
randomDoubleBattleMoves: ["crunch", "stoneedge", "rockslide", "earthquake", "firepunch", "icepunch", "stealthrock", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["thrash", "scaryface", "crunch", "earthquake"]},
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "icebeam", "stoneedge", "crunch"], "pokeball": "cherishball"},
{"generation": 5, "level": 55, "gender": "M", "isHidden": true, "moves":["payback", "crunch", "earthquake", "seismictoss"]},
{"generation": 6, "level": 50, "isHidden": false, "moves":["stoneedge", "crunch", "earthquake", "icepunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Jolly", "isHidden": false, "moves":["rockslide", "earthquake", "crunch", "stoneedge"], "pokeball": "cherishball"},
{"generation": 6, "level": 55, "shiny": true, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 0}, "isHidden": false, "moves":["crunch", "rockslide", "lowkick", "protect"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": false, "moves":["rockslide", "crunch", "icepunch", "lowkick"], "pokeball": "cherishball"},
],
tier: "Bank",
},
tyranitarmega: {
randomBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance"],
randomDoubleBattleMoves: ["crunch", "stoneedge", "earthquake", "icepunch", "dragondance", "rockslide", "protect"],
requiredItem: "Tyranitarite",
tier: "Bank",
},
lugia: {
randomBattleMoves: ["toxic", "roost", "substitute", "whirlwind", "thunderwave", "dragontail", "aeroblast"],
randomDoubleBattleMoves: ["aeroblast", "roost", "substitute", "tailwind", "icebeam", "psychic", "calmmind", "skydrop", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "hydropump", "raindance", "swift"]},
{"generation": 3, "level": 50, "moves":["psychoboost", "earthquake", "hydropump", "featherdance"]},
{"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "raindance", "hydropump", "aeroblast"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["aeroblast", "punishment", "ancientpower", "safeguard"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["raindance", "hydropump", "aeroblast", "punishment"]},
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "moves":["aeroblast", "hydropump", "dragonrush", "icebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
hooh: {
randomBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "flamecharge"],
randomDoubleBattleMoves: ["substitute", "sacredfire", "bravebird", "earthquake", "roost", "toxic", "tailwind", "skydrop", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["recover", "fireblast", "sunnyday", "swift"]},
{"generation": 4, "level": 45, "shiny": 1, "moves":["extrasensory", "sunnyday", "fireblast", "sacredfire"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["sacredfire", "punishment", "ancientpower", "safeguard"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["whirlwind", "weatherball"], "pokeball": "dreamball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["sunnyday", "fireblast", "sacredfire", "punishment"]},
{"generation": 6, "level": 50, "shiny": true, "isHidden": false, "moves":["sacredfire", "bravebird", "recover", "celebrate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
celebi: {
randomBattleMoves: ["nastyplot", "psychic", "gigadrain", "recover", "healbell", "batonpass", "earthpower", "hiddenpowerfire", "leafstorm", "uturn", "thunderwave"],
randomDoubleBattleMoves: ["protect", "psychic", "gigadrain", "leechseed", "recover", "earthpower", "hiddenpowerfire", "nastyplot", "leafstorm", "uturn", "thunderwave"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["confusion", "recover", "healbell", "safeguard"]},
{"generation": 3, "level": 70, "moves":["ancientpower", "futuresight", "batonpass", "perishsong"]},
{"generation": 3, "level": 10, "moves":["leechseed", "recover", "healbell", "safeguard"]},
{"generation": 3, "level": 30, "moves":["healbell", "safeguard", "ancientpower", "futuresight"]},
{"generation": 4, "level": 50, "moves":["leafstorm", "recover", "nastyplot", "healingwish"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "moves":["recover", "healbell", "safeguard", "holdback"], "pokeball": "luxuryball"},
{"generation": 6, "level": 100, "moves":["confusion", "recover", "healbell", "safeguard"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
treecko: {
randomBattleMoves: ["substitute", "leechseed", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["pound", "leer", "absorb"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "leer", "absorb"]},
],
tier: "Bank-LC",
},
grovyle: {
randomBattleMoves: ["substitute", "leechseed", "gigadrain", "leafstorm", "hiddenpowerice", "hiddenpowerrock", "endeavor"],
tier: "Bank-NFE",
},
sceptile: {
randomBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "hiddenpowerfire", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["leafstorm", "dragonpulse", "focusblast", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
sceptilemega: {
randomBattleMoves: ["substitute", "gigadrain", "dragonpulse", "focusblast", "swordsdance", "outrage", "leafblade", "earthquake", "hiddenpowerfire"],
randomDoubleBattleMoves: ["substitute", "gigadrain", "leafstorm", "hiddenpowerice", "focusblast", "dragonpulse", "hiddenpowerfire", "protect"],
requiredItem: "Sceptilite",
tier: "Bank",
},
torchic: {
randomBattleMoves: ["protect", "batonpass", "substitute", "hiddenpowergrass", "swordsdance", "firepledge"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "growl", "focusenergy", "ember"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"]},
{"generation": 6, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "growl", "focusenergy", "ember"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
combusken: {
randomBattleMoves: ["flareblitz", "skyuppercut", "protect", "swordsdance", "substitute", "batonpass", "shadowclaw"],
tier: "Bank",
},
blaziken: {
randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"],
eventPokemon: [
{"generation": 3, "level": 70, "moves":["blazekick", "slash", "mirrormove", "skyuppercut"]},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["flareblitz", "highjumpkick", "thunderpunch", "stoneedge"], "pokeball": "cherishball"},
],
tier: "Bank-Uber",
},
blazikenmega: {
randomBattleMoves: ["flareblitz", "highjumpkick", "protect", "swordsdance", "substitute", "batonpass", "stoneedge", "knockoff"],
requiredItem: "Blazikenite",
tier: "Bank-Uber",
},
mudkip: {
randomBattleMoves: ["hydropump", "earthpower", "hiddenpowerelectric", "icebeam", "sludgewave"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["tackle", "growl", "mudslap", "watergun"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "growl", "mudslap", "watergun"]},
],
tier: "Bank-LC",
},
marshtomp: {
randomBattleMoves: ["waterfall", "earthquake", "superpower", "icepunch", "rockslide", "stealthrock"],
tier: "Bank-NFE",
},
swampert: {
randomBattleMoves: ["stealthrock", "earthquake", "scald", "icebeam", "roar", "toxic", "protect"],
randomDoubleBattleMoves: ["waterfall", "earthquake", "icebeam", "stealthrock", "wideguard", "scald", "rockslide", "muddywater", "protect", "icywind"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthquake", "icebeam", "hydropump", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
swampertmega: {
randomBattleMoves: ["raindance", "waterfall", "earthquake", "icepunch", "superpower"],
randomDoubleBattleMoves: ["waterfall", "earthquake", "raindance", "icepunch", "superpower", "protect"],
requiredItem: "Swampertite",
tier: "Bank",
},
poochyena: {
randomBattleMoves: ["superfang", "foulplay", "suckerpunch", "toxic", "crunch", "firefang", "icefang", "poisonfang"],
eventPokemon: [
{"generation": 3, "level": 10, "abilities":["runaway"], "moves":["healbell", "dig", "poisonfang", "howl"]},
],
tier: "Bank-LC",
},
mightyena: {
randomBattleMoves: ["crunch", "suckerpunch", "playrough", "firefang", "irontail"],
randomDoubleBattleMoves: ["suckerpunch", "crunch", "playrough", "firefang", "taunt", "protect"],
tier: "Bank",
},
zigzagoon: {
randomBattleMoves: ["trick", "thunderwave", "icebeam", "thunderbolt", "gunkshot", "lastresort"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": true, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pickup"], "moves":["tackle", "growl", "tailwhip", "extremespeed"]},
],
tier: "Bank-LC",
},
linoone: {
randomBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "shadowclaw"],
randomDoubleBattleMoves: ["bellydrum", "extremespeed", "seedbomb", "protect", "shadowclaw"],
eventPokemon: [
{"generation": 6, "level": 50, "isHidden": false, "moves":["extremespeed", "helpinghand", "babydolleyes", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
wurmple: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-LC",
},
silcoon: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-NFE",
},
beautifly: {
randomBattleMoves: ["quiverdance", "bugbuzz", "aircutter", "psychic", "gigadrain", "hiddenpowerrock"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "gigadrain", "hiddenpowerrock", "aircutter", "tailwind", "stringshot", "protect"],
tier: "Bank",
},
cascoon: {
randomBattleMoves: ["bugbite", "poisonsting", "tackle", "electroweb"],
tier: "Bank-NFE",
},
dustox: {
randomBattleMoves: ["roost", "defog", "bugbuzz", "sludgebomb", "quiverdance", "uturn", "shadowball"],
randomDoubleBattleMoves: ["tailwind", "stringshot", "strugglebug", "bugbuzz", "protect", "sludgebomb", "quiverdance", "shadowball"],
tier: "Bank",
},
lotad: {
randomBattleMoves: ["gigadrain", "icebeam", "scald", "naturepower", "raindance"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "growl", "absorb"]},
],
tier: "Bank-LC",
},
lombre: {
randomBattleMoves: ["fakeout", "swordsdance", "waterfall", "seedbomb", "icepunch", "firepunch", "thunderpunch", "poweruppunch", "gigadrain", "icebeam"],
tier: "Bank-NFE",
},
ludicolo: {
randomBattleMoves: ["raindance", "hydropump", "scald", "gigadrain", "icebeam", "focusblast"],
randomDoubleBattleMoves: ["raindance", "hydropump", "surf", "gigadrain", "icebeam", "fakeout", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["swiftswim"], "moves":["fakeout", "hydropump", "icebeam", "gigadrain"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "M", "nature": "Calm", "isHidden": false, "abilities":["swiftswim"], "moves":["scald", "gigadrain", "icebeam", "sunnyday"]},
],
tier: "Bank",
},
seedot: {
randomBattleMoves: ["defog", "naturepower", "seedbomb", "explosion", "foulplay"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["bide", "harden", "growth"]},
{"generation": 3, "level": 17, "moves":["refresh", "gigadrain", "bulletseed", "secretpower"]},
],
tier: "Bank-LC",
},
nuzleaf: {
randomBattleMoves: ["naturepower", "seedbomb", "explosion", "swordsdance", "rockslide", "lowsweep"],
tier: "Bank-NFE",
},
shiftry: {
randomBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "defog", "lowkick", "knockoff"],
randomDoubleBattleMoves: ["leafstorm", "swordsdance", "leafblade", "suckerpunch", "knockoff", "lowkick", "fakeout", "protect"],
tier: "Bank",
},
taillow: {
randomBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "focusenergy", "featherdance"]},
],
tier: "Bank-LC",
},
swellow: {
randomBattleMoves: ["protect", "facade", "bravebird", "uturn", "quickattack"],
randomDoubleBattleMoves: ["bravebird", "facade", "quickattack", "uturn", "protect"],
eventPokemon: [
{"generation": 3, "level": 43, "moves":["batonpass", "skyattack", "agility", "facade"]},
],
tier: "Bank",
},
wingull: {
randomBattleMoves: ["scald", "icebeam", "tailwind", "uturn", "airslash", "knockoff", "defog"],
tier: "LC",
},
pelipper: {
randomBattleMoves: ["scald", "uturn", "hurricane", "toxic", "roost", "defog", "knockoff"],
randomDoubleBattleMoves: ["scald", "surf", "hurricane", "wideguard", "protect", "tailwind", "knockoff"],
tier: "New",
},
ralts: {
randomBattleMoves: ["trickroom", "destinybond", "psychic", "willowisp", "hypnosis", "dazzlinggleam", "substitute", "trick"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "charm"]},
{"generation": 3, "level": 20, "moves":["sing", "shockwave", "reflect", "confusion"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["growl", "encore"]},
],
tier: "Bank-LC",
},
kirlia: {
randomBattleMoves: ["trick", "dazzlinggleam", "psychic", "willowisp", "signalbeam", "thunderbolt", "destinybond", "substitute"],
tier: "Bank-NFE",
},
gardevoir: {
randomBattleMoves: ["psychic", "thunderbolt", "focusblast", "shadowball", "moonblast", "calmmind", "substitute", "willowisp"],
randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "moonblast", "taunt", "willowisp", "thunderbolt", "trickroom", "helpinghand", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "abilities":["trace"], "moves":["hypnosis", "thunderbolt", "focusblast", "psychic"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": true, "gender": "F", "isHidden": false, "abilities":["synchronize"], "moves":["dazzlinggleam", "moonblast", "storedpower", "calmmind"], "pokeball": "cherishball"},
],
tier: "Bank",
},
gardevoirmega: {
randomBattleMoves: ["calmmind", "hypervoice", "psyshock", "focusblast", "substitute", "taunt", "willowisp"],
randomDoubleBattleMoves: ["psyshock", "focusblast", "shadowball", "calmmind", "thunderbolt", "hypervoice", "protect"],
requiredItem: "Gardevoirite",
tier: "Bank",
},
gallade: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "shadowsneak", "closecombat", "zenheadbutt", "knockoff", "trick"],
randomDoubleBattleMoves: ["closecombat", "trick", "stoneedge", "shadowsneak", "drainpunch", "icepunch", "zenheadbutt", "knockoff", "trickroom", "protect", "helpinghand"],
tier: "Bank",
},
gallademega: {
randomBattleMoves: ["swordsdance", "closecombat", "drainpunch", "knockoff", "zenheadbutt", "substitute"],
randomDoubleBattleMoves: ["closecombat", "stoneedge", "drainpunch", "icepunch", "zenheadbutt", "swordsdance", "knockoff", "protect"],
requiredItem: "Galladite",
tier: "Bank",
},
surskit: {
randomBattleMoves: ["hydropump", "signalbeam", "hiddenpowerfire", "stickyweb", "gigadrain", "powersplit"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "mudsport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["bubble", "quickattack"]},
],
tier: "LC",
},
masquerain: {
randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "hydropump", "roost", "batonpass", "stickyweb"],
randomDoubleBattleMoves: ["hydropump", "bugbuzz", "airslash", "quiverdance", "tailwind", "roost", "strugglebug", "protect"],
tier: "New",
},
shroomish: {
randomBattleMoves: ["spore", "substitute", "leechseed", "gigadrain", "protect", "toxic", "stunspore"],
eventPokemon: [
{"generation": 3, "level": 15, "abilities":["effectspore"], "moves":["refresh", "falseswipe", "megadrain", "stunspore"]},
],
tier: "Bank-LC",
},
breloom: {
randomBattleMoves: ["spore", "machpunch", "bulletseed", "rocktomb", "swordsdance"],
randomDoubleBattleMoves: ["spore", "helpinghand", "machpunch", "bulletseed", "rocktomb", "protect", "drainpunch"],
tier: "Bank",
},
slakoth: {
randomBattleMoves: ["doubleedge", "hammerarm", "firepunch", "counter", "retaliate", "toxic"],
tier: "LC",
},
vigoroth: {
randomBattleMoves: ["bulkup", "return", "earthquake", "firepunch", "suckerpunch", "slackoff", "icepunch", "lowkick"],
tier: "New",
},
slaking: {
randomBattleMoves: ["earthquake", "pursuit", "nightslash", "doubleedge", "retaliate"],
randomDoubleBattleMoves: ["earthquake", "nightslash", "doubleedge", "retaliate", "hammerarm", "rockslide"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Adamant", "moves":["gigaimpact", "return", "shadowclaw", "aerialace"], "pokeball": "cherishball"},
],
tier: "New",
},
nincada: {
randomBattleMoves: ["xscissor", "dig", "aerialace", "nightslash"],
tier: "Bank-LC",
},
ninjask: {
randomBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "xscissor"],
randomDoubleBattleMoves: ["batonpass", "swordsdance", "substitute", "protect", "xscissor", "aerialace"],
tier: "Bank",
},
shedinja: {
randomBattleMoves: ["swordsdance", "willowisp", "xscissor", "shadowsneak", "shadowclaw", "batonpass"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["spite", "confuseray", "shadowball", "grudge"]},
{"generation": 3, "level": 20, "moves":["doubleteam", "furycutter", "screech"]},
{"generation": 3, "level": 25, "moves":["swordsdance"]},
{"generation": 3, "level": 31, "moves":["slash"]},
{"generation": 3, "level": 38, "moves":["agility"]},
{"generation": 3, "level": 45, "moves":["batonpass"]},
{"generation": 4, "level": 52, "moves":["xscissor"]},
],
tier: "Bank",
},
whismur: {
randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "extrasensory"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["pound", "uproar", "teeterdance"]},
],
tier: "Bank-LC",
},
loudred: {
randomBattleMoves: ["hypervoice", "fireblast", "shadowball", "icebeam", "circlethrow", "bodyslam"],
tier: "Bank-NFE",
},
exploud: {
randomBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast"],
randomDoubleBattleMoves: ["boomburst", "fireblast", "icebeam", "surf", "focusblast", "protect", "hypervoice"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["roar", "rest", "sleeptalk", "hypervoice"]},
{"generation": 3, "level": 50, "moves":["stomp", "screech", "hyperbeam", "roar"]},
],
tier: "Bank",
},
makuhita: {
randomBattleMoves: ["crosschop", "bulletpunch", "closecombat", "icepunch", "bulkup", "fakeout", "earthquake"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["refresh", "brickbreak", "armthrust", "rocktomb"]},
],
tier: "LC",
},
hariyama: {
randomBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["bulletpunch", "closecombat", "icepunch", "stoneedge", "fakeout", "knockoff", "helpinghand", "wideguard", "protect"],
tier: "New",
},
nosepass: {
randomBattleMoves: ["powergem", "thunderwave", "stealthrock", "painsplit", "explosion", "voltswitch"],
eventPokemon: [
{"generation": 3, "level": 26, "moves":["helpinghand", "thunderbolt", "thunderwave", "rockslide"]},
],
tier: "LC",
},
probopass: {
randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "flashcannon", "powergem", "voltswitch", "painsplit"],
randomDoubleBattleMoves: ["stealthrock", "thunderwave", "helpinghand", "earthpower", "powergem", "wideguard", "protect", "voltswitch"],
tier: "New",
},
skitty: {
randomBattleMoves: ["doubleedge", "zenheadbutt", "thunderwave", "fakeout", "playrough", "healbell"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["tackle", "growl", "tailwhip", "payday"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "rollout"]},
{"generation": 3, "level": 10, "gender": "M", "abilities":["cutecharm"], "moves":["growl", "tackle", "tailwhip", "attract"]},
],
tier: "Bank-LC",
},
delcatty: {
randomBattleMoves: ["doubleedge", "suckerpunch", "wildcharge", "fakeout", "thunderwave", "healbell"],
randomDoubleBattleMoves: ["doubleedge", "suckerpunch", "playrough", "wildcharge", "fakeout", "thunderwave", "protect", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 18, "abilities":["cutecharm"], "moves":["sweetkiss", "secretpower", "attract", "shockwave"]},
],
tier: "Bank",
},
sableye: {
randomBattleMoves: ["recover", "willowisp", "taunt", "toxic", "knockoff", "foulplay"],
randomDoubleBattleMoves: ["recover", "willowisp", "taunt", "fakeout", "knockoff", "foulplay", "helpinghand", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "abilities":["keeneye"], "moves":["leer", "scratch", "foresight", "nightshade"]},
{"generation": 3, "level": 33, "abilities":["keeneye"], "moves":["helpinghand", "shadowball", "feintattack", "recover"]},
{"generation": 5, "level": 50, "gender": "M", "isHidden": true, "moves":["foulplay", "octazooka", "tickle", "trick"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "nature": "Relaxed", "ivs": {"hp": 31, "spa": 31}, "isHidden": true, "moves":["calmmind", "willowisp", "recover", "shadowball"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Bold", "isHidden": true, "moves":["willowisp", "recover", "taunt", "shockwave"], "pokeball": "cherishball"},
],
tier: "New",
},
sableyemega: {
randomBattleMoves: ["recover", "willowisp", "darkpulse", "calmmind", "shadowball"],
randomDoubleBattleMoves: ["fakeout", "knockoff", "darkpulse", "shadowball", "willowisp", "protect"],
requiredItem: "Sablenite",
tier: "New",
},
mawile: {
randomBattleMoves: ["swordsdance", "ironhead", "substitute", "playrough", "suckerpunch", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["astonish", "faketears"]},
{"generation": 3, "level": 22, "moves":["sing", "falseswipe", "vicegrip", "irondefense"]},
{"generation": 6, "level": 50, "isHidden": false, "abilities":["intimidate"], "moves":["ironhead", "playrough", "firefang", "suckerpunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": false, "abilities":["intimidate"], "moves":["suckerpunch", "protect", "playrough", "ironhead"], "pokeball": "cherishball"},
],
tier: "Bank",
},
mawilemega: {
randomBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "focuspunch"],
randomDoubleBattleMoves: ["swordsdance", "ironhead", "firefang", "substitute", "playrough", "suckerpunch", "knockoff", "protect"],
requiredItem: "Mawilite",
tier: "Bank",
},
aron: {
randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock", "endeavor"],
tier: "Bank-LC",
},
lairon: {
randomBattleMoves: ["headsmash", "ironhead", "earthquake", "superpower", "stealthrock"],
tier: "Bank-NFE",
},
aggron: {
randomBattleMoves: ["autotomize", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock"],
randomDoubleBattleMoves: ["rockslide", "headsmash", "earthquake", "lowkick", "heavyslam", "aquatail", "stealthrock", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["irontail", "protect", "metalsound", "doubleedge"]},
{"generation": 3, "level": 50, "moves":["takedown", "irontail", "protect", "metalsound"]},
{"generation": 6, "level": 50, "nature": "Brave", "isHidden": false, "abilities":["rockhead"], "moves":["ironhead", "earthquake", "headsmash", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
aggronmega: {
randomBattleMoves: ["earthquake", "heavyslam", "icepunch", "stealthrock", "thunderwave", "roar", "toxic"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "lowkick", "heavyslam", "aquatail", "protect"],
requiredItem: "Aggronite",
tier: "Bank",
},
meditite: {
randomBattleMoves: ["highjumpkick", "psychocut", "icepunch", "thunderpunch", "trick", "fakeout", "bulletpunch", "drainpunch", "zenheadbutt"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["bide", "meditate", "confusion"]},
{"generation": 3, "level": 20, "moves":["dynamicpunch", "confusion", "shadowball", "detect"]},
],
tier: "Bank",
},
medicham: {
randomBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch"],
randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"],
tier: "Bank",
},
medichammega: {
randomBattleMoves: ["highjumpkick", "drainpunch", "icepunch", "fakeout", "zenheadbutt"],
randomDoubleBattleMoves: ["highjumpkick", "drainpunch", "zenheadbutt", "icepunch", "bulletpunch", "protect", "fakeout"],
requiredItem: "Medichamite",
tier: "Bank",
},
electrike: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "switcheroo", "flamethrower", "hiddenpowergrass"],
tier: "Bank-LC",
},
manectric: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"],
eventPokemon: [
{"generation": 3, "level": 44, "moves":["refresh", "thunder", "raindance", "bite"]},
{"generation": 6, "level": 50, "nature": "Timid", "isHidden": false, "abilities":["lightningrod"], "moves":["overheat", "thunderbolt", "voltswitch", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
manectricmega: {
randomBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "hiddenpowerice", "hiddenpowergrass", "overheat", "flamethrower", "snarl", "protect"],
requiredItem: "Manectite",
tier: "Bank",
},
plusle: {
randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "mudsport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]},
],
tier: "Bank",
},
minun: {
randomBattleMoves: ["nastyplot", "thunderbolt", "substitute", "batonpass", "hiddenpowerice", "encore"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "substitute", "protect", "hiddenpowerice", "encore", "helpinghand"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["growl", "thunderwave", "watersport"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["growl", "thunderwave", "quickattack"]},
],
tier: "Bank",
},
volbeat: {
randomBattleMoves: ["tailglow", "batonpass", "substitute", "bugbuzz", "thunderwave", "encore", "tailwind"],
randomDoubleBattleMoves: ["stringshot", "strugglebug", "helpinghand", "bugbuzz", "thunderwave", "encore", "tailwind", "protect"],
tier: "Bank",
},
illumise: {
randomBattleMoves: ["substitute", "batonpass", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn", "thunderwave"],
randomDoubleBattleMoves: ["protect", "helpinghand", "bugbuzz", "encore", "thunderbolt", "tailwind", "uturn"],
tier: "Bank",
},
budew: {
randomBattleMoves: ["spikes", "sludgebomb", "sleeppowder", "gigadrain", "stunspore", "rest"],
tier: "LC",
},
roselia: {
randomBattleMoves: ["spikes", "toxicspikes", "sleeppowder", "gigadrain", "stunspore", "rest", "sludgebomb", "synthesis"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["absorb", "growth", "poisonsting"]},
{"generation": 3, "level": 22, "moves":["sweetkiss", "magicalleaf", "leechseed", "grasswhistle"]},
],
tier: "New",
},
roserade: {
randomBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "spikes", "toxicspikes", "rest", "synthesis", "hiddenpowerfire"],
randomDoubleBattleMoves: ["sludgebomb", "gigadrain", "sleeppowder", "leafstorm", "protect", "hiddenpowerfire"],
tier: "New",
},
gulpin: {
randomBattleMoves: ["stockpile", "sludgebomb", "sludgewave", "icebeam", "toxic", "painsplit", "yawn", "encore"],
eventPokemon: [
{"generation": 3, "level": 17, "moves":["sing", "shockwave", "sludge", "toxic"]},
],
tier: "Bank-LC",
},
swalot: {
randomBattleMoves: ["sludgebomb", "icebeam", "toxic", "yawn", "encore", "painsplit", "earthquake"],
randomDoubleBattleMoves: ["sludgebomb", "icebeam", "protect", "yawn", "encore", "gunkshot", "earthquake"],
tier: "Bank",
},
carvanha: {
randomBattleMoves: ["protect", "hydropump", "icebeam", "waterfall", "crunch", "aquajet", "destinybond"],
eventPokemon: [
{"generation": 3, "level": 15, "moves":["refresh", "waterpulse", "bite", "scaryface"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["leer", "bite", "hydropump"]},
],
tier: "LC",
},
sharpedo: {
randomBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall", "destinybond"],
randomDoubleBattleMoves: ["protect", "icebeam", "crunch", "earthquake", "waterfall", "destinybond"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "isHidden": true, "moves":["aquajet", "crunch", "icefang", "destinybond"], "pokeball": "cherishball"},
{"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "moves":["scaryface", "slash", "poisonfang", "crunch"], "pokeball": "cherishball"},
],
tier: "New",
},
sharpedomega: {
randomBattleMoves: ["protect", "icefang", "crunch", "earthquake", "waterfall", "zenheadbutt"],
requiredItem: "Sharpedonite",
tier: "New",
},
wailmer: {
randomBattleMoves: ["waterspout", "surf", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerelectric"],
tier: "LC",
},
wailord: {
randomBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire"],
randomDoubleBattleMoves: ["waterspout", "hydropump", "icebeam", "hiddenpowergrass", "hiddenpowerfire", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["rest", "waterspout", "amnesia", "hydropump"]},
{"generation": 3, "level": 50, "moves":["waterpulse", "mist", "rest", "waterspout"]},
],
tier: "New",
},
numel: {
randomBattleMoves: ["curse", "earthquake", "rockslide", "fireblast", "flamecharge", "rest", "sleeptalk", "stockpile", "hiddenpowerelectric", "earthpower", "lavaplume"],
eventPokemon: [
{"generation": 3, "level": 14, "abilities":["oblivious"], "moves":["charm", "takedown", "dig", "ember"]},
{"generation": 6, "level": 1, "isHidden": false, "moves":["growl", "tackle", "ironhead"]},
],
tier: "Bank-LC",
},
camerupt: {
randomBattleMoves: ["rockpolish", "fireblast", "earthpower", "lavaplume", "stealthrock", "hiddenpowergrass", "roar", "stoneedge"],
randomDoubleBattleMoves: ["rockpolish", "fireblast", "earthpower", "heatwave", "eruption", "hiddenpowergrass", "protect"],
eventPokemon: [
{"generation": 6, "level": 43, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["solidrock"], "moves":["curse", "takedown", "rockslide", "yawn"], "pokeball": "cherishball"},
],
tier: "Bank",
},
cameruptmega: {
randomBattleMoves: ["stealthrock", "fireblast", "earthpower", "ancientpower", "willowisp", "toxic"],
randomDoubleBattleMoves: ["fireblast", "earthpower", "heatwave", "eruption", "rockslide", "protect"],
requiredItem: "Cameruptite",
tier: "Bank",
},
torkoal: {
randomBattleMoves: ["shellsmash", "fireblast", "earthpower", "hiddenpowergrass", "stealthrock", "rapidspin", "yawn", "lavaplume"],
randomDoubleBattleMoves: ["protect", "heatwave", "earthpower", "willowisp", "shellsmash", "fireblast", "hiddenpowergrass"],
tier: "New",
},
spoink: {
randomBattleMoves: ["psychic", "reflect", "lightscreen", "thunderwave", "trick", "healbell", "calmmind", "hiddenpowerfighting", "shadowball"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["owntempo"], "moves":["splash", "uproar"]},
],
tier: "Bank-LC",
},
grumpig: {
randomBattleMoves: ["psychic", "thunderwave", "healbell", "whirlwind", "toxic", "focusblast", "reflect", "lightscreen"],
randomDoubleBattleMoves: ["psychic", "psyshock", "thunderwave", "trickroom", "taunt", "protect", "focusblast", "reflect", "lightscreen"],
tier: "Bank",
},
spinda: {
randomBattleMoves: ["return", "superpower", "suckerpunch", "trickroom"],
randomDoubleBattleMoves: ["doubleedge", "return", "superpower", "suckerpunch", "trickroom", "fakeout", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["tackle", "uproar", "sing"]},
],
tier: "New",
},
trapinch: {
randomBattleMoves: ["earthquake", "rockslide", "crunch", "quickattack", "superpower"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["bite"]},
],
tier: "LC",
},
vibrava: {
randomBattleMoves: ["substitute", "earthquake", "outrage", "roost", "uturn", "superpower", "defog"],
tier: "NFE",
},
flygon: {
randomBattleMoves: ["earthquake", "outrage", "uturn", "roost", "stoneedge", "firepunch", "fireblast", "defog"],
randomDoubleBattleMoves: ["earthquake", "protect", "dragonclaw", "uturn", "rockslide", "firepunch", "fireblast", "tailwind", "feint"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["sandtomb", "crunch", "dragonbreath", "screech"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naive", "moves":["dracometeor", "uturn", "earthquake", "dragonclaw"], "pokeball": "cherishball"},
],
tier: "New",
},
cacnea: {
randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["poisonsting", "leer", "absorb", "encore"]},
],
tier: "Bank-LC",
},
cacturne: {
randomBattleMoves: ["swordsdance", "spikes", "suckerpunch", "seedbomb", "drainpunch", "substitute"],
randomDoubleBattleMoves: ["swordsdance", "spikyshield", "suckerpunch", "seedbomb", "drainpunch", "substitute"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["ingrain", "feintattack", "spikes", "needlearm"]},
],
tier: "Bank",
},
swablu: {
randomBattleMoves: ["roost", "toxic", "cottonguard", "pluck", "hypervoice", "return"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["peck", "growl", "falseswipe"]},
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["peck", "growl"]},
{"generation": 6, "level": 1, "isHidden": true, "moves":["peck", "growl", "hypervoice"]},
],
tier: "Bank-LC",
},
altaria: {
randomBattleMoves: ["dragondance", "dracometeor", "outrage", "dragonclaw", "earthquake", "roost", "fireblast", "healbell"],
randomDoubleBattleMoves: ["dragondance", "dracometeor", "protect", "dragonclaw", "earthquake", "fireblast", "tailwind"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["takedown", "dragonbreath", "dragondance", "refresh"]},
{"generation": 3, "level": 36, "moves":["healbell", "dragonbreath", "solarbeam", "aerialace"]},
{"generation": 5, "level": 35, "gender": "M", "isHidden": true, "moves":["takedown", "naturalgift", "dragonbreath", "falseswipe"]},
{"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["hypervoice", "fireblast", "protect", "agility"], "pokeball": "cherishball"},
],
tier: "Bank",
},
altariamega: {
randomBattleMoves: ["dragondance", "return", "hypervoice", "healbell", "earthquake", "roost", "dracometeor", "fireblast"],
randomDoubleBattleMoves: ["dragondance", "return", "doubleedge", "dragonclaw", "earthquake", "protect", "fireblast"],
requiredItem: "Altarianite",
tier: "Bank",
},
zangoose: {
randomBattleMoves: ["swordsdance", "closecombat", "knockoff", "quickattack", "facade"],
randomDoubleBattleMoves: ["protect", "closecombat", "knockoff", "quickattack", "facade"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["leer", "quickattack", "swordsdance", "furycutter"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["scratch", "leer", "quickattack", "swordsdance"]},
{"generation": 3, "level": 28, "moves":["refresh", "brickbreak", "counter", "crushclaw"]},
],
tier: "Bank",
},
seviper: {
randomBattleMoves: ["flamethrower", "sludgewave", "gigadrain", "darkpulse", "switcheroo", "coil", "earthquake", "poisonjab", "suckerpunch"],
randomDoubleBattleMoves: ["flamethrower", "gigadrain", "earthquake", "suckerpunch", "aquatail", "protect", "glare", "poisonjab", "sludgebomb"],
eventPokemon: [
{"generation": 3, "level": 18, "moves":["wrap", "lick", "bite", "poisontail"]},
{"generation": 3, "level": 30, "moves":["poisontail", "screech", "glare", "crunch"]},
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "lick", "bite"]},
],
tier: "Bank",
},
lunatone: {
randomBattleMoves: ["psychic", "earthpower", "stealthrock", "rockpolish", "batonpass", "calmmind", "icebeam", "ancientpower", "moonlight", "toxic"],
randomDoubleBattleMoves: ["psychic", "earthpower", "rockpolish", "calmmind", "helpinghand", "icebeam", "ancientpower", "moonlight", "trickroom", "protect"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]},
{"generation": 3, "level": 25, "moves":["batonpass", "psychic", "raindance", "rocktomb"]},
],
tier: "Bank",
},
solrock: {
randomBattleMoves: ["stealthrock", "explosion", "rockslide", "reflect", "lightscreen", "willowisp", "morningsun"],
randomDoubleBattleMoves: ["protect", "helpinghand", "stoneedge", "zenheadbutt", "willowisp", "trickroom", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 10, "moves":["tackle", "harden", "confusion"]},
{"generation": 3, "level": 41, "moves":["batonpass", "psychic", "sunnyday", "cosmicpower"]},
],
tier: "Bank",
},
barboach: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "return", "bounce"],
tier: "LC",
},
whiscash: {
randomBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt"],
randomDoubleBattleMoves: ["dragondance", "waterfall", "earthquake", "stoneedge", "zenheadbutt", "protect"],
eventPokemon: [
{"generation": 4, "level": 51, "gender": "F", "nature": "Gentle", "abilities":["oblivious"], "moves":["earthquake", "aquatail", "zenheadbutt", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "New",
},
corphish: {
randomBattleMoves: ["dragondance", "waterfall", "crunch", "superpower", "swordsdance", "knockoff", "aquajet"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["bubble", "watersport"]},
],
tier: "Bank-LC",
},
crawdaunt: {
randomBattleMoves: ["dragondance", "crabhammer", "superpower", "swordsdance", "knockoff", "aquajet"],
randomDoubleBattleMoves: ["dragondance", "crabhammer", "crunch", "superpower", "swordsdance", "knockoff", "aquajet", "protect"],
eventPokemon: [
{"generation": 3, "level": 100, "moves":["taunt", "crabhammer", "swordsdance", "guillotine"]},
{"generation": 3, "level": 50, "moves":["knockoff", "taunt", "crabhammer", "swordsdance"]},
],
tier: "Bank",
},
baltoy: {
randomBattleMoves: ["stealthrock", "earthquake", "toxic", "psychic", "reflect", "lightscreen", "icebeam", "rapidspin"],
eventPokemon: [
{"generation": 3, "level": 17, "moves":["refresh", "rocktomb", "mudslap", "psybeam"]},
],
tier: "Bank-LC",
},
claydol: {
randomBattleMoves: ["stealthrock", "toxic", "psychic", "icebeam", "earthquake", "rapidspin"],
randomDoubleBattleMoves: ["earthpower", "trickroom", "psychic", "icebeam", "earthquake", "protect"],
tier: "Bank",
},
lileep: {
randomBattleMoves: ["stealthrock", "recover", "ancientpower", "hiddenpowerfire", "gigadrain", "stockpile"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["recover", "rockslide", "constrict", "acid"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
cradily: {
randomBattleMoves: ["stealthrock", "recover", "gigadrain", "toxic", "seedbomb", "rockslide", "curse"],
randomDoubleBattleMoves: ["protect", "recover", "seedbomb", "rockslide", "earthquake", "curse", "swordsdance"],
tier: "Bank",
},
anorith: {
randomBattleMoves: ["stealthrock", "brickbreak", "toxic", "xscissor", "rockslide", "swordsdance", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["harden", "mudsport", "watergun", "crosspoison"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
armaldo: {
randomBattleMoves: ["stealthrock", "stoneedge", "toxic", "xscissor", "swordsdance", "knockoff", "rapidspin"],
randomDoubleBattleMoves: ["rockslide", "stoneedge", "stringshot", "xscissor", "swordsdance", "knockoff", "protect"],
tier: "Bank",
},
feebas: {
randomBattleMoves: ["protect", "confuseray", "hypnosis", "scald", "toxic"],
eventPokemon: [
{"generation": 4, "level": 5, "gender": "F", "nature": "Calm", "moves":["splash", "mirrorcoat"], "pokeball": "cherishball"},
],
tier: "LC",
},
milotic: {
randomBattleMoves: ["recover", "scald", "toxic", "icebeam", "dragontail", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["recover", "scald", "hydropump", "icebeam", "dragontail", "hypnosis", "protect", "hiddenpowergrass"],
eventPokemon: [
{"generation": 3, "level": 35, "moves":["waterpulse", "twister", "recover", "raindance"]},
{"generation": 4, "level": 50, "gender": "F", "nature": "Bold", "moves":["recover", "raindance", "icebeam", "hydropump"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "shiny": true, "gender": "M", "nature": "Timid", "moves":["raindance", "recover", "hydropump", "icywind"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["recover", "hydropump", "icebeam", "mirrorcoat"], "pokeball": "cherishball"},
{"generation": 5, "level": 58, "gender": "M", "nature": "Lax", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["recover", "surf", "icebeam", "toxic"], "pokeball": "cherishball"},
],
tier: "New",
},
castform: {
tier: "New",
},
castformsunny: {
randomBattleMoves: ["sunnyday", "weatherball", "solarbeam", "icebeam"],
battleOnly: true,
},
castformrainy: {
randomBattleMoves: ["raindance", "weatherball", "thunder", "hurricane"],
battleOnly: true,
},
castformsnowy: {
battleOnly: true,
},
kecleon: {
randomBattleMoves: ["fakeout", "knockoff", "drainpunch", "suckerpunch", "shadowsneak", "stealthrock", "recover"],
randomDoubleBattleMoves: ["knockoff", "fakeout", "trickroom", "recover", "drainpunch", "suckerpunch", "shadowsneak", "protect"],
tier: "Bank",
},
shuppet: {
randomBattleMoves: ["trickroom", "destinybond", "taunt", "shadowsneak", "suckerpunch", "willowisp"],
eventPokemon: [
{"generation": 3, "level": 45, "abilities":["insomnia"], "moves":["spite", "willowisp", "feintattack", "shadowball"]},
],
tier: "Bank-LC",
},
banette: {
randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff"],
randomDoubleBattleMoves: ["shadowclaw", "suckerpunch", "willowisp", "shadowsneak", "knockoff", "protect"],
eventPokemon: [
{"generation": 3, "level": 37, "abilities":["insomnia"], "moves":["helpinghand", "feintattack", "shadowball", "curse"]},
{"generation": 5, "level": 37, "gender": "F", "isHidden": true, "moves":["feintattack", "hex", "shadowball", "cottonguard"]},
],
tier: "Bank",
},
banettemega: {
randomBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff"],
randomDoubleBattleMoves: ["destinybond", "taunt", "shadowclaw", "suckerpunch", "willowisp", "knockoff", "protect"],
requiredItem: "Banettite",
tier: "Bank",
},
duskull: {
randomBattleMoves: ["willowisp", "shadowsneak", "painsplit", "substitute", "nightshade", "destinybond", "trickroom"],
eventPokemon: [
{"generation": 3, "level": 45, "moves":["pursuit", "curse", "willowisp", "meanlook"]},
{"generation": 3, "level": 19, "moves":["helpinghand", "shadowball", "astonish", "confuseray"]},
],
tier: "Bank-LC",
},
dusclops: {
randomBattleMoves: ["willowisp", "shadowsneak", "icebeam", "painsplit", "substitute", "seismictoss", "toxic", "trickroom"],
tier: "Bank-NFE",
},
dusknoir: {
randomBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "substitute", "earthquake", "focuspunch"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "icepunch", "painsplit", "protect", "earthquake", "helpinghand", "trickroom"],
tier: "Bank",
},
tropius: {
randomBattleMoves: ["leechseed", "substitute", "airslash", "gigadrain", "toxic", "protect"],
randomDoubleBattleMoves: ["leechseed", "protect", "airslash", "gigadrain", "earthquake", "hiddenpowerfire", "tailwind", "sunnyday", "roost"],
eventPokemon: [
{"generation": 4, "level": 53, "gender": "F", "nature": "Jolly", "abilities":["chlorophyll"], "moves":["airslash", "synthesis", "sunnyday", "solarbeam"], "pokeball": "cherishball"},
],
tier: "Bank",
},
chingling: {
randomBattleMoves: ["hypnosis", "reflect", "lightscreen", "toxic", "recover", "psychic", "signalbeam", "healbell"],
tier: "Bank-LC",
},
chimecho: {
randomBattleMoves: ["psychic", "yawn", "recover", "calmmind", "shadowball", "healingwish", "healbell", "taunt"],
randomDoubleBattleMoves: ["protect", "psychic", "thunderwave", "recover", "shadowball", "dazzlinggleam", "trickroom", "helpinghand", "taunt"],
eventPokemon: [
{"generation": 3, "level": 10, "gender": "M", "moves":["wrap", "growl", "astonish"]},
],
tier: "Bank",
},
absol: {
randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "superpower", "pursuit", "playrough"],
randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "abilities":["pressure"], "moves":["scratch", "leer", "spite"]},
{"generation": 3, "level": 35, "abilities":["pressure"], "moves":["razorwind", "bite", "swordsdance", "spite"]},
{"generation": 3, "level": 70, "abilities":["pressure"], "moves":["doubleteam", "slash", "futuresight", "perishsong"]},
],
tier: "New",
},
absolmega: {
randomBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "pursuit", "playrough", "icebeam"],
randomDoubleBattleMoves: ["swordsdance", "suckerpunch", "knockoff", "fireblast", "superpower", "protect", "playrough"],
requiredItem: "Absolite",
tier: "New",
},
snorunt: {
randomBattleMoves: ["spikes", "icebeam", "iceshard", "shadowball", "toxic"],
eventPokemon: [
{"generation": 3, "level": 20, "abilities":["innerfocus"], "moves":["sing", "waterpulse", "bite", "icywind"]},
],
tier: "LC",
},
glalie: {
randomBattleMoves: ["spikes", "icebeam", "iceshard", "taunt", "earthquake", "explosion", "superfang"],
randomDoubleBattleMoves: ["icebeam", "iceshard", "taunt", "earthquake", "protect"],
tier: "New",
},
glaliemega: {
randomBattleMoves: ["freezedry", "iceshard", "earthquake", "explosion", "return", "spikes"],
randomDoubleBattleMoves: ["crunch", "iceshard", "freezedry", "earthquake", "explosion", "protect", "return"],
requiredItem: "Glalitite",
tier: "New",
},
froslass: {
randomBattleMoves: ["icebeam", "spikes", "destinybond", "shadowball", "taunt", "thunderwave"],
randomDoubleBattleMoves: ["icebeam", "protect", "destinybond", "shadowball", "taunt", "thunderwave"],
tier: "New",
},
spheal: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"],
eventPokemon: [
{"generation": 3, "level": 17, "abilities":["thickfat"], "moves":["charm", "aurorabeam", "watergun", "mudslap"]},
],
tier: "LC",
},
sealeo: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "yawn", "superfang"],
tier: "NFE",
},
walrein: {
randomBattleMoves: ["substitute", "protect", "toxic", "surf", "icebeam", "roar"],
randomDoubleBattleMoves: ["protect", "icywind", "surf", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 50, "isHidden": false, "abilities":["thickfat"], "moves":["icebeam", "brine", "hail", "sheercold"], "pokeball": "cherishball"},
],
tier: "New",
},
clamperl: {
randomBattleMoves: ["shellsmash", "icebeam", "surf", "hiddenpowergrass", "hiddenpowerelectric", "substitute"],
tier: "Bank-LC",
},
huntail: {
randomBattleMoves: ["shellsmash", "waterfall", "icebeam", "batonpass", "suckerpunch"],
randomDoubleBattleMoves: ["shellsmash", "waterfall", "icefang", "batonpass", "suckerpunch", "protect"],
tier: "Bank",
},
gorebyss: {
randomBattleMoves: ["shellsmash", "batonpass", "hydropump", "icebeam", "hiddenpowergrass", "substitute"],
randomDoubleBattleMoves: ["shellsmash", "batonpass", "surf", "icebeam", "hiddenpowergrass", "substitute", "protect"],
tier: "Bank",
},
relicanth: {
randomBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "stealthrock", "toxic"],
randomDoubleBattleMoves: ["headsmash", "waterfall", "earthquake", "doubleedge", "rockslide", "protect"],
tier: "New",
},
luvdisc: {
randomBattleMoves: ["icebeam", "toxic", "sweetkiss", "protect", "scald"],
tier: "New",
},
bagon: {
randomBattleMoves: ["outrage", "dragondance", "firefang", "rockslide", "dragonclaw"],
eventPokemon: [
{"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "wish"]},
{"generation": 3, "level": 5, "shiny": 1, "moves":["rage", "bite", "irondefense"]},
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["rage"]},
{"generation": 6, "level": 1, "isHidden": false, "moves":["rage", "thrash"]},
],
tier: "LC",
},
shelgon: {
randomBattleMoves: ["outrage", "brickbreak", "dragonclaw", "dragondance", "crunch", "zenheadbutt"],
tier: "NFE",
},
salamence: {
randomBattleMoves: ["outrage", "fireblast", "earthquake", "dracometeor", "dragondance", "dragonclaw"],
randomDoubleBattleMoves: ["protect", "fireblast", "earthquake", "dracometeor", "tailwind", "dragondance", "dragonclaw", "hydropump", "rockslide"],
eventPokemon: [
{"generation": 3, "level": 50, "moves":["protect", "dragonbreath", "scaryface", "fly"]},
{"generation": 3, "level": 50, "moves":["refresh", "dragonclaw", "dragondance", "aerialace"]},
{"generation": 4, "level": 50, "gender": "M", "nature": "Naughty", "moves":["hydropump", "stoneedge", "fireblast", "dragonclaw"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["dragondance", "dragonclaw", "outrage", "aerialace"], "pokeball": "cherishball"},
],
tier: "New",
},
salamencemega: {
randomBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "roost", "dragondance"],
randomDoubleBattleMoves: ["doubleedge", "return", "fireblast", "earthquake", "dracometeor", "protect", "dragondance", "dragonclaw"],
requiredItem: "Salamencite",
tier: "Uber",
},
beldum: {
randomBattleMoves: ["ironhead", "zenheadbutt", "headbutt", "irondefense"],
eventPokemon: [
{"generation": 6, "level": 5, "shiny": true, "isHidden": false, "moves":["holdback", "ironhead", "zenheadbutt", "irondefense"], "pokeball": "cherishball"},
],
tier: "LC",
},
metang: {
randomBattleMoves: ["stealthrock", "meteormash", "toxic", "earthquake", "bulletpunch", "zenheadbutt"],
eventPokemon: [
{"generation": 3, "level": 30, "moves":["takedown", "confusion", "metalclaw", "refresh"]},
],
tier: "New",
},
metagross: {
randomBattleMoves: ["meteormash", "earthquake", "agility", "stealthrock", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch"],
randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "bulletpunch", "thunderpunch", "explosion", "icepunch", "hammerarm"],
eventPokemon: [
{"generation": 4, "level": 62, "nature": "Brave", "moves":["bulletpunch", "meteormash", "hammerarm", "zenheadbutt"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "shiny": 1, "isHidden": false, "moves":["meteormash", "earthquake", "bulletpunch", "hammerarm"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "isHidden": false, "moves":["bulletpunch", "zenheadbutt", "hammerarm", "icepunch"], "pokeball": "cherishball"},
{"generation": 5, "level": 45, "isHidden": false, "moves":["earthquake", "zenheadbutt", "protect", "meteormash"]},
{"generation": 5, "level": 45, "isHidden": true, "moves":["irondefense", "agility", "hammerarm", "doubleedge"]},
{"generation": 5, "level": 45, "isHidden": true, "moves":["psychic", "meteormash", "hammerarm", "doubleedge"]},
{"generation": 5, "level": 58, "nature": "Serious", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["earthquake", "hyperbeam", "psychic", "meteormash"], "pokeball": "cherishball"},
],
tier: "New",
},
metagrossmega: {
randomBattleMoves: ["meteormash", "earthquake", "agility", "zenheadbutt", "hammerarm", "icepunch"],
randomDoubleBattleMoves: ["meteormash", "earthquake", "protect", "zenheadbutt", "thunderpunch", "icepunch"],
requiredItem: "Metagrossite",
tier: "New",
},
regirock: {
randomBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rest", "rockslide", "toxic"],
randomDoubleBattleMoves: ["stealthrock", "thunderwave", "stoneedge", "drainpunch", "curse", "rockslide", "protect"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["rockthrow", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "rockthrow", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["irondefense", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "irondefense"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["explosion", "icepunch", "stoneedge", "hammerarm"]},
],
eventOnly: true,
tier: "Bank",
},
regice: {
randomBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "rest", "sleeptalk", "focusblast", "rockpolish"],
randomDoubleBattleMoves: ["thunderwave", "icebeam", "thunderbolt", "icywind", "protect", "focusblast", "rockpolish"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["icywind", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "icywind", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["bulldoze", "curse", "ancientpower", "amnesia"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["thunderbolt", "amnesia", "icebeam", "hail"]},
],
eventOnly: true,
tier: "Bank",
},
registeel: {
randomBattleMoves: ["stealthrock", "thunderwave", "toxic", "protect", "seismictoss", "curse", "ironhead", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["stealthrock", "ironhead", "curse", "rest", "thunderwave", "protect", "seismictoss"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["metalclaw", "curse", "superpower", "ancientpower"]},
{"generation": 3, "level": 40, "moves":["curse", "superpower", "ancientpower", "hyperbeam"]},
{"generation": 4, "level": 30, "shiny": 1, "moves":["stomp", "metalclaw", "curse", "superpower"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["amnesia", "chargebeam", "lockon", "zapcannon"]},
{"generation": 6, "level": 40, "shiny": 1, "isHidden": false, "moves":["curse", "ancientpower", "irondefense", "amnesia"]},
{"generation": 6, "level": 50, "isHidden": true, "moves":["ironhead", "rockslide", "gravity", "irondefense"]},
],
eventOnly: true,
tier: "Bank",
},
latias: {
randomBattleMoves: ["dracometeor", "psyshock", "hiddenpowerfire", "roost", "thunderbolt", "healingwish", "defog"],
randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "psychic"]},
{"generation": 3, "level": 50, "shiny": 1, "moves":["mistball", "psychic", "recover", "charm"]},
{"generation": 3, "level": 70, "moves":["mistball", "psychic", "recover", "charm"]},
{"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "watersport", "refresh", "mistball"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["watersport", "refresh", "mistball", "zenheadbutt"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "charm", "psychic", "healpulse"]},
{"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "mistball", "psychoshift"]},
],
eventOnly: true,
tier: "Bank",
},
latiasmega: {
randomBattleMoves: ["calmmind", "dragonpulse", "surf", "dracometeor", "roost", "hiddenpowerfire", "substitute", "psyshock"],
randomDoubleBattleMoves: ["dragonpulse", "psychic", "tailwind", "helpinghand", "healpulse", "lightscreen", "reflect", "protect"],
requiredItem: "Latiasite",
tier: "Bank",
},
latios: {
randomBattleMoves: ["dracometeor", "hiddenpowerfire", "surf", "thunderbolt", "psyshock", "roost", "trick", "defog"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "trick", "tailwind", "protect", "hiddenpowerfire"],
eventPokemon: [
{"generation": 3, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "psychic"]},
{"generation": 3, "level": 50, "shiny": 1, "moves":["lusterpurge", "psychic", "recover", "dragondance"]},
{"generation": 3, "level": 70, "moves":["lusterpurge", "psychic", "recover", "dragondance"]},
{"generation": 4, "level": 35, "shiny": 1, "moves":["dragonbreath", "protect", "refresh", "lusterpurge"]},
{"generation": 4, "level": 40, "shiny": 1, "moves":["protect", "refresh", "lusterpurge", "zenheadbutt"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["psychoshift", "dragondance", "psychic", "healpulse"]},
{"generation": 6, "level": 30, "shiny": 1, "moves":["healpulse", "dragonbreath", "lusterpurge", "psychoshift"]},
{"generation": 6, "level": 50, "nature": "Modest", "moves":["dragonpulse", "lusterpurge", "psychic", "healpulse"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
latiosmega: {
randomBattleMoves: ["calmmind", "dracometeor", "hiddenpowerfire", "psyshock", "roost", "memento", "defog"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "surf", "thunderbolt", "psyshock", "substitute", "tailwind", "protect", "hiddenpowerfire"],
requiredItem: "Latiosite",
tier: "Bank",
},
kyogre: {
randomBattleMoves: ["waterspout", "originpulse", "scald", "thunder", "icebeam"],
randomDoubleBattleMoves: ["waterspout", "muddywater", "originpulse", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"],
eventPokemon: [
{"generation": 3, "level": 45, "shiny": 1, "moves":["bodyslam", "calmmind", "icebeam", "hydropump"]},
{"generation": 3, "level": 70, "shiny": 1, "moves":["hydropump", "rest", "sheercold", "doubleedge"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["aquaring", "icebeam", "ancientpower", "waterspout"]},
{"generation": 5, "level": 80, "shiny": 1, "moves":["icebeam", "ancientpower", "waterspout", "thunder"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["waterspout", "thunder", "icebeam", "sheercold"], "pokeball": "cherishball"},
{"generation": 6, "level": 45, "moves":["bodyslam", "aquaring", "icebeam", "originpulse"]},
{"generation": 6, "level": 100, "nature": "Timid", "moves":["waterspout", "thunder", "sheercold", "icebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
kyogreprimal: {
randomBattleMoves: ["calmmind", "waterspout", "originpulse", "scald", "thunder", "icebeam", "rest", "sleeptalk"],
randomDoubleBattleMoves: ["waterspout", "originpulse", "muddywater", "thunder", "icebeam", "calmmind", "rest", "sleeptalk", "protect"],
requiredItem: "Blue Orb",
},
groudon: {
randomBattleMoves: ["precipiceblades", "earthquake", "stealthrock", "lavaplume", "stoneedge", "dragontail", "roar", "toxic", "swordsdance", "rockpolish", "firepunch"],
randomDoubleBattleMoves: ["precipiceblades", "rockslide", "protect", "stoneedge", "swordsdance", "rockpolish", "dragonclaw", "firepunch"],
eventPokemon: [
{"generation": 3, "level": 45, "shiny": 1, "moves":["slash", "bulkup", "earthquake", "fireblast"]},
{"generation": 3, "level": 70, "shiny": 1, "moves":["fireblast", "rest", "fissure", "solarbeam"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "earthquake", "ancientpower", "eruption"]},
{"generation": 5, "level": 80, "shiny": 1, "moves":["earthquake", "ancientpower", "eruption", "solarbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["eruption", "hammerarm", "earthpower", "solarbeam"], "pokeball": "cherishball"},
{"generation": 6, "level": 45, "moves":["lavaplume", "rest", "earthquake", "precipiceblades"]},
{"generation": 6, "level": 100, "nature": "Adamant", "moves":["firepunch", "solarbeam", "hammerarm", "rockslide"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
groudonprimal: {
randomBattleMoves: ["stealthrock", "precipiceblades", "earthquake", "lavaplume", "stoneedge", "overheat", "rockpolish", "thunderwave"],
randomDoubleBattleMoves: ["precipiceblades", "lavaplume", "rockslide", "stoneedge", "swordsdance", "overheat", "rockpolish", "firepunch", "protect"],
requiredItem: "Red Orb",
},
rayquaza: {
randomBattleMoves: ["outrage", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw"],
randomDoubleBattleMoves: ["tailwind", "vcreate", "extremespeed", "dragondance", "earthquake", "dracometeor", "dragonclaw", "protect"],
eventPokemon: [
{"generation": 3, "level": 70, "shiny": 1, "moves":["fly", "rest", "extremespeed", "outrage"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["rest", "airslash", "ancientpower", "outrage"]},
{"generation": 5, "level": 70, "shiny": true, "moves":["dragonpulse", "ancientpower", "outrage", "dragondance"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["extremespeed", "hyperbeam", "dragonpulse", "vcreate"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "moves":["extremespeed", "dragonpulse", "dragondance", "dragonascent"]},
{"generation": 6, "level": 70, "shiny": true, "moves":["dragonpulse", "thunder", "twister", "extremespeed"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "shiny": true, "moves":["dragonascent", "dragonclaw", "extremespeed", "dragondance"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "shiny": true, "moves":["dragonascent", "dracometeor", "fly", "celebrate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
rayquazamega: {
randomBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance"],
randomDoubleBattleMoves: ["vcreate", "extremespeed", "swordsdance", "earthquake", "dragonascent", "dragonclaw", "dragondance", "protect"],
requiredMove: "Dragon Ascent",
tier: "Bank",
},
jirachi: {
randomBattleMoves: ["ironhead", "uturn", "firepunch", "icepunch", "trick", "stealthrock", "bodyslam", "toxic", "wish", "substitute"],
randomDoubleBattleMoves: ["bodyslam", "ironhead", "icywind", "thunderwave", "helpinghand", "trickroom", "uturn", "followme", "zenheadbutt", "protect"],
eventPokemon: [
{"generation": 3, "level": 5, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Bashful", "ivs": {"hp": 24, "atk": 3, "def": 30, "spa": 12, "spd": 16, "spe": 11}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Careful", "ivs": {"hp": 10, "atk": 0, "def": 10, "spa": 10, "spd": 26, "spe": 12}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Docile", "ivs": {"hp": 19, "atk": 7, "def": 10, "spa": 19, "spd": 10, "spe": 16}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Hasty", "ivs": {"hp": 3, "atk": 12, "def": 12, "spa": 7, "spd": 11, "spe": 9}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Jolly", "ivs": {"hp": 11, "atk": 8, "def": 6, "spa": 14, "spd": 5, "spe": 20}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Lonely", "ivs": {"hp": 31, "atk": 23, "def": 26, "spa": 29, "spd": 18, "spe": 5}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Naughty", "ivs": {"hp": 21, "atk": 31, "def": 31, "spa": 18, "spd": 24, "spe": 19}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Serious", "ivs": {"hp": 29, "atk": 10, "def": 31, "spa": 25, "spd": 23, "spe": 21}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 5, "shiny": true, "nature": "Timid", "ivs": {"hp": 15, "atk": 28, "def": 29, "spa": 3, "spd": 0, "spe": 7}, "moves":["wish", "confusion", "rest"]},
{"generation": 3, "level": 30, "moves":["helpinghand", "psychic", "refresh", "rest"]},
{"generation": 4, "level": 5, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"},
{"generation": 4, "level": 5, "moves":["wish", "confusion", "rest", "dracometeor"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["healingwish", "psychic", "swift", "meteormash"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["dracometeor", "meteormash", "wish", "followme"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["wish", "healingwish", "cosmicpower", "meteormash"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["wish", "healingwish", "swift", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "shiny": true, "moves":["wish", "swift", "healingwish", "moonblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "shiny": true, "moves":["wish", "confusion", "helpinghand", "return"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["heartstamp", "playrough", "wish", "cosmicpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 25, "shiny": true, "moves":["wish", "confusion", "swift", "happyhour"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["wish", "confusion", "rest"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
deoxys: {
randomBattleMoves: ["psychoboost", "stealthrock", "spikes", "firepunch", "superpower", "extremespeed", "knockoff", "taunt"],
randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff", "psyshock"],
eventPokemon: [
{"generation": 3, "level": 30, "shiny": 1, "moves":["taunt", "pursuit", "psychic", "superpower"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "spikes", "psychic", "snatch"]},
{"generation": 3, "level": 30, "shiny": 1, "moves":["knockoff", "pursuit", "psychic", "swift"]},
{"generation": 3, "level": 70, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "zapcannon", "irondefense", "extremespeed"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["psychoboost", "swift", "doubleteam", "extremespeed"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "detect", "counter", "mirrorcoat"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "meteormash", "superpower", "hyperbeam"]},
{"generation": 4, "level": 50, "moves":["psychoboost", "leer", "wrap", "nightshade"]},
{"generation": 5, "level": 100, "moves":["nastyplot", "darkpulse", "recover", "psychoboost"], "pokeball": "duskball"},
{"generation": 6, "level": 80, "moves":["cosmicpower", "recover", "psychoboost", "hyperbeam"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysattack: {
randomBattleMoves: ["psychoboost", "superpower", "icebeam", "knockoff", "extremespeed", "firepunch", "stealthrock"],
randomDoubleBattleMoves: ["psychoboost", "superpower", "extremespeed", "icebeam", "thunderbolt", "firepunch", "protect", "knockoff"],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysdefense: {
randomBattleMoves: ["spikes", "stealthrock", "recover", "taunt", "toxic", "seismictoss", "knockoff"],
randomDoubleBattleMoves: ["protect", "stealthrock", "recover", "taunt", "reflect", "seismictoss", "lightscreen", "trickroom"],
eventOnly: true,
tier: "Bank-Uber",
},
deoxysspeed: {
randomBattleMoves: ["spikes", "stealthrock", "superpower", "psychoboost", "taunt", "magiccoat", "knockoff"],
randomDoubleBattleMoves: ["superpower", "icebeam", "psychoboost", "taunt", "lightscreen", "reflect", "protect", "knockoff"],
eventOnly: true,
tier: "Bank-Uber",
},
turtwig: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["tackle", "withdraw", "absorb", "stockpile"]},
],
tier: "Bank-LC",
},
grotle: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "seedbomb", "substitute", "leechseed", "toxic"],
tier: "Bank-NFE",
},
torterra: {
randomBattleMoves: ["stealthrock", "earthquake", "woodhammer", "stoneedge", "synthesis", "rockpolish"],
randomDoubleBattleMoves: ["protect", "earthquake", "woodhammer", "stoneedge", "rockslide", "wideguard", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["woodhammer", "earthquake", "outrage", "stoneedge"], "pokeball": "cherishball"},
],
tier: "Bank",
},
chimchar: {
randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "uturn", "gunkshot"],
eventPokemon: [
{"generation": 4, "level": 40, "gender": "M", "nature": "Mild", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["scratch", "leer", "ember", "taunt"]},
{"generation": 4, "level": 40, "gender": "M", "nature": "Hardy", "moves":["flamethrower", "thunderpunch", "grassknot", "helpinghand"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "ember", "taunt", "fakeout"]},
],
tier: "Bank-LC",
},
monferno: {
randomBattleMoves: ["stealthrock", "overheat", "hiddenpowergrass", "fakeout", "vacuumwave", "uturn", "gunkshot"],
tier: "Bank",
},
infernape: {
randomBattleMoves: ["stealthrock", "uturn", "swordsdance", "closecombat", "flareblitz", "thunderpunch", "machpunch", "nastyplot", "fireblast", "vacuumwave", "grassknot", "hiddenpowerice"],
randomDoubleBattleMoves: ["fakeout", "heatwave", "closecombat", "uturn", "grassknot", "stoneedge", "machpunch", "feint", "taunt", "flareblitz", "hiddenpowerice", "thunderpunch", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["fireblast", "closecombat", "uturn", "grassknot"], "pokeball": "cherishball"},
{"generation": 6, "level": 88, "isHidden": true, "moves":["fireblast", "closecombat", "firepunch", "focuspunch"], "pokeball": "cherishball"},
],
tier: "Bank",
},
piplup: {
randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble"]},
{"generation": 5, "level": 15, "shiny": 1, "isHidden": false, "moves":["hydropump", "featherdance", "watersport", "peck"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["sing", "round", "featherdance", "peck"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["pound", "growl", "bubble", "featherdance"]},
{"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "return"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
prinplup: {
randomBattleMoves: ["stealthrock", "hydropump", "scald", "icebeam", "hiddenpowerelectric", "hiddenpowerfire", "yawn", "defog"],
tier: "Bank",
},
empoleon: {
randomBattleMoves: ["hydropump", "flashcannon", "grassknot", "hiddenpowerfire", "icebeam", "scald", "toxic", "roar", "stealthrock"],
randomDoubleBattleMoves: ["icywind", "scald", "surf", "icebeam", "hiddenpowerelectric", "protect", "grassknot", "flashcannon"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "aquajet", "grassknot"], "pokeball": "cherishball"},
],
tier: "Bank",
},
starly: {
randomBattleMoves: ["bravebird", "return", "uturn", "pursuit"],
eventPokemon: [
{"generation": 4, "level": 1, "gender": "M", "nature": "Mild", "moves":["tackle", "growl"]},
],
tier: "LC",
},
staravia: {
randomBattleMoves: ["bravebird", "return", "uturn", "pursuit", "defog"],
tier: "NFE",
},
staraptor: {
randomBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "roost", "doubleedge"],
randomDoubleBattleMoves: ["bravebird", "closecombat", "uturn", "quickattack", "doubleedge", "tailwind", "protect"],
tier: "New",
},
bidoof: {
randomBattleMoves: ["return", "aquatail", "curse", "quickattack", "stealthrock", "superfang"],
eventPokemon: [
{"generation": 4, "level": 1, "gender": "M", "nature": "Lonely", "abilities":["simple"], "moves":["tackle"]},
],
tier: "Bank-LC",
},
bibarel: {
randomBattleMoves: ["return", "waterfall", "curse", "quickattack", "stealthrock", "rest"],
randomDoubleBattleMoves: ["return", "waterfall", "curse", "quickattack", "protect", "rest"],
tier: "Bank",
},
kricketot: {
randomBattleMoves: ["endeavor", "mudslap", "bugbite", "strugglebug"],
tier: "Bank-LC",
},
kricketune: {
randomBattleMoves: ["xscissor", "endeavor", "taunt", "toxic", "stickyweb", "knockoff"],
randomDoubleBattleMoves: ["bugbite", "protect", "taunt", "stickyweb", "knockoff"],
tier: "Bank",
},
shinx: {
randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"],
tier: "LC",
},
luxio: {
randomBattleMoves: ["wildcharge", "icefang", "firefang", "crunch"],
tier: "NFE",
},
luxray: {
randomBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade"],
randomDoubleBattleMoves: ["wildcharge", "icefang", "voltswitch", "crunch", "superpower", "facade", "protect"],
tier: "New",
},
cranidos: {
randomBattleMoves: ["headsmash", "rockslide", "earthquake", "zenheadbutt", "firepunch", "rockpolish", "crunch"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["pursuit", "takedown", "crunch", "headbutt"], "pokeball": "cherishball"},
],
tier: "LC",
},
rampardos: {
randomBattleMoves: ["headsmash", "earthquake", "rockpolish", "crunch", "rockslide", "firepunch"],
randomDoubleBattleMoves: ["headsmash", "earthquake", "zenheadbutt", "rockslide", "crunch", "stoneedge", "protect"],
tier: "New",
},
shieldon: {
randomBattleMoves: ["stealthrock", "metalburst", "fireblast", "icebeam", "protect", "toxic", "roar"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "moves":["metalsound", "takedown", "bodyslam", "protect"], "pokeball": "cherishball"},
],
tier: "LC",
},
bastiodon: {
randomBattleMoves: ["stealthrock", "rockblast", "metalburst", "protect", "toxic", "roar"],
randomDoubleBattleMoves: ["stealthrock", "stoneedge", "metalburst", "protect", "wideguard", "guardsplit"],
tier: "New",
},
burmy: {
randomBattleMoves: ["bugbite", "hiddenpowerice", "electroweb", "protect"],
tier: "Bank-LC",
},
wormadam: {
randomBattleMoves: ["gigadrain", "signalbeam", "protect", "toxic", "synthesis"],
randomDoubleBattleMoves: ["leafstorm", "gigadrain", "signalbeam", "hiddenpowerice", "hiddenpowerrock", "stringshot", "protect"],
tier: "Bank",
},
wormadamsandy: {
randomBattleMoves: ["earthquake", "toxic", "rockblast", "protect", "stealthrock"],
randomDoubleBattleMoves: ["earthquake", "suckerpunch", "rockblast", "protect", "stringshot"],
tier: "Bank",
},
wormadamtrash: {
randomBattleMoves: ["stealthrock", "toxic", "gyroball", "protect"],
randomDoubleBattleMoves: ["strugglebug", "stringshot", "gyroball", "protect"],
tier: "Bank",
},
mothim: {
randomBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "hiddenpowerground", "uturn"],
randomDoubleBattleMoves: ["quiverdance", "bugbuzz", "airslash", "gigadrain", "roost", "protect"],
tier: "Bank",
},
combee: {
randomBattleMoves: ["bugbuzz", "aircutter", "endeavor", "ominouswind", "tailwind"],
tier: "Bank-LC",
},
vespiquen: {
randomBattleMoves: ["substitute", "healorder", "toxic", "attackorder", "defendorder", "infestation"],
randomDoubleBattleMoves: ["tailwind", "healorder", "stringshot", "attackorder", "strugglebug", "protect"],
tier: "Bank",
},
pachirisu: {
randomBattleMoves: ["nuzzle", "thunderbolt", "superfang", "toxic", "uturn"],
randomDoubleBattleMoves: ["nuzzle", "thunderbolt", "superfang", "followme", "uturn", "helpinghand", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Impish", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 14, "spd": 31, "spe": 31}, "isHidden": true, "moves":["nuzzle", "superfang", "followme", "protect"], "pokeball": "cherishball"},
],
tier: "Bank",
},
buizel: {
randomBattleMoves: ["waterfall", "aquajet", "switcheroo", "brickbreak", "bulkup", "batonpass", "icepunch"],
tier: "Bank-LC",
},
floatzel: {
randomBattleMoves: ["bulkup", "batonpass", "waterfall", "icepunch", "substitute", "taunt", "aquajet", "brickbreak"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "switcheroo", "raindance", "protect", "icepunch", "crunch", "taunt"],
tier: "Bank",
},
cherubi: {
randomBattleMoves: ["sunnyday", "solarbeam", "weatherball", "hiddenpowerice", "aromatherapy", "dazzlinggleam"],
tier: "Bank-LC",
},
cherrim: {
randomBattleMoves: ["energyball", "dazzlinggleam", "hiddenpowerfire", "synthesis", "healingwish"],
randomDoubleBattleMoves: ["sunnyday", "solarbeam", "weatherball", "gigadrain", "protect"],
tier: "Bank",
},
cherrimsunshine: {
randomBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "hiddenpowerice"],
randomDoubleBattleMoves: ["sunnyday", "solarbeam", "gigadrain", "weatherball", "protect"],
battleOnly: true,
},
shellos: {
randomBattleMoves: ["scald", "clearsmog", "recover", "toxic", "icebeam", "stockpile"],
tier: "LC",
},
gastrodon: {
randomBattleMoves: ["earthquake", "icebeam", "scald", "toxic", "recover", "clearsmog"],
randomDoubleBattleMoves: ["earthpower", "icebeam", "scald", "muddywater", "recover", "icywind", "protect"],
tier: "New",
},
drifloon: {
randomBattleMoves: ["shadowball", "substitute", "calmmind", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp"],
tier: "LC Uber",
},
drifblim: {
randomBattleMoves: ["acrobatics", "willowisp", "substitute", "destinybond", "shadowball"],
randomDoubleBattleMoves: ["shadowball", "substitute", "hypnosis", "hiddenpowerfighting", "thunderbolt", "destinybond", "willowisp", "protect"],
tier: "New",
},
buneary: {
randomBattleMoves: ["fakeout", "return", "switcheroo", "thunderpunch", "jumpkick", "firepunch", "icepunch", "healingwish"],
tier: "Bank-LC",
},
lopunny: {
randomBattleMoves: ["return", "switcheroo", "highjumpkick", "icepunch", "healingwish"],
randomDoubleBattleMoves: ["return", "switcheroo", "highjumpkick", "firepunch", "icepunch", "fakeout", "protect", "encore"],
tier: "Bank",
},
lopunnymega: {
randomBattleMoves: ["return", "highjumpkick", "substitute", "thunderpunch", "icepunch"],
randomDoubleBattleMoves: ["return", "highjumpkick", "protect", "fakeout", "icepunch", "encore"],
requiredItem: "Lopunnite",
tier: "Bank",
},
glameow: {
randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "hypnosis", "quickattack", "return", "foulplay"],
tier: "Bank-LC",
},
purugly: {
randomBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "uturn", "suckerpunch", "quickattack", "return", "knockoff", "protect"],
tier: "Bank",
},
stunky: {
randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "explosion", "taunt", "playrough", "defog"],
tier: "Bank-LC",
},
skuntank: {
randomBattleMoves: ["pursuit", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "defog"],
randomDoubleBattleMoves: ["protect", "suckerpunch", "crunch", "fireblast", "taunt", "poisonjab", "playrough", "snarl"],
tier: "Bank",
},
bronzor: {
randomBattleMoves: ["stealthrock", "psychic", "toxic", "hypnosis", "reflect", "lightscreen", "trickroom", "trick"],
tier: "Bank-LC",
},
bronzong: {
randomBattleMoves: ["stealthrock", "earthquake", "toxic", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"],
randomDoubleBattleMoves: ["earthquake", "protect", "reflect", "lightscreen", "trickroom", "explosion", "gyroball"],
tier: "Bank",
},
chatot: {
randomBattleMoves: ["nastyplot", "boomburst", "heatwave", "hiddenpowerground", "substitute", "chatter", "uturn"],
randomDoubleBattleMoves: ["nastyplot", "heatwave", "encore", "substitute", "chatter", "uturn", "protect", "hypervoice", "boomburst"],
eventPokemon: [
{"generation": 4, "level": 25, "gender": "M", "nature": "Jolly", "abilities":["keeneye"], "moves":["mirrormove", "furyattack", "chatter", "taunt"]},
],
tier: "Bank",
},
spiritomb: {
randomBattleMoves: ["shadowsneak", "suckerpunch", "pursuit", "willowisp", "darkpulse", "rest", "sleeptalk", "foulplay", "painsplit", "calmmind"],
randomDoubleBattleMoves: ["shadowsneak", "suckerpunch", "icywind", "willowisp", "snarl", "darkpulse", "protect", "foulplay", "painsplit"],
eventPokemon: [
{"generation": 5, "level": 61, "gender": "F", "nature": "Quiet", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["darkpulse", "psychic", "silverwind", "embargo"], "pokeball": "cherishball"},
],
tier: "Bank",
},
gible: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"],
tier: "LC",
},
gabite: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "fireblast", "stoneedge", "stealthrock"],
tier: "New",
},
garchomp: {
randomBattleMoves: ["outrage", "dragonclaw", "earthquake", "stoneedge", "fireblast", "swordsdance", "stealthrock", "firefang"],
randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["outrage", "earthquake", "swordsdance", "stoneedge"], "pokeball": "cherishball"},
{"generation": 5, "level": 48, "gender": "M", "isHidden": true, "moves":["dragonclaw", "dig", "crunch", "outrage"]},
{"generation": 6, "level": 48, "gender": "M", "isHidden": false, "moves":["dracometeor", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "gender": "M", "isHidden": false, "moves":["slash", "dragonclaw", "dig", "crunch"], "pokeball": "cherishball"},
{"generation": 6, "level": 66, "gender": "F", "perfectIVs": 3, "isHidden": false, "moves":["dragonrush", "earthquake", "brickbreak", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "New",
},
garchompmega: {
randomBattleMoves: ["outrage", "dracometeor", "earthquake", "stoneedge", "fireblast", "swordsdance"],
randomDoubleBattleMoves: ["substitute", "dragonclaw", "earthquake", "stoneedge", "rockslide", "swordsdance", "protect", "fireblast"],
requiredItem: "Garchompite",
tier: "(OU)",
},
riolu: {
randomBattleMoves: ["crunch", "rockslide", "copycat", "drainpunch", "highjumpkick", "icepunch", "swordsdance"],
eventPokemon: [
{"generation": 4, "level": 30, "gender": "M", "nature": "Serious", "abilities":["steadfast"], "moves":["aurasphere", "shadowclaw", "bulletpunch", "drainpunch"]},
],
tier: "LC",
},
lucario: {
randomBattleMoves: ["swordsdance", "closecombat", "crunch", "extremespeed", "icepunch", "nastyplot", "aurasphere", "darkpulse", "vacuumwave", "flashcannon"],
randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "gender": "M", "nature": "Modest", "abilities":["steadfast"], "moves":["aurasphere", "darkpulse", "dragonpulse", "waterpulse"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "gender": "M", "nature": "Adamant", "abilities":["innerfocus"], "moves":["forcepalm", "bonerush", "sunnyday", "blazekick"], "pokeball": "cherishball"},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["detect", "metalclaw", "counter", "bulletpunch"]},
{"generation": 5, "level": 50, "gender": "M", "nature": "Naughty", "ivs": {"atk": 31}, "isHidden": true, "moves":["bulletpunch", "closecombat", "stoneedge", "shadowclaw"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Jolly", "isHidden": false, "abilities":["innerfocus"], "moves":["closecombat", "aurasphere", "flashcannon", "quickattack"], "pokeball": "cherishball"},
],
tier: "New",
},
lucariomega: {
randomBattleMoves: ["swordsdance", "closecombat", "crunch", "icepunch", "bulletpunch", "nastyplot", "aurasphere", "darkpulse", "flashcannon"],
randomDoubleBattleMoves: ["followme", "closecombat", "crunch", "extremespeed", "icepunch", "bulletpunch", "aurasphere", "darkpulse", "vacuumwave", "flashcannon", "protect"],
requiredItem: "Lucarionite",
tier: "Uber",
},
hippopotas: {
randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "protect", "toxic", "stockpile"],
tier: "Bank-LC",
},
hippowdon: {
randomBattleMoves: ["earthquake", "slackoff", "whirlwind", "stealthrock", "toxic", "stoneedge"],
randomDoubleBattleMoves: ["earthquake", "slackoff", "rockslide", "stealthrock", "protect", "stoneedge"],
tier: "Bank",
},
skorupi: {
randomBattleMoves: ["toxicspikes", "xscissor", "poisonjab", "knockoff", "pinmissile", "whirlwind"],
tier: "Bank-LC",
},
drapion: {
randomBattleMoves: ["knockoff", "taunt", "toxicspikes", "poisonjab", "whirlwind", "swordsdance", "aquatail", "earthquake"],
randomDoubleBattleMoves: ["snarl", "taunt", "protect", "earthquake", "aquatail", "swordsdance", "poisonjab", "knockoff"],
tier: "Bank",
},
croagunk: {
randomBattleMoves: ["fakeout", "vacuumwave", "suckerpunch", "drainpunch", "darkpulse", "knockoff", "gunkshot", "toxic"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["astonish", "mudslap", "poisonsting", "taunt"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["mudslap", "poisonsting", "taunt", "poisonjab"]},
],
tier: "Bank-LC",
},
toxicroak: {
randomBattleMoves: ["swordsdance", "gunkshot", "drainpunch", "suckerpunch", "icepunch", "substitute"],
randomDoubleBattleMoves: ["suckerpunch", "drainpunch", "substitute", "swordsdance", "knockoff", "icepunch", "gunkshot", "fakeout", "protect"],
tier: "Bank",
},
carnivine: {
randomBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "powerwhip", "return", "sleeppowder", "substitute", "leechseed", "knockoff", "ragepowder", "protect"],
tier: "Bank",
},
finneon: {
randomBattleMoves: ["surf", "uturn", "icebeam", "hiddenpowerelectric", "hiddenpowergrass"],
tier: "LC",
},
lumineon: {
randomBattleMoves: ["scald", "waterfall", "icebeam", "uturn", "toxic", "defog"],
randomDoubleBattleMoves: ["surf", "uturn", "icebeam", "toxic", "raindance", "tailwind", "protect"],
tier: "New",
},
snover: {
randomBattleMoves: ["blizzard", "iceshard", "gigadrain", "leechseed", "substitute", "woodhammer"],
tier: "Bank-LC",
},
abomasnow: {
randomBattleMoves: ["woodhammer", "iceshard", "blizzard", "gigadrain", "leechseed", "substitute", "focuspunch", "earthquake"],
randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"],
tier: "Bank",
},
abomasnowmega: {
randomBattleMoves: ["blizzard", "gigadrain", "woodhammer", "earthquake", "iceshard", "hiddenpowerfire"],
randomDoubleBattleMoves: ["blizzard", "iceshard", "gigadrain", "protect", "focusblast", "woodhammer", "earthquake"],
requiredItem: "Abomasite",
tier: "Bank",
},
rotom: {
randomBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp"],
randomDoubleBattleMoves: ["thunderbolt", "voltswitch", "shadowball", "substitute", "painsplit", "hiddenpowerice", "trick", "willowisp", "electroweb", "protect"],
eventPokemon: [
{"generation": 5, "level": 10, "nature": "Naughty", "moves":["uproar", "astonish", "trick", "thundershock"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "nature": "Quirky", "moves":["shockwave", "astonish", "trick", "thunderwave"], "pokeball": "cherishball"},
],
tier: "Bank",
},
rotomheat: {
randomBattleMoves: ["overheat", "thunderbolt", "voltswitch", "hiddenpowerice", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["overheat", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
rotomwash: {
randomBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerice", "willowisp", "trick"],
randomDoubleBattleMoves: ["hydropump", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "trick", "electroweb", "protect", "hiddenpowergrass"],
tier: "Bank",
},
rotomfrost: {
randomBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["blizzard", "thunderbolt", "voltswitch", "substitute", "painsplit", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
rotomfan: {
randomBattleMoves: ["airslash", "thunderbolt", "voltswitch", "painsplit", "willowisp", "trick"],
randomDoubleBattleMoves: ["airslash", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerice", "willowisp", "electroweb", "discharge", "protect"],
tier: "Bank",
},
rotommow: {
randomBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "painsplit", "hiddenpowerfire", "willowisp", "trick"],
randomDoubleBattleMoves: ["leafstorm", "thunderbolt", "voltswitch", "substitute", "painsplit", "hiddenpowerfire", "willowisp", "trick", "electroweb", "protect"],
tier: "Bank",
},
uxie: {
randomBattleMoves: ["stealthrock", "thunderwave", "psychic", "uturn", "healbell", "knockoff", "yawn"],
randomDoubleBattleMoves: ["uturn", "psyshock", "yawn", "healbell", "stealthrock", "thunderbolt", "protect", "helpinghand", "thunderwave", "skillswap"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "yawn", "futuresight", "amnesia"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "yawn", "futuresight", "amnesia"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["futuresight", "amnesia", "extrasensory", "flail"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["yawn", "futuresight", "amnesia", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
mesprit: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "energyball", "signalbeam", "hiddenpowerfire", "icebeam", "healingwish", "stealthrock", "uturn"],
randomDoubleBattleMoves: ["calmmind", "psychic", "thunderbolt", "icebeam", "substitute", "uturn", "trick", "protect", "knockoff", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "luckychant", "futuresight", "charm"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "luckychant", "futuresight", "charm"]},
{"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "charm", "extrasensory", "copycat"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["luckychant", "futuresight", "charm", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
azelf: {
randomBattleMoves: ["nastyplot", "psyshock", "fireblast", "dazzlinggleam", "stealthrock", "knockoff", "taunt", "explosion"],
randomDoubleBattleMoves: ["nastyplot", "psychic", "fireblast", "thunderbolt", "icepunch", "knockoff", "zenheadbutt", "uturn", "trick", "taunt", "protect", "dazzlinggleam"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["confusion", "uproar", "futuresight", "nastyplot"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["swift", "uproar", "futuresight", "nastyplot"]},
{"generation": 5, "level": 50, "shiny": 1, "moves":["futuresight", "nastyplot", "extrasensory", "lastresort"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["uproar", "futuresight", "nastyplot", "extrasensory"]},
],
eventOnly: true,
tier: "Bank",
},
dialga: {
randomBattleMoves: ["stealthrock", "toxic", "dracometeor", "fireblast", "flashcannon", "roar", "thunderbolt"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "protect", "thunderbolt", "flashcannon", "earthpower", "fireblast", "aurasphere"],
eventPokemon: [
{"generation": 4, "level": 47, "shiny": 1, "moves":["metalclaw", "ancientpower", "dragonclaw", "roaroftime"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["roaroftime", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dracometeor", "aurasphere", "roaroftime"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "irontail", "roaroftime", "flashcannon"]},
{"generation": 6, "level": 100, "nature": "Modest", "isHidden": true, "moves":["metalburst", "overheat", "roaroftime", "flashcannon"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
palkia: {
randomBattleMoves: ["spacialrend", "dracometeor", "hydropump", "thunderwave", "dragontail", "fireblast"],
randomDoubleBattleMoves: ["spacialrend", "dracometeor", "surf", "hydropump", "thunderbolt", "fireblast", "protect"],
eventPokemon: [
{"generation": 4, "level": 47, "shiny": 1, "moves":["waterpulse", "ancientpower", "dragonclaw", "spacialrend"]},
{"generation": 4, "level": 70, "shiny": 1, "moves":["spacialrend", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["hydropump", "dracometeor", "spacialrend", "aurasphere"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"]},
{"generation": 6, "level": 100, "nature": "Timid", "isHidden": true, "moves":["earthpower", "aurasphere", "spacialrend", "hydropump"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
heatran: {
randomBattleMoves: ["fireblast", "lavaplume", "stealthrock", "earthpower", "flashcannon", "protect", "toxic", "roar"],
randomDoubleBattleMoves: ["heatwave", "substitute", "earthpower", "protect", "eruption", "willowisp"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]},
{"generation": 4, "level": 50, "nature": "Quiet", "moves":["eruption", "magmastorm", "earthpower", "ancientpower"]},
{"generation": 5, "level": 68, "shiny": 1, "isHidden": false, "moves":["scaryface", "lavaplume", "firespin", "ironhead"]},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["metalsound", "crunch", "scaryface", "lavaplume"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "Bank",
},
regigigas: {
randomBattleMoves: ["thunderwave", "confuseray", "substitute", "return", "knockoff", "drainpunch"],
randomDoubleBattleMoves: ["thunderwave", "substitute", "return", "icywind", "rockslide", "earthquake", "knockoff", "wideguard"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["confuseray", "stomp", "superpower", "zenheadbutt"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dizzypunch", "knockoff", "foresight", "confuseray"]},
{"generation": 4, "level": 100, "moves":["ironhead", "rockslide", "icywind", "crushgrip"], "pokeball": "cherishball"},
{"generation": 5, "level": 68, "shiny": 1, "moves":["revenge", "wideguard", "zenheadbutt", "payback"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["foresight", "revenge", "wideguard", "zenheadbutt"]},
],
eventOnly: true,
tier: "Bank",
},
giratina: {
randomBattleMoves: ["rest", "sleeptalk", "dragontail", "roar", "willowisp", "shadowball", "dragonpulse"],
randomDoubleBattleMoves: ["tailwind", "icywind", "protect", "dragontail", "willowisp", "calmmind", "dragonpulse", "shadowball"],
eventPokemon: [
{"generation": 4, "level": 70, "shiny": 1, "moves":["shadowforce", "healblock", "earthpower", "slash"]},
{"generation": 4, "level": 47, "shiny": 1, "moves":["ominouswind", "ancientpower", "dragonclaw", "shadowforce"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["dragonbreath", "scaryface"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["dragonbreath", "scaryface"], "pokeball": "dreamball"},
{"generation": 5, "level": 100, "shiny": true, "isHidden": false, "moves":["dragonpulse", "dragonclaw", "aurasphere", "shadowforce"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["aurasphere", "shadowclaw", "shadowforce", "hex"]},
{"generation": 6, "level": 100, "nature": "Brave", "isHidden": true, "moves":["aurasphere", "dracometeor", "shadowforce", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
giratinaorigin: {
randomBattleMoves: ["dracometeor", "shadowsneak", "dragontail", "willowisp", "defog", "toxic", "shadowball", "earthquake"],
randomDoubleBattleMoves: ["dracometeor", "shadowsneak", "tailwind", "hiddenpowerfire", "willowisp", "calmmind", "substitute", "dragonpulse", "shadowball", "aurasphere", "protect", "earthquake"],
eventOnly: true,
requiredItem: "Griseous Orb",
tier: "Bank-Uber",
},
cresselia: {
randomBattleMoves: ["moonlight", "psychic", "icebeam", "thunderwave", "toxic", "substitute", "psyshock", "moonblast", "calmmind"],
randomDoubleBattleMoves: ["psyshock", "icywind", "thunderwave", "trickroom", "moonblast", "moonlight", "skillswap", "reflect", "lightscreen", "icebeam", "protect", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]},
{"generation": 5, "level": 68, "shiny": 1, "moves":["futuresight", "slash", "moonlight", "psychocut"]},
{"generation": 5, "level": 68, "nature": "Modest", "moves":["icebeam", "psyshock", "energyball", "hiddenpower"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["mist", "aurorabeam", "futuresight", "slash"]},
],
eventOnly: true,
tier: "Bank",
},
phione: {
randomBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam"],
randomDoubleBattleMoves: ["raindance", "scald", "uturn", "rest", "icebeam", "helpinghand", "icywind", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "moves":["grassknot", "raindance", "rest", "surf"], "pokeball": "cherishball"},
],
tier: "Bank",
},
manaphy: {
randomBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "psychic"],
randomDoubleBattleMoves: ["tailglow", "surf", "icebeam", "energyball", "protect", "scald", "icywind", "helpinghand"],
eventPokemon: [
{"generation": 4, "level": 5, "moves":["tailglow", "bubble", "watersport"]},
{"generation": 4, "level": 1, "shiny": 1, "moves":["tailglow", "bubble", "watersport"]},
{"generation": 4, "level": 50, "moves":["heartswap", "waterpulse", "whirlpool", "acidarmor"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "nature": "Impish", "moves":["aquaring", "waterpulse", "watersport", "heartswap"], "pokeball": "cherishball"},
{"generation": 6, "level": 1, "moves":["tailglow", "bubble", "watersport", "heartswap"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["tailglow", "bubble", "watersport"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
darkrai: {
randomBattleMoves: ["hypnosis", "darkpulse", "focusblast", "nastyplot", "substitute", "sludgebomb"],
randomDoubleBattleMoves: ["darkpulse", "focusblast", "nastyplot", "substitute", "snarl", "protect"],
eventPokemon: [
{"generation": 4, "level": 40, "shiny": 1, "moves":["quickattack", "hypnosis", "pursuit", "nightmare"]},
{"generation": 4, "level": 50, "moves":["roaroftime", "spacialrend", "nightmare", "hypnosis"], "pokeball": "cherishball"},
{"generation": 4, "level": 50, "moves":["darkvoid", "darkpulse", "shadowball", "doubleteam"]},
{"generation": 4, "level": 50, "shiny": 1, "moves":["hypnosis", "feintattack", "nightmare", "doubleteam"]},
{"generation": 5, "level": 50, "moves":["darkvoid", "ominouswind", "feintattack", "nightmare"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["darkvoid", "darkpulse", "phantomforce", "dreameater"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["darkvoid", "ominouswind", "nightmare", "feintattack"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
shaymin: {
randomBattleMoves: ["seedflare", "earthpower", "airslash", "psychic", "rest", "substitute", "leechseed"],
randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect"],
eventPokemon: [
{"generation": 4, "level": 50, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"},
{"generation": 4, "level": 30, "shiny": 1, "moves":["growth", "magicalleaf", "leechseed", "synthesis"]},
{"generation": 5, "level": 50, "moves":["seedflare", "leechseed", "synthesis", "sweetscent"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["growth", "magicalleaf", "seedflare", "airslash"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["seedflare", "aromatherapy", "substitute", "energyball"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
shayminsky: {
randomBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "substitute", "leechseed", "healingwish"],
randomDoubleBattleMoves: ["seedflare", "earthpower", "airslash", "hiddenpowerfire", "rest", "substitute", "leechseed", "tailwind", "protect", "hiddenpowerice"],
eventOnly: true,
tier: "Bank-Uber",
},
arceus: {
randomBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover"],
randomDoubleBattleMoves: ["swordsdance", "extremespeed", "shadowclaw", "earthquake", "recover", "protect"],
eventPokemon: [
{"generation": 4, "level": 100, "moves":["judgment", "roaroftime", "spacialrend", "shadowforce"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["recover", "hyperbeam", "perishsong", "judgment"]},
{"generation": 6, "level": 100, "shiny": 1, "moves":["judgment", "blastburn", "hydrocannon", "earthpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["judgment", "perishsong", "hyperbeam", "recover"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
arceusbug: {
randomBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead"],
randomDoubleBattleMoves: ["swordsdance", "xscissor", "stoneedge", "recover", "earthquake", "ironhead", "protect"],
eventOnly: true,
requiredItems: ["Insect Plate", "Buginium Z"],
},
arceusdark: {
randomBattleMoves: ["calmmind", "judgment", "recover", "fireblast", "thunderbolt"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "focusblast", "safeguard", "snarl", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Dread Plate", "Darkinium Z"],
},
arceusdragon: {
randomBattleMoves: ["swordsdance", "outrage", "extremespeed", "earthquake", "recover", "calmmind", "judgment", "fireblast", "earthpower"],
randomDoubleBattleMoves: ["swordsdance", "dragonclaw", "extremespeed", "earthquake", "recover", "protect"],
eventOnly: true,
requiredItems: ["Draco Plate", "Dragonium Z"],
},
arceuselectric: {
randomBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "grassknot", "fireblast", "willowisp"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "icebeam", "protect"],
eventOnly: true,
requiredItems: ["Zap Plate", "Electrium Z"],
},
arceusfairy: {
randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "defog", "thunderbolt", "toxic", "fireblast"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "protect", "earthpower", "thunderbolt"],
eventOnly: true,
requiredItems: ["Pixie Plate", "Fairium Z"],
},
arceusfighting: {
randomBattleMoves: ["calmmind", "judgment", "stoneedge", "shadowball", "recover", "toxic", "defog"],
randomDoubleBattleMoves: ["calmmind", "judgment", "icebeam", "shadowball", "recover", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Fist Plate", "Fightinium Z"],
},
arceusfire: {
randomBattleMoves: ["calmmind", "judgment", "grassknot", "thunderbolt", "icebeam", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "recover", "heatwave", "protect", "willowisp"],
eventOnly: true,
requiredItems: ["Flame Plate", "Firium Z"],
},
arceusflying: {
randomBattleMoves: ["calmmind", "judgment", "earthpower", "fireblast", "substitute", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "safeguard", "recover", "substitute", "tailwind", "protect"],
eventOnly: true,
requiredItems: ["Sky Plate", "Flyinium Z"],
},
arceusghost: {
randomBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "roar", "defog"],
randomDoubleBattleMoves: ["calmmind", "judgment", "focusblast", "recover", "swordsdance", "shadowforce", "brickbreak", "willowisp", "protect"],
eventOnly: true,
requiredItems: ["Spooky Plate", "Ghostium Z"],
},
arceusgrass: {
randomBattleMoves: ["judgment", "recover", "calmmind", "icebeam", "fireblast"],
randomDoubleBattleMoves: ["calmmind", "icebeam", "judgment", "earthpower", "recover", "safeguard", "thunderwave", "protect"],
eventOnly: true,
requiredItems: ["Meadow Plate", "Grassium Z"],
},
arceusground: {
randomBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "extremespeed", "icebeam"],
randomDoubleBattleMoves: ["swordsdance", "earthquake", "stoneedge", "recover", "calmmind", "judgment", "icebeam", "rockslide", "protect"],
eventOnly: true,
requiredItems: ["Earth Plate", "Groundium Z"],
},
arceusice: {
randomBattleMoves: ["calmmind", "judgment", "thunderbolt", "fireblast", "recover"],
randomDoubleBattleMoves: ["calmmind", "judgment", "thunderbolt", "focusblast", "recover", "protect", "icywind"],
eventOnly: true,
requiredItems: ["Icicle Plate", "Icium Z"],
},
arceuspoison: {
randomBattleMoves: ["calmmind", "sludgebomb", "fireblast", "recover", "willowisp", "defog", "thunderwave"],
randomDoubleBattleMoves: ["calmmind", "judgment", "sludgebomb", "heatwave", "recover", "willowisp", "protect", "earthpower"],
eventOnly: true,
requiredItems: ["Toxic Plate", "Poisonium Z"],
},
arceuspsychic: {
randomBattleMoves: ["judgment", "calmmind", "focusblast", "recover", "defog", "thunderbolt", "willowisp"],
randomDoubleBattleMoves: ["calmmind", "psyshock", "focusblast", "recover", "willowisp", "judgment", "protect"],
eventOnly: true,
requiredItems: ["Mind Plate", "Psychium Z"],
},
arceusrock: {
randomBattleMoves: ["recover", "swordsdance", "earthquake", "stoneedge", "extremespeed"],
randomDoubleBattleMoves: ["swordsdance", "stoneedge", "recover", "rockslide", "earthquake", "protect"],
eventOnly: true,
requiredItems: ["Stone Plate", "Rockium Z"],
},
arceussteel: {
randomBattleMoves: ["calmmind", "judgment", "recover", "willowisp", "thunderbolt", "swordsdance", "ironhead", "earthquake", "stoneedge"],
randomDoubleBattleMoves: ["calmmind", "judgment", "recover", "protect", "willowisp"],
eventOnly: true,
requiredItems: ["Iron Plate", "Steelium Z"],
},
arceuswater: {
randomBattleMoves: ["recover", "calmmind", "judgment", "substitute", "willowisp", "thunderbolt"],
randomDoubleBattleMoves: ["recover", "calmmind", "judgment", "icebeam", "fireblast", "icywind", "surf", "protect"],
eventOnly: true,
requiredItems: ["Splash Plate", "Waterium Z"],
},
victini: {
randomBattleMoves: ["vcreate", "boltstrike", "uturn", "zenheadbutt", "grassknot", "focusblast", "blueflare"],
randomDoubleBattleMoves: ["vcreate", "boltstrike", "uturn", "psychic", "focusblast", "blueflare", "protect"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["quickattack", "incinerate", "confusion", "endure"]},
{"generation": 5, "level": 50, "moves":["vcreate", "fusionflare", "fusionbolt", "searingshot"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "moves":["vcreate", "blueflare", "boltstrike", "glaciate"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["confusion", "quickattack", "vcreate", "searingshot"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["incinerate", "quickattack", "endure", "confusion"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["quickattack", "swagger", "vcreate"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
snivy: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"],
eventPokemon: [
{"generation": 5, "level": 5, "gender": "M", "nature": "Hardy", "isHidden": false, "moves":["growth", "synthesis", "energyball", "aromatherapy"], "pokeball": "cherishball"},
],
tier: "LC",
},
servine: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "leechseed", "hiddenpowerice", "gigadrain"],
tier: "NFE",
},
serperior: {
randomBattleMoves: ["leafstorm", "dragonpulse", "hiddenpowerfire", "substitute", "leechseed", "glare"],
randomDoubleBattleMoves: ["leafstorm", "hiddenpowerfire", "substitute", "taunt", "dragonpulse", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["leafstorm", "substitute", "gigadrain", "leechseed"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["leafstorm", "holdback", "wringout", "gigadrain"], "pokeball": "cherishball"},
],
tier: "New",
},
tepig: {
randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"],
tier: "LC",
},
pignite: {
randomBattleMoves: ["flamecharge", "flareblitz", "wildcharge", "superpower", "headsmash"],
tier: "NFE",
},
emboar: {
randomBattleMoves: ["flareblitz", "superpower", "wildcharge", "stoneedge", "fireblast", "grassknot", "suckerpunch"],
randomDoubleBattleMoves: ["flareblitz", "superpower", "flamecharge", "wildcharge", "headsmash", "protect", "heatwave", "rockslide"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["flareblitz", "hammerarm", "wildcharge", "headsmash"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["flareblitz", "holdback", "headsmash", "takedown"], "pokeball": "cherishball"},
],
tier: "New",
},
oshawott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"],
tier: "LC",
},
dewott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "xscissor"],
tier: "NFE",
},
samurott: {
randomBattleMoves: ["swordsdance", "waterfall", "aquajet", "megahorn", "superpower", "hydropump", "icebeam", "grassknot"],
randomDoubleBattleMoves: ["hydropump", "aquajet", "icebeam", "scald", "hiddenpowergrass", "taunt", "helpinghand", "protect"],
eventPokemon: [
{"generation": 5, "level": 100, "gender": "M", "isHidden": false, "moves":["hydropump", "icebeam", "megahorn", "superpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "isHidden": true, "moves":["razorshell", "holdback", "confide", "hydropump"], "pokeball": "cherishball"},
],
tier: "New",
},
patrat: {
randomBattleMoves: ["swordsdance", "batonpass", "substitute", "hypnosis", "return", "superfang"],
tier: "Bank-LC",
},
watchog: {
randomBattleMoves: ["hypnosis", "substitute", "batonpass", "superfang", "swordsdance", "return", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "knockoff", "substitute", "hypnosis", "return", "superfang", "protect"],
tier: "Bank",
},
lillipup: {
randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"],
tier: "LC",
},
herdier: {
randomBattleMoves: ["return", "wildcharge", "firefang", "crunch", "icefang"],
tier: "NFE",
},
stoutland: {
randomBattleMoves: ["return", "crunch", "wildcharge", "superpower", "icefang"],
randomDoubleBattleMoves: ["return", "wildcharge", "superpower", "crunch", "icefang", "protect"],
tier: "New",
},
purrloin: {
randomBattleMoves: ["encore", "taunt", "uturn", "knockoff", "thunderwave"],
tier: "Bank-LC",
},
liepard: {
randomBattleMoves: ["knockoff", "encore", "suckerpunch", "thunderwave", "uturn", "substitute", "nastyplot", "darkpulse", "copycat"],
randomDoubleBattleMoves: ["encore", "thunderwave", "substitute", "knockoff", "playrough", "uturn", "suckerpunch", "fakeout", "protect"],
eventPokemon: [
{"generation": 5, "level": 20, "gender": "F", "nature": "Jolly", "isHidden": true, "moves":["fakeout", "foulplay", "encore", "swagger"]},
],
tier: "Bank",
},
pansage: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "nastyplot", "substitute", "leechseed"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Brave", "ivs": {"spa": 31}, "isHidden": false, "moves":["bulletseed", "bite", "solarbeam", "dig"]},
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "vinewhip", "leafstorm"]},
{"generation": 5, "level": 30, "gender": "M", "nature": "Serious", "isHidden": false, "moves":["seedbomb", "solarbeam", "rocktomb", "dig"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
simisage: {
randomBattleMoves: ["nastyplot", "gigadrain", "focusblast", "hiddenpowerice", "substitute", "leafstorm", "knockoff", "superpower"],
randomDoubleBattleMoves: ["nastyplot", "leafstorm", "hiddenpowerfire", "hiddenpowerice", "gigadrain", "focusblast", "substitute", "taunt", "synthesis", "helpinghand", "protect"],
tier: "Bank",
},
pansear: {
randomBattleMoves: ["nastyplot", "fireblast", "hiddenpowerelectric", "hiddenpowerground", "sunnyday", "solarbeam", "overheat"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "incinerate", "heatwave"]},
],
tier: "Bank-LC",
},
simisear: {
randomBattleMoves: ["substitute", "nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerrock"],
randomDoubleBattleMoves: ["nastyplot", "fireblast", "focusblast", "grassknot", "hiddenpowerground", "substitute", "heatwave", "taunt", "protect"],
eventPokemon: [
{"generation": 6, "level": 5, "perfectIVs": 2, "isHidden": false, "moves":["workup", "honeclaws", "poweruppunch", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "Bank",
},
panpour: {
randomBattleMoves: ["nastyplot", "hydropump", "hiddenpowergrass", "substitute", "surf", "icebeam"],
eventPokemon: [
{"generation": 5, "level": 10, "gender": "M", "isHidden": true, "moves":["leer", "lick", "watergun", "hydropump"]},
],
tier: "Bank-LC",
},
simipour: {
randomBattleMoves: ["substitute", "nastyplot", "hydropump", "icebeam", "focusblast"],
randomDoubleBattleMoves: ["nastyplot", "hydropump", "icebeam", "substitute", "surf", "taunt", "helpinghand", "protect"],
tier: "Bank",
},
munna: {
randomBattleMoves: ["psychic", "hiddenpowerfighting", "hypnosis", "calmmind", "moonlight", "thunderwave", "batonpass", "psyshock", "healbell", "signalbeam"],
tier: "Bank-LC",
},
musharna: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "signalbeam", "batonpass", "moonlight", "healbell", "thunderwave"],
randomDoubleBattleMoves: ["trickroom", "thunderwave", "moonlight", "psychic", "hiddenpowerfighting", "helpinghand", "psyshock", "healbell", "signalbeam", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "isHidden": true, "moves":["defensecurl", "luckychant", "psybeam", "hypnosis"]},
],
tier: "Bank",
},
pidove: {
randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "F", "nature": "Hardy", "ivs": {"atk": 31}, "isHidden": false, "abilities":["superluck"], "moves":["gust", "quickattack", "aircutter"]},
],
tier: "Bank-LC",
},
tranquill: {
randomBattleMoves: ["pluck", "uturn", "return", "detect", "roost", "wish"],
tier: "Bank-NFE",
},
unfezant: {
randomBattleMoves: ["return", "pluck", "hypnosis", "tailwind", "uturn", "roost", "nightslash"],
randomDoubleBattleMoves: ["pluck", "uturn", "return", "protect", "tailwind", "taunt", "roost", "nightslash"],
tier: "Bank",
},
blitzle: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "wildcharge", "mefirst"],
tier: "Bank-LC",
},
zebstrika: {
randomBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "thunderbolt"],
randomDoubleBattleMoves: ["voltswitch", "hiddenpowergrass", "overheat", "wildcharge", "protect"],
tier: "Bank",
},
roggenrola: {
randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"],
tier: "LC",
},
boldore: {
randomBattleMoves: ["autotomize", "stoneedge", "stealthrock", "rockblast", "earthquake", "explosion"],
tier: "NFE",
},
gigalith: {
randomBattleMoves: ["stealthrock", "rockblast", "earthquake", "explosion", "stoneedge", "superpower"],
randomDoubleBattleMoves: ["stealthrock", "rockslide", "earthquake", "explosion", "stoneedge", "autotomize", "superpower", "wideguard", "protect"],
tier: "New",
},
woobat: {
randomBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "roost", "heatwave", "storedpower"],
tier: "Bank-LC",
},
swoobat: {
randomBattleMoves: ["substitute", "calmmind", "storedpower", "heatwave", "psychic", "airslash", "roost"],
randomDoubleBattleMoves: ["calmmind", "psychic", "airslash", "gigadrain", "protect", "heatwave", "tailwind"],
tier: "Bank",
},
drilbur: {
randomBattleMoves: ["swordsdance", "rapidspin", "earthquake", "rockslide", "shadowclaw", "return", "xscissor"],
tier: "Bank-LC",
},
excadrill: {
randomBattleMoves: ["swordsdance", "earthquake", "ironhead", "rockslide", "rapidspin"],
randomDoubleBattleMoves: ["swordsdance", "drillrun", "earthquake", "rockslide", "ironhead", "substitute", "protect"],
tier: "Bank",
},
audino: {
randomBattleMoves: ["wish", "protect", "healbell", "toxic", "thunderwave", "reflect", "lightscreen", "doubleedge"],
randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "reflect", "lightscreen", "doubleedge", "helpinghand"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "F", "nature": "Calm", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "doubleslap"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "F", "nature": "Serious", "isHidden": false, "abilities":["healer"], "moves":["healpulse", "helpinghand", "refresh", "present"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "nature": "Relaxed", "isHidden": false, "abilities":["regenerator"], "moves":["trickroom", "healpulse", "simplebeam", "thunderbolt"], "pokeball": "cherishball"},
],
tier: "Bank",
},
audinomega: {
randomBattleMoves: ["wish", "calmmind", "healbell", "dazzlinggleam", "hypervoice", "protect"],
randomDoubleBattleMoves: ["healpulse", "protect", "healbell", "trickroom", "thunderwave", "hypervoice", "helpinghand", "dazzlinggleam"],
requiredItem: "Audinite",
tier: "Bank",
},
timburr: {
randomBattleMoves: ["machpunch", "bulkup", "drainpunch", "icepunch", "knockoff"],
tier: "LC",
},
gurdurr: {
randomBattleMoves: ["bulkup", "machpunch", "drainpunch", "icepunch", "knockoff"],
tier: "New",
},
conkeldurr: {
randomBattleMoves: ["bulkup", "drainpunch", "icepunch", "knockoff", "machpunch"],
randomDoubleBattleMoves: ["wideguard", "machpunch", "drainpunch", "icepunch", "knockoff", "protect"],
tier: "New",
},
tympole: {
randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric"],
tier: "Bank-LC",
},
palpitoad: {
randomBattleMoves: ["hydropump", "surf", "sludgewave", "earthpower", "hiddenpowerelectric", "stealthrock"],
tier: "Bank-NFE",
},
seismitoad: {
randomBattleMoves: ["hydropump", "scald", "sludgewave", "earthquake", "knockoff", "stealthrock", "toxic", "raindance"],
randomDoubleBattleMoves: ["hydropump", "muddywater", "sludgebomb", "earthquake", "hiddenpowerelectric", "icywind", "protect"],
tier: "Bank",
},
throh: {
randomBattleMoves: ["bulkup", "circlethrow", "icepunch", "stormthrow", "rest", "sleeptalk", "knockoff"],
randomDoubleBattleMoves: ["helpinghand", "circlethrow", "icepunch", "stormthrow", "wideguard", "knockoff", "protect"],
tier: "Bank",
},
sawk: {
randomBattleMoves: ["closecombat", "earthquake", "icepunch", "poisonjab", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["closecombat", "knockoff", "icepunch", "rockslide", "protect"],
tier: "Bank",
},
sewaddle: {
randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash"],
tier: "LC",
},
swadloon: {
randomBattleMoves: ["calmmind", "gigadrain", "bugbuzz", "hiddenpowerfire", "hiddenpowerice", "airslash", "stickyweb"],
tier: "NFE",
},
leavanny: {
randomBattleMoves: ["stickyweb", "swordsdance", "leafblade", "xscissor", "knockoff", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "leafblade", "xscissor", "protect", "stickyweb", "poisonjab"],
tier: "New",
},
venipede: {
randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"],
tier: "LC",
},
whirlipede: {
randomBattleMoves: ["toxicspikes", "infestation", "spikes", "endeavor", "protect"],
tier: "NFE",
},
scolipede: {
randomBattleMoves: ["substitute", "spikes", "toxicspikes", "megahorn", "rockslide", "earthquake", "swordsdance", "batonpass", "poisonjab"],
randomDoubleBattleMoves: ["substitute", "protect", "megahorn", "rockslide", "poisonjab", "swordsdance", "batonpass", "aquatail", "superpower"],
tier: "New",
},
cottonee: {
randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "toxic", "stunspore"],
tier: "LC",
},
whimsicott: {
randomBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "toxic", "stunspore", "memento", "tailwind", "moonblast"],
randomDoubleBattleMoves: ["encore", "taunt", "substitute", "leechseed", "uturn", "helpinghand", "stunspore", "moonblast", "tailwind", "dazzlinggleam", "gigadrain", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "F", "nature": "Timid", "ivs": {"spe": 31}, "isHidden": false, "abilities":["prankster"], "moves":["swagger", "gigadrain", "beatup", "helpinghand"], "pokeball": "cherishball"},
],
tier: "New",
},
petilil: {
randomBattleMoves: ["sunnyday", "sleeppowder", "solarbeam", "hiddenpowerfire", "hiddenpowerice", "healingwish"],
tier: "LC",
},
lilligant: {
randomBattleMoves: ["sleeppowder", "quiverdance", "petaldance", "gigadrain", "hiddenpowerfire", "hiddenpowerrock"],
randomDoubleBattleMoves: ["quiverdance", "gigadrain", "sleeppowder", "hiddenpowerice", "hiddenpowerfire", "hiddenpowerrock", "petaldance", "helpinghand", "protect"],
tier: "New",
},
basculin: {
randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "zenheadbutt"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"],
tier: "Bank",
},
basculinbluestriped: {
randomBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "zenheadbutt"],
randomDoubleBattleMoves: ["waterfall", "aquajet", "superpower", "crunch", "doubleedge", "protect"],
tier: "Bank",
},
sandile: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"],
tier: "LC",
},
krokorok: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "crunch"],
tier: "NFE",
},
krookodile: {
randomBattleMoves: ["earthquake", "stoneedge", "pursuit", "knockoff", "stealthrock", "superpower"],
randomDoubleBattleMoves: ["earthquake", "stoneedge", "protect", "knockoff", "superpower"],
tier: "New",
},
darumaka: {
randomBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "superpower"],
tier: "Bank-LC",
},
darmanitan: {
randomBattleMoves: ["uturn", "flareblitz", "rockslide", "earthquake", "superpower"],
randomDoubleBattleMoves: ["uturn", "flareblitz", "firepunch", "rockslide", "earthquake", "superpower", "protect"],
eventPokemon: [
{"generation": 5, "level": 35, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"]},
{"generation": 6, "level": 35, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": true, "moves":["thrash", "bellydrum", "flareblitz", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
darmanitanzen: {
requiredAbility: "Zen Mode",
battleOnly: true,
},
maractus: {
randomBattleMoves: ["spikes", "gigadrain", "leechseed", "hiddenpowerfire", "toxic", "suckerpunch", "spikyshield"],
randomDoubleBattleMoves: ["grassyterrain", "gigadrain", "leechseed", "hiddenpowerfire", "helpinghand", "suckerpunch", "spikyshield"],
tier: "Bank",
},
dwebble: {
randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"],
tier: "Bank-LC",
},
crustle: {
randomBattleMoves: ["stealthrock", "spikes", "shellsmash", "earthquake", "rockblast", "xscissor", "stoneedge"],
randomDoubleBattleMoves: ["protect", "shellsmash", "earthquake", "rockslide", "xscissor", "stoneedge"],
tier: "Bank",
},
scraggy: {
randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "crunch", "knockoff"],
eventPokemon: [
{"generation": 5, "level": 1, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moxie"], "moves":["headbutt", "leer", "highjumpkick", "lowkick"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
scrafty: {
randomBattleMoves: ["dragondance", "icepunch", "highjumpkick", "drainpunch", "rest", "bulkup", "knockoff"],
randomDoubleBattleMoves: ["fakeout", "drainpunch", "knockoff", "icepunch", "stoneedge", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Brave", "isHidden": false, "abilities":["moxie"], "moves":["firepunch", "payback", "drainpunch", "substitute"], "pokeball": "cherishball"},
],
tier: "Bank",
},
sigilyph: {
randomBattleMoves: ["cosmicpower", "roost", "storedpower", "psychoshift"],
randomDoubleBattleMoves: ["psyshock", "heatwave", "icebeam", "airslash", "energyball", "shadowball", "tailwind", "protect"],
tier: "Bank",
},
yamask: {
randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "rest", "sleeptalk", "painsplit"],
tier: "Bank-LC",
},
cofagrigus: {
randomBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "haze", "painsplit"],
randomDoubleBattleMoves: ["nastyplot", "trickroom", "shadowball", "hiddenpowerfighting", "willowisp", "protect", "painsplit"],
tier: "Bank",
},
tirtouga: {
randomBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "stealthrock"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "isHidden": false, "abilities":["sturdy"], "moves":["bite", "protect", "aquajet", "bodyslam"], "pokeball": "cherishball"},
],
tier: "LC",
},
carracosta: {
randomBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "stealthrock"],
randomDoubleBattleMoves: ["shellsmash", "aquajet", "waterfall", "stoneedge", "earthquake", "protect", "wideguard", "rockslide"],
tier: "New",
},
archen: {
randomBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "pluck", "headsmash"],
eventPokemon: [
{"generation": 5, "level": 15, "gender": "M", "moves":["headsmash", "wingattack", "doubleteam", "scaryface"], "pokeball": "cherishball"},
],
tier: "LC",
},
archeops: {
randomBattleMoves: ["headsmash", "acrobatics", "stoneedge", "earthquake", "aquatail", "uturn", "tailwind"],
randomDoubleBattleMoves: ["stoneedge", "rockslide", "earthquake", "uturn", "acrobatics", "tailwind", "taunt", "protect"],
tier: "New",
},
trubbish: {
randomBattleMoves: ["clearsmog", "toxicspikes", "spikes", "gunkshot", "painsplit", "toxic"],
tier: "LC",
},
garbodor: {
randomBattleMoves: ["spikes", "toxicspikes", "gunkshot", "haze", "painsplit", "toxic", "rockblast"],
randomDoubleBattleMoves: ["protect", "painsplit", "gunkshot", "seedbomb", "drainpunch", "explosion", "rockblast"],
tier: "New",
},
zorua: {
randomBattleMoves: ["suckerpunch", "extrasensory", "darkpulse", "hiddenpowerfighting", "uturn", "knockoff"],
tier: "Bank-LC",
},
zoroark: {
randomBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "trick"],
randomDoubleBattleMoves: ["suckerpunch", "darkpulse", "focusblast", "flamethrower", "uturn", "nastyplot", "knockoff", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "M", "nature": "Quirky", "moves":["agility", "embargo", "punishment", "snarl"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "moves":["sludgebomb", "darkpulse", "flamethrower", "suckerpunch"], "pokeball": "ultraball"},
],
tier: "Bank",
},
minccino: {
randomBattleMoves: ["return", "tailslap", "wakeupslap", "uturn", "aquatail"],
tier: "Bank-LC",
},
cinccino: {
randomBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast"],
randomDoubleBattleMoves: ["tailslap", "aquatail", "uturn", "knockoff", "bulletseed", "rockblast", "protect"],
tier: "Bank",
},
gothita: {
randomBattleMoves: ["psychic", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"],
tier: "LC",
},
gothorita: {
randomBattleMoves: ["psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "shadowball", "substitute", "calmmind", "trick", "grassknot"],
eventPokemon: [
{"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "mirrorcoat"]},
{"generation": 5, "level": 32, "gender": "M", "isHidden": true, "moves":["psyshock", "flatter", "futuresight", "imprison"]},
],
tier: "NFE",
},
gothitelle: {
randomBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfire", "hiddenpowerfighting", "substitute", "calmmind", "trick", "psyshock"],
randomDoubleBattleMoves: ["psychic", "thunderbolt", "shadowball", "hiddenpowerfighting", "reflect", "lightscreen", "psyshock", "energyball", "trickroom", "taunt", "healpulse", "protect"],
tier: "New",
},
solosis: {
randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"],
tier: "LC",
},
duosion: {
randomBattleMoves: ["calmmind", "recover", "psychic", "hiddenpowerfighting", "shadowball", "trickroom", "psyshock"],
tier: "NFE",
},
reuniclus: {
randomBattleMoves: ["calmmind", "recover", "psychic", "focusblast", "shadowball", "trickroom", "psyshock"],
randomDoubleBattleMoves: ["energyball", "helpinghand", "psychic", "focusblast", "shadowball", "trickroom", "psyshock", "hiddenpowerfire", "protect"],
tier: "New",
},
ducklett: {
randomBattleMoves: ["scald", "airslash", "roost", "hurricane", "icebeam", "hiddenpowergrass", "bravebird", "defog"],
tier: "Bank-LC",
},
swanna: {
randomBattleMoves: ["airslash", "roost", "hurricane", "surf", "icebeam", "raindance", "defog", "scald"],
randomDoubleBattleMoves: ["airslash", "roost", "hurricane", "surf", "icebeam", "raindance", "tailwind", "scald", "protect"],
tier: "Bank",
},
vanillite: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"],
tier: "LC",
},
vanillish: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerelectric", "hiddenpowerfighting", "autotomize"],
tier: "NFE",
},
vanilluxe: {
randomBattleMoves: ["icebeam", "explosion", "hiddenpowerground", "flashcannon", "autotomize", "freezedry"],
randomDoubleBattleMoves: ["icebeam", "taunt", "hiddenpowerground", "flashcannon", "autotomize", "protect", "freezedry"],
tier: "New",
},
deerling: {
randomBattleMoves: ["agility", "batonpass", "seedbomb", "jumpkick", "synthesis", "return", "thunderwave"],
eventPokemon: [
{"generation": 5, "level": 30, "gender": "F", "isHidden": true, "moves":["feintattack", "takedown", "jumpkick", "aromatherapy"]},
],
tier: "Bank-LC",
},
sawsbuck: {
randomBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "batonpass"],
randomDoubleBattleMoves: ["swordsdance", "hornleech", "jumpkick", "return", "substitute", "synthesis", "protect"],
tier: "Bank",
},
emolga: {
randomBattleMoves: ["encore", "chargebeam", "batonpass", "substitute", "thunderbolt", "airslash", "roost"],
randomDoubleBattleMoves: ["helpinghand", "tailwind", "encore", "substitute", "thunderbolt", "airslash", "roost", "protect"],
tier: "New",
},
karrablast: {
randomBattleMoves: ["swordsdance", "megahorn", "return", "substitute"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["furyattack", "headbutt", "falseswipe", "bugbuzz"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["megahorn", "takedown", "xscissor", "flail"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
escavalier: {
randomBattleMoves: ["megahorn", "pursuit", "ironhead", "knockoff", "swordsdance", "drillrun"],
randomDoubleBattleMoves: ["megahorn", "protect", "ironhead", "knockoff", "swordsdance", "drillrun"],
tier: "Bank",
},
foongus: {
randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb"],
tier: "Bank-LC",
},
amoonguss: {
randomBattleMoves: ["spore", "stunspore", "gigadrain", "clearsmog", "hiddenpowerfire", "synthesis", "sludgebomb", "foulplay"],
randomDoubleBattleMoves: ["spore", "stunspore", "gigadrain", "ragepowder", "hiddenpowerfire", "synthesis", "sludgebomb", "protect"],
tier: "Bank",
},
frillish: {
randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "taunt"],
tier: "Bank-LC",
},
jellicent: {
randomBattleMoves: ["scald", "willowisp", "recover", "toxic", "shadowball", "icebeam", "taunt"],
randomDoubleBattleMoves: ["scald", "willowisp", "recover", "trickroom", "shadowball", "icebeam", "waterspout", "icywind", "protect"],
eventPokemon: [
{"generation": 5, "level": 40, "isHidden": true, "moves":["waterpulse", "ominouswind", "brine", "raindance"]},
],
tier: "Bank",
},
alomomola: {
randomBattleMoves: ["wish", "protect", "knockoff", "toxic", "scald"],
randomDoubleBattleMoves: ["wish", "protect", "knockoff", "icywind", "scald", "helpinghand", "wideguard"],
tier: "New",
},
joltik: {
randomBattleMoves: ["thunderbolt", "bugbuzz", "hiddenpowerice", "gigadrain", "voltswitch"],
tier: "Bank-LC",
},
galvantula: {
randomBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb"],
randomDoubleBattleMoves: ["thunder", "hiddenpowerice", "gigadrain", "bugbuzz", "voltswitch", "stickyweb", "protect"],
tier: "Bank",
},
ferroseed: {
randomBattleMoves: ["spikes", "stealthrock", "leechseed", "seedbomb", "protect", "thunderwave", "gyroball"],
tier: "Bank",
},
ferrothorn: {
randomBattleMoves: ["spikes", "stealthrock", "leechseed", "powerwhip", "thunderwave", "protect", "knockoff", "gyroball"],
randomDoubleBattleMoves: ["gyroball", "stealthrock", "leechseed", "powerwhip", "thunderwave", "protect"],
tier: "Bank",
},
klink: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
tier: "LC",
},
klang: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
tier: "NFE",
},
klinklang: {
randomBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "substitute"],
randomDoubleBattleMoves: ["shiftgear", "return", "geargrind", "wildcharge", "protect"],
tier: "New",
},
tynamo: {
randomBattleMoves: ["spark", "chargebeam", "thunderwave", "tackle"],
tier: "LC",
},
eelektrik: {
randomBattleMoves: ["uturn", "voltswitch", "acidspray", "wildcharge", "thunderbolt", "gigadrain", "aquatail", "coil"],
tier: "NFE",
},
eelektross: {
randomBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "acidspray", "gigadrain", "knockoff", "superpower", "aquatail"],
randomDoubleBattleMoves: ["thunderbolt", "flamethrower", "uturn", "voltswitch", "knockoff", "gigadrain", "protect"],
tier: "New",
},
elgyem: {
randomBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trickroom", "signalbeam"],
tier: "Bank-LC",
},
beheeyem: {
randomBattleMoves: ["nastyplot", "psychic", "psyshock", "thunderbolt", "hiddenpowerfighting", "trick", "trickroom", "signalbeam"],
randomDoubleBattleMoves: ["nastyplot", "psychic", "thunderbolt", "hiddenpowerfighting", "recover", "trick", "trickroom", "signalbeam", "protect"],
tier: "Bank",
},
litwick: {
randomBattleMoves: ["shadowball", "energyball", "fireblast", "hiddenpowerground", "trickroom", "substitute", "painsplit"],
tier: "LC",
},
lampent: {
randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "substitute", "painsplit"],
tier: "NFE",
},
chandelure: {
randomBattleMoves: ["calmmind", "shadowball", "energyball", "fireblast", "hiddenpowerground", "trick", "substitute", "painsplit"],
randomDoubleBattleMoves: ["shadowball", "energyball", "overheat", "heatwave", "hiddenpowerice", "trick", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "gender": "F", "nature": "Modest", "ivs": {"spa": 31}, "isHidden": false, "abilities":["flashfire"], "moves":["heatwave", "shadowball", "energyball", "psychic"], "pokeball": "cherishball"},
],
tier: "New",
},
axew: {
randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "swordsdance", "aquatail", "superpower", "poisonjab", "taunt", "substitute"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": 1, "gender": "M", "nature": "Naive", "ivs": {"spe": 31}, "isHidden": false, "abilities":["moldbreaker"], "moves":["scratch", "dragonrage"]},
{"generation": 5, "level": 10, "gender": "F", "isHidden": false, "abilities":["moldbreaker"], "moves":["dragonrage", "return", "endure", "dragonclaw"], "pokeball": "cherishball"},
{"generation": 5, "level": 30, "gender": "M", "nature": "Naive", "isHidden": false, "abilities":["rivalry"], "moves":["dragonrage", "scratch", "outrage", "gigaimpact"], "pokeball": "cherishball"},
],
tier: "LC",
},
fraxure: {
randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "aquatail", "superpower", "poisonjab", "taunt", "substitute"],
tier: "NFE",
},
haxorus: {
randomBattleMoves: ["dragondance", "swordsdance", "outrage", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"],
randomDoubleBattleMoves: ["dragondance", "swordsdance", "protect", "dragonclaw", "earthquake", "poisonjab", "taunt", "substitute"],
eventPokemon: [
{"generation": 5, "level": 59, "gender": "F", "nature": "Naive", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "abilities":["moldbreaker"], "moves":["earthquake", "dualchop", "xscissor", "dragondance"], "pokeball": "cherishball"},
],
tier: "New",
},
cubchoo: {
randomBattleMoves: ["icebeam", "surf", "hiddenpowergrass", "superpower"],
eventPokemon: [
{"generation": 5, "level": 15, "isHidden": false, "moves":["powdersnow", "growl", "bide", "icywind"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
beartic: {
randomBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet"],
randomDoubleBattleMoves: ["iciclecrash", "superpower", "nightslash", "stoneedge", "swordsdance", "aquajet", "protect"],
tier: "Bank",
},
cryogonal: {
randomBattleMoves: ["icebeam", "recover", "toxic", "rapidspin", "haze", "freezedry", "hiddenpowerground"],
randomDoubleBattleMoves: ["icebeam", "recover", "icywind", "protect", "reflect", "freezedry", "hiddenpowerground"],
tier: "Bank",
},
shelmet: {
randomBattleMoves: ["spikes", "yawn", "substitute", "acidarmor", "batonpass", "recover", "toxic", "bugbuzz", "infestation"],
eventPokemon: [
{"generation": 5, "level": 30, "isHidden": false, "moves":["strugglebug", "megadrain", "yawn", "protect"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "isHidden": false, "moves":["encore", "gigadrain", "bodyslam", "bugbuzz"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
accelgor: {
randomBattleMoves: ["spikes", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore"],
randomDoubleBattleMoves: ["protect", "yawn", "bugbuzz", "focusblast", "gigadrain", "hiddenpowerrock", "encore", "sludgebomb"],
tier: "Bank",
},
stunfisk: {
randomBattleMoves: ["discharge", "earthpower", "scald", "toxic", "rest", "sleeptalk", "stealthrock"],
randomDoubleBattleMoves: ["discharge", "earthpower", "scald", "electroweb", "protect", "stealthrock"],
tier: "Bank",
},
mienfoo: {
randomBattleMoves: ["uturn", "drainpunch", "stoneedge", "swordsdance", "batonpass", "highjumpkick", "fakeout", "knockoff"],
tier: "Bank-LC",
},
mienshao: {
randomBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "substitute", "swordsdance", "batonpass", "knockoff"],
randomDoubleBattleMoves: ["uturn", "fakeout", "highjumpkick", "stoneedge", "drainpunch", "swordsdance", "wideguard", "knockoff", "feint", "protect"],
tier: "Bank",
},
druddigon: {
randomBattleMoves: ["outrage", "earthquake", "suckerpunch", "dragonclaw", "dragontail", "substitute", "glare", "stealthrock", "firepunch", "gunkshot"],
randomDoubleBattleMoves: ["superpower", "earthquake", "suckerpunch", "dragonclaw", "glare", "protect", "firepunch", "thunderpunch"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "isHidden": false, "moves":["leer", "scratch"]},
],
tier: "Bank",
},
golett: {
randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"],
tier: "Bank-LC",
},
golurk: {
randomBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stealthrock", "rockpolish"],
randomDoubleBattleMoves: ["earthquake", "shadowpunch", "dynamicpunch", "icepunch", "stoneedge", "protect", "rockpolish"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": true, "isHidden": false, "abilities":["ironfist"], "moves":["shadowpunch", "hyperbeam", "gyroball", "hammerarm"], "pokeball": "cherishball"},
],
tier: "Bank",
},
pawniard: {
randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"],
tier: "Bank",
},
bisharp: {
randomBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff"],
randomDoubleBattleMoves: ["swordsdance", "substitute", "suckerpunch", "ironhead", "brickbreak", "knockoff", "protect"],
tier: "Bank",
},
bouffalant: {
randomBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower"],
randomDoubleBattleMoves: ["headcharge", "earthquake", "stoneedge", "megahorn", "swordsdance", "superpower", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": true, "moves":["headcharge", "facade", "earthquake", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
rufflet: {
randomBattleMoves: ["bravebird", "rockslide", "return", "uturn", "substitute", "bulkup", "roost"],
tier: "LC",
},
braviary: {
randomBattleMoves: ["bravebird", "superpower", "return", "uturn", "substitute", "rockslide", "bulkup", "roost"],
randomDoubleBattleMoves: ["bravebird", "superpower", "return", "uturn", "tailwind", "rockslide", "bulkup", "roost", "skydrop", "protect"],
eventPokemon: [
{"generation": 5, "level": 25, "gender": "M", "isHidden": true, "moves":["wingattack", "honeclaws", "scaryface", "aerialace"]},
],
tier: "New",
},
vullaby: {
randomBattleMoves: ["knockoff", "roost", "taunt", "whirlwind", "toxic", "defog", "uturn", "bravebird"],
tier: "New",
},
mandibuzz: {
randomBattleMoves: ["foulplay", "knockoff", "roost", "taunt", "whirlwind", "toxic", "uturn", "bravebird", "defog"],
randomDoubleBattleMoves: ["knockoff", "roost", "taunt", "tailwind", "snarl", "uturn", "bravebird", "protect"],
eventPokemon: [
{"generation": 5, "level": 25, "gender": "F", "isHidden": true, "moves":["pluck", "nastyplot", "flatter", "feintattack"]},
],
tier: "New",
},
heatmor: {
randomBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "knockoff"],
randomDoubleBattleMoves: ["fireblast", "suckerpunch", "focusblast", "gigadrain", "heatwave", "protect"],
tier: "Bank",
},
durant: {
randomBattleMoves: ["honeclaws", "ironhead", "xscissor", "stoneedge", "batonpass", "superpower"],
randomDoubleBattleMoves: ["honeclaws", "ironhead", "xscissor", "rockslide", "protect", "superpower"],
tier: "Bank",
},
deino: {
randomBattleMoves: ["outrage", "crunch", "firefang", "dragontail", "thunderwave", "superpower"],
eventPokemon: [
{"generation": 5, "level": 1, "shiny": true, "moves":["tackle", "dragonrage"]},
],
tier: "LC",
},
zweilous: {
randomBattleMoves: ["outrage", "crunch", "headsmash", "dragontail", "superpower", "rest", "sleeptalk"],
tier: "NFE",
},
hydreigon: {
randomBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower"],
randomDoubleBattleMoves: ["uturn", "dracometeor", "dragonpulse", "earthpower", "fireblast", "darkpulse", "roost", "flashcannon", "superpower", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": true, "gender": "M", "moves":["hypervoice", "dragonbreath", "flamethrower", "focusblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 52, "gender": "M", "perfectIVs": 2, "moves":["dragonrush", "crunch", "rockslide", "frustration"], "pokeball": "cherishball"},
],
tier: "New",
},
larvesta: {
randomBattleMoves: ["flareblitz", "uturn", "wildcharge", "zenheadbutt", "morningsun", "willowisp"],
tier: "Bank-LC",
},
volcarona: {
randomBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "hiddenpowerground"],
randomDoubleBattleMoves: ["quiverdance", "fierydance", "fireblast", "bugbuzz", "roost", "gigadrain", "hiddenpowerice", "heatwave", "willowisp", "ragepowder", "tailwind", "protect"],
eventPokemon: [
{"generation": 5, "level": 35, "isHidden": false, "moves":["stringshot", "leechlife", "gust", "firespin"]},
{"generation": 5, "level": 77, "gender": "M", "nature": "Calm", "ivs": {"hp": 30, "atk": 30, "def": 30, "spa": 30, "spd": 30, "spe": 30}, "isHidden": false, "moves":["bugbuzz", "overheat", "hyperbeam", "quiverdance"], "pokeball": "cherishball"},
],
tier: "Bank",
},
cobalion: {
randomBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "voltswitch", "hiddenpowerice", "taunt", "stealthrock"],
randomDoubleBattleMoves: ["closecombat", "ironhead", "swordsdance", "substitute", "stoneedge", "thunderwave", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "ironhead", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "ironhead", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
terrakion: {
randomBattleMoves: ["stoneedge", "closecombat", "swordsdance", "substitute", "stealthrock", "earthquake"],
randomDoubleBattleMoves: ["stoneedge", "closecombat", "substitute", "rockslide", "earthquake", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "rockslide", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "rockslide", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
virizion: {
randomBattleMoves: ["swordsdance", "closecombat", "leafblade", "stoneedge", "calmmind", "focusblast", "gigadrain", "hiddenpowerice", "substitute"],
randomDoubleBattleMoves: ["taunt", "closecombat", "stoneedge", "leafblade", "swordsdance", "synthesis", "protect"],
eventPokemon: [
{"generation": 5, "level": 42, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]},
{"generation": 5, "level": 45, "shiny": 1, "moves":["helpinghand", "retaliate", "gigadrain", "sacredsword"]},
{"generation": 5, "level": 65, "shiny": 1, "moves":["sacredsword", "swordsdance", "quickguard", "workup"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["retaliate", "gigadrain", "sacredsword", "swordsdance"]},
],
eventOnly: true,
tier: "Bank",
},
tornadus: {
randomBattleMoves: ["bulkup", "acrobatics", "knockoff", "substitute", "hurricane", "heatwave", "superpower", "uturn", "taunt", "tailwind"],
randomDoubleBattleMoves: ["hurricane", "airslash", "uturn", "superpower", "focusblast", "taunt", "substitute", "heatwave", "tailwind", "protect", "skydrop"],
eventPokemon: [
{"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "aircutter", "extrasensory", "agility"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "gust"], "pokeball": "dreamball"},
{"generation": 5, "level": 70, "isHidden": false, "moves":["hurricane", "hammerarm", "airslash", "hiddenpower"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["extrasensory", "agility", "airslash", "crunch"]},
],
eventOnly: true,
tier: "Bank",
},
tornadustherian: {
randomBattleMoves: ["hurricane", "airslash", "heatwave", "knockoff", "superpower", "uturn", "taunt"],
randomDoubleBattleMoves: ["hurricane", "airslash", "focusblast", "uturn", "heatwave", "skydrop", "tailwind", "taunt", "protect"],
eventOnly: true,
tier: "Bank",
},
thundurus: {
randomBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt"],
randomDoubleBattleMoves: ["thunderwave", "nastyplot", "thunderbolt", "hiddenpowerice", "hiddenpowerflying", "focusblast", "substitute", "knockoff", "taunt", "protect"],
eventPokemon: [
{"generation": 5, "level": 40, "shiny": 1, "isHidden": false, "moves":["revenge", "shockwave", "healblock", "agility"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["uproar", "astonish", "thundershock"], "pokeball": "dreamball"},
{"generation": 5, "level": 70, "isHidden": false, "moves":["thunder", "hammerarm", "focusblast", "wildcharge"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "isHidden": false, "moves":["healblock", "agility", "discharge", "crunch"]},
],
eventOnly: true,
tier: "Bank",
},
thundurustherian: {
randomBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch"],
randomDoubleBattleMoves: ["nastyplot", "thunderbolt", "hiddenpowerflying", "hiddenpowerice", "focusblast", "voltswitch", "protect"],
eventOnly: true,
tier: "Bank",
},
reshiram: {
randomBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "toxic", "flamecharge", "stoneedge", "roost"],
randomDoubleBattleMoves: ["blueflare", "dracometeor", "dragonpulse", "heatwave", "flamecharge", "roost", "protect", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]},
{"generation": 5, "level": 70, "moves":["extrasensory", "fusionflare", "dragonpulse", "imprison"]},
{"generation": 5, "level": 100, "moves":["blueflare", "fusionflare", "mist", "dracometeor"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "extrasensory", "fusionflare"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
zekrom: {
randomBattleMoves: ["boltstrike", "outrage", "dragonclaw", "dracometeor", "voltswitch", "honeclaws", "substitute", "roost"],
randomDoubleBattleMoves: ["voltswitch", "protect", "dragonclaw", "boltstrike", "honeclaws", "substitute", "dracometeor", "fusionbolt", "roost", "tailwind"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]},
{"generation": 5, "level": 70, "moves":["zenheadbutt", "fusionbolt", "dragonclaw", "imprison"]},
{"generation": 5, "level": 100, "moves":["boltstrike", "fusionbolt", "haze", "outrage"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "zenheadbutt", "fusionbolt"]},
],
eventOnly: true,
tier: "Bank-Uber",
},
landorus: {
randomBattleMoves: ["calmmind", "rockpolish", "earthpower", "focusblast", "psychic", "sludgewave", "stealthrock", "knockoff", "rockslide"],
randomDoubleBattleMoves: ["earthpower", "focusblast", "hiddenpowerice", "psychic", "sludgebomb", "rockslide", "protect"],
eventPokemon: [
{"generation": 5, "level": 70, "shiny": 1, "isHidden": false, "moves":["rockslide", "earthquake", "sandstorm", "fissure"]},
{"generation": 5, "level": 5, "isHidden": true, "moves":["block", "mudshot", "rocktomb"], "pokeball": "dreamball"},
{"generation": 6, "level": 65, "shiny": 1, "isHidden": false, "moves":["extrasensory", "swordsdance", "earthpower", "rockslide"]},
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31, "def": 31, "spa": 1, "spd": 31, "spe": 24}, "isHidden": false, "moves":["earthquake", "knockoff", "uturn", "rocktomb"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
landorustherian: {
randomBattleMoves: ["swordsdance", "rockpolish", "earthquake", "stoneedge", "uturn", "superpower", "stealthrock"],
randomDoubleBattleMoves: ["rockslide", "earthquake", "stoneedge", "uturn", "superpower", "knockoff", "protect"],
eventOnly: true,
tier: "Bank",
},
kyurem: {
randomBattleMoves: ["dracometeor", "icebeam", "earthpower", "outrage", "substitute", "dragonpulse", "focusblast", "roost"],
randomDoubleBattleMoves: ["substitute", "icebeam", "dracometeor", "dragonpulse", "focusblast", "glaciate", "earthpower", "roost", "protect"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["glaciate", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["scaryface", "glaciate", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "scaryface", "glaciate"]},
{"generation": 6, "level": 100, "moves":["glaciate", "scaryface", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
kyuremblack: {
randomBattleMoves: ["outrage", "fusionbolt", "icebeam", "roost", "substitute", "earthpower", "dragonclaw"],
randomDoubleBattleMoves: ["protect", "fusionbolt", "icebeam", "roost", "substitute", "honeclaws", "earthpower", "dragonclaw"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["freezeshock", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["fusionbolt", "freezeshock", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionbolt", "freezeshock"]},
{"generation": 6, "level": 100, "moves":["freezeshock", "fusionbolt", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
kyuremwhite: {
randomBattleMoves: ["dracometeor", "icebeam", "fusionflare", "earthpower", "focusblast", "dragonpulse", "substitute", "roost", "toxic"],
randomDoubleBattleMoves: ["dracometeor", "dragonpulse", "icebeam", "fusionflare", "earthpower", "focusblast", "roost", "protect"],
eventPokemon: [
{"generation": 5, "level": 75, "shiny": 1, "moves":["iceburn", "dragonpulse", "imprison", "endeavor"]},
{"generation": 5, "level": 70, "shiny": 1, "moves":["fusionflare", "iceburn", "dragonpulse", "imprison"]},
{"generation": 6, "level": 50, "shiny": 1, "moves":["dragonbreath", "slash", "fusionflare", "iceburn"]},
{"generation": 6, "level": 100, "moves":["iceburn", "fusionflare", "dracometeor", "ironhead"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
keldeo: {
randomBattleMoves: ["hydropump", "secretsword", "calmmind", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "scald", "icywind"],
randomDoubleBattleMoves: ["hydropump", "secretsword", "protect", "hiddenpowerflying", "hiddenpowerelectric", "substitute", "surf", "icywind", "taunt"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["sacredsword", "hydropump", "aquajet", "swordsdance"], "pokeball": "cherishball"},
{"generation": 6, "level": 15, "moves":["aquajet", "leer", "doublekick", "hydropump"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["aquajet", "leer", "doublekick", "bubblebeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
keldeoresolute: {
eventOnly: true,
requiredMove: "Secret Sword",
},
meloetta: {
randomBattleMoves: ["uturn", "calmmind", "psyshock", "hypervoice", "shadowball", "focusblast"],
randomDoubleBattleMoves: ["calmmind", "psyshock", "thunderbolt", "hypervoice", "shadowball", "focusblast", "protect"],
eventPokemon: [
{"generation": 5, "level": 15, "moves":["quickattack", "confusion", "round"], "pokeball": "cherishball"},
{"generation": 5, "level": 50, "moves":["round", "teeterdance", "psychic", "closecombat"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
meloettapirouette: {
randomBattleMoves: ["relicsong", "closecombat", "knockoff", "return"],
randomDoubleBattleMoves: ["relicsong", "closecombat", "knockoff", "return", "protect"],
requiredMove: "Relic Song",
battleOnly: true,
},
genesect: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "ironhead", "shiftgear", "extremespeed", "blazekick", "protect"],
eventPokemon: [
{"generation": 5, "level": 50, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 15, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
{"generation": 5, "level": 100, "shiny": true, "nature": "Hasty", "ivs": {"atk": 31, "spe": 31}, "moves":["extremespeed", "technoblast", "blazekick", "shiftgear"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "moves":["technoblast", "magnetbomb", "solarbeam", "signalbeam"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
genesectburn: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "technoblast", "thunderbolt", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Burn Drive",
},
genesectchill: {
randomBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "technoblast", "flamethrower", "thunderbolt", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Chill Drive",
},
genesectdouse: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "thunderbolt", "technoblast", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Douse Drive",
},
genesectshock: {
randomBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed"],
randomDoubleBattleMoves: ["uturn", "bugbuzz", "icebeam", "flamethrower", "technoblast", "ironhead", "extremespeed", "protect"],
eventOnly: true,
requiredItem: "Shock Drive",
},
chespin: {
randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"],
tier: "Bank-LC",
},
quilladin: {
randomBattleMoves: ["curse", "gyroball", "seedbomb", "stoneedge", "spikes", "synthesis"],
tier: "Bank-NFE",
},
chesnaught: {
randomBattleMoves: ["leechseed", "synthesis", "spikes", "drainpunch", "spikyshield", "woodhammer"],
randomDoubleBattleMoves: ["leechseed", "synthesis", "hammerarm", "spikyshield", "stoneedge", "woodhammer", "rockslide"],
tier: "Bank",
},
fennekin: {
randomBattleMoves: ["fireblast", "psychic", "psyshock", "grassknot", "willowisp", "hypnosis", "hiddenpowerrock", "flamecharge"],
eventPokemon: [
{"generation": 6, "level": 15, "gender": "F", "nature": "Hardy", "isHidden": false, "moves":["scratch", "flamethrower", "hiddenpower"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
braixen: {
randomBattleMoves: ["fireblast", "flamethrower", "psychic", "psyshock", "grassknot", "willowisp", "hiddenpowerrock"],
tier: "Bank-NFE",
},
delphox: {
randomBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball"],
randomDoubleBattleMoves: ["calmmind", "fireblast", "psyshock", "grassknot", "switcheroo", "shadowball", "heatwave", "dazzlinggleam", "protect"],
tier: "Bank",
},
froakie: {
randomBattleMoves: ["quickattack", "hydropump", "icebeam", "waterfall", "toxicspikes", "poweruppunch", "uturn"],
eventPokemon: [
{"generation": 6, "level": 7, "isHidden": false, "moves":["pound", "growl", "bubble", "return"], "pokeball": "cherishball"},
],
tier: "LC",
},
frogadier: {
randomBattleMoves: ["hydropump", "surf", "icebeam", "uturn", "taunt", "toxicspikes"],
tier: "NFE",
},
greninja: {
randomBattleMoves: ["hydropump", "icebeam", "darkpulse", "gunkshot", "uturn", "spikes", "toxicspikes", "taunt"],
randomDoubleBattleMoves: ["hydropump", "uturn", "surf", "icebeam", "matblock", "taunt", "darkpulse", "protect"],
eventPokemon: [
{"generation": 6, "level": 36, "ivs": {"spe": 31}, "isHidden": true, "moves":["watershuriken", "shadowsneak", "hydropump", "substitute"], "pokeball": "cherishball"},
{"generation": 6, "level": 100, "isHidden": true, "moves":["hydrocannon", "gunkshot", "matblock", "happyhour"], "pokeball": "cherishball"},
],
tier: "New",
},
greninjaash: {
gen: 7,
requiredAbility: "Battle Bond",
battleOnly: true,
},
bunnelby: {
randomBattleMoves: ["agility", "earthquake", "return", "quickattack", "uturn", "stoneedge", "spikes", "bounce"],
tier: "Bank-LC",
},
diggersby: {
randomBattleMoves: ["earthquake", "return", "wildcharge", "uturn", "swordsdance", "quickattack", "knockoff", "agility"],
randomDoubleBattleMoves: ["earthquake", "uturn", "return", "wildcharge", "protect", "quickattack"],
tier: "Bank",
},
fletchling: {
randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind"],
tier: "LC",
},
fletchinder: {
randomBattleMoves: ["roost", "swordsdance", "uturn", "return", "overheat", "flamecharge", "tailwind", "acrobatics"],
tier: "New",
},
talonflame: {
randomBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind"],
randomDoubleBattleMoves: ["bravebird", "flareblitz", "roost", "swordsdance", "uturn", "willowisp", "tailwind", "taunt", "protect"],
tier: "New",
},
scatterbug: {
randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"],
tier: "Bank-LC",
},
spewpa: {
randomBattleMoves: ["tackle", "stringshot", "stunspore", "bugbite", "poisonpowder"],
tier: "Bank-NFE",
},
vivillon: {
randomBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "substitute"],
randomDoubleBattleMoves: ["sleeppowder", "quiverdance", "hurricane", "bugbuzz", "roost", "protect"],
tier: "Bank",
},
vivillonfancy: {
eventPokemon: [
{"generation": 6, "level": 12, "isHidden": false, "moves":["gust", "lightscreen", "strugglebug", "holdhands"], "pokeball": "cherishball"},
],
eventOnly: true,
},
vivillonpokeball: {
eventPokemon: [
{"generation": 6, "level": 12, "isHidden": false, "moves":["stunspore", "gust", "lightscreen", "strugglebug"]},
],
eventOnly: true,
},
litleo: {
randomBattleMoves: ["hypervoice", "fireblast", "willowisp", "bulldoze", "yawn"],
tier: "Bank-LC",
},
pyroar: {
randomBattleMoves: ["sunnyday", "fireblast", "hypervoice", "solarbeam", "willowisp", "darkpulse"],
randomDoubleBattleMoves: ["hypervoice", "fireblast", "willowisp", "protect", "sunnyday", "solarbeam"],
eventPokemon: [
{"generation": 6, "level": 49, "gender": "M", "perfectIVs": 2, "isHidden": false, "abilities":["unnerve"], "moves":["hypervoice", "fireblast", "darkpulse"], "pokeball": "cherishball"},
],
tier: "Bank",
},
flabebe: {
randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank-LC",
},
floette: {
randomBattleMoves: ["moonblast", "toxic", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank-NFE",
},
floetteeternal: {
randomBattleMoves: ["lightofruin", "psychic", "hiddenpowerfire", "hiddenpowerground", "moonblast"],
randomDoubleBattleMoves: ["lightofruin", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
isUnreleased: true,
tier: "Unreleased",
},
florges: {
randomBattleMoves: ["calmmind", "moonblast", "synthesis", "aromatherapy", "wish", "toxic", "protect"],
randomDoubleBattleMoves: ["moonblast", "dazzlinggleam", "wish", "psychic", "aromatherapy", "protect", "calmmind"],
tier: "Bank",
},
skiddo: {
randomBattleMoves: ["hornleech", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide"],
tier: "Bank-LC",
},
gogoat: {
randomBattleMoves: ["bulkup", "hornleech", "earthquake", "rockslide", "substitute", "leechseed", "milkdrink"],
randomDoubleBattleMoves: ["hornleech", "earthquake", "brickbreak", "bulkup", "leechseed", "milkdrink", "rockslide", "protect"],
tier: "Bank",
},
pancham: {
randomBattleMoves: ["partingshot", "skyuppercut", "crunch", "stoneedge", "bulldoze", "shadowclaw", "bulkup"],
eventPokemon: [
{"generation": 6, "level": 30, "gender": "M", "nature": "Adamant", "isHidden": false, "abilities":["moldbreaker"], "moves":["armthrust", "stoneedge", "darkpulse"], "pokeball": "cherishball"},
],
tier: "LC",
},
pangoro: {
randomBattleMoves: ["knockoff", "superpower", "gunkshot", "icepunch", "partingshot", "drainpunch"],
randomDoubleBattleMoves: ["partingshot", "hammerarm", "crunch", "circlethrow", "icepunch", "earthquake", "poisonjab", "protect"],
tier: "New",
},
furfrou: {
randomBattleMoves: ["return", "cottonguard", "thunderwave", "substitute", "toxic", "suckerpunch", "uturn", "rest"],
randomDoubleBattleMoves: ["return", "cottonguard", "uturn", "thunderwave", "suckerpunch", "snarl", "wildcharge", "protect"],
tier: "Bank",
},
espurr: {
randomBattleMoves: ["fakeout", "yawn", "thunderwave", "psychic", "trick", "darkpulse"],
tier: "Bank-LC",
},
meowstic: {
randomBattleMoves: ["toxic", "yawn", "thunderwave", "psychic", "reflect", "lightscreen", "healbell"],
randomDoubleBattleMoves: ["fakeout", "thunderwave", "psychic", "reflect", "lightscreen", "safeguard", "protect"],
tier: "Bank",
},
meowsticf: {
randomBattleMoves: ["calmmind", "psychic", "psyshock", "shadowball", "energyball", "thunderbolt"],
randomDoubleBattleMoves: ["psyshock", "darkpulse", "fakeout", "energyball", "signalbeam", "thunderbolt", "protect", "helpinghand"],
tier: "Bank",
},
honedge: {
randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "rockslide", "aerialace", "destinybond"],
tier: "LC",
},
doublade: {
randomBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword"],
randomDoubleBattleMoves: ["swordsdance", "shadowclaw", "shadowsneak", "ironhead", "sacredsword", "rockslide", "protect"],
tier: "New",
},
aegislash: {
randomBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "hiddenpowerice", "shadowball", "flashcannon"],
randomDoubleBattleMoves: ["kingsshield", "swordsdance", "shadowclaw", "sacredsword", "ironhead", "shadowsneak", "wideguard", "hiddenpowerice", "shadowball", "flashcannon"],
eventPokemon: [
{"generation": 6, "level": 50, "gender": "F", "nature": "Quiet", "moves":["wideguard", "kingsshield", "shadowball", "flashcannon"], "pokeball": "cherishball"},
],
tier: "New",
},
aegislashblade: {
battleOnly: true,
},
spritzee: {
randomBattleMoves: ["calmmind", "drainingkiss", "moonblast", "psychic", "aromatherapy", "wish", "trickroom", "thunderbolt"],
tier: "Bank-LC",
},
aromatisse: {
randomBattleMoves: ["wish", "protect", "moonblast", "aromatherapy", "reflect", "lightscreen"],
randomDoubleBattleMoves: ["moonblast", "aromatherapy", "wish", "trickroom", "thunderbolt", "protect", "healpulse"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Relaxed", "isHidden": true, "moves":["trickroom", "healpulse", "disable", "moonblast"], "pokeball": "cherishball"},
],
tier: "Bank",
},
swirlix: {
randomBattleMoves: ["calmmind", "drainingkiss", "dazzlinggleam", "surf", "psychic", "flamethrower", "bellydrum", "thunderbolt", "return", "thief", "cottonguard"],
tier: "Bank",
},
slurpuff: {
randomBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "calmmind", "drainingkiss", "dazzlinggleam", "flamethrower", "surf"],
randomDoubleBattleMoves: ["substitute", "bellydrum", "playrough", "return", "drainpunch", "dazzlinggleam", "surf", "psychic", "flamethrower", "protect"],
tier: "Bank",
},
inkay: {
randomBattleMoves: ["topsyturvy", "switcheroo", "superpower", "psychocut", "flamethrower", "rockslide", "trickroom"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": false, "moves":["happyhour", "foulplay", "hypnosis", "topsyturvy"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
malamar: {
randomBattleMoves: ["superpower", "knockoff", "psychocut", "rockslide", "substitute", "trickroom"],
randomDoubleBattleMoves: ["superpower", "psychocut", "rockslide", "trickroom", "knockoff", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "nature": "Adamant", "ivs": {"hp": 31, "atk": 31}, "isHidden": false, "abilities":["contrary"], "moves":["superpower", "knockoff", "facade", "rockslide"], "pokeball": "cherishball"},
],
tier: "Bank",
},
binacle: {
randomBattleMoves: ["shellsmash", "razorshell", "stoneedge", "earthquake", "crosschop", "poisonjab", "xscissor", "rockslide"],
tier: "Bank-LC",
},
barbaracle: {
randomBattleMoves: ["shellsmash", "stoneedge", "razorshell", "earthquake", "crosschop", "stealthrock"],
randomDoubleBattleMoves: ["shellsmash", "razorshell", "earthquake", "crosschop", "rockslide", "protect"],
tier: "Bank",
},
skrelp: {
randomBattleMoves: ["scald", "sludgebomb", "thunderbolt", "shadowball", "toxicspikes", "hydropump"],
tier: "Bank-LC",
},
dragalge: {
randomBattleMoves: ["dracometeor", "sludgewave", "focusblast", "scald", "hiddenpowerfire", "toxicspikes", "dragonpulse"],
randomDoubleBattleMoves: ["dracometeor", "sludgebomb", "focusblast", "scald", "hiddenpowerfire", "protect", "dragonpulse"],
tier: "Bank",
},
clauncher: {
randomBattleMoves: ["waterpulse", "flashcannon", "uturn", "crabhammer", "aquajet", "sludgebomb"],
tier: "Bank-LC",
},
clawitzer: {
randomBattleMoves: ["scald", "waterpulse", "darkpulse", "aurasphere", "icebeam", "uturn"],
randomDoubleBattleMoves: ["waterpulse", "icebeam", "uturn", "darkpulse", "aurasphere", "muddywater", "helpinghand", "protect"],
tier: "Bank",
},
helioptile: {
randomBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt"],
tier: "Bank-LC",
},
heliolisk: {
randomBattleMoves: ["raindance", "thunder", "hypervoice", "surf", "darkpulse", "hiddenpowerice", "voltswitch", "thunderbolt"],
randomDoubleBattleMoves: ["surf", "voltswitch", "hiddenpowerice", "raindance", "thunder", "darkpulse", "thunderbolt", "electricterrain", "protect"],
tier: "Bank",
},
tyrunt: {
randomBattleMoves: ["stealthrock", "dragondance", "stoneedge", "dragonclaw", "earthquake", "icefang", "firefang"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": true, "moves":["tailwhip", "tackle", "roar", "stomp"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
tyrantrum: {
randomBattleMoves: ["stealthrock", "dragondance", "dragonclaw", "earthquake", "superpower", "outrage", "headsmash"],
randomDoubleBattleMoves: ["rockslide", "dragondance", "headsmash", "dragonclaw", "earthquake", "icefang", "firefang", "protect"],
tier: "Bank",
},
amaura: {
randomBattleMoves: ["naturepower", "hypervoice", "ancientpower", "thunderbolt", "darkpulse", "thunderwave", "dragontail", "flashcannon"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": true, "moves":["growl", "powdersnow", "thunderwave", "rockthrow"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
aurorus: {
randomBattleMoves: ["ancientpower", "thunderbolt", "encore", "thunderwave", "earthpower", "freezedry", "hypervoice", "stealthrock"],
randomDoubleBattleMoves: ["hypervoice", "ancientpower", "thunderbolt", "encore", "thunderwave", "flashcannon", "freezedry", "icywind", "protect"],
tier: "Bank",
},
sylveon: {
randomBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "batonpass", "shadowball"],
randomDoubleBattleMoves: ["hypervoice", "calmmind", "wish", "protect", "psyshock", "helpinghand", "shadowball", "hiddenpowerground"],
eventPokemon: [
{"generation": 6, "level": 10, "isHidden": false, "moves":["celebrate", "helpinghand", "sandattack", "fairywind"], "pokeball": "cherishball"},
{"generation": 6, "level": 10, "gender": "F", "isHidden": false, "moves":["disarmingvoice", "babydolleyes", "quickattack", "drainingkiss"], "pokeball": "cherishball"},
],
tier: "New",
},
hawlucha: {
randomBattleMoves: ["substitute", "swordsdance", "highjumpkick", "acrobatics", "roost", "stoneedge"],
randomDoubleBattleMoves: ["swordsdance", "highjumpkick", "uturn", "stoneedge", "skydrop", "encore", "protect"],
tier: "Bank",
},
dedenne: {
randomBattleMoves: ["substitute", "recycle", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "toxic"],
randomDoubleBattleMoves: ["voltswitch", "thunderbolt", "nuzzle", "grassknot", "hiddenpowerice", "uturn", "helpinghand", "protect"],
tier: "Bank",
},
carbink: {
randomBattleMoves: ["stealthrock", "lightscreen", "reflect", "explosion", "powergem", "moonblast"],
randomDoubleBattleMoves: ["trickroom", "lightscreen", "reflect", "explosion", "powergem", "moonblast", "protect"],
tier: "New",
},
goomy: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation"],
tier: "LC",
},
sliggoo: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "toxic", "protect", "infestation", "icebeam"],
tier: "NFE",
},
goodra: {
randomBattleMoves: ["dracometeor", "dragonpulse", "fireblast", "sludgebomb", "thunderbolt", "earthquake", "dragontail"],
randomDoubleBattleMoves: ["thunderbolt", "icebeam", "dragonpulse", "fireblast", "muddywater", "dracometeor", "focusblast", "protect"],
tier: "New",
},
klefki: {
randomBattleMoves: ["reflect", "lightscreen", "spikes", "magnetrise", "playrough", "thunderwave", "foulplay", "toxic"],
randomDoubleBattleMoves: ["reflect", "lightscreen", "safeguard", "playrough", "substitute", "thunderwave", "protect", "flashcannon", "dazzlinggleam"],
tier: "New",
},
phantump: {
randomBattleMoves: ["hornleech", "leechseed", "phantomforce", "substitute", "willowisp", "rest"],
tier: "LC",
},
trevenant: {
randomBattleMoves: ["hornleech", "shadowclaw", "leechseed", "willowisp", "rest", "substitute", "phantomforce"],
randomDoubleBattleMoves: ["hornleech", "woodhammer", "leechseed", "shadowclaw", "willowisp", "trickroom", "earthquake", "rockslide", "protect"],
tier: "New",
},
pumpkaboo: {
randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb", "leechseed"],
tier: "Bank-LC",
},
pumpkaboosmall: {
randomBattleMoves: ["willowisp", "shadowsneak", "destinybond", "synthesis", "seedbomb"],
unreleasedHidden: true,
tier: "Bank-LC",
},
pumpkaboolarge: {
randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"],
unreleasedHidden: true,
tier: "Bank-LC",
},
pumpkaboosuper: {
randomBattleMoves: ["willowisp", "shadowsneak", "leechseed", "synthesis", "seedbomb"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["trickortreat", "astonish", "scaryface", "shadowsneak"], "pokeball": "cherishball"},
],
tier: "Bank-LC",
},
gourgeist: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"],
tier: "Bank",
},
gourgeistsmall: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect"],
unreleasedHidden: true,
tier: "Bank",
},
gourgeistlarge: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"],
unreleasedHidden: true,
tier: "Bank",
},
gourgeistsuper: {
randomBattleMoves: ["willowisp", "seedbomb", "leechseed", "shadowsneak", "substitute", "synthesis"],
randomDoubleBattleMoves: ["willowisp", "shadowsneak", "painsplit", "seedbomb", "leechseed", "phantomforce", "explosion", "protect", "trickroom"],
tier: "Bank",
},
bergmite: {
randomBattleMoves: ["avalanche", "recover", "stoneedge", "curse", "gyroball", "rapidspin"],
tier: "Bank-LC",
},
avalugg: {
randomBattleMoves: ["avalanche", "recover", "toxic", "rapidspin", "roar", "earthquake"],
randomDoubleBattleMoves: ["avalanche", "recover", "earthquake", "protect"],
tier: "Bank",
},
noibat: {
randomBattleMoves: ["airslash", "hurricane", "dracometeor", "uturn", "roost", "switcheroo"],
tier: "Bank-LC",
},
noivern: {
randomBattleMoves: ["dracometeor", "hurricane", "airslash", "flamethrower", "boomburst", "switcheroo", "uturn", "roost", "taunt"],
randomDoubleBattleMoves: ["airslash", "hurricane", "dragonpulse", "dracometeor", "focusblast", "flamethrower", "uturn", "roost", "boomburst", "switcheroo", "tailwind", "taunt", "protect"],
tier: "Bank",
},
xerneas: {
randomBattleMoves: ["geomancy", "moonblast", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat"],
randomDoubleBattleMoves: ["geomancy", "dazzlinggleam", "thunder", "focusblast", "thunderbolt", "hiddenpowerfire", "psyshock", "rockslide", "closecombat", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["gravity", "geomancy", "moonblast", "megahorn"]},
{"generation": 6, "level": 100, "shiny": true, "moves":["geomancy", "moonblast", "aromatherapy", "focusblast"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
yveltal: {
randomBattleMoves: ["darkpulse", "hurricane", "foulplay", "oblivionwing", "uturn", "suckerpunch", "taunt", "toxic", "roost"],
randomDoubleBattleMoves: ["darkpulse", "oblivionwing", "taunt", "focusblast", "hurricane", "roost", "suckerpunch", "snarl", "skydrop", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["snarl", "oblivionwing", "disable", "darkpulse"]},
{"generation": 6, "level": 100, "shiny": true, "moves":["oblivionwing", "suckerpunch", "darkpulse", "foulplay"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank-Uber",
},
zygarde: {
randomBattleMoves: ["dragondance", "earthquake", "outrage", "extremespeed", "stoneedge"],
randomDoubleBattleMoves: ["dragondance", "landswrath", "extremespeed", "rockslide", "coil", "stoneedge", "glare", "protect"],
eventPokemon: [
{"generation": 6, "level": 70, "moves":["crunch", "earthquake", "camouflage", "dragonpulse"]},
{"generation": 6, "level": 100, "moves":["landswrath", "extremespeed", "glare", "outrage"], "pokeball": "cherishball"},
{"generation": 7, "level": 50, "moves":["bind", "landswrath", "sandstorm", "haze"]},
],
eventOnly: true,
tier: "New",
},
zygarde10: {
randomBattleMoves: ["dragondance", "thousandarrows", "outrage", "extremespeed", "irontail", "substitute"],
eventPokemon: [
{"generation": 7, "level": 30, "moves":["safeguard", "dig", "bind", "landswrath"]},
],
eventOnly: true,
gen: 7,
tier: "New",
},
zygardecomplete: {
gen: 7,
requiredAbility: "Power Construct",
battleOnly: true,
},
diancie: {
randomBattleMoves: ["reflect", "lightscreen", "stealthrock", "diamondstorm", "moonblast", "hiddenpowerfire"],
randomDoubleBattleMoves: ["diamondstorm", "moonblast", "reflect", "lightscreen", "safeguard", "substitute", "calmmind", "psychic", "dazzlinggleam", "protect"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["diamondstorm", "reflect", "return", "moonblast"], "pokeball": "cherishball"},
{"generation": 6, "level": 50, "shiny": true, "moves":["diamondstorm", "moonblast", "reflect", "return"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
dianciemega: {
randomBattleMoves: ["calmmind", "moonblast", "earthpower", "hiddenpowerfire", "psyshock", "diamondstorm"],
randomDoubleBattleMoves: ["diamondstorm", "moonblast", "calmmind", "psyshock", "earthpower", "hiddenpowerfire", "dazzlinggleam", "protect"],
requiredItem: "Diancite",
tier: "Bank",
},
hoopa: {
randomBattleMoves: ["nastyplot", "psyshock", "shadowball", "focusblast", "trick"],
randomDoubleBattleMoves: ["hyperspacehole", "shadowball", "focusblast", "protect", "psychic", "trickroom"],
eventPokemon: [
{"generation": 6, "level": 50, "moves":["hyperspacehole", "nastyplot", "psychic", "astonish"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
hoopaunbound: {
randomBattleMoves: ["nastyplot", "substitute", "psyshock", "psychic", "darkpulse", "focusblast", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot", "knockoff", "trick"],
randomDoubleBattleMoves: ["psychic", "darkpulse", "focusblast", "protect", "hyperspacefury", "zenheadbutt", "icepunch", "drainpunch", "gunkshot"],
eventOnly: true,
tier: "Bank",
},
volcanion: {
randomBattleMoves: ["substitute", "steameruption", "fireblast", "sludgewave", "hiddenpowerice", "earthpower", "superpower"],
randomDoubleBattleMoves: ["substitute", "steameruption", "heatwave", "sludgebomb", "rockslide", "earthquake", "protect"],
eventPokemon: [
{"generation": 6, "level": 70, "moves":["steameruption", "overheat", "hydropump", "mist"], "pokeball": "cherishball"},
{"generation": 6, "level": 70, "moves":["steameruption", "flamethrower", "hydropump", "explosion"], "pokeball": "cherishball"},
],
eventOnly: true,
tier: "Bank",
},
rowlet: {
unreleasedHidden: true,
tier: "LC",
},
dartrix: {
unreleasedHidden: true,
tier: "NFE",
},
decidueye: {
randomBattleMoves: ["spiritshackle", "uturn", "leafblade", "roost", "swordsdance", "suckerpunch"],
unreleasedHidden: true,
tier: "New",
},
litten: {
unreleasedHidden: true,
tier: "LC",
},
torracat: {
unreleasedHidden: true,
tier: "NFE",
},
incineroar: {
randomBattleMoves: ["fakeout", "darkestlariat", "flareblitz", "uturn", "earthquake"],
unreleasedHidden: true,
tier: "New",
},
popplio: {
unreleasedHidden: true,
tier: "LC",
},
brionne: {
unreleasedHidden: true,
tier: "NFE",
},
primarina: {
randomBattleMoves: ["hypervoice", "moonblast", "icebeam", "encore", "reflect", "lightscreen", "scald"],
unreleasedHidden: true,
tier: "New",
},
pikipek: {
tier: "LC",
},
trumbeak: {
tier: "NFE",
},
toucannon: {
randomBattleMoves: ["substitute", "beakblast", "swordsdance", "roost", "brickbreak"],
tier: "New",
},
yungoos: {
tier: "LC",
},
gumshoos: {
randomBattleMoves: ["uturn", "return", "crunch", "earthquake"],
tier: "New",
},
grubbin: {
tier: "LC",
},
charjabug: {
tier: "NFE",
},
vikavolt: {
randomBattleMoves: ["agility", "bugbuzz", "thunderbolt", "voltswitch", "energyball"],
tier: "New",
},
crabrawler: {
tier: "LC",
},
crabominable: {
randomBattleMoves: ["icehammer", "closecombat", "earthquake", "stoneedge"],
tier: "New",
},
oricorio: {
randomBattleMoves: ["revelationdance", "hurricane", "toxic", "roost", "uturn"],
tier: "New",
},
oricoriopompom: {
tier: "New",
},
oricoriopau: {
tier: "New",
},
oricoriosensu: {
tier: "New",
},
cutiefly: {
tier: "LC",
},
ribombee: {
randomBattleMoves: ["quiverdance", "bugbuzz", "moonblast", "hiddenpowerfire", "roost", "batonpass"],
tier: "New",
},
rockruff: {
tier: "LC",
},
lycanroc: {
randomBattleMoves: ["swordsdance", "accelerock", "stoneedge", "crunch", "firefang"],
tier: "New",
},
lycanrocmidnight: {
randomBattleMoves: ["bulkup", "stoneedge", "stealthrock", "suckerpunch", "swordsdance", "firefang", "rockclimb"],
tier: "New",
},
wishiwashi: {
randomBattleMoves: ["scald", "hydropump", "icebeam", "hiddenpowergrass", "earthquake"],
tier: "New",
},
wishiwashischool: {
battleOnly: true,
},
mareanie: {
tier: "LC",
},
toxapex: {
randomBattleMoves: ["toxicspikes", "banefulbunker", "recover", "liquidation", "venoshock"],
tier: "New",
},
mudbray: {
tier: "LC",
},
mudsdale: {
randomBattleMoves: ["earthquake", "closecombat", "payback", "rockslide"],
tier: "New",
},
dewpider: {
tier: "LC",
},
araquanid: {
randomBattleMoves: ["liquidation", "lunge", "infestation", "mirrorcoat"],
tier: "New",
},
fomantis: {
tier: "LC",
},
lurantis: {
randomBattleMoves: ["leafstorm", "hiddenpowerfire", "gigadrain", "substitute"],
tier: "New",
},
morelull: {
tier: "LC",
},
shiinotic: {
randomBattleMoves: ["spore", "strengthsap", "moonblast", "substitute", "leechseed"],
tier: "New",
},
salandit: {
tier: "LC",
},
salazzle: {
randomBattleMoves: ["nastyplot", "fireblast", "sludgewave", "hiddenpowerground"],
tier: "New",
},
stufful: {
tier: "LC",
},
bewear: {
randomBattleMoves: ["hammerarm", "icepunch", "swordsdance", "painsplit", "substitute"],
tier: "New",
},
bounsweet: {
tier: "LC",
},
steenee: {
tier: "NFE",
},
tsareena: {
randomBattleMoves: ["highjumpkick", "tropkick", "playrough", "uturn"],
tier: "New",
},
comfey: {
randomBattleMoves: ["sweetkiss", "aromatherapy", "drainingkiss", "toxic", "synthesis"],
tier: "New",
},
oranguru: {
randomBattleMoves: ["nastyplot", "psyshock", "focusblast", "thunderbolt"],
tier: "New",
},
passimian: {
randomBattleMoves: ["rocktomb", "closecombat", "earthquake", "ironhead"],
tier: "New",
},
wimpod: {
tier: "LC",
},
golisopod: {
randomBattleMoves: ["spikes", "firstimpression", "liquidation", "suckerpunch", "aquajet", "toxic"],
tier: "New",
},
sandygast: {
tier: "LC",
},
palossand: {
randomBattleMoves: ["shoreup", "earthpower", "shadowball", "protect", "toxic"],
tier: "New",
},
pyukumuku: {
randomBattleMoves: ["curse", "batonpass", "recover", "counter", "reflect", "lightscreen"],
tier: "New",
},
typenull: {
eventPokemon: [
{"generation": 7, "level": 40, "moves":["crushclaw", "scaryface", "xscissor", "takedown"]},
],
eventOnly: true,
tier: "NFE",
},
silvally: {
randomBattleMoves: ["swordsdance", "return", "doubleedge", "crunch", "flamecharge", "flamethrower", "icebeam", "uturn", "ironhead"],
tier: "New",
},
silvallybug: {
tier: "New",
requiredItem: "Bug Memory",
},
silvallydark: {
tier: "New",
requiredItem: "Dark Memory",
},
silvallydragon: {
tier: "New",
requiredItem: "Dragon Memory",
},
silvallyelectric: {
tier: "New",
requiredItem: "Electric Memory",
},
silvallyfairy: {
tier: "New",
requiredItem: "Fairy Memory",
},
silvallyfighting: {
tier: "New",
requiredItem: "Fighting Memory",
},
silvallyfire: {
tier: "New",
requiredItem: "Fire Memory",
},
silvallyflying: {
tier: "New",
requiredItem: "Flying Memory",
},
silvallyghost: {
randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"],
tier: "New",
requiredItem: "Ghost Memory",
},
silvallygrass: {
tier: "New",
requiredItem: "Grass Memory",
},
silvallyground: {
tier: "New",
requiredItem: "Ground Memory",
},
silvallyice: {
tier: "New",
requiredItem: "Ice Memory",
},
silvallypoison: {
tier: "New",
requiredItem: "Poison Memory",
},
silvallypsychic: {
tier: "New",
requiredItem: "Psychic Memory",
},
silvallyrock: {
tier: "New",
requiredItem: "Rock Memory",
},
silvallysteel: {
tier: "New",
requiredItem: "Steel Memory",
},
silvallywater: {
tier: "New",
requiredItem: "Water Memory",
},
minior: {
randomBattleMoves: ["shellsmash", "powergem", "acrobatics", "earthquake"],
tier: "New",
},
miniormeteor: {
battleOnly: true,
},
komala: {
randomBattleMoves: ["return", "suckerpunch", "woodhammer", "earthquake", "playrough", "uturn"],
tier: "New",
},
turtonator: {
randomBattleMoves: ["overheat", "shelltrap", "earthquake", "dragontail", "explosion"],
tier: "New",
},
togedemaru: {
randomBattleMoves: ["spikyshield", "zingzap", "nuzzle", "uturn", "wish"],
tier: "New",
},
mimikyu: {
randomBattleMoves: ["swordsdance", "shadowsneak", "playrough", "woodhammer", "shadowclaw"],
tier: "New",
},
mimikyubusted: {
battleOnly: true,
},
bruxish: {
randomBattleMoves: ["psychicfangs", "crunch", "waterfall", "icefang", "aquajet", "swordsdance"],
tier: "New",
},
drampa: {
randomBattleMoves: ["dracometeor", "dragonpulse", "hypervoice", "fireblast", "thunderbolt", "glare", "substitute", "roost"],
tier: "New",
},
dhelmise: {
randomBattleMoves: ["swordsdance", "powerwhip", "phantomforce", "anchorshot", "switcheroo", "earthquake"],
tier: "New",
},
jangmoo: {
tier: "LC",
},
hakamoo: {
tier: "NFE",
},
kommoo: {
randomBattleMoves: ["dragondance", "outrage", "dragonclaw", "skyuppercut", "poisonjab"],
tier: "New",
},
tapukoko: {
randomBattleMoves: ["wildcharge", "voltswitch", "naturesmadness", "bravebird", "uturn"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "discharge", "agility", "electroball"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapulele: {
randomBattleMoves: ["moonblast", "psyshock", "calmmind", "focusblast", "aromatherapy"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "extrasensory", "flatter", "moonblast"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapubulu: {
randomBattleMoves: ["woodhammer", "naturesmadness", "rocktomb", "superpower", "megahorn"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "zenheadbutt", "megahorn", "skullbash"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
tapufini: {
randomBattleMoves: ["calmmind", "moonblast", "scald", "substitute", "icebeam"],
eventPokemon: [
{"generation": 7, "level": 60, "isHidden": false, "moves":["naturesmadness", "muddywater", "aquaring", "hydropump"]},
],
eventOnly: true,
unreleasedHidden: true,
tier: "New",
},
cosmog: {
eventPokemon: [
{"generation": 7, "level": 5, "moves":["splash"]},
],
eventOnly: true,
tier: "LC",
},
cosmoem: {
tier: "NFE",
},
solgaleo: {
randomBattleMoves: ["sunsteelstrike", "zenheadbutt", "flareblitz", "morningsun", "stoneedge", "earthquake"],
eventPokemon: [
{"generation": 7, "level": 55, "moves":["sunsteelstrike", "cosmicpower", "crunch", "zenheadbutt"]},
],
tier: "Uber",
},
lunala: {
randomBattleMoves: ["moongeistbeam", "psyshock", "calmmind", "focusblast", "moonlight"],
eventPokemon: [
{"generation": 7, "level": 55, "moves":["moongeistbeam", "cosmicpower", "nightdaze", "shadowball"]},
],
tier: "Uber",
},
nihilego: {
randomBattleMoves: ["stealthrock", "acidspray", "powergem", "toxicspikes"],
tier: "New",
},
buzzwole: {
randomBattleMoves: ["lunge", "substitute", "focuspunch", "thunderpunch"],
tier: "New",
},
pheromosa: {
randomBattleMoves: ["highjumpkick", "uturn", "icebeam", "poisonjab", "bugbuzz"],
tier: "New",
},
xurkitree: {
randomBattleMoves: ["thunderbolt", "voltswitch", "energyball", "dazzlinggleam", "hiddenpowerice"],
tier: "New",
},
celesteela: {
randomBattleMoves: ["autotomize", "flashcannon", "airslash", "fireblast", "energyball"],
tier: "New",
},
kartana: {
randomBattleMoves: ["leafblade", "sacredsword", "smartstrike", "psychocut", "swordsdance"],
tier: "New",
},
guzzlord: {
randomBattleMoves: ["dracometeor", "hammerarm", "crunch", "earthquake", "fireblast"],
tier: "New",
},
necrozma: {
randomBattleMoves: ["autotomize", "swordsdance", "stoneedge", "psychocut", "earthquake", "psyshock"],
tier: "New",
},
magearna: {
randomBattleMoves: ["shiftgear", "flashcannon", "aurasphere", "fleurcannon", "ironhead", "thunderbolt", "icebeam"],
eventPokemon: [
{"generation": 7, "level": 50, "moves":["fleurcannon", "flashcannon", "luckychant", "helpinghand"]},
],
eventOnly: true,
tier: "New",
},
marshadow: {
randomBattleMoves: ["spectralthief", "closecombat", "stoneedge", "shadowsneak", "icepunch"],
isUnreleased: true,
tier: "Unreleased",
},
missingno: {
randomBattleMoves: ["watergun", "skyattack", "doubleedge", "metronome"],
isNonstandard: true,
tier: "Illegal",
},
tomohawk: {
randomBattleMoves: ["aurasphere", "roost", "stealthrock", "rapidspin", "hurricane", "airslash", "taunt", "substitute", "toxic", "naturepower", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
necturna: {
randomBattleMoves: ["powerwhip", "hornleech", "willowisp", "shadowsneak", "stoneedge", "sacredfire", "boltstrike", "vcreate", "extremespeed", "closecombat", "shellsmash", "spore", "milkdrink", "batonpass", "stickyweb"],
isNonstandard: true,
tier: "CAP",
},
mollux: {
randomBattleMoves: ["fireblast", "thunderbolt", "sludgebomb", "thunderwave", "willowisp", "recover", "rapidspin", "trick", "stealthrock", "toxicspikes", "lavaplume"],
isNonstandard: true,
tier: "CAP",
},
aurumoth: {
randomBattleMoves: ["dragondance", "quiverdance", "closecombat", "bugbuzz", "hydropump", "megahorn", "psychic", "blizzard", "thunder", "focusblast", "zenheadbutt"],
isNonstandard: true,
tier: "CAP",
},
malaconda: {
randomBattleMoves: ["powerwhip", "glare", "toxic", "suckerpunch", "rest", "substitute", "uturn", "synthesis", "rapidspin", "knockoff"],
isNonstandard: true,
tier: "CAP",
},
cawmodore: {
randomBattleMoves: ["bellydrum", "bulletpunch", "drainpunch", "acrobatics", "drillpeck", "substitute", "ironhead", "quickattack"],
isNonstandard: true,
tier: "CAP",
},
volkraken: {
randomBattleMoves: ["scald", "powergem", "hydropump", "memento", "hiddenpowerice", "fireblast", "willowisp", "uturn", "substitute", "flashcannon", "surf"],
isNonstandard: true,
tier: "CAP",
},
plasmanta: {
randomBattleMoves: ["sludgebomb", "thunderbolt", "substitute", "hiddenpowerice", "psyshock", "dazzlinggleam", "flashcannon"],
isNonstandard: true,
tier: "CAP",
},
naviathan: {
randomBattleMoves: ["dragondance", "waterfall", "ironhead", "iciclecrash"],
isNonstandard: true,
tier: "CAP",
},
crucibelle: {
randomBattleMoves: ["headsmash", "gunkshot", "coil", "lowkick", "uturn", "stealthrock"],
isNonstandard: true,
tier: "CAP",
},
crucibellemega: {
randomBattleMoves: ["headsmash", "gunkshot", "coil", "woodhammer", "lowkick", "uturn"],
requiredItem: "Crucibellite",
isNonstandard: true,
tier: "CAP",
},
kerfluffle: {
randomBattleMoves: ["aurasphere", "moonblast", "taunt", "partingshot", "gigadrain", "yawn"],
isNonstandard: true,
eventPokemon: [
{"generation": 6, "level": 16, "isHidden": false, "abilities":["naturalcure"], "moves":["celebrate", "holdhands", "fly", "metronome"], "pokeball": "cherishball"},
],
tier: "CAP",
},
syclant: {
randomBattleMoves: ["bugbuzz", "icebeam", "blizzard", "earthpower", "spikes", "superpower", "tailglow", "uturn", "focusblast"],
isNonstandard: true,
tier: "CAP",
},
revenankh: {
randomBattleMoves: ["bulkup", "shadowsneak", "drainpunch", "rest", "moonlight", "icepunch", "glare"],
isNonstandard: true,
tier: "CAP",
},
pyroak: {
randomBattleMoves: ["leechseed", "lavaplume", "substitute", "protect", "gigadrain"],
isNonstandard: true,
tier: "CAP",
},
fidgit: {
randomBattleMoves: ["spikes", "stealthrock", "toxicspikes", "wish", "rapidspin", "encore", "uturn", "sludgebomb", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
stratagem: {
randomBattleMoves: ["paleowave", "earthpower", "fireblast", "gigadrain", "calmmind", "substitute"],
isNonstandard: true,
tier: "CAP",
},
arghonaut: {
randomBattleMoves: ["recover", "bulkup", "waterfall", "drainpunch", "crosschop", "stoneedge", "thunderpunch", "aquajet", "machpunch"],
isNonstandard: true,
tier: "CAP",
},
kitsunoh: {
randomBattleMoves: ["shadowstrike", "earthquake", "superpower", "meteormash", "uturn", "icepunch", "trick", "willowisp"],
isNonstandard: true,
tier: "CAP",
},
cyclohm: {
randomBattleMoves: ["slackoff", "dracometeor", "dragonpulse", "fireblast", "thunderbolt", "hydropump", "discharge", "healbell"],
isNonstandard: true,
tier: "CAP",
},
colossoil: {
randomBattleMoves: ["earthquake", "crunch", "suckerpunch", "uturn", "rapidspin", "encore", "pursuit", "knockoff"],
isNonstandard: true,
tier: "CAP",
},
krilowatt: {
randomBattleMoves: ["surf", "thunderbolt", "icebeam", "earthpower"],
isNonstandard: true,
tier: "CAP",
},
voodoom: {
randomBattleMoves: ["aurasphere", "darkpulse", "taunt", "painsplit", "substitute", "hiddenpowerice", "vacuumwave"],
isNonstandard: true,
tier: "CAP",
},
};
| Random Battle: Add more Silvally sets
| data/formats-data.js | Random Battle: Add more Silvally sets | <ide><path>ata/formats-data.js
<ide> requiredItem: "Bug Memory",
<ide> },
<ide> silvallydark: {
<add> randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "ironhead"],
<ide> tier: "New",
<ide> requiredItem: "Dark Memory",
<ide> },
<ide> requiredItem: "Dragon Memory",
<ide> },
<ide> silvallyelectric: {
<add> randomBattleMoves: ["multiattack", "flamethrower", "icebeam", "partingshot", "toxic"],
<ide> tier: "New",
<ide> requiredItem: "Electric Memory",
<ide> },
<ide> requiredItem: "Grass Memory",
<ide> },
<ide> silvallyground: {
<add> randomBattleMoves: ["multiattack", "swordsdance", "flamecharge", "rockslide"],
<ide> tier: "New",
<ide> requiredItem: "Ground Memory",
<ide> }, |
|
Java | apache-2.0 | 2dfc77887976057036c72d30ca6121163c2358db | 0 | jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2014 Ausenco Engineering Canada Inc.
*
* 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.
*/
package com.jaamsim.input;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
public class ExpResult {
public static final ExpResult BAD_RESULT = new ExpResult(Double.NaN, DimensionlessUnit.class);
public double value;
public Class<? extends Unit> unitType;
public ExpResult(double val, Class<? extends Unit> ut) {
value = val;
unitType = ut;
}
public boolean isBad() {
return this == BAD_RESULT;
}
}
| src/main/java/com/jaamsim/input/ExpResult.java | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2014 Ausenco Engineering Canada Inc.
*
* 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.
*/
package com.jaamsim.input;
import com.jaamsim.units.DimensionlessUnit;
import com.jaamsim.units.Unit;
public class ExpResult {
public double value;
public Class<? extends Unit> unitType;
public ExpResult(double val, Class<? extends Unit> ut) {
value = val;
unitType = ut;
}
public static ExpResult BAD_RESULT = new ExpResult(Double.NaN, DimensionlessUnit.class);
public boolean isBad() {
return this == BAD_RESULT;
}
}
| JS: mark the BAD_Result constant as final
Signed-off-by: Harvey Harrison <[email protected]>
| src/main/java/com/jaamsim/input/ExpResult.java | JS: mark the BAD_Result constant as final | <ide><path>rc/main/java/com/jaamsim/input/ExpResult.java
<ide> import com.jaamsim.units.DimensionlessUnit;
<ide> import com.jaamsim.units.Unit;
<ide>
<add>public class ExpResult {
<add> public static final ExpResult BAD_RESULT = new ExpResult(Double.NaN, DimensionlessUnit.class);
<ide>
<del>public class ExpResult {
<ide> public double value;
<ide> public Class<? extends Unit> unitType;
<ide>
<ide> unitType = ut;
<ide> }
<ide>
<del> public static ExpResult BAD_RESULT = new ExpResult(Double.NaN, DimensionlessUnit.class);
<del>
<ide> public boolean isBad() {
<ide> return this == BAD_RESULT;
<ide> } |
|
Java | apache-2.0 | c1e0a31e1878e2042ea95d116d885a195779b925 | 0 | carloseduardosx/github-java-trends | package com.carloseduardo.github.base;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseAdapter<VH extends RecyclerView.ViewHolder, T> extends RecyclerView.Adapter<VH>{
protected List<T> items;
public BaseAdapter(List<T> items) {
this.items = items;
}
@Override
public int getItemCount() {
return items.size();
}
public void appendItems(@NonNull List<T> items) {
this.items.addAll(items);
notifyDataSetChanged();
}
public void setContent(@NonNull List<T> items) {
this.items.clear();
this.items = new ArrayList<>(items);
notifyDataSetChanged();
}
} | app/src/main/java/com/carloseduardo/github/base/BaseAdapter.java | package com.carloseduardo.github.base;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import java.util.List;
public abstract class BaseAdapter<VH extends RecyclerView.ViewHolder, T> extends RecyclerView.Adapter<VH>{
protected List<T> items;
public BaseAdapter(List<T> items) {
this.items = items;
}
@Override
public int getItemCount() {
return items.size();
}
public void appendItems(@NonNull List<T> items) {
this.items.addAll(items);
notifyDataSetChanged();
}
public void setContent(@NonNull List<T> items) {
this.items.clear();
this.items.addAll(items);
notifyDataSetChanged();
}
} | Assign new array after clean list content
| app/src/main/java/com/carloseduardo/github/base/BaseAdapter.java | Assign new array after clean list content | <ide><path>pp/src/main/java/com/carloseduardo/github/base/BaseAdapter.java
<ide> import android.support.annotation.NonNull;
<ide> import android.support.v7.widget.RecyclerView;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> public abstract class BaseAdapter<VH extends RecyclerView.ViewHolder, T> extends RecyclerView.Adapter<VH>{
<ide> public void setContent(@NonNull List<T> items) {
<ide>
<ide> this.items.clear();
<del> this.items.addAll(items);
<add> this.items = new ArrayList<>(items);
<ide> notifyDataSetChanged();
<ide> }
<ide> } |
|
Java | apache-2.0 | f303622e88f9511faba56e1cfee170504f0f66cb | 0 | McLeodMoores/starling,jerome79/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,nssales/OG-Platform,ChinaQuants/OG-Platform | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.test;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.difference;
import static com.opengamma.util.RegexUtils.extract;
import static com.opengamma.util.RegexUtils.matches;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.BuildException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ZipUtils;
/**
* Manager of database scripts.
*/
public final class DbScripts {
/** Script files by relative location. */
private static final File SCRIPT_RELATIVE_PATH = new File(DbTool.getWorkingDirectory(), "../OG-MasterDB");
/** Script files using zips built by Ant. */
private static final File SCRIPT_ZIP_PATH = new File(DbTool.getWorkingDirectory(), "lib/sql/com.opengamma/og-masterdb");
/** Script expansion. */
private static final File SCRIPT_INSTALL_DIR = new File(DbTool.getWorkingDirectory(), "temp/" + DbScripts.class.getSimpleName());
/** The script directories. */
private static volatile Collection<File> s_scriptDir;
private static final String DATABASE_INSTALL_FOLDER = "install/db";
private static final Pattern DATABASE_SCRIPT_FOLDER_PATTERN = Pattern.compile("(.+)_db");
private static final String DATABASE_CREATE_FOLDER = DATABASE_INSTALL_FOLDER + File.separatorChar + "create";
private static final String DATABASE_MIGRATE_FOLDER = DATABASE_INSTALL_FOLDER + File.separatorChar + "migrate";
private static final String DATABASE_CREATE_SCRIPT_PREFIX = "V_";
private static final String DATABASE_MIGRATE_SCRIPT_PREFIX = "V_";
private static final Pattern CREATE_SCRIPT_PATTERN = Pattern.compile("^" + DATABASE_CREATE_SCRIPT_PREFIX + "([0-9]+)__create_(.+?)\\.sql");
private static final Pattern MIGRATE_SCRIPT_PATTERN = Pattern.compile("^" + DATABASE_MIGRATE_SCRIPT_PREFIX + "([0-9]+)__(.+?)\\.sql");
/** The base script directories. */
private final Collection<File> _scriptDirs;
/** The database type. */
private final String _databaseType;
/** The scripts, by database type and version. */
private final Map<String, SortedMap<Integer, DbScriptPair>> _scripts;
//-------------------------------------------------------------------------
/**
* Gets the initialized the script directory.
*
* @return the script directory, not null
*/
public static Collection<File> getSqlScriptDir() {
if (s_scriptDir == null) {
synchronized (DbScripts.class) {
if (s_scriptDir == null) {
s_scriptDir = createSQLScripts();
}
}
}
return s_scriptDir;
}
private static Collection<File> createSQLScripts() {
try {
Collection<File> dirs = Sets.newHashSet();
File local = new File(DbTool.getWorkingDirectory(), DATABASE_INSTALL_FOLDER).getCanonicalFile();
File relative = new File(SCRIPT_RELATIVE_PATH, DATABASE_INSTALL_FOLDER).getCanonicalFile();
if (local.exists()) {
dirs.add(new File(DbTool.getWorkingDirectory()).getCanonicalFile());
}
if (relative.exists()) {
dirs.add(SCRIPT_RELATIVE_PATH);
}
if (dirs.isEmpty()) {
if (SCRIPT_ZIP_PATH.exists()) {
if (SCRIPT_INSTALL_DIR.exists()) {
FileUtils.deleteQuietly(SCRIPT_INSTALL_DIR);
}
for (File file : (Collection<File>) FileUtils.listFiles(SCRIPT_ZIP_PATH, new String[] {"zip"}, false)) {
try {
ZipUtils.unzipArchive(file, SCRIPT_INSTALL_DIR);
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Unable to unzip database scripts: " + SCRIPT_INSTALL_DIR);
}
}
dirs.add(SCRIPT_INSTALL_DIR.getCanonicalFile());
} else {
throw new IllegalArgumentException("Unable to find database scripts. Tried: " + local + ", " + relative + " and " + SCRIPT_ZIP_PATH);
}
}
return dirs;
} catch (IOException ex) {
throw new OpenGammaRuntimeException(ex.getMessage(), ex);
}
}
/**
* Deletes the script directory.
*/
public static void deleteSqlScriptDir() {
FileUtils.deleteQuietly(SCRIPT_INSTALL_DIR);
}
/**
* Gets the latest versions of the scripts across all databases.
*
* @param scriptDirs the script directories, not null
* @return the latest versions by , not null
*/
public static Map<String, Integer> getLatestVersions(Collection<File> scriptDirs) {
Map<String, Integer> result = new HashMap<>();
for (File scriptDir : scriptDirs) {
File parentDirectory = new File(scriptDir, DATABASE_CREATE_FOLDER);
for (File dialectDir : parentDirectory.listFiles()) {
if (dialectDir.isDirectory() == false) {
continue;
}
Map<File, Map<Integer, File>> scripts = findScriptFiles(dialectDir, CREATE_SCRIPT_PATTERN);
for (Map.Entry<File, Map<Integer, File>> masterScripts : scripts.entrySet()) {
String masterName = masterScripts.getKey().getName();
Set<Integer> versions = masterScripts.getValue().keySet();
if (versions.isEmpty()) {
continue;
}
int maxVersion = Collections.max(versions);
if (result.containsKey(masterName)) {
if (result.get(masterName).intValue() != maxVersion) {
throw new BuildException("Latest versions differ between database dialects for master '" + masterName +
"'. Found latest versions of both " + result.get(masterName) + " and " + maxVersion + ".");
}
} else {
result.put(masterName, maxVersion);
}
}
}
}
return result;
}
//-------------------------------------------------------------------------
/**
* Gets the scripts.
*
* @param scriptDirs the script directories, not null
* @param databaseType the database type, not null
* @return the scripts, not null
* @throws IllegalArgumentException if the scripts do not exist
*/
public static DbScripts of(Collection<File> scriptDirs, String databaseType) {
ArgumentChecker.notNull(databaseType, "databaseType");
return new DbScripts(scriptDirs, databaseType);
}
//-------------------------------------------------------------------------
/**
* Creates an instance.
*
* @param databaseType the database type, not null
* @param version the version
* @param createScript the create script, not null
* @param migrateScript the migrate script, not null
*/
private DbScripts(Collection<File> scriptDirs, String databaseType) {
ArgumentChecker.notNull(scriptDirs, "scriptDirs");
ArgumentChecker.notNull(databaseType, "databaseType");
_scriptDirs = ImmutableList.copyOf(scriptDirs);
_databaseType = databaseType;
_scripts = buildMap();
}
//-------------------------------------------------------------------------
/**
* Gets the SQL database creation script.
*
* @return the script file, not null
*/
public Collection<File> getScriptDirs() {
return _scriptDirs;
}
/**
* Gets the database type.
*
* @return the database type, not null
*/
public String getDatabaseType() {
return _databaseType;
}
/**
* Gets the script pairs.
* Keyed by table set and version.
*
* @return the map of scripts, not null
*/
public Map<String, SortedMap<Integer, DbScriptPair>> getScriptPairs() {
return _scripts;
}
/**
* Gets the latest script pair for a schema.
* Keyed by schema and version.
*
* @param tableSet the table set, not null
* @return the script pair, not null
*/
public DbScriptPair getLatestScriptPair(String tableSet) {
SortedMap<Integer, DbScriptPair> versions = _scripts.get(tableSet);
if (versions == null) {
throw new IllegalArgumentException("Unknown table set");
}
return versions.get(versions.lastKey());
}
//-------------------------------------------------------------------------
/**
* @return schema => version_number => (create_script, migrate_script)
*/
private Map<String, SortedMap<Integer, DbScriptPair>> buildMap() {
ConcurrentMap<String, ConcurrentMap<Integer, File>> createScripts = new ConcurrentHashMap<String, ConcurrentMap<Integer, File>>();
ConcurrentMap<String, ConcurrentMap<Integer, File>> migrateScripts = new ConcurrentHashMap<String, ConcurrentMap<Integer, File>>();
// for each script directory, find the files
for (File scriptDir : _scriptDirs) {
findScriptFiles(scriptDir, createScripts, DATABASE_CREATE_FOLDER, CREATE_SCRIPT_PATTERN);
findScriptFiles(scriptDir, migrateScripts, DATABASE_MIGRATE_FOLDER, MIGRATE_SCRIPT_PATTERN);
}
// ensure valid script file setup
Set<String> createTableSets = createScripts.keySet();
Set<String> migrateTableSets = migrateScripts.keySet();
Set<String> unmatchedCreateDbDirs = difference(migrateTableSets, createTableSets);
if (unmatchedCreateDbDirs.size() > 0) {
StringBuilder errorMessage = new StringBuilder();
for (String unmatchedCreateDbDir : unmatchedCreateDbDirs) {
errorMessage.append("There is no corresponding create db directory for migrate one: " + unmatchedCreateDbDir + "\n");
}
throw new OpenGammaRuntimeException(errorMessage.toString());
}
Set<String> unmatchedMigrateDbDirs = difference(createTableSets, migrateTableSets);
if (unmatchedMigrateDbDirs.size() > 0) {
StringBuilder errorMessage = new StringBuilder();
for (String unmatchedMigrateDbDir : unmatchedMigrateDbDirs) {
errorMessage.append("There is no corresponding migrate db directory for create one: " + unmatchedMigrateDbDir + "\n");
}
throw new OpenGammaRuntimeException(errorMessage.toString());
}
// build output
final ConcurrentMap<String, SortedMap<Integer, DbScriptPair>> scripts = new ConcurrentHashMap<>();
for (String tableSet : migrateTableSets) {
ConcurrentMap<Integer, File> versionedCreateScripts = createScripts.get(tableSet);
ConcurrentMap<Integer, File> versionedMigrateScripts = migrateScripts.get(tableSet);
Set<Integer> versions = versionedCreateScripts.keySet();
for (Integer version : versions) {
File createScript = versionedCreateScripts.get(version);
File migrateScript = versionedMigrateScripts.get(version);
scripts.putIfAbsent(tableSet, new TreeMap<Integer, DbScriptPair>());
scripts.get(tableSet).put(version, new DbScriptPair(_databaseType, tableSet, version, createScript, migrateScript));
}
}
if (scripts.isEmpty()) {
throw new OpenGammaRuntimeException("No script directories found: " + _scriptDirs);
}
return scripts;
}
private void findScriptFiles(File scriptDir, ConcurrentMap<String, ConcurrentMap<Integer, File>> scriptMap, String subDir, Pattern pattern) {
// find the files
File dialectDir = new File(scriptDir, subDir + File.separatorChar + _databaseType);
Map<File, Map<Integer, File>> scriptsFiles = findScriptFiles(dialectDir, pattern);
// build the map
for (Map.Entry<File, Map<Integer, File>> dbFolder2versionedScripts : scriptsFiles.entrySet()) {
File dbFolder = dbFolder2versionedScripts.getKey();
scriptMap.putIfAbsent(dbFolder.getName(), new ConcurrentHashMap<Integer, File>());
Map<Integer, File> versionedScripts = dbFolder2versionedScripts.getValue();
for (Map.Entry<Integer, File> version2script : versionedScripts.entrySet()) {
Integer version = version2script.getKey();
File script = version2script.getValue();
ConcurrentMap<Integer, File> dbScripts = scriptMap.get(dbFolder.getName());
File prev = dbScripts.putIfAbsent(version, script.getAbsoluteFile());
if (prev != null) {
throw new OpenGammaRuntimeException("Can't add " + script.getAbsolutePath() + " script. Version " + version + " already added by " + prev.getAbsolutePath() + " script");
}
}
}
}
/**
* Creates map from versions to sql scripts.
*
* @param dialectDir the directory holding versioned scripts, not null
* @param scriptPattern the pattern to search for, not null
* @return the map, not null
*/
private static Map<File, Map<Integer, File>> findScriptFiles(File dialectDir, final Pattern scriptPattern) {
ArgumentChecker.isTrue(dialectDir.exists(), "Directory " + dialectDir.getAbsolutePath() + " does not exist");
ArgumentChecker.isTrue(dialectDir.isDirectory(), "dbCreateSuperDir must be directory not a regular file");
// find the candidate directories, such as foo_db
final File[] dbCreateScriptDirs = dialectDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return matches(pathname.getName(), DATABASE_SCRIPT_FOLDER_PATTERN);
}
});
// find the versioned files
Map<File, Map<Integer, File>> dbFolder2versionedScripts = newHashMap();
for (File dbCreateScriptDir : dbCreateScriptDirs) {
final File[] scriptFiles = dbCreateScriptDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile()
&& matches(pathname.getName(), scriptPattern);
}
});
Map<Integer, File> versionedScripts = newHashMap();
for (File scriptFile : scriptFiles) {
String versionStr = extract(scriptFile.getName(), scriptPattern, 1);
Integer version = Integer.valueOf(versionStr);
versionedScripts.put(version, scriptFile);
}
dbFolder2versionedScripts.put(dbCreateScriptDir, versionedScripts);
}
return dbFolder2versionedScripts;
}
//-------------------------------------------------------------------------
@Override
public String toString() {
return getDatabaseType();
}
}
| projects/OG-UtilDB/src/main/java/com/opengamma/util/test/DbScripts.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.test;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Sets.difference;
import static com.opengamma.util.RegexUtils.extract;
import static com.opengamma.util.RegexUtils.matches;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.BuildException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.ZipUtils;
/**
* Manager of database scripts.
*/
public final class DbScripts {
/** Script files by relative location. */
private static final File SCRIPT_RELATIVE_PATH = new File(DbTool.getWorkingDirectory(), "../OG-MasterDB");
/** Script files using zips built by Ant. */
private static final File SCRIPT_ZIP_PATH = new File(DbTool.getWorkingDirectory(), "lib/sql/com.opengamma/og-masterdb");
/** Script expansion. */
private static final File SCRIPT_INSTALL_DIR = new File(DbTool.getWorkingDirectory(), "temp/" + DbScripts.class.getSimpleName());
/** The script directories. */
private static volatile Collection<File> s_scriptDir;
private static final String DATABASE_INSTALL_FOLDER = "install/db";
private static final Pattern DATABASE_SCRIPT_FOLDER_PATTERN = Pattern.compile("(.+)_db");
private static final String DATABASE_CREATE_FOLDER = DATABASE_INSTALL_FOLDER + File.separatorChar + "create";
private static final String DATABASE_MIGRATE_FOLDER = DATABASE_INSTALL_FOLDER + File.separatorChar + "migrate";
private static final String DATABASE_CREATE_SCRIPT_PREFIX = "V_";
private static final String DATABASE_MIGRATE_SCRIPT_PREFIX = "V_";
private static final Pattern CREATE_SCRIPT_PATTERN = Pattern.compile("^" + DATABASE_CREATE_SCRIPT_PREFIX + "([0-9]+)__create_(.+?)\\.sql");
private static final Pattern MIGRATE_SCRIPT_PATTERN = Pattern.compile("^" + DATABASE_MIGRATE_SCRIPT_PREFIX + "([0-9]+)__(.+?)\\.sql");
/** The base script directories. */
private final Collection<File> _scriptDirs;
/** The database type. */
private final String _databaseType;
/** The scripts, by database type and version. */
private final Map<String, SortedMap<Integer, DbScriptPair>> _scripts;
//-------------------------------------------------------------------------
/**
* Gets the initialized the script directory.
*
* @return the script directory, not null
*/
public static Collection<File> getSqlScriptDir() {
if (s_scriptDir == null) {
synchronized (DbScripts.class) {
if (s_scriptDir == null) {
s_scriptDir = createSQLScripts();
}
}
}
return s_scriptDir;
}
private static Collection<File> createSQLScripts() {
try {
Collection<File> dirs = Sets.newHashSet();
File local = new File(DbTool.getWorkingDirectory(), DATABASE_INSTALL_FOLDER).getCanonicalFile();
File relative = new File(SCRIPT_RELATIVE_PATH, DATABASE_INSTALL_FOLDER).getCanonicalFile();
if (local.exists()) {
dirs.add(local);
}
if (relative.exists()) {
dirs.add(relative);
}
if (dirs.isEmpty()) {
if (SCRIPT_ZIP_PATH.exists()) {
if (SCRIPT_INSTALL_DIR.exists()) {
FileUtils.deleteQuietly(SCRIPT_INSTALL_DIR);
}
for (File file : (Collection<File>) FileUtils.listFiles(SCRIPT_ZIP_PATH, new String[] {"zip"}, false)) {
try {
ZipUtils.unzipArchive(file, SCRIPT_INSTALL_DIR);
} catch (IOException ex) {
throw new OpenGammaRuntimeException("Unable to unzip database scripts: " + SCRIPT_INSTALL_DIR);
}
}
dirs.add(SCRIPT_INSTALL_DIR.getCanonicalFile());
} else {
throw new IllegalArgumentException("Unable to find database scripts. Tried: " + local + ", " + relative + " and " + SCRIPT_ZIP_PATH);
}
}
return dirs;
} catch (IOException ex) {
throw new OpenGammaRuntimeException(ex.getMessage(), ex);
}
}
/**
* Deletes the script directory.
*/
public static void deleteSqlScriptDir() {
FileUtils.deleteQuietly(SCRIPT_INSTALL_DIR);
}
/**
* Gets the latest versions of the scripts across all databases.
*
* @param scriptDirs the script directories, not null
* @return the latest versions by , not null
*/
public static Map<String, Integer> getLatestVersions(Collection<File> scriptDirs) {
Map<String, Integer> result = new HashMap<>();
for (File scriptDir : scriptDirs) {
File parentDirectory = new File(scriptDir, DATABASE_CREATE_FOLDER);
for (File dialectDir : parentDirectory.listFiles()) {
if (dialectDir.isDirectory() == false) {
continue;
}
Map<File, Map<Integer, File>> scripts = findScriptFiles(dialectDir, CREATE_SCRIPT_PATTERN);
for (Map.Entry<File, Map<Integer, File>> masterScripts : scripts.entrySet()) {
String masterName = masterScripts.getKey().getName();
Set<Integer> versions = masterScripts.getValue().keySet();
if (versions.isEmpty()) {
continue;
}
int maxVersion = Collections.max(versions);
if (result.containsKey(masterName)) {
if (result.get(masterName).intValue() != maxVersion) {
throw new BuildException("Latest versions differ between database dialects for master '" + masterName +
"'. Found latest versions of both " + result.get(masterName) + " and " + maxVersion + ".");
}
} else {
result.put(masterName, maxVersion);
}
}
}
}
return result;
}
//-------------------------------------------------------------------------
/**
* Gets the scripts.
*
* @param scriptDirs the script directories, not null
* @param databaseType the database type, not null
* @return the scripts, not null
* @throws IllegalArgumentException if the scripts do not exist
*/
public static DbScripts of(Collection<File> scriptDirs, String databaseType) {
ArgumentChecker.notNull(databaseType, "databaseType");
return new DbScripts(scriptDirs, databaseType);
}
//-------------------------------------------------------------------------
/**
* Creates an instance.
*
* @param databaseType the database type, not null
* @param version the version
* @param createScript the create script, not null
* @param migrateScript the migrate script, not null
*/
private DbScripts(Collection<File> scriptDirs, String databaseType) {
ArgumentChecker.notNull(scriptDirs, "scriptDirs");
ArgumentChecker.notNull(databaseType, "databaseType");
_scriptDirs = ImmutableList.copyOf(scriptDirs);
_databaseType = databaseType;
_scripts = buildMap();
}
//-------------------------------------------------------------------------
/**
* Gets the SQL database creation script.
*
* @return the script file, not null
*/
public Collection<File> getScriptDirs() {
return _scriptDirs;
}
/**
* Gets the database type.
*
* @return the database type, not null
*/
public String getDatabaseType() {
return _databaseType;
}
/**
* Gets the script pairs.
* Keyed by table set and version.
*
* @return the map of scripts, not null
*/
public Map<String, SortedMap<Integer, DbScriptPair>> getScriptPairs() {
return _scripts;
}
/**
* Gets the latest script pair for a schema.
* Keyed by schema and version.
*
* @param tableSet the table set, not null
* @return the script pair, not null
*/
public DbScriptPair getLatestScriptPair(String tableSet) {
SortedMap<Integer, DbScriptPair> versions = _scripts.get(tableSet);
if (versions == null) {
throw new IllegalArgumentException("Unknown table set");
}
return versions.get(versions.lastKey());
}
//-------------------------------------------------------------------------
/**
* @return schema => version_number => (create_script, migrate_script)
*/
private Map<String, SortedMap<Integer, DbScriptPair>> buildMap() {
ConcurrentMap<String, ConcurrentMap<Integer, File>> createScripts = new ConcurrentHashMap<String, ConcurrentMap<Integer, File>>();
ConcurrentMap<String, ConcurrentMap<Integer, File>> migrateScripts = new ConcurrentHashMap<String, ConcurrentMap<Integer, File>>();
// for each script directory, find the files
for (File scriptDir : _scriptDirs) {
findScriptFiles(scriptDir, createScripts, DATABASE_CREATE_FOLDER, CREATE_SCRIPT_PATTERN);
findScriptFiles(scriptDir, migrateScripts, DATABASE_MIGRATE_FOLDER, MIGRATE_SCRIPT_PATTERN);
}
// ensure valid script file setup
Set<String> createTableSets = createScripts.keySet();
Set<String> migrateTableSets = migrateScripts.keySet();
Set<String> unmatchedCreateDbDirs = difference(migrateTableSets, createTableSets);
if (unmatchedCreateDbDirs.size() > 0) {
StringBuilder errorMessage = new StringBuilder();
for (String unmatchedCreateDbDir : unmatchedCreateDbDirs) {
errorMessage.append("There is no corresponding create db directory for migrate one: " + unmatchedCreateDbDir + "\n");
}
throw new OpenGammaRuntimeException(errorMessage.toString());
}
Set<String> unmatchedMigrateDbDirs = difference(createTableSets, migrateTableSets);
if (unmatchedMigrateDbDirs.size() > 0) {
StringBuilder errorMessage = new StringBuilder();
for (String unmatchedMigrateDbDir : unmatchedMigrateDbDirs) {
errorMessage.append("There is no corresponding migrate db directory for create one: " + unmatchedMigrateDbDir + "\n");
}
throw new OpenGammaRuntimeException(errorMessage.toString());
}
// build output
final ConcurrentMap<String, SortedMap<Integer, DbScriptPair>> scripts = new ConcurrentHashMap<>();
for (String tableSet : migrateTableSets) {
ConcurrentMap<Integer, File> versionedCreateScripts = createScripts.get(tableSet);
ConcurrentMap<Integer, File> versionedMigrateScripts = migrateScripts.get(tableSet);
Set<Integer> versions = versionedCreateScripts.keySet();
for (Integer version : versions) {
File createScript = versionedCreateScripts.get(version);
File migrateScript = versionedMigrateScripts.get(version);
scripts.putIfAbsent(tableSet, new TreeMap<Integer, DbScriptPair>());
scripts.get(tableSet).put(version, new DbScriptPair(_databaseType, tableSet, version, createScript, migrateScript));
}
}
if (scripts.isEmpty()) {
throw new OpenGammaRuntimeException("No script directories found: " + _scriptDirs);
}
return scripts;
}
private void findScriptFiles(File scriptDir, ConcurrentMap<String, ConcurrentMap<Integer, File>> scriptMap, String subDir, Pattern pattern) {
// find the files
File dialectDir = new File(scriptDir, subDir + File.separatorChar + _databaseType);
Map<File, Map<Integer, File>> scriptsFiles = findScriptFiles(dialectDir, pattern);
// build the map
for (Map.Entry<File, Map<Integer, File>> dbFolder2versionedScripts : scriptsFiles.entrySet()) {
File dbFolder = dbFolder2versionedScripts.getKey();
scriptMap.putIfAbsent(dbFolder.getName(), new ConcurrentHashMap<Integer, File>());
Map<Integer, File> versionedScripts = dbFolder2versionedScripts.getValue();
for (Map.Entry<Integer, File> version2script : versionedScripts.entrySet()) {
Integer version = version2script.getKey();
File script = version2script.getValue();
ConcurrentMap<Integer, File> dbScripts = scriptMap.get(dbFolder.getName());
File prev = dbScripts.putIfAbsent(version, script.getAbsoluteFile());
if (prev != null) {
throw new OpenGammaRuntimeException("Can't add " + script.getAbsolutePath() + " script. Version " + version + " already added by " + prev.getAbsolutePath() + " script");
}
}
}
}
/**
* Creates map from versions to sql scripts.
*
* @param dialectDir the directory holding versioned scripts, not null
* @param scriptPattern the pattern to search for, not null
* @return the map, not null
*/
private static Map<File, Map<Integer, File>> findScriptFiles(File dialectDir, final Pattern scriptPattern) {
ArgumentChecker.isTrue(dialectDir.exists(), "Directory " + dialectDir.getAbsolutePath() + " does not exist");
ArgumentChecker.isTrue(dialectDir.isDirectory(), "dbCreateSuperDir must be directory not a regular file");
// find the candidate directories, such as foo_db
final File[] dbCreateScriptDirs = dialectDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return matches(pathname.getName(), DATABASE_SCRIPT_FOLDER_PATTERN);
}
});
// find the versioned files
Map<File, Map<Integer, File>> dbFolder2versionedScripts = newHashMap();
for (File dbCreateScriptDir : dbCreateScriptDirs) {
final File[] scriptFiles = dbCreateScriptDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile()
&& matches(pathname.getName(), scriptPattern);
}
});
Map<Integer, File> versionedScripts = newHashMap();
for (File scriptFile : scriptFiles) {
String versionStr = extract(scriptFile.getName(), scriptPattern, 1);
Integer version = Integer.valueOf(versionStr);
versionedScripts.put(version, scriptFile);
}
dbFolder2versionedScripts.put(dbCreateScriptDir, versionedScripts);
}
return dbFolder2versionedScripts;
}
//-------------------------------------------------------------------------
@Override
public String toString() {
return getDatabaseType();
}
}
| [PLAT-3409] Fix script loading to also look locally
| projects/OG-UtilDB/src/main/java/com/opengamma/util/test/DbScripts.java | [PLAT-3409] Fix script loading to also look locally | <ide><path>rojects/OG-UtilDB/src/main/java/com/opengamma/util/test/DbScripts.java
<ide> File local = new File(DbTool.getWorkingDirectory(), DATABASE_INSTALL_FOLDER).getCanonicalFile();
<ide> File relative = new File(SCRIPT_RELATIVE_PATH, DATABASE_INSTALL_FOLDER).getCanonicalFile();
<ide> if (local.exists()) {
<del> dirs.add(local);
<add> dirs.add(new File(DbTool.getWorkingDirectory()).getCanonicalFile());
<ide> }
<ide> if (relative.exists()) {
<del> dirs.add(relative);
<add> dirs.add(SCRIPT_RELATIVE_PATH);
<ide> }
<ide> if (dirs.isEmpty()) {
<ide> if (SCRIPT_ZIP_PATH.exists()) { |
|
Java | apache-2.0 | 61bd0f466a0b9e353fdda49406dca4fba370aa70 | 0 | serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.ext.postgresql.ui.editors;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
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.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchSite;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.ext.postgresql.model.*;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseFolder;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.navigator.DBNNode;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
import org.jkiss.dbeaver.model.runtime.load.DatabaseLoadService;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.LoadingJob;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.ProgressPageControl;
import org.jkiss.dbeaver.ui.editors.AbstractDatabaseObjectEditor;
import org.jkiss.dbeaver.ui.navigator.NavigatorUtils;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorLabelProvider;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTree;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTreeFilter;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* PostgresRolePrivilegesEditor
*/
public class PostgresRolePrivilegesEditor extends AbstractDatabaseObjectEditor<PostgrePermissionsOwner>
{
private PageControl pageControl;
private boolean isLoaded;
private DatabaseNavigatorTree roleOrObjectTable;
private Table permissionTable;
private Action actionCheckAll;
private Action actionCheckNone;
private PostgrePermission currentPermission;
private DBSObject currentObject;
private Map<String, PostgrePermission> permissionMap = new HashMap<>();
public void createPartControl(Composite parent) {
{
/*
actionGrant = new Action("Grant " + (isRoleEditor() ? "object" : "role"), DBeaverIcons.getImageDescriptor(getObjectAddIcon())) {
@Override
public void run() {
try {
VoidProgressMonitor monitor = new VoidProgressMonitor();
if (isRoleEditor()) {
DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
DBNDatabaseNode schemasNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
List<DBNNode> tableNodes = BrowseObjectDialog.selectObjects(getSite().getShell(), "Select object", schemasNode, null,
new Class[]{Object.class}, new Class[]{PostgreTableBase.class});
if (tableNodes != null) {
for (DBNNode node : tableNodes) {
}
}
} else {
List<PostgreRole> allRoles = new ArrayList<>(getDatabaseObject().getDatabase().getAuthIds(monitor));
if (currentPrivs != null) {
for (PostgrePermission p : currentPrivs) {
allRoles.remove(p.getTargetObject(monitor));
}
}
SelectObjectDialog<PostgreRole> roleSelector = new SelectObjectDialog<>(
getSite().getShell(),
"Select role",
true,
"Permissions/Role/Selector",
allRoles,
null);
if (roleSelector.open() == IDialogConstants.OK_ID) {
}
}
} catch (DBException e) {
DBeaverUI.getInstance().showError("Load object", "Error loading permission objects", e);
}
}
};
actionRevoke = new Action("Revoke " + (isRoleEditor() ? "object" : "role"), DBeaverIcons.getImageDescriptor(getObjectRemoveIcon())) {
@Override
public void run() {
super.run();
}
};
*/
actionCheckAll = new Action("All") {
@Override
public void run() {
boolean hadNonChecked = false;
for (TableItem item : permissionTable.getItems()) {
if (!item.getChecked()) hadNonChecked = true;
item.setChecked(true);
}
if (hadNonChecked) updateCurrentPrivileges();
}
};
actionCheckNone = new Action("None") {
@Override
public void run() {
boolean hadChecked = false;
for (TableItem item : permissionTable.getItems()) {
item.setChecked(false);
if (item.getChecked()) hadChecked = true;
}
if (hadChecked) {
updateCurrentPrivileges();
}
}
};
}
this.pageControl = new PageControl(parent);
SashForm composite = UIUtils.createPartDivider(getSite().getPart(), this.pageControl, SWT.HORIZONTAL);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
roleOrObjectTable = new DatabaseNavigatorTree(composite, DBeaverCore.getInstance().getNavigatorModel().getRoot(), SWT.FULL_SELECTION, false, new DatabaseNavigatorTreeFilter());
roleOrObjectTable.setLayoutData(new GridData(GridData.FILL_BOTH));
final TreeViewer treeViewer = roleOrObjectTable.getViewer();
treeViewer.setLabelProvider(new DatabaseNavigatorLabelProvider(treeViewer) {
@Override
public Font getFont(Object element) {
if (element instanceof DBNDatabaseNode) {
DBSObject object = ((DBNDatabaseNode) element).getObject();
if (getObjectPermissions(object) != null) {
return boldFont;
}
}
return null;
}
});
treeViewer.addSelectionChangedListener(event -> {
DBSObject selectedObject = NavigatorUtils.getSelectedObject(treeViewer.getSelection());
if (selectedObject == null) {
updateObjectPermissions(null, null);
} else {
updateObjectPermissions(getObjectPermissions(selectedObject), selectedObject);
}
});
treeViewer.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof DBNNode && !(element instanceof DBNDatabaseNode)) {
return false;
}
if (element instanceof DBNDatabaseFolder) {
try {
Class<?> childType = Class.forName(((DBNDatabaseFolder) element).getMeta().getType());
return PostgreTableReal.class.isAssignableFrom(childType);
} catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
});
permissionTable = new Table(composite, SWT.FULL_SELECTION | SWT.CHECK);
permissionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
permissionTable.setHeaderVisible(true);
permissionTable.setLinesVisible(true);
UIUtils.createTableColumn(permissionTable, SWT.LEFT, "Permission");
UIUtils.createTableColumn(permissionTable, SWT.CENTER, "With GRANT");
UIUtils.createTableColumn(permissionTable, SWT.CENTER, "With Hierarchy");
permissionTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (e.detail == SWT.CHECK) {
updateCurrentPrivileges();
}
}
});
permissionTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
super.mouseDown(e);
}
});
for (PostgrePrivilegeType pt : PostgrePrivilegeType.values()) {
if (!pt.isValid()) {
continue;
}
TableItem privItem = new TableItem(permissionTable, SWT.LEFT);
privItem.setText(0, pt.name());
privItem.setData(pt);
}
pageControl.createOrSubstituteProgressPanel(getSite());
updateObjectPermissions(null, null);
registerContextMenu();
}
private PostgrePermission getObjectPermissions(DBSObject object) {
return permissionMap.get(DBUtils.getObjectFullName(object, DBPEvaluationContext.DDL));
}
private void updateCurrentPrivileges() {
//System.out.println("Privs changed");
}
private void registerContextMenu()
{
/*
// Register objects context menu
{
MenuManager menuMgr = new MenuManager();
menuMgr.addMenuListener(manager -> {
manager.add(actionGrant);
manager.add(actionRevoke);
});
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(roleOrObjectTable);
roleOrObjectTable.setMenu(menu);
}
*/
// Register objects context menu
{
MenuManager menuMgr = new MenuManager();
menuMgr.addMenuListener(manager -> {
manager.add(actionCheckAll);
manager.add(actionCheckNone);
});
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(permissionTable);
permissionTable.setMenu(menu);
}
}
private void openPermObject() {
DBSObject selectedObject = NavigatorUtils.getSelectedObject(roleOrObjectTable.getViewer().getSelection());
if (selectedObject == null) {
updateObjectPermissions(null, null);
} else {
PostgrePermission permission = permissionMap.get(selectedObject);
updateObjectPermissions(permission, selectedObject);
}
/*
new AbstractJob("Open target object") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
final PostgreObject targetObject = permission.getTargetObject(monitor);
if (targetObject != null) {
DBeaverUI.syncExec(() -> NavigatorHandlerObjectOpen.openEntityEditor(targetObject));
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
*/
}
private void updateObjectPermissions(PostgrePermission data, DBSObject curObject) {
this.currentPermission = data;
if (curObject instanceof PostgreTableBase || curObject instanceof PostgreRole) {
this.currentObject = curObject;
} else {
this.currentObject = curObject = null;
}
if (data == null) {
permissionTable.setEnabled(curObject != null);
for (TableItem item : permissionTable.getItems()) {
item.setChecked(false);
item.setText(1, "");
item.setText(2, "");
}
} else {
permissionTable.setEnabled(true);
for (TableItem item : permissionTable.getItems()) {
PostgrePrivilegeType privType = (PostgrePrivilegeType) item.getData();
short perm = data.getPermission(privType);
item.setChecked((perm & PostgrePermission.GRANTED) != 0);
if ((perm & PostgrePermission.WITH_GRANT_OPTION) != 0) {
item.setText(1, "X");
} else {
item.setText(1, "");
}
if ((perm & PostgrePermission.WITH_HIERARCHY) != 0) {
item.setText(2, "X");
} else {
item.setText(2, "");
}
}
}
actionCheckAll.setEnabled(data != null);
actionCheckNone.setEnabled(data != null);
}
private boolean isRoleEditor() {
return getDatabaseObject() instanceof PostgreRole;
}
@Override
public void setFocus() {
if (this.pageControl != null) {
// Important! activation of page control fills action toolbar
this.pageControl.activate(true);
}
if (roleOrObjectTable != null) {
roleOrObjectTable.getViewer().getControl().setFocus();
}
}
@Override
public synchronized void activatePart()
{
if (isLoaded) {
return;
}
isLoaded = true;
DBeaverUI.asyncExec(() -> {
UIUtils.packColumns(permissionTable, false);
});
LoadingJob.createService(
new DatabaseLoadService<Collection<PostgrePermission>>("Load permissions", getExecutionContext()) {
@Override
public Collection<PostgrePermission> evaluate(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Load privileges from database..", 1);
try {
monitor.subTask("Load " + getDatabaseObject().getName() + " privileges");
return getDatabaseObject().getPermissions(monitor);
} catch (DBException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
},
pageControl.createLoadVisualizer())
.schedule();
}
@Override
public void refreshPart(Object source, boolean force)
{
isLoaded = false;
DBeaverUI.syncExec(() -> {
updateObjectPermissions(null, null);
});
activatePart();
}
private class PageControl extends ProgressPageControl {
PageControl(Composite parent) {
super(parent, SWT.SHEET);
}
ProgressVisualizer<Collection<PostgrePermission>> createLoadVisualizer() {
return new ProgressVisualizer<Collection<PostgrePermission>>() {
@Override
public void completeLoading(Collection<PostgrePermission> privs) {
super.completeLoading(privs);
for (PostgrePermission perm : privs) {
permissionMap.put(perm.getName(), perm);
}
// Load navigator tree
DBRProgressMonitor monitor = new VoidProgressMonitor();
DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
DBNDatabaseNode rootNode;
if (isRoleEditor()) {
rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
} else {
rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreRole.class);
}
if (rootNode == null) {
DBeaverUI.getInstance().showError("Object tree", "Can't detect root node for objects tree");
} else {
roleOrObjectTable.reloadTree(rootNode);
}
}
};
}
@Override
protected void fillCustomActions(IContributionManager contributionManager) {
super.fillCustomActions(contributionManager);
contributionManager.add(new Separator());
contributionManager.add(actionCheckAll);
contributionManager.add(actionCheckNone);
contributionManager.add(new Separator());
IWorkbenchSite workbenchSite = getSite();
if (workbenchSite != null) {
contributionManager.add(ActionUtils.makeCommandContribution(workbenchSite, IWorkbenchCommandConstants.FILE_REFRESH));
}
}
}
} | plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/ui/editors/PostgresRolePrivilegesEditor.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.ext.postgresql.ui.editors;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
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.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchSite;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.ext.postgresql.model.*;
import org.jkiss.dbeaver.model.DBIcon;
import org.jkiss.dbeaver.model.DBPEvaluationContext;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseFolder;
import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
import org.jkiss.dbeaver.model.runtime.load.DatabaseLoadService;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.LoadingJob;
import org.jkiss.dbeaver.ui.UIIcon;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.ProgressPageControl;
import org.jkiss.dbeaver.ui.editors.AbstractDatabaseObjectEditor;
import org.jkiss.dbeaver.ui.navigator.NavigatorUtils;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorLabelProvider;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTree;
import org.jkiss.dbeaver.ui.navigator.database.DatabaseNavigatorTreeFilter;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* PostgresRolePrivilegesEditor
*/
public class PostgresRolePrivilegesEditor extends AbstractDatabaseObjectEditor<PostgrePermissionsOwner>
{
private PageControl pageControl;
private boolean isLoaded;
private DatabaseNavigatorTree roleOrObjectTable;
private Table permissionTable;
private Action actionCheckAll;
private Action actionCheckNone;
private PostgrePermission currentPermission;
private DBSObject currentObject;
private Map<String, PostgrePermission> permissionMap = new HashMap<>();
public void createPartControl(Composite parent) {
{
/*
actionGrant = new Action("Grant " + (isRoleEditor() ? "object" : "role"), DBeaverIcons.getImageDescriptor(getObjectAddIcon())) {
@Override
public void run() {
try {
VoidProgressMonitor monitor = new VoidProgressMonitor();
if (isRoleEditor()) {
DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
DBNDatabaseNode schemasNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
List<DBNNode> tableNodes = BrowseObjectDialog.selectObjects(getSite().getShell(), "Select object", schemasNode, null,
new Class[]{Object.class}, new Class[]{PostgreTableBase.class});
if (tableNodes != null) {
for (DBNNode node : tableNodes) {
}
}
} else {
List<PostgreRole> allRoles = new ArrayList<>(getDatabaseObject().getDatabase().getAuthIds(monitor));
if (currentPrivs != null) {
for (PostgrePermission p : currentPrivs) {
allRoles.remove(p.getTargetObject(monitor));
}
}
SelectObjectDialog<PostgreRole> roleSelector = new SelectObjectDialog<>(
getSite().getShell(),
"Select role",
true,
"Permissions/Role/Selector",
allRoles,
null);
if (roleSelector.open() == IDialogConstants.OK_ID) {
}
}
} catch (DBException e) {
DBeaverUI.getInstance().showError("Load object", "Error loading permission objects", e);
}
}
};
actionRevoke = new Action("Revoke " + (isRoleEditor() ? "object" : "role"), DBeaverIcons.getImageDescriptor(getObjectRemoveIcon())) {
@Override
public void run() {
super.run();
}
};
*/
actionCheckAll = new Action("All") {
@Override
public void run() {
boolean hadNonChecked = false;
for (TableItem item : permissionTable.getItems()) {
if (!item.getChecked()) hadNonChecked = true;
item.setChecked(true);
}
if (hadNonChecked) updateCurrentPrivileges();
}
};
actionCheckNone = new Action("None") {
@Override
public void run() {
boolean hadChecked = false;
for (TableItem item : permissionTable.getItems()) {
item.setChecked(false);
if (item.getChecked()) hadChecked = true;
}
if (hadChecked) {
updateCurrentPrivileges();
}
}
};
}
this.pageControl = new PageControl(parent);
SashForm composite = UIUtils.createPartDivider(getSite().getPart(), this.pageControl, SWT.HORIZONTAL);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
roleOrObjectTable = new DatabaseNavigatorTree(composite, DBeaverCore.getInstance().getNavigatorModel().getRoot(), SWT.FULL_SELECTION, false, new DatabaseNavigatorTreeFilter());
roleOrObjectTable.setLayoutData(new GridData(GridData.FILL_BOTH));
final TreeViewer treeViewer = roleOrObjectTable.getViewer();
treeViewer.setLabelProvider(new DatabaseNavigatorLabelProvider(treeViewer) {
@Override
public Font getFont(Object element) {
if (element instanceof DBNDatabaseNode) {
DBSObject object = ((DBNDatabaseNode) element).getObject();
if (getObjectPermissions(object) != null) {
return boldFont;
}
}
return null;
}
});
treeViewer.addSelectionChangedListener(event -> {
DBSObject selectedObject = NavigatorUtils.getSelectedObject(treeViewer.getSelection());
if (selectedObject == null) {
updateObjectPermissions(null, null);
} else {
updateObjectPermissions(getObjectPermissions(selectedObject), selectedObject);
}
});
treeViewer.addFilter(new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof DBNDatabaseFolder) {
try {
Class<?> childType = Class.forName(((DBNDatabaseFolder) element).getMeta().getType());
return PostgreTableReal.class.isAssignableFrom(childType);
} catch (ClassNotFoundException e) {
return false;
}
}
return true;
}
});
permissionTable = new Table(composite, SWT.FULL_SELECTION | SWT.CHECK);
permissionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
permissionTable.setHeaderVisible(true);
permissionTable.setLinesVisible(true);
UIUtils.createTableColumn(permissionTable, SWT.LEFT, "Permission");
UIUtils.createTableColumn(permissionTable, SWT.CENTER, "With GRANT");
UIUtils.createTableColumn(permissionTable, SWT.CENTER, "With Hierarchy");
permissionTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (e.detail == SWT.CHECK) {
updateCurrentPrivileges();
}
}
});
permissionTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
super.mouseDown(e);
}
});
for (PostgrePrivilegeType pt : PostgrePrivilegeType.values()) {
if (!pt.isValid()) {
continue;
}
TableItem privItem = new TableItem(permissionTable, SWT.LEFT);
privItem.setText(0, pt.name());
privItem.setData(pt);
}
pageControl.createOrSubstituteProgressPanel(getSite());
updateObjectPermissions(null, null);
registerContextMenu();
}
private PostgrePermission getObjectPermissions(DBSObject object) {
return permissionMap.get(DBUtils.getObjectFullName(object, DBPEvaluationContext.DDL));
}
private void updateCurrentPrivileges() {
//System.out.println("Privs changed");
}
private void registerContextMenu()
{
/*
// Register objects context menu
{
MenuManager menuMgr = new MenuManager();
menuMgr.addMenuListener(manager -> {
manager.add(actionGrant);
manager.add(actionRevoke);
});
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(roleOrObjectTable);
roleOrObjectTable.setMenu(menu);
}
*/
// Register objects context menu
{
MenuManager menuMgr = new MenuManager();
menuMgr.addMenuListener(manager -> {
manager.add(actionCheckAll);
manager.add(actionCheckNone);
});
menuMgr.setRemoveAllWhenShown(true);
Menu menu = menuMgr.createContextMenu(permissionTable);
permissionTable.setMenu(menu);
}
}
private void openPermObject() {
DBSObject selectedObject = NavigatorUtils.getSelectedObject(roleOrObjectTable.getViewer().getSelection());
if (selectedObject == null) {
updateObjectPermissions(null, null);
} else {
PostgrePermission permission = permissionMap.get(selectedObject);
updateObjectPermissions(permission, selectedObject);
}
/*
new AbstractJob("Open target object") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
final PostgreObject targetObject = permission.getTargetObject(monitor);
if (targetObject != null) {
DBeaverUI.syncExec(() -> NavigatorHandlerObjectOpen.openEntityEditor(targetObject));
}
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
}
return Status.OK_STATUS;
}
}.schedule();
*/
}
private void updateObjectPermissions(PostgrePermission data, DBSObject curObject) {
this.currentPermission = data;
if (curObject instanceof PostgreTableBase || curObject instanceof PostgreRole) {
this.currentObject = curObject;
} else {
this.currentObject = curObject = null;
}
if (data == null) {
permissionTable.setEnabled(curObject != null);
for (TableItem item : permissionTable.getItems()) {
item.setChecked(false);
item.setText(1, "");
item.setText(2, "");
}
} else {
permissionTable.setEnabled(true);
for (TableItem item : permissionTable.getItems()) {
PostgrePrivilegeType privType = (PostgrePrivilegeType) item.getData();
short perm = data.getPermission(privType);
item.setChecked((perm & PostgrePermission.GRANTED) != 0);
if ((perm & PostgrePermission.WITH_GRANT_OPTION) != 0) {
item.setText(1, "X");
} else {
item.setText(1, "");
}
if ((perm & PostgrePermission.WITH_HIERARCHY) != 0) {
item.setText(2, "X");
} else {
item.setText(2, "");
}
}
}
actionCheckAll.setEnabled(data != null);
actionCheckNone.setEnabled(data != null);
}
public DBIcon getObjectIcon() {
return isRoleEditor() ? UIIcon.ACTION_OBJECT : UIIcon.ACTION_USER;
}
public DBIcon getObjectAddIcon() {
return isRoleEditor() ? UIIcon.ACTION_OBJECT_ADD : UIIcon.ACTION_USER_ADD;
}
public DBIcon getObjectRemoveIcon() {
return isRoleEditor() ? UIIcon.ACTION_OBJECT_DELETE : UIIcon.ACTION_USER_DELETE;
}
private boolean isRoleEditor() {
return getDatabaseObject() instanceof PostgreRole;
}
@Override
public void setFocus() {
if (this.pageControl != null) {
// Important! activation of page control fills action toolbar
this.pageControl.activate(true);
}
if (roleOrObjectTable != null) {
roleOrObjectTable.getViewer().getControl().setFocus();
}
}
@Override
public synchronized void activatePart()
{
if (isLoaded) {
return;
}
isLoaded = true;
{
// Load navigator tree
DBRProgressMonitor monitor = new VoidProgressMonitor();
DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
DBNDatabaseNode rootNode;
if (isRoleEditor()) {
rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
} else {
rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreRole.class);
}
if (rootNode == null) {
DBeaverUI.getInstance().showError("Object tree", "Can't detect root node for objects tree");
} else {
roleOrObjectTable.reloadTree(rootNode);
}
}
DBeaverUI.asyncExec(() -> {
UIUtils.packColumns(permissionTable, false);
});
LoadingJob.createService(
new DatabaseLoadService<Collection<PostgrePermission>>("Load permissions", getExecutionContext()) {
@Override
public Collection<PostgrePermission> evaluate(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
monitor.beginTask("Load privileges from database..", 1);
try {
monitor.subTask("Load " + getDatabaseObject().getName() + " privileges");
return getDatabaseObject().getPermissions(monitor);
} catch (DBException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
},
pageControl.createLoadVisualizer())
.schedule();
}
@Override
public void refreshPart(Object source, boolean force)
{
isLoaded = false;
DBeaverUI.syncExec(() -> {
updateObjectPermissions(null, null);
});
activatePart();
}
private class PageControl extends ProgressPageControl {
PageControl(Composite parent) {
super(parent, SWT.SHEET);
}
ProgressVisualizer<Collection<PostgrePermission>> createLoadVisualizer() {
return new ProgressVisualizer<Collection<PostgrePermission>>() {
@Override
public void completeLoading(Collection<PostgrePermission> privs) {
super.completeLoading(privs);
for (PostgrePermission perm : privs) {
permissionMap.put(perm.getName(), perm);
}
}
};
}
@Override
protected void fillCustomActions(IContributionManager contributionManager) {
super.fillCustomActions(contributionManager);
contributionManager.add(new Separator());
contributionManager.add(actionCheckAll);
contributionManager.add(actionCheckNone);
contributionManager.add(new Separator());
IWorkbenchSite workbenchSite = getSite();
if (workbenchSite != null) {
contributionManager.add(ActionUtils.makeCommandContribution(workbenchSite, IWorkbenchCommandConstants.FILE_REFRESH));
}
}
}
} | #1712 PG privilege editor redesign (use nav tree)
Former-commit-id: bce8da43cb20719adcea8fea214cc16b8cb836ae | plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/ui/editors/PostgresRolePrivilegesEditor.java | #1712 PG privilege editor redesign (use nav tree) | <ide><path>lugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/ui/editors/PostgresRolePrivilegesEditor.java
<ide> import org.jkiss.dbeaver.model.DBUtils;
<ide> import org.jkiss.dbeaver.model.navigator.DBNDatabaseFolder;
<ide> import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode;
<add>import org.jkiss.dbeaver.model.navigator.DBNNode;
<ide> import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
<ide> import org.jkiss.dbeaver.model.runtime.VoidProgressMonitor;
<ide> import org.jkiss.dbeaver.model.runtime.load.DatabaseLoadService;
<ide> treeViewer.addFilter(new ViewerFilter() {
<ide> @Override
<ide> public boolean select(Viewer viewer, Object parentElement, Object element) {
<add> if (element instanceof DBNNode && !(element instanceof DBNDatabaseNode)) {
<add> return false;
<add> }
<ide> if (element instanceof DBNDatabaseFolder) {
<ide> try {
<ide> Class<?> childType = Class.forName(((DBNDatabaseFolder) element).getMeta().getType());
<ide> actionCheckNone.setEnabled(data != null);
<ide> }
<ide>
<del> public DBIcon getObjectIcon() {
<del> return isRoleEditor() ? UIIcon.ACTION_OBJECT : UIIcon.ACTION_USER;
<del> }
<del>
<del> public DBIcon getObjectAddIcon() {
<del> return isRoleEditor() ? UIIcon.ACTION_OBJECT_ADD : UIIcon.ACTION_USER_ADD;
<del> }
<del>
<del> public DBIcon getObjectRemoveIcon() {
<del> return isRoleEditor() ? UIIcon.ACTION_OBJECT_DELETE : UIIcon.ACTION_USER_DELETE;
<del> }
<del>
<ide> private boolean isRoleEditor() {
<ide> return getDatabaseObject() instanceof PostgreRole;
<ide> }
<ide> return;
<ide> }
<ide> isLoaded = true;
<del>
<del> {
<del> // Load navigator tree
<del> DBRProgressMonitor monitor = new VoidProgressMonitor();
<del> DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
<del> DBNDatabaseNode rootNode;
<del> if (isRoleEditor()) {
<del> rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
<del> } else {
<del> rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreRole.class);
<del> }
<del> if (rootNode == null) {
<del> DBeaverUI.getInstance().showError("Object tree", "Can't detect root node for objects tree");
<del> } else {
<del> roleOrObjectTable.reloadTree(rootNode);
<del> }
<del> }
<ide>
<ide> DBeaverUI.asyncExec(() -> {
<ide> UIUtils.packColumns(permissionTable, false);
<ide> for (PostgrePermission perm : privs) {
<ide> permissionMap.put(perm.getName(), perm);
<ide> }
<add> // Load navigator tree
<add> DBRProgressMonitor monitor = new VoidProgressMonitor();
<add> DBNDatabaseNode dbNode = NavigatorUtils.getNodeByObject(getDatabaseObject().getDatabase());
<add> DBNDatabaseNode rootNode;
<add> if (isRoleEditor()) {
<add> rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreSchema.class);
<add> } else {
<add> rootNode = NavigatorUtils.getChildFolder(monitor, dbNode, PostgreRole.class);
<add> }
<add> if (rootNode == null) {
<add> DBeaverUI.getInstance().showError("Object tree", "Can't detect root node for objects tree");
<add> } else {
<add> roleOrObjectTable.reloadTree(rootNode);
<add> }
<ide> }
<ide> };
<ide> } |
|
Java | bsd-3-clause | eb0a8641cbed8ec4776c18bfb289a987f073b99a | 0 | Open-MBEE/MDK,Open-MBEE/MDK | /*******************************************************************************
* Copyright (c) <2013>, California Institute of Technology ("Caltech").
* U.S. Government sponsorship acknowledged.
*
* 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 Caltech nor its operating division, the Jet Propulsion Laboratory,
* 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 gov.nasa.jpl.mbee;
import gov.nasa.jpl.mbee.actions.ViewViewCommentsAction;
import gov.nasa.jpl.mbee.actions.docgen.GenerateDocumentAction;
import gov.nasa.jpl.mbee.actions.docgen.InstanceViewpointAction;
import gov.nasa.jpl.mbee.actions.docgen.NumberDependencyAction;
import gov.nasa.jpl.mbee.actions.docgen.RunUserScriptAction;
import gov.nasa.jpl.mbee.actions.docgen.RunUserValidationScriptAction;
import gov.nasa.jpl.mbee.actions.docgen.ValidateDocument3Action;
import gov.nasa.jpl.mbee.actions.docgen.ValidateViewStructureAction;
import gov.nasa.jpl.mbee.actions.docgen.ViewDocument3Action;
import gov.nasa.jpl.mbee.actions.ems.ExportModelAction;
import gov.nasa.jpl.mbee.actions.ems.InitializeProjectAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateModelAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateViewAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewCommentsAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewHierarchyAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewCommentsAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewDryAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.SynchronizeViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.SynchronizeViewRecursiveAction;
import gov.nasa.jpl.mbee.generator.DocumentGenerator;
import gov.nasa.jpl.mbee.lib.MDUtils;
import gov.nasa.jpl.mbee.lib.Utils;
import gov.nasa.jpl.mbee.model.CollectActionsVisitor;
import gov.nasa.jpl.mbee.model.Document;
import gov.nasa.jpl.mbee.model.UserScript;
import gov.nasa.jpl.mbee.viewedit.ViewEditUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.nomagic.actions.ActionsCategory;
import com.nomagic.actions.ActionsManager;
import com.nomagic.actions.NMAction;
import com.nomagic.magicdraw.actions.BrowserContextAMConfigurator;
import com.nomagic.magicdraw.actions.ConfiguratorWithPriority;
import com.nomagic.magicdraw.actions.DiagramContextAMConfigurator;
import com.nomagic.magicdraw.actions.MDAction;
import com.nomagic.magicdraw.actions.MDActionsCategory;
import com.nomagic.magicdraw.core.Project;
import com.nomagic.magicdraw.ui.browser.Node;
import com.nomagic.magicdraw.ui.browser.Tree;
import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement;
import com.nomagic.magicdraw.uml.symbols.PresentationElement;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.activities.mdfundamentalactivities.Activity;
import com.nomagic.uml2.ext.magicdraw.auxiliaryconstructs.mdmodels.Model;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
public class DocGenConfigurator implements BrowserContextAMConfigurator, DiagramContextAMConfigurator {
private Set<ActionsManager> viewQueryCalled = new HashSet<ActionsManager>();
@Override
public int getPriority() {
return ConfiguratorWithPriority.MEDIUM_PRIORITY;
}
@Override
public void configure(ActionsManager manager, Tree browser) {
Node no = browser.getSelectedNode();
if (no == null)
return;
Object o = no.getUserObject();
if (!(o instanceof Element))
return;
addElementActions(manager, (Element)o);
}
@Override
public void configure(ActionsManager manager, DiagramPresentationElement diagram,
PresentationElement[] selected, PresentationElement requestor) {
if (requestor != null) {
Element e = requestor.getElement();
addElementActions(manager, e);
} else {
addDiagramActions(manager, diagram);
}
}
private void addElementActions(ActionsManager manager, Element e) {
Project prj = Project.getProject(e);
if (prj == null)
return;
Stereotype sysmlview = Utils.getViewStereotype();
Stereotype sysmlviewpoint = Utils.getViewpointStereotype();
Stereotype documentView = StereotypesHelper.getStereotype(prj, DocGen3Profile.documentViewStereotype,
"Document Profile");
if (e == null)
return;
if (ViewEditUtils.isPasswordSet()) {
if (MDUtils.isDeveloperMode()) {
ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
if (manager.getActionFor(ExportModelAction.actionid) == null)
modelLoad.addAction(new ExportModelAction(e));
if (e instanceof Model && manager.getActionFor(InitializeProjectAction.actionid) == null)
modelLoad.addAction(new InitializeProjectAction());
if (manager.getActionFor(ValidateModelAction.actionid) == null)
modelLoad.addAction(new ValidateModelAction(e));
} else if (e instanceof Model) {
ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
if (manager.getActionFor(ValidateModelAction.actionid) == null)
modelLoad.addAction(new ValidateModelAction(e));
}
}
// add menus in reverse order since they are inserted at top
// View Interaction menu
if (StereotypesHelper.hasStereotypeOrDerived(e, DocGen3Profile.validationScriptStereotype)) {
ActionsCategory c = myCategory(manager, "ViewInteraction", "View Interaction");
UserScript us = new UserScript();
us.setDgElement(e);
List<Element> targets = Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.queriesStereotype, 1, false, 1);
targets.addAll(Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.oldQueriesStereotype, 1, false, 1));
us.setTargets(targets);
if (manager.getActionFor(RunUserValidationScriptAction.actionid) == null)
c.addAction(new RunUserValidationScriptAction(us, true));
} else if (StereotypesHelper.hasStereotypeOrDerived(e, DocGen3Profile.userScriptStereotype)) {
ActionsCategory c = myCategory(manager, "ViewInteraction", "View Interaction");
UserScript us = new UserScript();
us.setDgElement(e);
List<Element> targets = Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.queriesStereotype, 1, false, 1);
targets.addAll(Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.oldQueriesStereotype, 1, false, 1));
us.setTargets(targets);
if (manager.getActionFor(RunUserScriptAction.actionid) == null)
c.addAction(new RunUserScriptAction(us, true));
}
if (StereotypesHelper.hasStereotypeOrDerived(e, sysmlview)) {
// There may be no view query actions to add, in which case we need
// to avoid adding an empty menu category, so the category is
// removed in this case.
ActionsCategory category = (ActionsCategory)manager.getActionFor("ViewInteraction");
if (category == null) {
category = new MDActionsCategory("ViewInteraction", "View Interaction");
category.setNested(true);
boolean added = addViewQueryActions(manager, category, (NamedElement)e);
if (added)
manager.addCategory(0, category);
}
if (ViewEditUtils.isPasswordSet()) {
ActionsCategory modelLoad2 = myCategory(manager, "AlfrescoModel", "MMS");
NMAction action = manager.getActionFor(ValidateViewAction.actionid);
if (action == null)
modelLoad2.addAction(new ValidateViewAction(e));
action = manager.getActionFor(ValidateViewRecursiveAction.actionid);
if (action == null)
modelLoad2.addAction(new ValidateViewRecursiveAction(e));
}
//ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
//action = manager.getActionFor(ExportViewAction.actionid);
//if (action == null)
//addEditableViewActions(c, (NamedElement)e);
}
/*if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.project)) { // REVIEW
// --
// hasStereotypeOrDerived()?
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(OrganizeViewEditorAction.actionid);
if (act == null)
c.addAction(new OrganizeViewEditorAction(e));
act = manager.getActionFor(DeleteProjectAction.actionid);
if (act == null)
c.addAction(new DeleteProjectAction(e));
act = manager.getActionFor(EMSLogoutAction.actionid);
if (act == null)
c.addAction(new EMSLogoutAction());
}
if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.volume)) { // REVIEW
// --
// hasStereotypeOrDerived()?
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(DeleteVolumeAction.actionid);
if (act == null)
c.addAction(new DeleteVolumeAction(e));
act = manager.getActionFor(EMSLogoutAction.actionid);
if (act == null)
c.addAction(new EMSLogoutAction());
}
if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.document)
|| StereotypesHelper.hasStereotypeOrDerived(e, documentView)) {
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(DeleteDocumentAction.actionid);
if (act == null)
c.addAction(new DeleteDocumentAction(e));
if (StereotypesHelper.hasStereotypeOrDerived(e, documentView)) {
act = manager.getActionFor(OrganizeDocumentAction.actionid);
if (act == null)
c.addAction(new OrganizeDocumentAction(e));
}
}*/
// DocGen menu
if ((e instanceof Activity && StereotypesHelper.hasStereotypeOrDerived(e,
DocGen3Profile.documentStereotype)) || StereotypesHelper.hasStereotypeOrDerived(e, sysmlview)) {
NMAction act = null;
ActionsCategory c = myCategory(manager, "DocGen", "DocGen");
// DefaultPropertyResourceProvider pp = new
// DefaultPropertyResourceProvider();
act = manager.getActionFor(ValidateDocument3Action.actionid);
if (act == null)
c.addAction(new ValidateDocument3Action(e));
act = manager.getActionFor(ValidateViewStructureAction.actionid);
if (act == null)
c.addAction(new ValidateViewStructureAction(e));
act = manager.getActionFor(ViewDocument3Action.actionid);
if (act == null)
c.addAction(new ViewDocument3Action(e));
act = manager.getActionFor(GenerateDocumentAction.actionid);
if (act == null)
c.addAction(new GenerateDocumentAction(e));
if (StereotypesHelper.hasStereotype(e, documentView)) {
/*
* act = manager.getActionFor(PublishDocWebAction.actionid); if
* (act == null) c.addAction(new
* PublishDocWebAction((NamedElement)e));
*/
act = manager.getActionFor(NumberDependencyAction.actionid);
if (act == null)
c.addAction(new NumberDependencyAction(e));
}
/*
* if (e instanceof Activity &&
* StereotypesHelper.hasStereotypeOrDerived(e,
* DocGen3Profile.documentStereotype)) { act =
* manager.getActionFor(PublishDocWebAction.actionid); if (act ==
* null) c.addAction(new PublishDocWebAction((NamedElement)e)); }
*/
}
if (StereotypesHelper.hasStereotypeOrDerived(e, sysmlviewpoint)) {
ActionsCategory c = myCategory(manager, "DocGen", "DocGen");
NMAction act = manager.getActionFor(InstanceViewpointAction.actionid);
if (act == null)
c.addAction(new InstanceViewpointAction(e));
}
// if ( ( e instanceof Activity &&
// StereotypesHelper.hasStereotypeOrDerived( e,
// DocGen3Profile.documentStereotype ) ) ||
// StereotypesHelper.hasStereotypeOrDerived( e, sysmlview ) ) {
// ActionsCategory c = myCategory( manager, "DocGen", "DocGen" );
// NMAction act = manager.getActionFor( "DocGenComments" );
// if ( act == null ) addCommentActions( c, (NamedElement)e );
// }
}
private void addDiagramActions(ActionsManager manager, DiagramPresentationElement diagram) {
if (diagram == null)
return;
Element element = diagram.getActualElement();
if (element == null)
return;
Element owner = element.getOwner();
if (owner == null || !(owner instanceof NamedElement))
return;
// //this add actions for syncing to docweb comments
// if (StereotypesHelper.hasStereotypeOrDerived(owner,
// DocGen3Profile.documentViewStereotype)) {
// ActionsCategory category = myCategory(manager, "DocGen", "DocGen");
// NMAction action = manager.getActionFor("DocGenComments");
// if (action == null)
// addCommentActions(category, (NamedElement) owner);
// }
}
/**
* add actions related to view editor (this includes view comments)
*
* @param parent
* @param e
*/
private void addEditableViewActions(ActionsCategory parent, NamedElement e) {
ActionsCategory c = parent; // new ActionsCategory("EditableView",
// "Editable View");
c.addAction(new ImportViewDryAction(e));
c.addAction(new ExportViewAction(e));
c.addAction(new ExportViewHierarchyAction(e));
c.addAction(new ImportViewAction(e));
c.addAction(new SynchronizeViewAction(e));
c.addAction(new ExportViewCommentsAction(e));
c.addAction(new ImportViewCommentsAction(e));
c.addAction(new ViewViewCommentsAction(e));
ActionsCategory a = new MDActionsCategory("AdvanceEditor", "ModelLoad");
a.setNested(true);
a.addAction(new ImportViewRecursiveAction(e));
a.addAction(new ExportViewRecursiveAction(e));
a.addAction(new SynchronizeViewRecursiveAction(e));
c.addAction(a);
// c.setNested(true);
// synchronized (this) { // saw a concurrency error at some point
// parent.addAction(c);
// parent.getCategories().add(c);
// }
}
/**
* Gets the specified category, creates it if necessary.
*
* @param manager
* @param id
* @param name
* @return category with given id/name
*/
private ActionsCategory myCategory(ActionsManager manager, String id, String name) {
ActionsCategory category = (ActionsCategory)manager.getActionFor(id); // getCategory(id);
if (category == null) {
category = new MDActionsCategory(id, name);
category.setNested(true);
manager.addCategory(0, category);
}
return category;
}
/**
* this should be used to add actions that're possible when user right
* clicks on a view<br/>
* it parses the single view, gets any document model that'll result in
* running script, editable table, validation rule
*
* @param parent
* @param e
*/
private boolean addViewQueryActions(ActionsManager manager, ActionsCategory parent, NamedElement e) {
if (viewQueryCalled.contains(manager))
return false;
DocumentGenerator dg = new DocumentGenerator(e, null, null);
Document dge = dg.parseDocument(true, false);
CollectActionsVisitor cav = new CollectActionsVisitor();
dge.accept(cav);
boolean added = false;
if (cav.getActions().size() > 0) {
for (MDAction a: cav.getActions()) {
parent.addAction(a);
}
added = true;
}
parent.setNested(true);
viewQueryCalled.clear();
viewQueryCalled.add(manager);
return added;
}
}
| src/main/java/gov/nasa/jpl/mbee/DocGenConfigurator.java | /*******************************************************************************
* Copyright (c) <2013>, California Institute of Technology ("Caltech").
* U.S. Government sponsorship acknowledged.
*
* 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 Caltech nor its operating division, the Jet Propulsion Laboratory,
* 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 gov.nasa.jpl.mbee;
import gov.nasa.jpl.mbee.actions.ViewViewCommentsAction;
import gov.nasa.jpl.mbee.actions.docgen.GenerateDocumentAction;
import gov.nasa.jpl.mbee.actions.docgen.InstanceViewpointAction;
import gov.nasa.jpl.mbee.actions.docgen.NumberDependencyAction;
import gov.nasa.jpl.mbee.actions.docgen.RunUserScriptAction;
import gov.nasa.jpl.mbee.actions.docgen.RunUserValidationScriptAction;
import gov.nasa.jpl.mbee.actions.docgen.ValidateDocument3Action;
import gov.nasa.jpl.mbee.actions.docgen.ValidateViewStructureAction;
import gov.nasa.jpl.mbee.actions.docgen.ViewDocument3Action;
import gov.nasa.jpl.mbee.actions.ems.ExportModelAction;
import gov.nasa.jpl.mbee.actions.ems.InitializeProjectAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateModelAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateViewAction;
import gov.nasa.jpl.mbee.actions.ems.ValidateViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewCommentsAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewHierarchyAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ExportViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewCommentsAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewDryAction;
import gov.nasa.jpl.mbee.actions.vieweditor.ImportViewRecursiveAction;
import gov.nasa.jpl.mbee.actions.vieweditor.SynchronizeViewAction;
import gov.nasa.jpl.mbee.actions.vieweditor.SynchronizeViewRecursiveAction;
import gov.nasa.jpl.mbee.generator.DocumentGenerator;
import gov.nasa.jpl.mbee.lib.MDUtils;
import gov.nasa.jpl.mbee.lib.Utils;
import gov.nasa.jpl.mbee.model.CollectActionsVisitor;
import gov.nasa.jpl.mbee.model.Document;
import gov.nasa.jpl.mbee.model.UserScript;
import gov.nasa.jpl.mbee.viewedit.ViewEditUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.nomagic.actions.ActionsCategory;
import com.nomagic.actions.ActionsManager;
import com.nomagic.actions.NMAction;
import com.nomagic.magicdraw.actions.BrowserContextAMConfigurator;
import com.nomagic.magicdraw.actions.ConfiguratorWithPriority;
import com.nomagic.magicdraw.actions.DiagramContextAMConfigurator;
import com.nomagic.magicdraw.actions.MDAction;
import com.nomagic.magicdraw.actions.MDActionsCategory;
import com.nomagic.magicdraw.core.Project;
import com.nomagic.magicdraw.ui.browser.Node;
import com.nomagic.magicdraw.ui.browser.Tree;
import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement;
import com.nomagic.magicdraw.uml.symbols.PresentationElement;
import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper;
import com.nomagic.uml2.ext.magicdraw.activities.mdfundamentalactivities.Activity;
import com.nomagic.uml2.ext.magicdraw.auxiliaryconstructs.mdmodels.Model;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.NamedElement;
import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype;
public class DocGenConfigurator implements BrowserContextAMConfigurator, DiagramContextAMConfigurator {
private Set<ActionsManager> viewQueryCalled = new HashSet<ActionsManager>();
@Override
public int getPriority() {
return ConfiguratorWithPriority.MEDIUM_PRIORITY;
}
@Override
public void configure(ActionsManager manager, Tree browser) {
Node no = browser.getSelectedNode();
if (no == null)
return;
Object o = no.getUserObject();
if (!(o instanceof Element))
return;
addElementActions(manager, (Element)o);
}
@Override
public void configure(ActionsManager manager, DiagramPresentationElement diagram,
PresentationElement[] selected, PresentationElement requestor) {
if (requestor != null) {
Element e = requestor.getElement();
addElementActions(manager, e);
} else {
addDiagramActions(manager, diagram);
}
}
private void addElementActions(ActionsManager manager, Element e) {
Project prj = Project.getProject(e);
if (prj == null)
return;
Stereotype sysmlview = Utils.getViewStereotype();
Stereotype sysmlviewpoint = Utils.getViewpointStereotype();
Stereotype documentView = StereotypesHelper.getStereotype(prj, DocGen3Profile.documentViewStereotype,
"Document Profile");
if (e == null)
return;
if (ViewEditUtils.isPasswordSet()) {
ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
if (MDUtils.isDeveloperMode()) {
if (manager.getActionFor(ExportModelAction.actionid) == null)
modelLoad.addAction(new ExportModelAction(e));
if (e instanceof Model && manager.getActionFor(InitializeProjectAction.actionid) == null)
modelLoad.addAction(new InitializeProjectAction());
if (manager.getActionFor(ValidateModelAction.actionid) == null)
modelLoad.addAction(new ValidateModelAction(e));
} else if (e instanceof Model){
if (manager.getActionFor(ValidateModelAction.actionid) == null)
modelLoad.addAction(new ValidateModelAction(e));
}
}
// add menus in reverse order since they are inserted at top
// View Interaction menu
if (StereotypesHelper.hasStereotypeOrDerived(e, DocGen3Profile.validationScriptStereotype)) {
ActionsCategory c = myCategory(manager, "ViewInteraction", "View Interaction");
UserScript us = new UserScript();
us.setDgElement(e);
List<Element> targets = Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.queriesStereotype, 1, false, 1);
targets.addAll(Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.oldQueriesStereotype, 1, false, 1));
us.setTargets(targets);
if (manager.getActionFor(RunUserValidationScriptAction.actionid) == null)
c.addAction(new RunUserValidationScriptAction(us, true));
} else if (StereotypesHelper.hasStereotypeOrDerived(e, DocGen3Profile.userScriptStereotype)) {
ActionsCategory c = myCategory(manager, "ViewInteraction", "View Interaction");
UserScript us = new UserScript();
us.setDgElement(e);
List<Element> targets = Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.queriesStereotype, 1, false, 1);
targets.addAll(Utils.collectDirectedRelatedElementsByRelationshipStereotypeString(e,
DocGen3Profile.oldQueriesStereotype, 1, false, 1));
us.setTargets(targets);
if (manager.getActionFor(RunUserScriptAction.actionid) == null)
c.addAction(new RunUserScriptAction(us, true));
}
if (StereotypesHelper.hasStereotypeOrDerived(e, sysmlview)) {
// There may be no view query actions to add, in which case we need
// to avoid adding an empty menu category, so the category is
// removed in this case.
ActionsCategory category = (ActionsCategory)manager.getActionFor("ViewInteraction");
if (category == null) {
category = new MDActionsCategory("ViewInteraction", "View Interaction");
category.setNested(true);
boolean added = addViewQueryActions(manager, category, (NamedElement)e);
if (added)
manager.addCategory(0, category);
}
if (ViewEditUtils.isPasswordSet()) {
ActionsCategory modelLoad2 = myCategory(manager, "AlfrescoModel", "MMS");
NMAction action = manager.getActionFor(ValidateViewAction.actionid);
if (action == null)
modelLoad2.addAction(new ValidateViewAction(e));
action = manager.getActionFor(ValidateViewRecursiveAction.actionid);
if (action == null)
modelLoad2.addAction(new ValidateViewRecursiveAction(e));
}
//ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
//action = manager.getActionFor(ExportViewAction.actionid);
//if (action == null)
//addEditableViewActions(c, (NamedElement)e);
}
/*if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.project)) { // REVIEW
// --
// hasStereotypeOrDerived()?
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(OrganizeViewEditorAction.actionid);
if (act == null)
c.addAction(new OrganizeViewEditorAction(e));
act = manager.getActionFor(DeleteProjectAction.actionid);
if (act == null)
c.addAction(new DeleteProjectAction(e));
act = manager.getActionFor(EMSLogoutAction.actionid);
if (act == null)
c.addAction(new EMSLogoutAction());
}
if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.volume)) { // REVIEW
// --
// hasStereotypeOrDerived()?
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(DeleteVolumeAction.actionid);
if (act == null)
c.addAction(new DeleteVolumeAction(e));
act = manager.getActionFor(EMSLogoutAction.actionid);
if (act == null)
c.addAction(new EMSLogoutAction());
}
if (StereotypesHelper.hasStereotype(e, ViewEditorProfile.document)
|| StereotypesHelper.hasStereotypeOrDerived(e, documentView)) {
ActionsCategory c = myCategory(manager, "ViewEditor", "View Editor");
NMAction act = manager.getActionFor(DeleteDocumentAction.actionid);
if (act == null)
c.addAction(new DeleteDocumentAction(e));
if (StereotypesHelper.hasStereotypeOrDerived(e, documentView)) {
act = manager.getActionFor(OrganizeDocumentAction.actionid);
if (act == null)
c.addAction(new OrganizeDocumentAction(e));
}
}*/
// DocGen menu
if ((e instanceof Activity && StereotypesHelper.hasStereotypeOrDerived(e,
DocGen3Profile.documentStereotype)) || StereotypesHelper.hasStereotypeOrDerived(e, sysmlview)) {
NMAction act = null;
ActionsCategory c = myCategory(manager, "DocGen", "DocGen");
// DefaultPropertyResourceProvider pp = new
// DefaultPropertyResourceProvider();
act = manager.getActionFor(ValidateDocument3Action.actionid);
if (act == null)
c.addAction(new ValidateDocument3Action(e));
act = manager.getActionFor(ValidateViewStructureAction.actionid);
if (act == null)
c.addAction(new ValidateViewStructureAction(e));
act = manager.getActionFor(ViewDocument3Action.actionid);
if (act == null)
c.addAction(new ViewDocument3Action(e));
act = manager.getActionFor(GenerateDocumentAction.actionid);
if (act == null)
c.addAction(new GenerateDocumentAction(e));
if (StereotypesHelper.hasStereotype(e, documentView)) {
/*
* act = manager.getActionFor(PublishDocWebAction.actionid); if
* (act == null) c.addAction(new
* PublishDocWebAction((NamedElement)e));
*/
act = manager.getActionFor(NumberDependencyAction.actionid);
if (act == null)
c.addAction(new NumberDependencyAction(e));
}
/*
* if (e instanceof Activity &&
* StereotypesHelper.hasStereotypeOrDerived(e,
* DocGen3Profile.documentStereotype)) { act =
* manager.getActionFor(PublishDocWebAction.actionid); if (act ==
* null) c.addAction(new PublishDocWebAction((NamedElement)e)); }
*/
}
if (StereotypesHelper.hasStereotypeOrDerived(e, sysmlviewpoint)) {
ActionsCategory c = myCategory(manager, "DocGen", "DocGen");
NMAction act = manager.getActionFor(InstanceViewpointAction.actionid);
if (act == null)
c.addAction(new InstanceViewpointAction(e));
}
// if ( ( e instanceof Activity &&
// StereotypesHelper.hasStereotypeOrDerived( e,
// DocGen3Profile.documentStereotype ) ) ||
// StereotypesHelper.hasStereotypeOrDerived( e, sysmlview ) ) {
// ActionsCategory c = myCategory( manager, "DocGen", "DocGen" );
// NMAction act = manager.getActionFor( "DocGenComments" );
// if ( act == null ) addCommentActions( c, (NamedElement)e );
// }
}
private void addDiagramActions(ActionsManager manager, DiagramPresentationElement diagram) {
if (diagram == null)
return;
Element element = diagram.getActualElement();
if (element == null)
return;
Element owner = element.getOwner();
if (owner == null || !(owner instanceof NamedElement))
return;
// //this add actions for syncing to docweb comments
// if (StereotypesHelper.hasStereotypeOrDerived(owner,
// DocGen3Profile.documentViewStereotype)) {
// ActionsCategory category = myCategory(manager, "DocGen", "DocGen");
// NMAction action = manager.getActionFor("DocGenComments");
// if (action == null)
// addCommentActions(category, (NamedElement) owner);
// }
}
/**
* add actions related to view editor (this includes view comments)
*
* @param parent
* @param e
*/
private void addEditableViewActions(ActionsCategory parent, NamedElement e) {
ActionsCategory c = parent; // new ActionsCategory("EditableView",
// "Editable View");
c.addAction(new ImportViewDryAction(e));
c.addAction(new ExportViewAction(e));
c.addAction(new ExportViewHierarchyAction(e));
c.addAction(new ImportViewAction(e));
c.addAction(new SynchronizeViewAction(e));
c.addAction(new ExportViewCommentsAction(e));
c.addAction(new ImportViewCommentsAction(e));
c.addAction(new ViewViewCommentsAction(e));
ActionsCategory a = new MDActionsCategory("AdvanceEditor", "ModelLoad");
a.setNested(true);
a.addAction(new ImportViewRecursiveAction(e));
a.addAction(new ExportViewRecursiveAction(e));
a.addAction(new SynchronizeViewRecursiveAction(e));
c.addAction(a);
// c.setNested(true);
// synchronized (this) { // saw a concurrency error at some point
// parent.addAction(c);
// parent.getCategories().add(c);
// }
}
/**
* Gets the specified category, creates it if necessary.
*
* @param manager
* @param id
* @param name
* @return category with given id/name
*/
private ActionsCategory myCategory(ActionsManager manager, String id, String name) {
ActionsCategory category = (ActionsCategory)manager.getActionFor(id); // getCategory(id);
if (category == null) {
category = new MDActionsCategory(id, name);
category.setNested(true);
manager.addCategory(0, category);
}
return category;
}
/**
* this should be used to add actions that're possible when user right
* clicks on a view<br/>
* it parses the single view, gets any document model that'll result in
* running script, editable table, validation rule
*
* @param parent
* @param e
*/
private boolean addViewQueryActions(ActionsManager manager, ActionsCategory parent, NamedElement e) {
if (viewQueryCalled.contains(manager))
return false;
DocumentGenerator dg = new DocumentGenerator(e, null, null);
Document dge = dg.parseDocument(true, false);
CollectActionsVisitor cav = new CollectActionsVisitor();
dge.accept(cav);
boolean added = false;
if (cav.getActions().size() > 0) {
for (MDAction a: cav.getActions()) {
parent.addAction(a);
}
added = true;
}
parent.setNested(true);
viewQueryCalled.clear();
viewQueryCalled.add(manager);
return added;
}
}
| take out empty mms category when not in developer mode | src/main/java/gov/nasa/jpl/mbee/DocGenConfigurator.java | take out empty mms category when not in developer mode | <ide><path>rc/main/java/gov/nasa/jpl/mbee/DocGenConfigurator.java
<ide> return;
<ide>
<ide> if (ViewEditUtils.isPasswordSet()) {
<del> ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
<ide> if (MDUtils.isDeveloperMode()) {
<add> ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
<ide> if (manager.getActionFor(ExportModelAction.actionid) == null)
<ide> modelLoad.addAction(new ExportModelAction(e));
<ide> if (e instanceof Model && manager.getActionFor(InitializeProjectAction.actionid) == null)
<ide> modelLoad.addAction(new InitializeProjectAction());
<ide> if (manager.getActionFor(ValidateModelAction.actionid) == null)
<ide> modelLoad.addAction(new ValidateModelAction(e));
<del> } else if (e instanceof Model){
<add> } else if (e instanceof Model) {
<add> ActionsCategory modelLoad = myCategory(manager, "AlfrescoModel", "MMS");
<ide> if (manager.getActionFor(ValidateModelAction.actionid) == null)
<ide> modelLoad.addAction(new ValidateModelAction(e));
<ide> } |
|
JavaScript | apache-2.0 | 718e711b6be1e039228ee84e93695bdbf805e710 | 0 | dotnetCarpenter/eloquent,dotnetCarpenter/eloquent | var input;
if(process && process.argv) { // test if we are in a nodejs compatible environment
if(process.argv.length > 2) {
input = process.argv[process.argv.length-1];
}
}
var testString = input || "Bobby Boob Blubber";
console.log("%s has %d capital Bs in it.", testString, countBs(testString));
/*
function countBs(string) { // version 1
var Bs = 0;
for(var n = 0, len = string.length; n < len; n++)
Bs += string.charAt(n) === "B" ? 1 : 0;
return Bs;
}
*/
function countBs(string) { // version 2
return countChar(string, "B");
}
function countChar(string, char) {
var charsFound = 0;
for(var n = 0, len = string.length; n < len; n++)
charsFound += string.charAt(n) === char ? 1 : 0;
return charsFound;
}
| chapter03/countBs.js | var input;
if(process && process.argv) { // test if we are in a nodejs compatible environment
if(process.argv.length > 2) {
input = process.argv[process.argv.length-1];
}
}
var testString = input || "Bobby Boob Blubber";
console.log("%s has %d capital Bs in it.", testString, countBs(testString));
function countBs(string) { // version 1
var Bs = 0;
for(var n = 0, len = string.length; n < len; n++)
Bs += string.charAt(n) === "B" ? 1 : 0;
return Bs;
}
| Bean Counting - version 2
| chapter03/countBs.js | Bean Counting - version 2 | <ide><path>hapter03/countBs.js
<ide> var testString = input || "Bobby Boob Blubber";
<ide> console.log("%s has %d capital Bs in it.", testString, countBs(testString));
<ide>
<add>/*
<ide> function countBs(string) { // version 1
<ide> var Bs = 0;
<ide> for(var n = 0, len = string.length; n < len; n++)
<ide> Bs += string.charAt(n) === "B" ? 1 : 0;
<ide> return Bs;
<ide> }
<add>*/
<add>
<add>function countBs(string) { // version 2
<add> return countChar(string, "B");
<add>}
<add>
<add>function countChar(string, char) {
<add> var charsFound = 0;
<add> for(var n = 0, len = string.length; n < len; n++)
<add> charsFound += string.charAt(n) === char ? 1 : 0;
<add> return charsFound;
<add>} |
|
Java | apache-2.0 | 588216f66ded237ec1fbfcd423be4f91a074aac6 | 0 | jondwillis/ElectricSleep | package com.androsz.electricsleepbeta.app;
import java.util.ArrayList;
import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.StaleDataException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.ActionBar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.db.SleepSessions;
import com.androsz.electricsleepbeta.widget.calendar.MonthView;
import com.androsz.electricsleepbeta.widget.calendar.Utils;
import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitleProvider;
public class HistoryMonthActivity extends HostActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private final class IndicatorPageChangeListener implements OnPageChangeListener {
private final TitlePageIndicator indicator;
private IndicatorPageChangeListener(TitlePageIndicator indicator) {
this.indicator = indicator;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
lastPosition = position;
}
private int lastSettledPosition = 1;
private int lastPosition = 1;
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (lastSettledPosition == lastPosition)
return;
lastSettledPosition = lastPosition;
MonthView leftMonth = (MonthView) monthPager.getChildAt(0);
MonthView centerMonth = (MonthView) monthPager.getChildAt(1);
MonthView rightMonth = (MonthView) monthPager.getChildAt(2);
final Time oldCenterTime = new Time(centerMonth.getTime());
String[] newTitles = new String[3];
int focusedPage = HistoryMonthActivity.this.focusedPage;
if (focusedPage == 0) {
final Time oldTopTime = new Time(leftMonth.getTime());
final Time time = new Time(oldTopTime);
time.month--;
time.normalize(true);
// TODO: load and switch shown events
leftMonth.setTime(time);
centerMonth.setTime(oldTopTime);
rightMonth.setTime(oldCenterTime);
} else if (focusedPage == 2) {
final Time oldBottomTime = new Time(rightMonth.getTime());
final Time time = new Time(oldBottomTime);
time.month++;
time.normalize(true);
leftMonth.setTime(oldCenterTime);
centerMonth.setTime(oldBottomTime);
rightMonth.setTime(time);
}
newTitles[0] = Utils
.formatMonthYear(HistoryMonthActivity.this, leftMonth.getTime());
newTitles[1] = Utils.formatMonthYear(HistoryMonthActivity.this,
centerMonth.getTime());
newTitles[2] = Utils.formatMonthYear(HistoryMonthActivity.this,
rightMonth.getTime());
monthAdapter.setTitles(newTitles);
// always set to middle page to continue to be able to
// scroll up/down
indicator.setCurrentItem(1, false);
eventsChanged(focusedPage);
}
}
@Override
public void onPageSelected(int position) {
focusedPage = position;
}
}
private class MonthPagerAdapter extends PagerAdapter implements TitleProvider {
private String[] titles = new String[] { "", "", "" };
public String[] getTitles() {
return titles;
}
public void setTitles(String[] titles) {
this.titles = titles.clone();
}
public MonthView addMonthViewAt(ViewPager container, int position, Time time) {
final MonthView mv = new MonthView(HistoryMonthActivity.this);
mv.setLayoutParams(new ViewSwitcher.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT));
mv.setSelectedTime(time);
container.addView(mv, position);
return mv;
}
@Override
public void destroyItem(View container, int position, Object object) {
// simply reuse items...
// ((ViewPager) container).removeViewAt(position);
}
@Override
public int getCount() {
return titles.length;
}
@Override
public String getTitle(int position) {
String title = titles[position];
return title;
}
@Override
public Object instantiateItem(View container, int position) {
MonthView childAt = (MonthView) ((ViewPager) container).getChildAt(position);
if (childAt == null) {
final Time time = new Time();
time.setToNow();
// set to first day in month. this prevents errors when the
// current
// month (TODAY) has more days than the neighbor month.
time.set(1, time.month, time.year);
time.month += (position - 1); // add the offset from the center
// time
time.normalize(true);
MonthView mv = addMonthViewAt((ViewPager) container, position, time);
titles[position] = Utils.formatMonthYear(HistoryMonthActivity.this, mv.getTime());
return mv;
}
return childAt;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View container) {
}
boolean alreadyLoaded = false;
@Override
public void finishUpdate(View container) {
if (!alreadyLoaded && ((ViewPager) container).getChildCount() == getCount()) {
getSupportLoaderManager().getLoader(0).forceLoad();
alreadyLoaded = true;
}
}
}
private class SessionsContentObserver extends ContentObserver {
public SessionsContentObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
getSupportLoaderManager().getLoader(0).forceLoad();
super.onChange(selfChange);
}
}
private static final int DAY_OF_WEEK_KINDS[] = { Calendar.SUNDAY, Calendar.MONDAY,
Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY,
Calendar.SATURDAY };
private static final int DAY_OF_WEEK_LABEL_IDS[] = { R.id.day0, R.id.day1, R.id.day2,
R.id.day3, R.id.day4, R.id.day5, R.id.day6 };
private ViewPager monthPager;
private MonthPagerAdapter monthAdapter;
private int startDay;
ArrayList<Long[]> mSessions = new ArrayList<Long[]>(0);
private int focusedPage = 0;
private SessionsContentObserver sessionsObserver;
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED)
|| action.equals(Intent.ACTION_DATE_CHANGED)
|| action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
eventsChanged(-1);
}
}
};
void eventsChanged(final int whichPage) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// if (whichPage == -1) {
ViewPager vp = monthPager;
for (int i = 0; i < vp.getChildCount(); i++) {
final MonthView mv = (MonthView) monthPager.getChildAt(i);
Time t = mv.getTime();
mv.forceReloadEvents(mSessions);/*
* getSessionsInInterval(t.
* toMillis(true), 31));
*/
}
// } else {
// final MonthView mv = (MonthView)
// monthPager.getChildAt(whichPage);
// Time t = mv.getTime();
// mv.forceReloadEvents(getSessionsInInterval(mv.getTime().toMillis(true),
// 31));
// }
}
});
}
@Override
protected int getContentAreaLayoutId() {
return R.layout.activity_history_month;
}
public ArrayList<Long[]> getSessionsInInterval(long startMillis, int days) {
final ArrayList<Long[]> sessions = new ArrayList<Long[]>(20);
final Time local = new Time();
local.set(startMillis);
// expand start and days to include days shown from previous month
// and next month. can be slightly wasteful.
// start -= 1000 * 60 * 60 * 24 * 7; // 7 days
// days += 7;
final int startJulianDay = Time.getJulianDay(startMillis, local.gmtoff);
local.monthDay += days;
local.normalize(true);
final int endJulianDay = Time.getJulianDay(local.toMillis(true), local.gmtoff);
synchronized (mSessions) {
for (final Long[] session : mSessions) {
final long sessionStartJulianDay = session[2];
final long sessionEndJulianDay = session[3];
if (sessionStartJulianDay >= startJulianDay && sessionEndJulianDay <= endJulianDay) {
sessions.add(session);
}
}
// TODO ?
// SleepSession.computePositions(sessions.values());
return sessions;
}
}
public int getStartDay() {
return startDay;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionsObserver = new SessionsContentObserver();
getContentResolver().registerContentObserver(SleepSessions.MainTable.CONTENT_URI, true,
sessionsObserver);
ActionBar bar = getSupportActionBar();
// bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
final Time now = new Time();
now.setToNow();
// Get first day of week based on locale and populate the day headers
startDay = Calendar.getInstance().getFirstDayOfWeek();
final int diff = startDay - Calendar.SUNDAY - 1;
final int startDay = Utils.getFirstDayOfWeek();
final int weekendColor = getResources().getColor(R.color.primary1);
for (int day = 0; day < 7; day++) {
final String dayString = DateUtils.getDayOfWeekString(
(DAY_OF_WEEK_KINDS[day] + diff) % 7 + 1, DateUtils.LENGTH_MEDIUM);
final TextView label = (TextView) findViewById(DAY_OF_WEEK_LABEL_IDS[day]);
label.setText(dayString);
if (Utils.isSunday(day, startDay) || Utils.isSaturday(day, startDay)) {
label.setTextColor(weekendColor);
}
}
monthAdapter = new MonthPagerAdapter();
monthPager = (ViewPager) findViewById(R.id.monthpager);
monthPager.setAdapter(monthAdapter);
final TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
indicator.setFooterColor(getResources().getColor(R.color.primary1));
indicator.setViewPager(monthPager, 1);
indicator.setOnPageChangeListener(new IndicatorPageChangeListener(indicator));
getSupportLoaderManager().initLoader(0, null, HistoryMonthActivity.this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, SleepSessions.MainTable.CONTENT_URI,
SleepSessions.MainTable.ALL_COLUMNS_PROJECTION, null, null, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_multiple_history, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(sessionsObserver);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
new Thread(new Runnable() {
// @Override
public void run() {
// android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try {
mSessions = new ArrayList<Long[]>(0);
mSessions = SleepSessions.getStartAndEndTimesFromCursor(
HistoryMonthActivity.this, data);
} catch (IllegalArgumentException ex) {
} catch (IllegalStateException ex) {
} catch (StaleDataException ex) {
} finally {
eventsChanged(-1);
}
}
}).start();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_all:
// TODO
break;
case R.id.menu_item_export_all:
// TODO
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mIntentReceiver);
}
@Override
protected void onResume() {
super.onResume();
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(mIntentReceiver, filter);
}
}
| src/com/androsz/electricsleepbeta/app/HistoryMonthActivity.java | package com.androsz.electricsleepbeta.app;
import java.util.ArrayList;
import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.StaleDataException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.ActionBar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.androsz.electricsleepbeta.R;
import com.androsz.electricsleepbeta.db.SleepSessions;
import com.androsz.electricsleepbeta.widget.calendar.MonthView;
import com.androsz.electricsleepbeta.widget.calendar.Utils;
import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitleProvider;
public class HistoryMonthActivity extends HostActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private final class IndicatorPageChangeListener implements OnPageChangeListener {
private final TitlePageIndicator indicator;
private IndicatorPageChangeListener(TitlePageIndicator indicator) {
this.indicator = indicator;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
lastPosition = position;
}
private int lastSettledPosition = 1;
private int lastPosition = 1;
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_SETTLING) {
if (lastSettledPosition == lastPosition)
return;
lastSettledPosition = lastPosition;
MonthView leftMonth = (MonthView) monthPager.getChildAt(0);
MonthView centerMonth = (MonthView) monthPager.getChildAt(1);
MonthView rightMonth = (MonthView) monthPager.getChildAt(2);
final Time oldCenterTime = new Time(centerMonth.getTime());
String[] newTitles = new String[3];
int focusedPage = HistoryMonthActivity.this.focusedPage;
if (focusedPage == 0) {
final Time oldTopTime = new Time(leftMonth.getTime());
final Time time = new Time(oldTopTime);
time.month--;
time.normalize(true);
// TODO: load and switch shown events
leftMonth.setTime(time);
centerMonth.setTime(oldTopTime);
rightMonth.setTime(oldCenterTime);
} else if (focusedPage == 2) {
final Time oldBottomTime = new Time(rightMonth.getTime());
final Time time = new Time(oldBottomTime);
time.month++;
time.normalize(true);
leftMonth.setTime(oldCenterTime);
centerMonth.setTime(oldBottomTime);
rightMonth.setTime(time);
}
newTitles[0] = Utils
.formatMonthYear(HistoryMonthActivity.this, leftMonth.getTime());
newTitles[1] = Utils.formatMonthYear(HistoryMonthActivity.this,
centerMonth.getTime());
newTitles[2] = Utils.formatMonthYear(HistoryMonthActivity.this,
rightMonth.getTime());
monthAdapter.setTitles(newTitles);
// always set to middle page to continue to be able to
// scroll up/down
indicator.setCurrentItem(1, false);
eventsChanged(focusedPage);
}
}
@Override
public void onPageSelected(int position) {
focusedPage = position;
}
}
private class MonthPagerAdapter extends PagerAdapter implements TitleProvider {
private String[] titles = new String[] { "", "", "" };
public String[] getTitles() {
return titles;
}
public void setTitles(String[] titles) {
this.titles = titles.clone();
}
public MonthView addMonthViewAt(ViewPager container, int position, Time time) {
final MonthView mv = new MonthView(HistoryMonthActivity.this);
mv.setLayoutParams(new ViewSwitcher.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT));
mv.setSelectedTime(time);
container.addView(mv, position);
return mv;
}
@Override
public void destroyItem(View container, int position, Object object) {
// simply reuse items...
// ((ViewPager) container).removeViewAt(position);
}
@Override
public int getCount() {
return titles.length;
}
@Override
public String getTitle(int position) {
String title = titles[position];
return title;
}
@Override
public Object instantiateItem(View container, int position) {
MonthView childAt = (MonthView) ((ViewPager) container).getChildAt(position);
if (childAt == null) {
final Time time = new Time();
time.setToNow();
// set to first day in month. this prevents errors when the
// current
// month (TODAY) has more days than the neighbor month.
time.set(1, time.month, time.year);
time.month += (position - 1); // add the offset from the center
// time
time.normalize(true);
MonthView mv = addMonthViewAt((ViewPager) container, position, time);
titles[position] = Utils.formatMonthYear(HistoryMonthActivity.this, mv.getTime());
return mv;
}
return childAt;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View container) {
}
boolean alreadyLoaded = false;
@Override
public void finishUpdate(View container) {
if (!alreadyLoaded && ((ViewPager) container).getChildCount() == getCount()) {
getSupportLoaderManager().getLoader(0).forceLoad();
alreadyLoaded = true;
}
}
}
private class SessionsContentObserver extends ContentObserver {
public SessionsContentObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
getSupportLoaderManager().getLoader(0).forceLoad();
super.onChange(selfChange);
}
}
private static final int DAY_OF_WEEK_KINDS[] = { Calendar.SUNDAY, Calendar.MONDAY,
Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY,
Calendar.SATURDAY };
private static final int DAY_OF_WEEK_LABEL_IDS[] = { R.id.day0, R.id.day1, R.id.day2,
R.id.day3, R.id.day4, R.id.day5, R.id.day6 };
private ViewPager monthPager;
private MonthPagerAdapter monthAdapter;
private int startDay;
ArrayList<Long[]> mSessions = new ArrayList<Long[]>(0);
private int focusedPage = 0;
private SessionsContentObserver sessionsObserver;
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED)
|| action.equals(Intent.ACTION_DATE_CHANGED)
|| action.equals(Intent.ACTION_TIMEZONE_CHANGED)) {
eventsChanged(-1);
}
}
};
void eventsChanged(final int whichPage) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// if (whichPage == -1) {
ViewPager vp = monthPager;
for (int i = 0; i < vp.getChildCount(); i++) {
final MonthView mv = (MonthView) monthPager.getChildAt(i);
Time t = mv.getTime();
mv.forceReloadEvents(mSessions);/*
* getSessionsInInterval(t.
* toMillis(true), 31));
*/
}
// } else {
// final MonthView mv = (MonthView)
// monthPager.getChildAt(whichPage);
// Time t = mv.getTime();
// mv.forceReloadEvents(getSessionsInInterval(mv.getTime().toMillis(true),
// 31));
// }
}
});
}
@Override
protected int getContentAreaLayoutId() {
return R.layout.activity_history_month;
}
public ArrayList<Long[]> getSessionsInInterval(long startMillis, int days) {
final ArrayList<Long[]> sessions = new ArrayList<Long[]>(20);
final Time local = new Time();
local.set(startMillis);
// expand start and days to include days shown from previous month
// and next month. can be slightly wasteful.
// start -= 1000 * 60 * 60 * 24 * 7; // 7 days
// days += 7;
final int startJulianDay = Time.getJulianDay(startMillis, local.gmtoff);
local.monthDay += days;
local.normalize(true);
final int endJulianDay = Time.getJulianDay(local.toMillis(true), local.gmtoff);
synchronized (mSessions) {
for (final Long[] session : mSessions) {
final long sessionStartJulianDay = session[2];
final long sessionEndJulianDay = session[3];
if (sessionStartJulianDay >= startJulianDay && sessionEndJulianDay <= endJulianDay) {
sessions.add(session);
}
}
// TODO ?
// SleepSession.computePositions(sessions.values());
return sessions;
}
}
public int getStartDay() {
return startDay;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionsObserver = new SessionsContentObserver();
getContentResolver().registerContentObserver(SleepSessions.MainTable.CONTENT_URI, true,
sessionsObserver);
ActionBar bar = getSupportActionBar();
// bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
final Time now = new Time();
now.setToNow();
// Get first day of week based on locale and populate the day headers
startDay = Calendar.getInstance().getFirstDayOfWeek();
final int diff = startDay - Calendar.SUNDAY - 1;
final int startDay = Utils.getFirstDayOfWeek();
final int weekendColor = getResources().getColor(R.color.primary1);
for (int day = 0; day < 7; day++) {
final String dayString = DateUtils.getDayOfWeekString(
(DAY_OF_WEEK_KINDS[day] + diff) % 7 + 1, DateUtils.LENGTH_MEDIUM);
final TextView label = (TextView) findViewById(DAY_OF_WEEK_LABEL_IDS[day]);
label.setText(dayString);
if (Utils.isSunday(day, startDay) || Utils.isSaturday(day, startDay)) {
label.setTextColor(weekendColor);
}
}
monthAdapter = new MonthPagerAdapter();
monthPager = (ViewPager) findViewById(R.id.monthpager);
monthPager.setAdapter(monthAdapter);
final TitlePageIndicator indicator = (TitlePageIndicator) findViewById(R.id.indicator);
indicator.setFooterColor(getResources().getColor(R.color.primary1));
indicator.setViewPager(monthPager, 1);
indicator.setOnPageChangeListener(new IndicatorPageChangeListener(indicator));
getSupportLoaderManager().initLoader(0, null, HistoryMonthActivity.this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, SleepSessions.MainTable.CONTENT_URI,
SleepSessions.MainTable.ALL_COLUMNS_PROJECTION, null, null, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_multiple_history, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
@Override
protected void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(sessionsObserver);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
new Thread(new Runnable() {
// @Override
public void run() {
// android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try {
mSessions = new ArrayList<Long[]>(0);
mSessions = SleepSessions.getStartAndEndTimesFromCursor(
HistoryMonthActivity.this, data);
} catch (IllegalArgumentException ex) {
} catch (IllegalStateException ex) {
} catch (StaleDataException ex) {
} finally {
eventsChanged(-1);
}
}
}).start();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_delete_all:
// TODO
break;
case R.id.menu_item_export_all:
// TODO
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mIntentReceiver);
}
@Override
protected void onResume() {
super.onResume();
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_DATE_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(mIntentReceiver, filter);
}
}
| Reverted accidental change to HistoryMonthActivity. | src/com/androsz/electricsleepbeta/app/HistoryMonthActivity.java | Reverted accidental change to HistoryMonthActivity. | <ide><path>rc/com/androsz/electricsleepbeta/app/HistoryMonthActivity.java
<ide> @Override
<ide> public void onPageScrollStateChanged(int state) {
<ide>
<del> if (state == ViewPager.SCROLL_STATE_SETTLING) {
<add> if (state == ViewPager.SCROLL_STATE_IDLE) {
<ide>
<ide> if (lastSettledPosition == lastPosition)
<ide> return; |
|
Java | bsd-3-clause | 2fa7ec5252004c210087ccce5e3e2c95205ba515 | 0 | mdcao/japsa,mdcao/japsa | /*****************************************************************************
* Copyright (c) Minh Duc Cao, Monash Uni & UQ, All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. Neither the names of the institutions nor the names of the 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. *
****************************************************************************/
/************************** REVISION HISTORY **************************
* 20/12/2014 - Minh Duc Cao: Created
*
****************************************************************************/
package japsadev.bio.hts.scaffold;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import japsa.seq.Alphabet;
import japsa.seq.JapsaFeature;
import japsa.seq.Sequence;
import japsa.seq.SequenceOutputStream;
import japsa.seq.SequenceReader;
import japsa.util.Logging;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
public class ScaffoldGraph{
public static int maxRepeatLength=7500; //for ribosomal repeat cluster in bacteria (Koren S et al 2013), it's 9.1kb for yeast.
public static int marginThres = 1000;
public static int minContigLength = 300;
public static int minSupportReads = 1;
public static boolean verbose = false;
public static boolean reportAll = false;
public boolean annotation = false;
public static byte assembler =0b00; // 0 for SPAdes, 1 for ABySS
public static HashMap<Integer,Integer> countOccurence=new HashMap<Integer,Integer>();
public String prefix = "out";
public static double estimatedCov = 0;
private static double estimatedLength = 0;
//below maps contain avatar of contigs and bridges only,
//not the actual ones in used (because of the repeats that need to be cloned)
ArrayList<Contig> contigs;
HashMap<String, ContigBridge> bridgeMap= new HashMap<String, ContigBridge>();
static HashMap<Integer, ArrayList<ContigBridge>> bridgesFromContig = new HashMap<Integer, ArrayList<ContigBridge>>();
Scaffold [] scaffolds; // DNA translator, previous image of sequence is stored for real-time processing
// Constructor for the graph with contigs FASTA file (contigs.fasta from SPAdes output)
public ScaffoldGraph(String sequenceFile) throws IOException{
//1. read in contigs
SequenceReader reader = SequenceReader.getReader(sequenceFile);
Sequence seq;
contigs = new ArrayList<Contig>();
int index = 0;
while ((seq = reader.nextSequence(Alphabet.DNA())) != null){
Contig ctg = new Contig(index, seq);
String name = seq.getName(),
desc = seq.getDesc();
double mycov = 1.0;
//SPAdes header: >%d_length_%d_cov_%f, ID, length, coverage
if(assembler==0b00){
String [] toks = name.split("_");
for (int i = 0; i < toks.length - 1;i++){
if ("cov".equals(toks[i])){
mycov = Double.parseDouble(toks[i+1]);
break;
}
}
}
//ABySS header: >%d %d %d, ID, length, kmer_sum
else if(assembler==0b01){
String [] toks = desc.split("\\s");
mycov = Double.parseDouble(toks[1])/Double.parseDouble(toks[0]);
}
estimatedCov += mycov * seq.length();
estimatedLength += seq.length();
ctg.setCoverage(mycov);
contigs.add(ctg);
bridgesFromContig.put(ctg.getIndex(), new ArrayList<ContigBridge>());
index ++;
}
reader.close();
estimatedCov /= estimatedLength;
if(verbose)
System.out.println("Cov " + estimatedCov + " Length " + estimatedLength);
//2. Initialise scaffold graph
scaffolds = new Scaffold[contigs.size()];
for (int i = 0; i < contigs.size();i++){
scaffolds[i] = new Scaffold(contigs.get(i));
//point to the head of the scaffold
contigs.get(i).head = i;
}//for
}//constructor
public String getAssemblerName(){
if(assembler==0b01)
return new String("ABySS");
else
return new String("SPAdes");
}
/* Read short-read assembly information from SPAdes output: assembly graph (assembly_graph.fastg) and
** traversed paths (contigs.pahth) to make up the contigs
*/
public void readMore(String assemblyGraph, String paths) throws IOException{
//1. Read assembly graph and store in a string graph
Graph g = new Graph(assemblyGraph,assembler);
// for(Vertex v:g.getVertices()){
// System.out.println("Neighbors of vertex " + v.getLabel() + " (" + v.getNeighborCount() +"):");
// for(Edge e:v.getNeighbors())
// System.out.println(e + "; ");
// System.out.println();
// }
Contig.setGraph(g);
if(assembler==0b00){
//2. read file contigs.paths from SPAdes
BufferedReader pathReader = new BufferedReader(new FileReader(paths));
String s;
//Read contigs from contigs.paths and refer themselves to contigs.fasta
Contig curContig = null;
while((s=pathReader.readLine()) != null){
if(s.contains("NODE"))
curContig=getSPadesContig(s);
else if(curContig!=null)
curContig.setPath(new Path(g,s));
}
pathReader.close();
} else if(assembler==0b01){ //for the case of ABySS: contig and vertex of assembly graph are the same
for(Contig ctg:contigs)
ctg.setPath(new Path(g,ctg.getName()+"+"));
}
if(ScaffoldGraph.verbose)
Logging.info("Short read assembler " + (assembler==0b00?"SPAdes":"ABySS") + " kmer=" + Graph.getKmerSize());
}
public Contig getSPadesContig(String name){
if(name.contains("'")){
if(verbose)
System.out.println("Ignored (redundant) reversed sequence: " + name);
return null;
}
Contig res = null;
for(Contig ctg:contigs){
// Extract to find contig named NODE_x_
//because sometimes there are disagreement between contig name (_length_) in contigs.paths and contigs.fasta in SPAdes!!!
//
if(ctg.getName().contains("NODE_"+name.split("_")[1]+"_")){
res = ctg;
break;
}
}
if(res==null && verbose){
System.out.println("Contig not found:" + name);
}
return res;
}
public synchronized int getN50(){
int [] lengths = new int[scaffolds.length];
int count=0;
double sum = 0;
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].length();
// if ((contigs.get(i).head == i
// && !isRepeat(contigs.get(i))
// && len > maxRepeatLength
// )
// || scaffolds[i].closeBridge != null)
if(contigs.get(i).head == i || scaffolds[i].closeBridge != null)
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short,repetitive sequences here if required
{
lengths[count] = len;
sum+=len;
count++;
}
}
Arrays.sort(lengths);
int index = lengths.length;
double contains = 0;
while (contains < sum/2){
index --;
contains += lengths[index];
}
return lengths[index];
}
public synchronized String getGapsInfo(){
int gapCount=0,
gapMaxLen=0;
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].length();
if ((contigs.get(i).head == i
&& !isRepeat(contigs.get(i))
&& len > maxRepeatLength
)
|| scaffolds[i].closeBridge != null)
{
for(ContigBridge brg:scaffolds[i].bridges){
if(brg.getBridgePath()==null){
gapCount++;
if(brg.getTransVector().distance(brg.firstContig, brg.secondContig) > gapMaxLen)
gapMaxLen=brg.getTransVector().distance(brg.firstContig, brg.secondContig);
}
}
if(scaffolds[i].closeBridge!=null){
ContigBridge brg=scaffolds[i].closeBridge;
if(brg.getBridgePath()==null){
gapCount++;
if(brg.getTransVector().distance(brg.firstContig, brg.secondContig) > gapMaxLen)
gapMaxLen=brg.getTransVector().distance(brg.firstContig, brg.secondContig);
}
}
}
}
return gapCount+" ("+gapMaxLen+")";
}
/**
* MDC added second version that include bwa
* @param bamFile
* @param minCov
* @param qual
* @throws IOException
* @throws InterruptedException
*/
public void makeConnections2(String inFile, double minCov, int qual, String format, String bwaExe, int bwaThread, String bwaIndex) throws IOException, InterruptedException{
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReader reader = null;
Process bwaProcess = null;
if (format.endsWith("am")){//bam or sam
if ("-".equals(inFile))
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
else
reader = SamReaderFactory.makeDefault().open(new File(inFile));
}else{
Logging.info("Starting bwa at " + new Date());
ProcessBuilder pb = null;
if ("-".equals(inFile)){
pb = new ProcessBuilder(bwaExe,
"mem",
"-t",
"" + bwaThread,
"-k11",
"-W20",
"-r10",
"-A1",
"-B1",
"-O1",
"-E1",
"-L0",
"-a",
"-Y",
// "-K",
// "20000",
bwaIndex,
"-"
).
redirectInput(Redirect.INHERIT);
}else{
pb = new ProcessBuilder(bwaExe,
"mem",
"-t",
"" + bwaThread,
"-k11",
"-W20",
"-r10",
"-A1",
"-B1",
"-O1",
"-E1",
"-L0",
"-a",
"-Y",
// "-K",
// "20000",
bwaIndex,
inFile
);
}
bwaProcess = pb.redirectError(ProcessBuilder.Redirect.to(new File("/dev/null"))).start();
//Logging.info("bwa started x");
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(bwaProcess.getInputStream()));
}
//SamReader reader;
//if ("-".equals(bamFile))
// reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
//else
// reader = SamReaderFactory.makeDefault().open(new File(bamFile));
SAMRecordIterator iter = reader.iterator();
String readID = "";
ReadFilling readFilling = null;
ArrayList<AlignmentRecord> samList = null;// alignment record of the same read;
while (iter.hasNext()) {
SAMRecord rec = iter.next();
if (rec.getReadUnmappedFlag())
continue;
if (rec.getMappingQuality() < qual)
continue;
AlignmentRecord myRec = new AlignmentRecord(rec, contigs.get(rec.getReferenceIndex()));
//////////////////////////////////////////////////////////////////
// make bridge of contigs that align to the same (Nanopore) read.
// Note that SAM file MUST be sorted based on readID (samtools sort -n)
//not the first occurrance
if (readID.equals(myRec.readID)) {
if (myRec.useful){
for (AlignmentRecord s : samList) {
if (s.useful){
this.addBridge(readFilling, s, myRec, minCov); //stt(s) < stt(myRec) -> (s,myRec) appear once only!
//...update with synchronized
}
}
}
} else {
samList = new ArrayList<AlignmentRecord>();
readID = myRec.readID;
readFilling = new ReadFilling(new Sequence(Alphabet.DNA5(), rec.getReadString(), "R" + readID), samList);
}
samList.add(myRec);
}// while
iter.close();
//outOS.close();
reader.close();
if (bwaProcess != null){
bwaProcess.waitFor();
}
Logging.info("Sort list of bridges");
//Collections.sort(bridgeList);
}
/**
* Forming bridges based on alignments
*
* @param bamFile
* @param minCov
* @param maxCov
* @param threshold
* @param qual
* @throws IOException
*/
public void makeConnections(String bamFile, double minCov, int qual) throws IOException{
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReader reader;
if ("-".equals(bamFile))
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
else
reader = SamReaderFactory.makeDefault().open(new File(bamFile));
SAMRecordIterator iter = reader.iterator();
String readID = "";
ReadFilling readFilling = null;
ArrayList<AlignmentRecord> samList = null;// alignment record of the same read;
while (iter.hasNext()) {
SAMRecord rec = iter.next();
if (rec.getReadUnmappedFlag())
continue;
if (rec.getMappingQuality() < qual)
continue;
AlignmentRecord myRec = new AlignmentRecord(rec, contigs.get(rec.getReferenceIndex()));
//////////////////////////////////////////////////////////////////
// make bridge of contigs that align to the same (Nanopore) read.
// Note that SAM file MUST be sorted based on readID (samtools sort -n)
//not the first occurrance
if (readID.equals(myRec.readID)) {
if (myRec.useful){
for (AlignmentRecord s : samList) {
if (s.useful){
this.addBridge(readFilling, s, myRec, minCov); //stt(s) < stt(myRec) -> (s,myRec) appear once only!
//...update with synchronized
}
}
}
} else {
samList = new ArrayList<AlignmentRecord>();
readID = myRec.readID;
readFilling = new ReadFilling(new Sequence(Alphabet.DNA5(), rec.getReadString(), "R" + readID), samList);
}
samList.add(myRec);
}// while
iter.close();
//outOS.close();
reader.close();
Logging.info("Sort list of bridges");
//Collections.sort(bridgeList);
}
/*********************************************************************************/
protected void addBridge(ReadFilling readSequence, AlignmentRecord a, AlignmentRecord b, double minCov){
if (a.contig.index > b.contig.index){
AlignmentRecord t = a;a=b;b=t;
}
// Rate of aligned lengths: ref/read (illumina contig/nanopore read)
int alignedReadLen = Math.abs(a.readEnd - a.readStart) + Math.abs(b.readEnd - b.readStart),
alignedRefLen = Math.abs(a.refEnd - a.refStart) + Math.abs(b.refEnd - b.refStart);
double rate = 1.0 * alignedRefLen/alignedReadLen;
//See if this is reliable
double score = Math.min(a.score, b.score);
int alignP = (int) ((b.readStart - a.readStart) * rate);
int alignD = (a.strand == b.strand)?1:-1;
//(rough) relative position from ref_b (contig of b) to ref_a (contig of a) in the assembled genome
int gP = (alignP + (a.strand ? a.refStart:-a.refStart) - (b.strand?b.refStart:-b.refStart));
if (!a.strand)
gP = -gP;
if ( a.contig.getIndex() == b.contig.getIndex()
&& alignD > 0
&& (Math.abs(gP)*1.0 / a.contig.length()) < 1.1
&& (Math.abs(gP)*1.0 / a.contig.length()) > 0.9
&& a.readLength < 1.1* a.contig.length()
)
{
if( alignedReadLen*1.0/a.contig.length() > 0.7 ){ //need more than 70% alignment (error rate of nanopore read)
a.contig.cirProb ++;
if(verbose)
System.out.printf("Potential CIRCULAR or TANDEM contig %s map to read %s(length=%d): (%d,%d) => circular score: %d\n"
, a.contig.getName(), a.readID, a.readLength, gP, alignD, a.contig.cirProb);
}
}
else{
a.contig.cirProb--;
b.contig.cirProb--;
}
// overlap length on aligned read (<0 if not overlap)
int overlap = Math.min( a.readAlignmentEnd() - b.readAlignmentStart(), b.readAlignmentEnd() - a.readAlignmentStart());
if ( overlap > Math.min( .5 * Math.min(a.readAlignmentEnd()-a.readAlignmentStart(), b.readAlignmentEnd()-b.readAlignmentStart()),
minContigLength)
|| a.contig.getCoverage() < minCov // filter out contigs with inappropriate cov
|| b.contig.getCoverage() < minCov
){
return;
}
ScaffoldVector trans = new ScaffoldVector(gP, alignD);
int count = 0;
ContigBridge bridge, bridge_rev;
while (true){
int brgID = count, revID = count;
if(a.contig.getIndex()==b.contig.getIndex()){
brgID = 2*count;
revID = brgID+1;
}
String hash = ContigBridge.makeHash(a.contig.index, b.contig.index, brgID),
hash_rev = ContigBridge.makeHash(b.contig.index, a.contig.index, revID);
bridge = bridgeMap.get(hash);
bridge_rev = bridgeMap.get(hash_rev);
if (bridge == null){
assert bridge_rev==null:hash_rev + " not null!";
bridge = new ContigBridge(a.contig, b.contig, brgID);
bridge_rev = new ContigBridge(b.contig, a.contig, revID);
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
// a.contig.bridges.add(bridge);
// b.contig.bridges.add(bridge_rev);
bridgesFromContig.get(a.contig.getIndex()).add(bridge);
bridgesFromContig.get(b.contig.getIndex()).add(bridge_rev);
bridgeMap.put(hash, bridge);
bridgeMap.put(hash_rev, bridge_rev);
break;
}
if ((a.contig.getIndex() != b.contig.getIndex()) && bridge.consistentWith(trans)){
assert bridge_rev!=null:hash_rev + "is null!";
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
if(a.contig.getIndex() == b.contig.getIndex()){
assert bridge_rev!=null:hash_rev + "is null";
if(bridge.consistentWith(trans)){
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
if(bridge.consistentWith(ScaffoldVector.reverse(trans))){
bridge_rev.addConnection(readSequence, b, a, trans, score);
bridge.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
}
count ++;
}//while
}
public static ArrayList<ContigBridge> getListOfBridgesFromContig(Contig ctg){
return bridgesFromContig.get(ctg.getIndex());
}
/**********************************************************************************************/
public ContigBridge getReversedBridge(ContigBridge bridge){
String hash = ContigBridge.makeHash(bridge.secondContig.index, bridge.firstContig.index, bridge.orderIndex);
return bridgeMap.get(hash);
}
/**********************************************************************************************/
/*
* Check if it's possible to extend from *contig* with *bridge* to another extended-already contig (contigF)
* use for markers and unique bridge only.
* This is a pre-step to join 2 scaffolds: scaffoldT going to scaffoldF
* @param Contig: a contig to start with
* ContigBridge: a bridge from given contig to a candidate unique contig for the extension
* @return int: direction on targeted scaffold (scaffoldF) that can be traversed
*/
protected int extendDirection(Contig contig, ContigBridge bridge){
Contig contigF = bridge.secondContig;
ScaffoldVector trans = bridge.getTransVector(); //contig->contigF
int pointer = Integer.signum(trans.magnitude * trans.direction); //pointer < 0 => tail of contigF on bridge
assert scaffolds[contigF.head].size() > 1 : contigF.head;
int headF = contigF.head;
int direction = 0; //direction of extension on scaffoldT (we need to return direction on scaffoldF)
ScaffoldVector headT2contigF = ScaffoldVector.composition(trans, contig.getVector());
int rEnd = contig.rightMost(), rEndF = contigF.rightMost(headT2contigF),
lEnd = contig.leftMost(), lEndF = contigF.leftMost(headT2contigF);
if(rEndF > rEnd){
direction = 1;
}
else if(lEndF < lEnd){
direction = -1;
}
else
return 0;
if(verbose)
System.out.println("Examining extending direction from contig " + contig.getIndex() + " to " + bridge.hashKey);
Scaffold scaffoldF = scaffolds[headF];
// Get order-based (order on scaffold other than orientation-based of contig) previous and next marker(unique contig)
Contig prevMarker = scaffoldF.nearestMarker(contigF, false), // previous marker of contigF on *corresponding scaffold*
nextMarker = scaffoldF.nearestMarker(contigF, true); // next marker of contigF on *corresponding scaffold*
ScaffoldVector rev = ScaffoldVector.reverse(contigF.getVector()); //rev = contigF->headF
if(prevMarker != null){
ScaffoldVector toPrev = ScaffoldVector.composition(prevMarker.getVector(),rev); //contigF->prevMarker
if(scaffoldF.indexOf(prevMarker) > scaffoldF.indexOf(contigF) && scaffoldF.closeBridge != null)
toPrev = ScaffoldVector.composition(ScaffoldVector.reverse(scaffoldF.circle), toPrev);
ScaffoldVector headT2Prev = ScaffoldVector.composition(toPrev, headT2contigF);
int rEndPrev = prevMarker.rightMost(headT2Prev),
lEndPrev = prevMarker.leftMost(headT2Prev);
if(verbose){
System.out.printf("Extending from contigT %d to targeted contig (contigF) %d with previous contig (prevMarker) %d \n", contig.getIndex(), contigF.getIndex(), prevMarker.getIndex());
System.out.println("...headT->contig, contigF and prevMarker: " + contig.getVector() + headT2contigF + headT2Prev);
}
if ((direction > 0?rEndPrev > rEndF: lEndPrev < lEndF)){
//check if the candidate ContigBridge is more confident than the current or not
if((pointer<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if(verbose)
System.out.printf("=> go from %d to %d to %d \n", contig.getIndex(), contigF.getIndex(), prevMarker.getIndex());
return -1;
}
else{
if(verbose)
System.out.printf("Bridge score not strong enough: %.2f < %.2f (%.2f)\n",
bridge.getScore(), pointer<0?contigF.nextScore:contigF.prevScore,
pointer<0?contigF.prevScore:contigF.nextScore);
return 0;
}
}else{
if(verbose)
System.out.printf("Direction conflict: %d, %d %d or %d %d. Checking otherway... \n", direction, rEndPrev, rEndF, lEndPrev, lEndF);
}
}
if(nextMarker != null){
ScaffoldVector toNext = ScaffoldVector.composition(nextMarker.getVector(),rev); //contigF->nextMarker
if(scaffoldF.indexOf(nextMarker) < scaffoldF.indexOf(contigF) && scaffoldF.closeBridge != null)
toNext = ScaffoldVector.composition(scaffoldF.circle, toNext);
ScaffoldVector headT2Next = ScaffoldVector.composition(toNext, headT2contigF);
int rEndNext = nextMarker.rightMost(headT2Next),
lEndNext = nextMarker.leftMost(headT2Next);
if(verbose){
System.out.printf("Extending from contigT %d to targeted contig (contigF) %d with next contig (nextMarker) %d \n", contig.getIndex(), contigF.getIndex(), nextMarker.getIndex());
System.out.println("...headT->contig, contigF and nextMarker: " + contig.getVector() + headT2contigF + headT2Next);
}
if ((direction > 0? rEndNext > rEndF : lEndNext < lEndF)){
//if((rev.direction<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if((pointer<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if(verbose)
System.out.printf("=> go from %d to %d to %d \n", contig.getIndex(), contigF.getIndex(), nextMarker.getIndex());
return 1;
}
else{
if(verbose)
System.out.printf("Bridge score not strong enough: %.2f < %.2f (%.2f)\n",
bridge.getScore(), pointer<0?contigF.nextScore:contigF.prevScore,
pointer<0?contigF.prevScore:contigF.nextScore);
return 0;
}
}else{
if(verbose)
System.out.printf("Direction conflict: %d, %d %d or %d %d. End searching! \n", direction, rEndNext, rEndF, lEndNext, lEndF);
}
}
return 0;
}
/*********************************************************************************/
public synchronized boolean joinScaffold(Contig contig, ContigBridge bridge, boolean firstDir, int secondDir){
if(verbose) {
System.out.println("PROCEED TO CONNECT " + bridge.hashKey + " with score " + bridge.getScore() +
", size " + bridge.getConnections().size() +
", vector (" + bridge.getTransVector().toString() +
"), distance " + bridge.getTransVector().distance(bridge.firstContig, bridge.secondContig));
bridge.display();
}
Contig contigF = bridge.secondContig, contigT = contig;
ScaffoldVector trans = bridge.getTransVector();
int headF = contigF.head,
headT = contigT.head;
Scaffold scaffoldF = scaffolds[headF],
scaffoldT = scaffolds[headT];
int posT = scaffoldT.isEnd(contigT);
if (posT == 0){
if(verbose)
System.out.println("Impossible to jump from the middle of a scaffold " + headT + ": contig " + contigT.index);
return false;
}
if(verbose)
System.out.println("Before joining " + contigF.index + " (" + headF +") to " + contigT.index
+ " (" + headT +") "
+ (scaffoldT.getLast().rightMost() - scaffoldT.getFirst().leftMost())
+ " " + (scaffoldF.getLast().rightMost() - scaffoldF.getFirst().leftMost())
+ " " + (scaffoldT.getLast().rightMost() - scaffoldT.getFirst().leftMost() + scaffoldF.getLast().rightMost() - scaffoldF.getFirst().leftMost()));
//===================================================================================================
int index = scaffoldF.indexOf(contigF),
count = index;
ScaffoldVector rev = ScaffoldVector.reverse(contigF.getVector()); //rev = contigF->headF
int addScf=-1;
if(secondDir == -1){
if(headF==headT){
//if(posT!=1)
if(firstDir)
return false;
else{
Contig nextMarker = scaffoldF.nearestMarker(contigF, true);
if(nextMarker!=null){
Contig ctg = scaffoldF.remove(index+1);
Scaffold newScf = new Scaffold(ctg);
ContigBridge brg = scaffoldF.bridges.remove(index);
while(true){
if(scaffoldF.size()==index+1) break;
ctg= scaffoldF.remove(index+1);
brg = scaffoldF.bridges.remove(index);
newScf.addRear(ctg,brg);
}
newScf.trim();
changeHead(newScf, nextMarker);
addScf=nextMarker.getIndex();
}
scaffoldF.setCloseBridge(getReversedBridge(bridge));
changeHead(scaffoldF, contigF);
}
}else{
Contig ctg = scaffoldF.remove(index);
ContigBridge brg = getReversedBridge(bridge);
//extend and connect
while(true){
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,brg);
}else{
scaffoldT.addRear(ctg,getReversedBridge(brg));
}
if(count<1) break;
ctg = scaffoldF.remove(--count);
brg = scaffoldF.bridges.remove(count);
}
if(scaffoldF.closeBridge!=null && !scaffoldF.isEmpty()){
count = scaffoldF.size()-1;
ctg = scaffoldF.removeLast();
brg = scaffoldF.closeBridge;
while(true){
ctg.myVector = ScaffoldVector.composition(ScaffoldVector.reverse(scaffoldF.circle),ctg.myVector);
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
//ctg.composite(ScaffoldVector.reverse(scaffoldF.circle)); //composite co tinh giao hoan k ma de day???
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,brg);
}else{
scaffoldT.addRear(ctg,getReversedBridge(brg));
}
if(count<1) break;
brg = scaffoldF.bridges.remove(count--);
ctg = scaffoldF.remove(count);
}
}
//set the remaining.FIXME
scaffoldT.trim();
scaffoldF.trim();
if(!scaffoldF.isEmpty()){
addScf=scaffoldF.getFirst().getIndex();//getFirst: NoSuchElementException
changeHead(scaffoldF, scaffoldF.getFirst());
}else
scaffoldF = new Scaffold(contigs.get(headF));
}
}
else if(secondDir == 1){
if(headF==headT){
//if(posT!=-1)
if(!firstDir)
return false;
else{
Contig prevMarker = scaffoldF.nearestMarker(contigF, false);
if(prevMarker!=null){
Contig ctg = scaffoldF.remove(--count);
Scaffold newScf = new Scaffold(ctg);
ContigBridge brg = scaffoldF.bridges.remove(count);
while(true){
if(count<1) break;
ctg= scaffoldF.remove(--count);
brg = scaffoldF.bridges.remove(count);
newScf.addFront(ctg,brg);
}
newScf.trim();
changeHead(newScf, prevMarker);
addScf=prevMarker.getIndex();
}
scaffoldF.setCloseBridge(bridge);
changeHead(scaffoldF, contigF);
}
}else{
Contig ctg = scaffoldF.remove(index);
ContigBridge brg = bridge;
//extend and connect
while(true){
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,getReversedBridge(brg));
}else{
scaffoldT.addRear(ctg,brg);
}
if(scaffoldF.size()==index) break;
ctg = scaffoldF.remove(index);
brg = scaffoldF.bridges.remove(index);
}
if(scaffoldF.closeBridge!=null && !scaffoldF.isEmpty()){
ctg = scaffoldF.removeFirst();
brg = scaffoldF.closeBridge;
while(true){
ctg.myVector = ScaffoldVector.composition(scaffoldF.circle,ctg.myVector);
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
//ctg.composite(scaffoldF.circle);
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,getReversedBridge(brg));
}else{
scaffoldT.addRear(ctg,brg);
}
if(scaffoldF.size()<1) break;
brg = scaffoldF.bridges.removeFirst();
ctg = scaffoldF.removeFirst();
}
}
//set the remaining
scaffoldT.trim();
scaffoldF.trim();
if(!scaffoldF.isEmpty()){
addScf=scaffoldF.getLast().getIndex(); //getLast: NoSuchElementException
changeHead(scaffoldF, scaffoldF.getLast());
}else
scaffoldF = new Scaffold(contigs.get(headF));
}
}
else
return false;
//===================================================================================================
if(verbose){
System.out.println("After Joining: " + (addScf<0?1:2) + " scaffolds!");
scaffolds[contigF.head].view();
if(addScf >=0)
scaffolds[addScf].view();
}
return true;
}
//change head of scaffold scf to newHead
//TODO: tidy this!!!
public void changeHead(Scaffold scf, Contig newHead){
if(isRepeat(newHead)){
if(verbose)
System.out.println("Cannot use repeat as a head! " + newHead.getName());
return;
}
//Scaffold scf = scaffolds[scfIndex];
int scfIndex = scf.scaffoldIndex;
int headPos = scf.indexOf(newHead);
if(headPos < 0){
if(verbose)
System.out.printf("Cannot find contig %d in scaffold %d\n" , newHead.getIndex(), scfIndex);
return;
}
Scaffold newScf = new Scaffold(newHead.getIndex());
ScaffoldVector rev = ScaffoldVector.reverse(newHead.getVector()); //rev = newHead->head
if(newHead.getRelDir() == 0){
if(verbose)
System.out.printf("Contig %d of scaffold %d got direction 0!\n" , newHead.getIndex(), scfIndex);
return;
}
else if(newHead.getRelDir() > 0){
while(!scf.isEmpty())
newScf.add(scf.removeFirst());
while(!scf.bridges.isEmpty())
newScf.bridges.add(scf.bridges.removeFirst());
if(scf.closeBridge != null){
newScf.closeBridge = scf.closeBridge;
newScf.circle = scf.circle;
}
}
else{
while(!scf.isEmpty())
newScf.add(scf.removeLast());
while(!scf.bridges.isEmpty())
newScf.bridges.add(getReversedBridge(scf.bridges.removeLast()));
if(scf.closeBridge != null){
newScf.closeBridge = getReversedBridge(scf.closeBridge);
newScf.circle = ScaffoldVector.reverse(scf.circle);
}
}
for (Contig ctg:newScf){
ctg.composite(rev); // leftmost->head + head->ctg = leftmost->ctg
}
newScf.setHead(newHead.getIndex());
scaffolds[newHead.getIndex()] = newScf;
}
public synchronized void printSequences() throws IOException{
//countOccurence=new HashMap<Integer,Integer>();
if(annotation){
SequenceOutputStream aout = SequenceOutputStream.makeOutputStream(prefix+".anno.japsa");
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].getLast().rightMost() - scaffolds[i].getFirst().leftMost();
if(contigs.get(i).head == i ){
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| scaffolds[i].closeBridge != null //here are the circular ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short,repetitive sequences here if required
{
if(verbose)
System.out.println("Scaffold " + i + " estimated length " + len);
scaffolds[i].viewAnnotation(aout);
}
}
}
aout.close();
} else{
SequenceOutputStream fout = SequenceOutputStream.makeOutputStream(prefix+".fin.fasta"),
jout = SequenceOutputStream.makeOutputStream(prefix+".fin.japsa");
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].getLast().rightMost() - scaffolds[i].getFirst().leftMost();
if(contigs.get(i).head == i){
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| scaffolds[i].closeBridge != null //here are the circular ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short/repeat sequences here if required
{
if(verbose)
System.out.println("Scaffold " + i + " estimated length " + len);
scaffolds[i].viewSequence(fout, jout);
}
}
}
fout.close();
jout.close();
}
}
public synchronized static void oneMore(Contig ctg){
if(countOccurence.get(ctg.getIndex())==null)
countOccurence.put(ctg.getIndex(), 1);
else
countOccurence.put(ctg.getIndex(), countOccurence.get(ctg.getIndex())+1);
}
synchronized boolean needMore(Contig ctg) {
Integer count = countOccurence.get(ctg.getIndex());
if(count==null) return true;
else return false; //if not occurred (Minh)
// int estimatedOccurence = (int) Math.floor(ctg.coverage/estimatedCov);
// if(estimatedOccurence <= Math.floor(.75*count))
// return true;
// else
// return false;
}
public synchronized void printRT(long tpoint) throws IOException{
for (Contig contig:contigs){
if(contig.oriRep.size() > 0){
String fname = contig.getName() + ".rtout";
File f = new File(fname);
if(!f.exists())
f.createNewFile();
//BufferedWriter out = new BufferedWriter(new FileWriter(f.getPath(), true));
FileWriter fw = new FileWriter(f,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
ArrayList<String> ctgList = new ArrayList<String>(),
origList = new ArrayList<String>(),
resList = new ArrayList<String>(),
genesList = new ArrayList<String>();
for(Contig ctg:scaffolds[contig.head]){
ctgList.add(ctg.getName());
if(ctg.oriRep.size()>0)
for(JapsaFeature ori:ctg.oriRep)
origList.add(ori.getID());
for (JapsaFeature feature:ctg.genes)
genesList.add(feature.toString());
for (JapsaFeature feature:ctg.resistanceGenes)
resList.add(feature.toString());
}
float streamData=tpoint/1000000;
pw.print(">");
for(String ctg:ctgList)
pw.printf("%s\t", ctg);
pw.printf("\n>%.2fMpb\t%d genes\t", streamData, genesList.size());
for(String ori:origList)
pw.printf("+%s", ori);
for(String genes:genesList)
pw.print(" \n\t"+genes);
pw.println("");
for(String res:resList)
pw.print(" \n\t"+res);
pw.println("");
pw.close();
}
}
}
// To check if this contig is likely a repeat or a singleton. If FALSE: able to be used as a marker.
public static boolean isRepeat(Contig ctg){
//for the case when no coverage information of contigs is found
if(estimatedCov == 1.0 && ctg.getCoverage() == 1.0){
if(ctg.length() > maxRepeatLength)
return false;
else
return true;
}
if (ctg.length() < minContigLength || ctg.getCoverage() < .3 * estimatedCov) return true;
else if (ctg.length() > maxRepeatLength || ctg.getCoverage() < 1.3 * estimatedCov)
return false;
else if (ctg.getCoverage() > 1.5 * estimatedCov)
return true;
else{
for(ContigBridge bridge:getListOfBridgesFromContig(ctg)){
Contig other = bridge.firstContig.getIndex()==ctg.getIndex()?bridge.secondContig:bridge.firstContig;
if(other.getIndex()==ctg.getIndex()) continue;
int dist=bridge.getTransVector().distance(bridge.firstContig, bridge.secondContig);
if( dist<0 && dist>-ctg.length()*.25){
if(other.length() > maxRepeatLength || other.getCoverage() < 1.3*estimatedCov)
return true;
}
}
}
if(ctg.length() < 2*minContigLength) // further filter: maybe not repeat but insignificant contig
return true;
else
return false;
}
public void connectBridges() {
// TODO Auto-generated method stub
}
} | src/dev/java/japsadev/bio/hts/scaffold/ScaffoldGraph.java | /*****************************************************************************
* Copyright (c) Minh Duc Cao, Monash Uni & UQ, All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. Neither the names of the institutions nor the names of the 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. *
****************************************************************************/
/************************** REVISION HISTORY **************************
* 20/12/2014 - Minh Duc Cao: Created
*
****************************************************************************/
package japsadev.bio.hts.scaffold;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import japsa.seq.Alphabet;
import japsa.seq.JapsaFeature;
import japsa.seq.Sequence;
import japsa.seq.SequenceOutputStream;
import japsa.seq.SequenceReader;
import japsa.util.Logging;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
public class ScaffoldGraph{
public static int maxRepeatLength=7500; //for ribosomal repeat cluster in bacteria (Koren S et al 2013), it's 9.1kb for yeast.
public static int marginThres = 1000;
public static int minContigLength = 300;
public static int minSupportReads = 1;
public static boolean verbose = false;
public static boolean reportAll = false;
public boolean annotation = false;
public static byte assembler =0b00; // 0 for SPAdes, 1 for ABySS
public static HashMap<Integer,Integer> countOccurence=new HashMap<Integer,Integer>();
public String prefix = "out";
public static double estimatedCov = 0;
private static double estimatedLength = 0;
//below maps contain avatar of contigs and bridges only,
//not the actual ones in used (because of the repeats that need to be cloned)
ArrayList<Contig> contigs;
HashMap<String, ContigBridge> bridgeMap= new HashMap<String, ContigBridge>();
static HashMap<Integer, ArrayList<ContigBridge>> bridgesFromContig = new HashMap<Integer, ArrayList<ContigBridge>>();
Scaffold [] scaffolds; // DNA translator, previous image of sequence is stored for real-time processing
// Constructor for the graph with contigs FASTA file (contigs.fasta from SPAdes output)
public ScaffoldGraph(String sequenceFile) throws IOException{
//1. read in contigs
SequenceReader reader = SequenceReader.getReader(sequenceFile);
Sequence seq;
contigs = new ArrayList<Contig>();
int index = 0;
while ((seq = reader.nextSequence(Alphabet.DNA())) != null){
Contig ctg = new Contig(index, seq);
String name = seq.getName(),
desc = seq.getDesc();
double mycov = 1.0;
//SPAdes header: >%d_length_%d_cov_%f, ID, length, coverage
if(assembler==0b00){
String [] toks = name.split("_");
for (int i = 0; i < toks.length - 1;i++){
if ("cov".equals(toks[i])){
mycov = Double.parseDouble(toks[i+1]);
break;
}
}
}
//ABySS header: >%d %d %d, ID, length, kmer_sum
else if(assembler==0b01){
String [] toks = desc.split("\\s");
mycov = Double.parseDouble(toks[1])/Double.parseDouble(toks[0]);
}
estimatedCov += mycov * seq.length();
estimatedLength += seq.length();
ctg.setCoverage(mycov);
contigs.add(ctg);
bridgesFromContig.put(ctg.getIndex(), new ArrayList<ContigBridge>());
index ++;
}
reader.close();
estimatedCov /= estimatedLength;
if(verbose)
System.out.println("Cov " + estimatedCov + " Length " + estimatedLength);
//2. Initialise scaffold graph
scaffolds = new Scaffold[contigs.size()];
for (int i = 0; i < contigs.size();i++){
scaffolds[i] = new Scaffold(contigs.get(i));
//point to the head of the scaffold
contigs.get(i).head = i;
}//for
}//constructor
public String getAssemblerName(){
if(assembler==0b01)
return new String("ABySS");
else
return new String("SPAdes");
}
/* Read short-read assembly information from SPAdes output: assembly graph (assembly_graph.fastg) and
** traversed paths (contigs.pahth) to make up the contigs
*/
public void readMore(String assemblyGraph, String paths) throws IOException{
//1. Read assembly graph and store in a string graph
Graph g = new Graph(assemblyGraph,assembler);
// for(Vertex v:g.getVertices()){
// System.out.println("Neighbors of vertex " + v.getLabel() + " (" + v.getNeighborCount() +"):");
// for(Edge e:v.getNeighbors())
// System.out.println(e + "; ");
// System.out.println();
// }
Contig.setGraph(g);
if(assembler==0b00){
//2. read file contigs.paths from SPAdes
BufferedReader pathReader = new BufferedReader(new FileReader(paths));
String s;
//Read contigs from contigs.paths and refer themselves to contigs.fasta
Contig curContig = null;
while((s=pathReader.readLine()) != null){
if(s.contains("NODE"))
curContig=getSPadesContig(s);
else if(curContig!=null)
curContig.setPath(new Path(g,s));
}
pathReader.close();
} else if(assembler==0b01){ //for the case of ABySS: contig and vertex of assembly graph are the same
for(Contig ctg:contigs)
ctg.setPath(new Path(g,ctg.getName()+"+"));
}
if(ScaffoldGraph.verbose)
Logging.info("Short read assembler " + (assembler==0b00?"SPAdes":"ABySS") + " kmer=" + Graph.getKmerSize());
}
public Contig getSPadesContig(String name){
if(name.contains("'")){
if(verbose)
System.out.println("Ignored (redundant) reversed sequence: " + name);
return null;
}
Contig res = null;
for(Contig ctg:contigs){
// Extract to find contig named NODE_x_
//because sometimes there are disagreement between contig name (_length_) in contigs.paths and contigs.fasta in SPAdes!!!
//
if(ctg.getName().contains("NODE_"+name.split("_")[1]+"_")){
res = ctg;
break;
}
}
if(res==null && verbose){
System.out.println("Contig not found:" + name);
}
return res;
}
public synchronized int getN50(){
int [] lengths = new int[scaffolds.length];
int count=0;
double sum = 0;
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].length();
// if ((contigs.get(i).head == i
// && !isRepeat(contigs.get(i))
// && len > maxRepeatLength
// )
// || scaffolds[i].closeBridge != null)
if(contigs.get(i).head == i || scaffolds[i].closeBridge != null)
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short,repetitive sequences here if required
{
lengths[count] = len;
sum+=len;
count++;
}
}
Arrays.sort(lengths);
int index = lengths.length;
double contains = 0;
while (contains < sum/2){
index --;
contains += lengths[index];
}
return lengths[index];
}
public synchronized String getGapsInfo(){
int gapCount=0,
gapMaxLen=0;
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].length();
if ((contigs.get(i).head == i
&& !isRepeat(contigs.get(i))
&& len > maxRepeatLength
)
|| scaffolds[i].closeBridge != null)
{
for(ContigBridge brg:scaffolds[i].bridges){
if(brg.getBridgePath()==null){
gapCount++;
if(brg.getTransVector().distance(brg.firstContig, brg.secondContig) > gapMaxLen)
gapMaxLen=brg.getTransVector().distance(brg.firstContig, brg.secondContig);
}
}
if(scaffolds[i].closeBridge!=null){
ContigBridge brg=scaffolds[i].closeBridge;
if(brg.getBridgePath()==null){
gapCount++;
if(brg.getTransVector().distance(brg.firstContig, brg.secondContig) > gapMaxLen)
gapMaxLen=brg.getTransVector().distance(brg.firstContig, brg.secondContig);
}
}
}
}
return gapCount+" ("+gapMaxLen+")";
}
/**
* MDC added second version that include bwa
* @param bamFile
* @param minCov
* @param qual
* @throws IOException
* @throws InterruptedException
*/
public void makeConnections2(String inFile, double minCov, int qual, String format, String bwaExe, int bwaThread, String bwaIndex) throws IOException, InterruptedException{
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReader reader = null;
Process bwaProcess = null;
if (format.endsWith("am")){//bam or sam
if ("-".equals(inFile))
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
else
reader = SamReaderFactory.makeDefault().open(new File(inFile));
}else{
Logging.info("Starting bwa at " + new Date());
ProcessBuilder pb = null;
if ("-".equals(inFile)){
pb = new ProcessBuilder(bwaExe,
"mem",
"-t",
"" + bwaThread,
"-k11",
"-W20",
"-r10",
"-A1",
"-B1",
"-O1",
"-E1",
"-L0",
"-a",
"-Y",
// "-K",
// "20000",
bwaIndex,
"-"
).
redirectInput(Redirect.INHERIT);
}else{
pb = new ProcessBuilder(bwaExe,
"mem",
"-t",
"" + bwaThread,
"-k11",
"-W20",
"-r10",
"-A1",
"-B1",
"-O1",
"-E1",
"-L0",
"-a",
"-Y",
// "-K",
// "20000",
bwaIndex,
inFile
);
}
bwaProcess = pb.redirectError(ProcessBuilder.Redirect.to(new File("/dev/null"))).start();
//Logging.info("bwa started x");
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(bwaProcess.getInputStream()));
}
//SamReader reader;
//if ("-".equals(bamFile))
// reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
//else
// reader = SamReaderFactory.makeDefault().open(new File(bamFile));
SAMRecordIterator iter = reader.iterator();
String readID = "";
ReadFilling readFilling = null;
ArrayList<AlignmentRecord> samList = null;// alignment record of the same read;
while (iter.hasNext()) {
SAMRecord rec = iter.next();
if (rec.getReadUnmappedFlag())
continue;
if (rec.getMappingQuality() < qual)
continue;
AlignmentRecord myRec = new AlignmentRecord(rec, contigs.get(rec.getReferenceIndex()));
//////////////////////////////////////////////////////////////////
// make bridge of contigs that align to the same (Nanopore) read.
// Note that SAM file MUST be sorted based on readID (samtools sort -n)
//not the first occurrance
if (readID.equals(myRec.readID)) {
if (myRec.useful){
for (AlignmentRecord s : samList) {
if (s.useful){
this.addBridge(readFilling, s, myRec, minCov); //stt(s) < stt(myRec) -> (s,myRec) appear once only!
//...update with synchronized
}
}
}
} else {
samList = new ArrayList<AlignmentRecord>();
readID = myRec.readID;
readFilling = new ReadFilling(new Sequence(Alphabet.DNA5(), rec.getReadString(), "R" + readID), samList);
}
samList.add(myRec);
}// while
iter.close();
//outOS.close();
reader.close();
if (bwaProcess != null){
bwaProcess.waitFor();
}
Logging.info("Sort list of bridges");
//Collections.sort(bridgeList);
}
/**
* Forming bridges based on alignments
*
* @param bamFile
* @param minCov
* @param maxCov
* @param threshold
* @param qual
* @throws IOException
*/
public void makeConnections(String bamFile, double minCov, int qual) throws IOException{
SamReaderFactory.setDefaultValidationStringency(ValidationStringency.SILENT);
SamReader reader;
if ("-".equals(bamFile))
reader = SamReaderFactory.makeDefault().open(SamInputResource.of(System.in));
else
reader = SamReaderFactory.makeDefault().open(new File(bamFile));
SAMRecordIterator iter = reader.iterator();
String readID = "";
ReadFilling readFilling = null;
ArrayList<AlignmentRecord> samList = null;// alignment record of the same read;
while (iter.hasNext()) {
SAMRecord rec = iter.next();
if (rec.getReadUnmappedFlag())
continue;
if (rec.getMappingQuality() < qual)
continue;
AlignmentRecord myRec = new AlignmentRecord(rec, contigs.get(rec.getReferenceIndex()));
//////////////////////////////////////////////////////////////////
// make bridge of contigs that align to the same (Nanopore) read.
// Note that SAM file MUST be sorted based on readID (samtools sort -n)
//not the first occurrance
if (readID.equals(myRec.readID)) {
if (myRec.useful){
for (AlignmentRecord s : samList) {
if (s.useful){
this.addBridge(readFilling, s, myRec, minCov); //stt(s) < stt(myRec) -> (s,myRec) appear once only!
//...update with synchronized
}
}
}
} else {
samList = new ArrayList<AlignmentRecord>();
readID = myRec.readID;
readFilling = new ReadFilling(new Sequence(Alphabet.DNA5(), rec.getReadString(), "R" + readID), samList);
}
samList.add(myRec);
}// while
iter.close();
//outOS.close();
reader.close();
Logging.info("Sort list of bridges");
//Collections.sort(bridgeList);
}
/*********************************************************************************/
protected void addBridge(ReadFilling readSequence, AlignmentRecord a, AlignmentRecord b, double minCov){
if (a.contig.index > b.contig.index){
AlignmentRecord t = a;a=b;b=t;
}
// Rate of aligned lengths: ref/read (illumina contig/nanopore read)
int alignedReadLen = Math.abs(a.readEnd - a.readStart) + Math.abs(b.readEnd - b.readStart),
alignedRefLen = Math.abs(a.refEnd - a.refStart) + Math.abs(b.refEnd - b.refStart);
double rate = 1.0 * alignedRefLen/alignedReadLen;
//See if this is reliable
double score = Math.min(a.score, b.score);
int alignP = (int) ((b.readStart - a.readStart) * rate);
int alignD = (a.strand == b.strand)?1:-1;
//(rough) relative position from ref_b (contig of b) to ref_a (contig of a) in the assembled genome
int gP = (alignP + (a.strand ? a.refStart:-a.refStart) - (b.strand?b.refStart:-b.refStart));
if (!a.strand)
gP = -gP;
if ( a.contig.getIndex() == b.contig.getIndex()
&& alignD > 0
&& (Math.abs(gP)*1.0 / a.contig.length()) < 1.1
&& (Math.abs(gP)*1.0 / a.contig.length()) > 0.9
&& a.readLength < 1.1* a.contig.length()
)
{
if( alignedReadLen*1.0/a.contig.length() > 0.7 ){ //need more than 70% alignment (error rate of nanopore read)
a.contig.cirProb ++;
if(verbose)
System.out.printf("Potential CIRCULAR or TANDEM contig %s map to read %s(length=%d): (%d,%d) => circular score: %d\n"
, a.contig.getName(), a.readID, a.readLength, gP, alignD, a.contig.cirProb);
}
}
else{
a.contig.cirProb--;
b.contig.cirProb--;
}
// overlap length on aligned read (<0 if not overlap)
int overlap = Math.min( a.readAlignmentEnd() - b.readAlignmentStart(), b.readAlignmentEnd() - a.readAlignmentStart());
if ( overlap > Math.min( .5 * Math.min(a.readAlignmentEnd()-a.readAlignmentStart(), b.readAlignmentEnd()-b.readAlignmentStart()),
minContigLength)
|| a.contig.getCoverage() < minCov // filter out contigs with inappropriate cov
|| b.contig.getCoverage() < minCov
){
return;
}
ScaffoldVector trans = new ScaffoldVector(gP, alignD);
int count = 0;
ContigBridge bridge, bridge_rev;
while (true){
int brgID = count, revID = count;
if(a.contig.getIndex()==b.contig.getIndex()){
brgID = 2*count;
revID = brgID+1;
}
String hash = ContigBridge.makeHash(a.contig.index, b.contig.index, brgID),
hash_rev = ContigBridge.makeHash(b.contig.index, a.contig.index, revID);
bridge = bridgeMap.get(hash);
bridge_rev = bridgeMap.get(hash_rev);
if (bridge == null){
assert bridge_rev==null:hash_rev + " not null!";
bridge = new ContigBridge(a.contig, b.contig, brgID);
bridge_rev = new ContigBridge(b.contig, a.contig, revID);
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
// a.contig.bridges.add(bridge);
// b.contig.bridges.add(bridge_rev);
bridgesFromContig.get(a.contig.getIndex()).add(bridge);
bridgesFromContig.get(b.contig.getIndex()).add(bridge_rev);
bridgeMap.put(hash, bridge);
bridgeMap.put(hash_rev, bridge_rev);
break;
}
if ((a.contig.getIndex() != b.contig.getIndex()) && bridge.consistentWith(trans)){
assert bridge_rev!=null:hash_rev + "is null!";
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
if(a.contig.getIndex() == b.contig.getIndex()){
assert bridge_rev!=null:hash_rev + "is null";
if(bridge.consistentWith(trans)){
bridge.addConnection(readSequence, a, b, trans, score);
bridge_rev.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
if(bridge.consistentWith(ScaffoldVector.reverse(trans))){
bridge_rev.addConnection(readSequence, b, a, trans, score);
bridge.addConnection(readSequence, b, a, ScaffoldVector.reverse(trans), score);
break;
}
}
count ++;
}//while
}
public static ArrayList<ContigBridge> getListOfBridgesFromContig(Contig ctg){
return bridgesFromContig.get(ctg.getIndex());
}
/**********************************************************************************************/
public ContigBridge getReversedBridge(ContigBridge bridge){
String hash = ContigBridge.makeHash(bridge.secondContig.index, bridge.firstContig.index, bridge.orderIndex);
return bridgeMap.get(hash);
}
/**********************************************************************************************/
/*
* Check if it's possible to extend from *contig* with *bridge* to another extended-already contig (contigF)
* use for markers and unique bridge only.
* This is a pre-step to join 2 scaffolds: scaffoldT going to scaffoldF
* @param Contig: a contig to start with
* ContigBridge: a bridge from given contig to a candidate unique contig for the extension
* @return int: direction on targeted scaffold (scaffoldF) that can be traversed
*/
protected int extendDirection(Contig contig, ContigBridge bridge){
Contig contigF = bridge.secondContig;
ScaffoldVector trans = bridge.getTransVector(); //contig->contigF
int pointer = Integer.signum(trans.magnitude * trans.direction); //pointer < 0 => tail of contigF on bridge
assert scaffolds[contigF.head].size() > 1 : contigF.head;
int headF = contigF.head;
int direction = 0; //direction of extension on scaffoldT (we need to return direction on scaffoldF)
ScaffoldVector headT2contigF = ScaffoldVector.composition(trans, contig.getVector());
int rEnd = contig.rightMost(), rEndF = contigF.rightMost(headT2contigF),
lEnd = contig.leftMost(), lEndF = contigF.leftMost(headT2contigF);
if(rEndF > rEnd){
direction = 1;
}
else if(lEndF < lEnd){
direction = -1;
}
else
return 0;
if(verbose)
System.out.println("Examining extending direction from contig " + contig.getIndex() + " to " + bridge.hashKey);
Scaffold scaffoldF = scaffolds[headF];
// Get order-based (order on scaffold other than orientation-based of contig) previous and next marker(unique contig)
Contig prevMarker = scaffoldF.nearestMarker(contigF, false), // previous marker of contigF on *corresponding scaffold*
nextMarker = scaffoldF.nearestMarker(contigF, true); // next marker of contigF on *corresponding scaffold*
ScaffoldVector rev = ScaffoldVector.reverse(contigF.getVector()); //rev = contigF->headF
if(prevMarker != null){
ScaffoldVector toPrev = ScaffoldVector.composition(prevMarker.getVector(),rev); //contigF->prevMarker
if(scaffoldF.indexOf(prevMarker) > scaffoldF.indexOf(contigF) && scaffoldF.closeBridge != null)
toPrev = ScaffoldVector.composition(ScaffoldVector.reverse(scaffoldF.circle), toPrev);
ScaffoldVector headT2Prev = ScaffoldVector.composition(toPrev, headT2contigF);
int rEndPrev = prevMarker.rightMost(headT2Prev),
lEndPrev = prevMarker.leftMost(headT2Prev);
if(verbose){
System.out.printf("Extending from contigT %d to targeted contig (contigF) %d with previous contig (prevMarker) %d \n", contig.getIndex(), contigF.getIndex(), prevMarker.getIndex());
System.out.println("...headT->contig, contigF and prevMarker: " + contig.getVector() + headT2contigF + headT2Prev);
}
if ((direction > 0?rEndPrev > rEndF: lEndPrev < lEndF)){
//check if the candidate ContigBridge is more confident than the current or not
if((pointer<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if(verbose)
System.out.printf("=> go from %d to %d to %d \n", contig.getIndex(), contigF.getIndex(), prevMarker.getIndex());
return -1;
}
else{
if(verbose)
System.out.printf("Bridge score not strong enough: %.2f < %.2f (%.2f)\n",
bridge.getScore(), pointer<0?contigF.nextScore:contigF.prevScore,
pointer<0?contigF.prevScore:contigF.nextScore);
return 0;
}
}else{
if(verbose)
System.out.printf("Direction conflict: %d, %d %d or %d %d. Checking otherway... \n", direction, rEndPrev, rEndF, lEndPrev, lEndF);
}
}
if(nextMarker != null){
ScaffoldVector toNext = ScaffoldVector.composition(nextMarker.getVector(),rev); //contigF->nextMarker
if(scaffoldF.indexOf(nextMarker) < scaffoldF.indexOf(contigF) && scaffoldF.closeBridge != null)
toNext = ScaffoldVector.composition(scaffoldF.circle, toNext);
ScaffoldVector headT2Next = ScaffoldVector.composition(toNext, headT2contigF);
int rEndNext = nextMarker.rightMost(headT2Next),
lEndNext = nextMarker.leftMost(headT2Next);
if(verbose){
System.out.printf("Extending from contigT %d to targeted contig (contigF) %d with next contig (nextMarker) %d \n", contig.getIndex(), contigF.getIndex(), nextMarker.getIndex());
System.out.println("...headT->contig, contigF and nextMarker: " + contig.getVector() + headT2contigF + headT2Next);
}
if ((direction > 0? rEndNext > rEndF : lEndNext < lEndF)){
//if((rev.direction<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if((pointer<0?contigF.nextScore:contigF.prevScore) < bridge.getScore()){
if(verbose)
System.out.printf("=> go from %d to %d to %d \n", contig.getIndex(), contigF.getIndex(), nextMarker.getIndex());
return 1;
}
else{
if(verbose)
System.out.printf("Bridge score not strong enough: %.2f < %.2f (%.2f)\n",
bridge.getScore(), pointer<0?contigF.nextScore:contigF.prevScore,
pointer<0?contigF.prevScore:contigF.nextScore);
return 0;
}
}else{
if(verbose)
System.out.printf("Direction conflict: %d, %d %d or %d %d. End searching! \n", direction, rEndNext, rEndF, lEndNext, lEndF);
}
}
return 0;
}
/*********************************************************************************/
public synchronized boolean joinScaffold(Contig contig, ContigBridge bridge, boolean firstDir, int secondDir){
if(verbose) {
System.out.println("PROCEED TO CONNECT " + bridge.hashKey + " with score " + bridge.getScore() +
", size " + bridge.getConnections().size() +
", vector (" + bridge.getTransVector().toString() +
"), distance " + bridge.getTransVector().distance(bridge.firstContig, bridge.secondContig));
bridge.display();
}
Contig contigF = bridge.secondContig, contigT = contig;
ScaffoldVector trans = bridge.getTransVector();
int headF = contigF.head,
headT = contigT.head;
Scaffold scaffoldF = scaffolds[headF],
scaffoldT = scaffolds[headT];
int posT = scaffoldT.isEnd(contigT);
if (posT == 0){
if(verbose)
System.out.println("Impossible to jump from the middle of a scaffold " + headT + ": contig " + contigT.index);
return false;
}
if(verbose)
System.out.println("Before joining " + contigF.index + " (" + headF +") to " + contigT.index
+ " (" + headT +") "
+ (scaffoldT.getLast().rightMost() - scaffoldT.getFirst().leftMost())
+ " " + (scaffoldF.getLast().rightMost() - scaffoldF.getFirst().leftMost())
+ " " + (scaffoldT.getLast().rightMost() - scaffoldT.getFirst().leftMost() + scaffoldF.getLast().rightMost() - scaffoldF.getFirst().leftMost()));
//===================================================================================================
int index = scaffoldF.indexOf(contigF),
count = index;
ScaffoldVector rev = ScaffoldVector.reverse(contigF.getVector()); //rev = contigF->headF
int addScf=-1;
if(secondDir == -1){
if(headF==headT){
//if(posT!=1)
if(firstDir)
return false;
else{
Contig nextMarker = scaffoldF.nearestMarker(contigF, true);
if(nextMarker!=null){
Contig ctg = scaffoldF.remove(index+1);
Scaffold newScf = new Scaffold(ctg);
ContigBridge brg = scaffoldF.bridges.remove(index);
while(true){
if(scaffoldF.size()==index+1) break;
ctg= scaffoldF.remove(index+1);
brg = scaffoldF.bridges.remove(index);
newScf.addRear(ctg,brg);
}
newScf.trim();
changeHead(newScf, nextMarker);
addScf=nextMarker.getIndex();
}
scaffoldF.setCloseBridge(getReversedBridge(bridge));
changeHead(scaffoldF, contigF);
}
}else{
Contig ctg = scaffoldF.remove(index);
ContigBridge brg = getReversedBridge(bridge);
//extend and connect
while(true){
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,brg);
}else{
scaffoldT.addRear(ctg,getReversedBridge(brg));
}
if(count<1) break;
ctg = scaffoldF.remove(--count);
brg = scaffoldF.bridges.remove(count);
}
if(scaffoldF.closeBridge!=null && !scaffoldF.isEmpty()){
count = scaffoldF.size()-1;
ctg = scaffoldF.removeLast();
brg = scaffoldF.closeBridge;
while(true){
ctg.myVector = ScaffoldVector.composition(ScaffoldVector.reverse(scaffoldF.circle),ctg.myVector);
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
//ctg.composite(ScaffoldVector.reverse(scaffoldF.circle)); //composite co tinh giao hoan k ma de day???
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,brg);
}else{
scaffoldT.addRear(ctg,getReversedBridge(brg));
}
if(count<1) break;
brg = scaffoldF.bridges.remove(count--);
ctg = scaffoldF.remove(count);
}
}
//set the remaining.FIXME
scaffoldT.trim();
if(scaffoldF.size() > 0){
scaffoldF.trim();
addScf=scaffoldF.getFirst().getIndex();
changeHead(scaffoldF, scaffoldF.getFirst());
}
}
scaffoldF = new Scaffold(contigs.get(headF));//????FIXME (is index matter when it comes to setHead???)
}
else if(secondDir == 1){
if(headF==headT){
//if(posT!=-1)
if(!firstDir)
return false;
else{
Contig prevMarker = scaffoldF.nearestMarker(contigF, false);
if(prevMarker!=null){
Contig ctg = scaffoldF.remove(--count);
Scaffold newScf = new Scaffold(ctg);
ContigBridge brg = scaffoldF.bridges.remove(count);
while(true){
if(count<1) break;
ctg= scaffoldF.remove(--count);
brg = scaffoldF.bridges.remove(count);
newScf.addFront(ctg,brg);
}
newScf.trim();
changeHead(newScf, prevMarker);
addScf=prevMarker.getIndex();
}
scaffoldF.setCloseBridge(bridge);
changeHead(scaffoldF, contigF);
}
}else{
Contig ctg = scaffoldF.remove(index);
ContigBridge brg = bridge;
//extend and connect
while(true){
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,getReversedBridge(brg));
}else{
scaffoldT.addRear(ctg,brg);
}
if(scaffoldF.size()==index) break;
ctg = scaffoldF.remove(index);
brg = scaffoldF.bridges.remove(index);
}
if(scaffoldF.closeBridge!=null && !scaffoldF.isEmpty()){
ctg = scaffoldF.removeFirst();
brg = scaffoldF.closeBridge;
while(true){
ctg.myVector = ScaffoldVector.composition(scaffoldF.circle,ctg.myVector);
ctg.composite(rev); // contigF->headF + headF->ctg = contigF->ctg
ctg.composite(trans); // contigT->contigF + contigF->ctg = contigT->ctg
ctg.composite(contigT.getVector()); //headT->contigT + contigT->ctg = headT->ctg : relative position of this ctg w.r.t headT
//ctg.composite(scaffoldF.circle);
ctg.head = headT;
//if (posT == 1){
if(!firstDir){
scaffoldT.addFront(ctg,getReversedBridge(brg));
}else{
scaffoldT.addRear(ctg,brg);
}
if(scaffoldF.size()<1) break;
brg = scaffoldF.bridges.removeFirst();
ctg = scaffoldF.removeFirst();
}
}
//set the remaining. FIXME
scaffoldT.trim();
if(scaffoldF.size() > 0){
scaffoldF.trim();
addScf=scaffoldF.getLast().getIndex();
changeHead(scaffoldF, scaffoldF.getLast());
}
}
scaffoldF = new Scaffold(contigs.get(headF));//???FIXME
}
else
return false;
//===================================================================================================
if(verbose){
System.out.println("After Joining: " + (addScf<0?1:2) + " scaffolds!");
scaffolds[contigF.head].view();
if(addScf >=0)
scaffolds[addScf].view();
}
return true;
}
//change head of scaffold scf to newHead
public void changeHead(Scaffold scf, Contig newHead){
if(isRepeat(newHead)){
if(verbose)
System.out.println("Cannot use repeat as a head! " + newHead.getName());
return;
}
//Scaffold scf = scaffolds[scfIndex];
int scfIndex = scf.scaffoldIndex;
int headPos = scf.indexOf(newHead);
if(headPos < 0){
if(verbose)
System.out.printf("Cannot find contig %d in scaffold %d\n" , newHead.getIndex(), scfIndex);
return;
}
Scaffold newScf = new Scaffold(newHead.getIndex());
ScaffoldVector rev = ScaffoldVector.reverse(newHead.getVector()); //rev = newHead->head
if(newHead.getRelDir() == 0){
if(verbose)
System.out.printf("Contig %d of scaffold %d got direction 0!\n" , newHead.getIndex(), scfIndex);
return;
}
else if(newHead.getRelDir() > 0){
while(!scf.isEmpty())
newScf.add(scf.removeFirst());
while(!scf.bridges.isEmpty())
newScf.bridges.add(scf.bridges.removeFirst());
if(scf.closeBridge != null){
newScf.closeBridge = scf.closeBridge;
newScf.circle = scf.circle;
}
}
else{
while(!scf.isEmpty())
newScf.add(scf.removeLast());
while(!scf.bridges.isEmpty())
newScf.bridges.add(getReversedBridge(scf.bridges.removeLast()));
if(scf.closeBridge != null){
newScf.closeBridge = getReversedBridge(scf.closeBridge);
newScf.circle = ScaffoldVector.reverse(scf.circle);
}
}
for (Contig ctg:newScf){
ctg.composite(rev); // leftmost->head + head->ctg = leftmost->ctg
}
newScf.setHead(newHead.getIndex());
scaffolds[newHead.getIndex()] = newScf;
}
public synchronized void printSequences() throws IOException{
//countOccurence=new HashMap<Integer,Integer>();
if(annotation){
SequenceOutputStream aout = SequenceOutputStream.makeOutputStream(prefix+".anno.japsa");
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].getLast().rightMost() - scaffolds[i].getFirst().leftMost();
if(contigs.get(i).head == i ){
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| scaffolds[i].closeBridge != null //here are the circular ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short,repetitive sequences here if required
{
if(verbose)
System.out.println("Scaffold " + i + " estimated length " + len);
scaffolds[i].viewAnnotation(aout);
}
}
}
aout.close();
} else{
SequenceOutputStream fout = SequenceOutputStream.makeOutputStream(prefix+".fin.fasta"),
jout = SequenceOutputStream.makeOutputStream(prefix+".fin.japsa");
for (int i = 0; i < scaffolds.length;i++){
if(scaffolds[i].isEmpty()) continue;
int len = scaffolds[i].getLast().rightMost() - scaffolds[i].getFirst().leftMost();
if(contigs.get(i).head == i){
if ( (!isRepeat(contigs.get(i)) && len > maxRepeatLength) //here are the big ones
|| scaffolds[i].closeBridge != null //here are the circular ones
|| (reportAll && needMore(contigs.get(i)) && contigs.get(i).coverage > .5*estimatedCov)) //short/repeat sequences here if required
{
if(verbose)
System.out.println("Scaffold " + i + " estimated length " + len);
scaffolds[i].viewSequence(fout, jout);
}
}
}
fout.close();
jout.close();
}
}
public synchronized static void oneMore(Contig ctg){
if(countOccurence.get(ctg.getIndex())==null)
countOccurence.put(ctg.getIndex(), 1);
else
countOccurence.put(ctg.getIndex(), countOccurence.get(ctg.getIndex())+1);
}
synchronized boolean needMore(Contig ctg) {
Integer count = countOccurence.get(ctg.getIndex());
if(count==null) return true;
else return false; //if not occurred (Minh)
// int estimatedOccurence = (int) Math.floor(ctg.coverage/estimatedCov);
// if(estimatedOccurence <= Math.floor(.75*count))
// return true;
// else
// return false;
}
public synchronized void printRT(long tpoint) throws IOException{
for (Contig contig:contigs){
if(contig.oriRep.size() > 0){
String fname = contig.getName() + ".rtout";
File f = new File(fname);
if(!f.exists())
f.createNewFile();
//BufferedWriter out = new BufferedWriter(new FileWriter(f.getPath(), true));
FileWriter fw = new FileWriter(f,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
ArrayList<String> ctgList = new ArrayList<String>(),
origList = new ArrayList<String>(),
resList = new ArrayList<String>(),
genesList = new ArrayList<String>();
for(Contig ctg:scaffolds[contig.head]){
ctgList.add(ctg.getName());
if(ctg.oriRep.size()>0)
for(JapsaFeature ori:ctg.oriRep)
origList.add(ori.getID());
for (JapsaFeature feature:ctg.genes)
genesList.add(feature.toString());
for (JapsaFeature feature:ctg.resistanceGenes)
resList.add(feature.toString());
}
float streamData=tpoint/1000000;
pw.print(">");
for(String ctg:ctgList)
pw.printf("%s\t", ctg);
pw.printf("\n>%.2fMpb\t%d genes\t", streamData, genesList.size());
for(String ori:origList)
pw.printf("+%s", ori);
for(String genes:genesList)
pw.print(" \n\t"+genes);
pw.println("");
for(String res:resList)
pw.print(" \n\t"+res);
pw.println("");
pw.close();
}
}
}
// To check if this contig is likely a repeat or a singleton. If FALSE: able to be used as a marker.
public static boolean isRepeat(Contig ctg){
//for the case when no coverage information of contigs is found
if(estimatedCov == 1.0 && ctg.getCoverage() == 1.0){
if(ctg.length() > maxRepeatLength)
return false;
else
return true;
}
if (ctg.length() < minContigLength || ctg.getCoverage() < .3 * estimatedCov) return true;
else if (ctg.length() > maxRepeatLength || ctg.getCoverage() < 1.3 * estimatedCov)
return false;
else if (ctg.getCoverage() > 1.5 * estimatedCov)
return true;
else{
for(ContigBridge bridge:getListOfBridgesFromContig(ctg)){
Contig other = bridge.firstContig.getIndex()==ctg.getIndex()?bridge.secondContig:bridge.firstContig;
if(other.getIndex()==ctg.getIndex()) continue;
int dist=bridge.getTransVector().distance(bridge.firstContig, bridge.secondContig);
if( dist<0 && dist>-ctg.length()*.25){
if(other.length() > maxRepeatLength || other.getCoverage() < 1.3*estimatedCov)
return true;
}
}
}
if(ctg.length() < 2*minContigLength) // further filter: maybe not repeat but insignificant contig
return true;
else
return false;
}
public void connectBridges() {
// TODO Auto-generated method stub
}
} | Trying to fix NoSuchElementException... | src/dev/java/japsadev/bio/hts/scaffold/ScaffoldGraph.java | Trying to fix NoSuchElementException... | <ide><path>rc/dev/java/japsadev/bio/hts/scaffold/ScaffoldGraph.java
<ide>
<ide> //set the remaining.FIXME
<ide> scaffoldT.trim();
<del> if(scaffoldF.size() > 0){
<del> scaffoldF.trim();
<del> addScf=scaffoldF.getFirst().getIndex();
<add> scaffoldF.trim();
<add> if(!scaffoldF.isEmpty()){
<add> addScf=scaffoldF.getFirst().getIndex();//getFirst: NoSuchElementException
<ide> changeHead(scaffoldF, scaffoldF.getFirst());
<del> }
<del>
<del> }
<del> scaffoldF = new Scaffold(contigs.get(headF));//????FIXME (is index matter when it comes to setHead???)
<add> }else
<add> scaffoldF = new Scaffold(contigs.get(headF));
<add>
<add> }
<ide> }
<ide> else if(secondDir == 1){
<ide> if(headF==headT){
<ide> ctg = scaffoldF.removeFirst();
<ide> }
<ide> }
<del> //set the remaining. FIXME
<add> //set the remaining
<ide> scaffoldT.trim();
<del> if(scaffoldF.size() > 0){
<del> scaffoldF.trim();
<del> addScf=scaffoldF.getLast().getIndex();
<add> scaffoldF.trim();
<add> if(!scaffoldF.isEmpty()){
<add> addScf=scaffoldF.getLast().getIndex(); //getLast: NoSuchElementException
<ide> changeHead(scaffoldF, scaffoldF.getLast());
<del> }
<del>
<del> }
<del> scaffoldF = new Scaffold(contigs.get(headF));//???FIXME
<add> }else
<add> scaffoldF = new Scaffold(contigs.get(headF));
<add>
<add> }
<ide> }
<ide> else
<ide> return false;
<ide> return true;
<ide> }
<ide> //change head of scaffold scf to newHead
<add> //TODO: tidy this!!!
<ide> public void changeHead(Scaffold scf, Contig newHead){
<ide> if(isRepeat(newHead)){
<ide> if(verbose) |
|
JavaScript | mit | 289e9c80daff3636c1e00d67851f05ea65075ff2 | 0 | wagerfield/colorgasm | (function(window, globalID) {
//----------------------------------------
// Vector
//----------------------------------------
var Vector = {
create: function(x, y) {
return {x:x||0, y:y||0};
},
identity: function(target) {
target.x = 0;
target.y = 0;
},
copy: function(target, a) {
target.x = a.x;
target.y = a.y;
},
subtract: function(target, a, b) {
target.x = a.x - b.x;
target.y = a.y - b.y;
},
add: function(target, a, b) {
target.x = a.x + b.x;
target.y = a.y + b.y;
},
scale: function(target, a, s) {
target.x = a.x * s;
target.y = a.y * s;
},
squaredLength: function(vector) {
var x = vector.x;
var y = vector.y;
return x*x + y*y;
},
length: function(vector) {
return Math.sqrt(this.squaredLength(vector));
},
normalise: function(target, a, opt_length) {
opt_length = opt_length || 1;
var l = this.squaredLength(a);
if (l > 0) {
l = opt_length / Math.sqrt(l);
this.scale(target, a, l);
} else {
this.identity(target);
}
return target;
},
rotate: function(target, a, angle) {
if (angle === 0) {
return this.copy(target, a);
} else {
var s = Math.sin(angle);
var c = Math.cos(angle);
var x = (a.x * c) - (a.y * s);
var y = (a.x * s) + (a.y * c);
target.x = x;
target.y = y;
return target;
}
}
};
//----------------------------------------
// Cord
//----------------------------------------
var Cord = function(radius, aOffset, bOffset) {
this.aOffset = aOffset || 0;
this.bOffset = bOffset || 0;
this.radius = radius || 10;
this._a = Vector.create();
this._b = Vector.create();
this.a = Vector.create();
this.b = Vector.create();
};
Cord.prototype = {
drawFoot: function(context, anchor) {
context.beginPath();
Vector.subtract(this._a, this.b, this.a);
Vector.rotate(this._a, this._a, HALF_PI);
Vector.normalise(this._a, this._a, this.radius);
Vector.subtract(this._b, anchor, this._a);
context.moveTo(this._b.x, this._b.y);
Vector.add(this._b, this._a, anchor);
context.lineTo(this._b.x, this._b.y);
context.stroke();
},
draw: function(context) {
context.beginPath();
context.moveTo(this.a.x, this.a.y);
context.lineTo(this.b.x, this.b.y);
context.stroke();
this.drawFoot(context, this.a);
this.drawFoot(context, this.b);
}
};
//----------------------------------------
// Deck
//----------------------------------------
var Deck = function(rpm) {
this.mtm = 1 / 1000 / 60;
this.rpm = rpm || 33;
this.rimRadius = 0;
this.pinRadius = 0;
this.rotation = 0;
this.x = 0;
this.y = 0;
};
Deck.prototype = {
update: function(time) {
},
draw: function(context) {
// Rim
context.beginPath();
context.arc(this.x, this.y, this.rimRadius, 0, TWO_PI, false);
context.stroke();
// Pin
context.beginPath();
context.arc(this.x, this.y, this.pinRadius, 0, TWO_PI, false);
context.stroke();
// Cord
// context.beginPath();
// context.moveTo.apply(this, this.polar(this.deck.rotation, this.deck.pin, this.deck.x, this.deck.y));
// context.lineTo.apply(this, this.polar(this.deck.rotation, this.deck.radius * 1, this.deck.x, this.deck.y));
// context.stroke();
}
};
//----------------------------------------
// Colorgasm
//----------------------------------------
var Colorgasm = function() {
this.palettes = {};
};
Colorgasm.prototype = {
setColorPalette: function(id, base, core, west, east) {
this.palettes[id] = {base:base, core:core, west:west, east:east};
return this.palettes[id];
},
getColorPalette: function(id) {
return this.palettes[id];
}
};
//----------------------------------------
// Sketch
//----------------------------------------
window[globalID] = Sketch.create({
container: document.getElementById('stage'),
setup: function() {
this.deck = new Deck();
this.mouse.cord = new Cord(20);
this.colorgasm = new Colorgasm();
this.setColorPalette(this.colorgasm.setColorPalette('main',
'#1E1A31', // Base
'#FFFFFF', // Core
[
'#FFE193',
'#FFB46B',
'#F98A75',
'#E2687C',
'#B14B77',
'#6B2A64'
],[
'#B9F7F5',
'#72D4E2',
'#5BAFCD',
'#518CBE',
'#4D64B0',
'#4C4690'
]));
},
setColorPalette: function(palette) {
if (this.palette !== palette) {
this.palette = palette;
this.container.style.backgroundColor = palette.base;
}
},
resize: function() {
this.centerX = Math.round(this.width * 0.5);
this.centerY = Math.round(this.height * 0.5);
// Position and resize deck
this.deck.x = this.centerX;
this.deck.y = this.centerY;
this.deck.rimRadius = Math.round(Math.min(this.centerX, this.centerY) * 0.7);
this.deck.pinRadius = Math.round(this.deck.rimRadius * 0.05);
this.draw();
},
update: function() {
Vector.copy(this.mouse.cord.a, this.deck);
Vector.copy(this.mouse.cord.b, this.mouse);
},
draw: function() {
// DECK
this.strokeStyle = this.palette.west[4];
this.deck.draw(this);
// MOUSE
if (this.dragging) {
this.strokeStyle = this.palette.west[2];
this.mouse.cord.draw(this);
}
},
mousedown: function() {
this.dragging = true;
},
mouseup: function() {
this.dragging = false;
},
hit: function(x, y, hx, hy, hw, hh) {
return x >= hx && x <= hx + hw && y >= hy && y <= hy + hh;
}
});
})(window, 'Colorgasm');
| assets/scripts/colorgasm.js | (function(window, globalID) {
//----------------------------------------
// Vector
//----------------------------------------
var Vector = {
create: function(x, y) {
return {x:x||0, y:y||0};
},
id: function(target) {
target.x = 0;
target.y = 0;
},
copy: function(target, a) {
target.x = a.x;
target.y = a.y;
},
sub: function(target, a, b) {
target.x = a.x - b.x;
target.y = a.y - b.y;
},
add: function(target, a, b) {
target.x = a.x + b.x;
target.y = a.y + b.y;
}
};
//----------------------------------------
// Cord
//----------------------------------------
var Cord = function(width, aOffset, bOffset) {
this.aOffset = aOffset || 0;
this.bOffset = bOffset || 0;
this.width = width || 10;
this.a = Vector.create();
this.b = Vector.create();
this.f = Vector.create();
};
Cord.prototype = {
draw: function(context) {
context.beginPath();
context.moveTo(this.a.x, this.a.y);
context.lineTo(this.b.x, this.b.y);
context.stroke();
// Vector.sub(this.z, this.b, this.a);
// Vector.rotate(this.z, HALF_PI);
}
};
//----------------------------------------
// Deck
//----------------------------------------
var Deck = function(rpm) {
this.mtm = 1 / 1000 / 60;
this.rpm = rpm || 33;
this.rimRadius = 0;
this.pinRadius = 0;
this.rotation = 0;
this.x = 0;
this.y = 0;
};
Deck.prototype = {
update: function(time) {
},
draw: function(context) {
// Rim
context.beginPath();
context.arc(this.x, this.y, this.rimRadius, 0, TWO_PI, false);
context.stroke();
// Pin
context.beginPath();
context.arc(this.x, this.y, this.pinRadius, 0, TWO_PI, false);
context.stroke();
// Cord
// context.beginPath();
// context.moveTo.apply(this, this.polar(this.deck.rotation, this.deck.pin, this.deck.x, this.deck.y));
// context.lineTo.apply(this, this.polar(this.deck.rotation, this.deck.radius * 1, this.deck.x, this.deck.y));
// context.stroke();
}
};
//----------------------------------------
// Colorgasm
//----------------------------------------
var Colorgasm = function() {
this.palettes = {};
};
Colorgasm.prototype = {
setColorPalette: function(id, base, core, west, east) {
this.palettes[id] = {base:base, core:core, west:west, east:east};
return this.palettes[id];
},
getColorPalette: function(id) {
return this.palettes[id];
}
};
//----------------------------------------
// Sketch
//----------------------------------------
Sketch.create({
container: document.getElementById('stage'),
setup: function() {
this.deck = new Deck();
this.mouse.cord = new Cord();
this.colorgasm = new Colorgasm();
this.setColorPalette(this.colorgasm.setColorPalette('main',
'#1E1A31', // Base
'#FFFFFF', // Core
[
'#FFE193',
'#FFB46B',
'#F98A75',
'#E2687C',
'#B14B77',
'#6B2A64'
],[
'#B9F7F5',
'#72D4E2',
'#5BAFCD',
'#518CBE',
'#4D64B0',
'#4C4690'
]));
},
setColorPalette: function(palette) {
if (this.palette !== palette) {
this.palette = palette;
this.container.style.backgroundColor = palette.base;
}
},
resize: function() {
this.centerX = Math.round(this.width * 0.5);
this.centerY = Math.round(this.height * 0.5);
// Position and resize deck
this.deck.x = this.centerX;
this.deck.y = this.centerY;
this.deck.rimRadius = Math.round(Math.min(this.centerX, this.centerY) * 0.7);
this.deck.pinRadius = Math.round(this.deck.rimRadius * 0.05);
},
update: function() {
Vector.copy(this.mouse.cord.a, this.deck);
Vector.copy(this.mouse.cord.b, this.mouse);
},
draw: function() {
// DECK
this.strokeStyle = this.palette.west[4];
this.deck.draw(this);
// MOUSE
if (this.dragging) {
this.strokeStyle = this.palette.west[2];
this.mouse.cord.draw(this);
}
},
mousedown: function() {
this.dragging = true;
},
mouseup: function() {
this.dragging = false;
},
hit: function(x, y, hx, hy, hw, hh) {
return x >= hx && x <= hx + hw && y >= hy && y <= hy + hh;
}
});
})(window, 'Colorgasm');
| :gb: Added rotate and normalise methods to Vector
| assets/scripts/colorgasm.js | :gb: Added rotate and normalise methods to Vector | <ide><path>ssets/scripts/colorgasm.js
<ide> create: function(x, y) {
<ide> return {x:x||0, y:y||0};
<ide> },
<del> id: function(target) {
<add> identity: function(target) {
<ide> target.x = 0;
<ide> target.y = 0;
<ide> },
<ide> target.x = a.x;
<ide> target.y = a.y;
<ide> },
<del> sub: function(target, a, b) {
<add> subtract: function(target, a, b) {
<ide> target.x = a.x - b.x;
<ide> target.y = a.y - b.y;
<ide> },
<ide> add: function(target, a, b) {
<ide> target.x = a.x + b.x;
<ide> target.y = a.y + b.y;
<add> },
<add> scale: function(target, a, s) {
<add> target.x = a.x * s;
<add> target.y = a.y * s;
<add> },
<add> squaredLength: function(vector) {
<add> var x = vector.x;
<add> var y = vector.y;
<add> return x*x + y*y;
<add> },
<add> length: function(vector) {
<add> return Math.sqrt(this.squaredLength(vector));
<add> },
<add> normalise: function(target, a, opt_length) {
<add> opt_length = opt_length || 1;
<add> var l = this.squaredLength(a);
<add> if (l > 0) {
<add> l = opt_length / Math.sqrt(l);
<add> this.scale(target, a, l);
<add> } else {
<add> this.identity(target);
<add> }
<add> return target;
<add> },
<add> rotate: function(target, a, angle) {
<add> if (angle === 0) {
<add> return this.copy(target, a);
<add> } else {
<add> var s = Math.sin(angle);
<add> var c = Math.cos(angle);
<add> var x = (a.x * c) - (a.y * s);
<add> var y = (a.x * s) + (a.y * c);
<add> target.x = x;
<add> target.y = y;
<add> return target;
<add> }
<ide> }
<ide> };
<ide>
<ide> // Cord
<ide> //----------------------------------------
<ide>
<del> var Cord = function(width, aOffset, bOffset) {
<add> var Cord = function(radius, aOffset, bOffset) {
<ide> this.aOffset = aOffset || 0;
<ide> this.bOffset = bOffset || 0;
<del> this.width = width || 10;
<add> this.radius = radius || 10;
<add> this._a = Vector.create();
<add> this._b = Vector.create();
<ide> this.a = Vector.create();
<ide> this.b = Vector.create();
<del> this.f = Vector.create();
<ide> };
<ide> Cord.prototype = {
<add> drawFoot: function(context, anchor) {
<add> context.beginPath();
<add> Vector.subtract(this._a, this.b, this.a);
<add> Vector.rotate(this._a, this._a, HALF_PI);
<add> Vector.normalise(this._a, this._a, this.radius);
<add> Vector.subtract(this._b, anchor, this._a);
<add> context.moveTo(this._b.x, this._b.y);
<add> Vector.add(this._b, this._a, anchor);
<add> context.lineTo(this._b.x, this._b.y);
<add> context.stroke();
<add> },
<ide> draw: function(context) {
<ide> context.beginPath();
<ide> context.moveTo(this.a.x, this.a.y);
<ide> context.lineTo(this.b.x, this.b.y);
<ide> context.stroke();
<del> // Vector.sub(this.z, this.b, this.a);
<del> // Vector.rotate(this.z, HALF_PI);
<add> this.drawFoot(context, this.a);
<add> this.drawFoot(context, this.b);
<ide> }
<ide> };
<ide>
<ide> // Sketch
<ide> //----------------------------------------
<ide>
<del> Sketch.create({
<add> window[globalID] = Sketch.create({
<ide>
<ide> container: document.getElementById('stage'),
<ide>
<ide> setup: function() {
<ide> this.deck = new Deck();
<del> this.mouse.cord = new Cord();
<add> this.mouse.cord = new Cord(20);
<ide> this.colorgasm = new Colorgasm();
<ide> this.setColorPalette(this.colorgasm.setColorPalette('main',
<ide> '#1E1A31', // Base
<ide> this.deck.y = this.centerY;
<ide> this.deck.rimRadius = Math.round(Math.min(this.centerX, this.centerY) * 0.7);
<ide> this.deck.pinRadius = Math.round(this.deck.rimRadius * 0.05);
<add> this.draw();
<ide> },
<ide>
<ide> update: function() { |
|
Java | apache-2.0 | fa401b2b2e859228ef60469266588852c7c89f0f | 0 | tony810430/flink,rmetzger/flink,twalthr/flink,rmetzger/flink,kl0u/flink,gyfora/flink,zentol/flink,kl0u/flink,gyfora/flink,StephanEwen/incubator-flink,rmetzger/flink,zjureel/flink,wwjiang007/flink,StephanEwen/incubator-flink,godfreyhe/flink,lincoln-lil/flink,apache/flink,gyfora/flink,zentol/flink,clarkyzl/flink,xccui/flink,wwjiang007/flink,zentol/flink,StephanEwen/incubator-flink,clarkyzl/flink,zjureel/flink,gyfora/flink,StephanEwen/incubator-flink,wwjiang007/flink,zjureel/flink,apache/flink,twalthr/flink,tony810430/flink,tony810430/flink,lincoln-lil/flink,lincoln-lil/flink,godfreyhe/flink,twalthr/flink,twalthr/flink,kl0u/flink,twalthr/flink,apache/flink,wwjiang007/flink,xccui/flink,tillrohrmann/flink,godfreyhe/flink,twalthr/flink,lincoln-lil/flink,rmetzger/flink,zentol/flink,rmetzger/flink,zjureel/flink,twalthr/flink,kl0u/flink,godfreyhe/flink,apache/flink,gyfora/flink,gyfora/flink,zjureel/flink,clarkyzl/flink,kl0u/flink,tony810430/flink,StephanEwen/incubator-flink,xccui/flink,gyfora/flink,StephanEwen/incubator-flink,tony810430/flink,tillrohrmann/flink,godfreyhe/flink,xccui/flink,rmetzger/flink,apache/flink,wwjiang007/flink,rmetzger/flink,tillrohrmann/flink,godfreyhe/flink,zjureel/flink,wwjiang007/flink,tillrohrmann/flink,tony810430/flink,lincoln-lil/flink,xccui/flink,godfreyhe/flink,kl0u/flink,xccui/flink,tillrohrmann/flink,zentol/flink,lincoln-lil/flink,zjureel/flink,clarkyzl/flink,zentol/flink,clarkyzl/flink,tillrohrmann/flink,tony810430/flink,wwjiang007/flink,zentol/flink,tillrohrmann/flink,xccui/flink,apache/flink,apache/flink,lincoln-lil/flink | /*
* 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.flink.runtime.concurrent;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.runtime.util.FatalExitExceptionHandler;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.function.RunnableWithException;
import org.apache.flink.util.function.SupplierWithException;
import akka.dispatch.OnComplete;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import scala.concurrent.Future;
import static org.apache.flink.util.Preconditions.checkCompletedNormally;
import static org.apache.flink.util.Preconditions.checkNotNull;
/** A collection of utilities that expand the usage of {@link CompletableFuture}. */
public class FutureUtils {
private static final CompletableFuture<Void> COMPLETED_VOID_FUTURE =
CompletableFuture.completedFuture(null);
/**
* Returns a completed future of type {@link Void}.
*
* @return a completed future of type {@link Void}
*/
public static CompletableFuture<Void> completedVoidFuture() {
return COMPLETED_VOID_FUTURE;
}
/**
* Fakes asynchronous execution by immediately executing the operation and completing the
* supplied future either noramlly or exceptionally.
*
* @param operation to executed
* @param <T> type of the result
*/
public static <T> void completeFromCallable(
CompletableFuture<T> future, Callable<T> operation) {
try {
future.complete(operation.call());
} catch (Exception e) {
future.completeExceptionally(e);
}
}
// ------------------------------------------------------------------------
// retrying operations
// ------------------------------------------------------------------------
/**
* Retry the given operation the given number of times in case of a failure.
*
* @param operation to executed
* @param retries if the operation failed
* @param executor to use to run the futures
* @param <T> type of the result
* @return Future containing either the result of the operation or a {@link RetryException}
*/
public static <T> CompletableFuture<T> retry(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Executor executor) {
return retry(operation, retries, ignore -> true, executor);
}
/**
* Retry the given operation the given number of times in case of a failure only when an
* exception is retryable.
*
* @param operation to executed
* @param retries if the operation failed
* @param retryPredicate Predicate to test whether an exception is retryable
* @param executor to use to run the futures
* @param <T> type of the result
* @return Future containing either the result of the operation or a {@link RetryException}
*/
public static <T> CompletableFuture<T> retry(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Predicate<Throwable> retryPredicate,
final Executor executor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retryOperation(resultFuture, operation, retries, retryPredicate, executor);
return resultFuture;
}
/**
* Helper method which retries the provided operation in case of a failure.
*
* @param resultFuture to complete
* @param operation to retry
* @param retries until giving up
* @param retryPredicate Predicate to test whether an exception is retryable
* @param executor to run the futures
* @param <T> type of the future's result
*/
private static <T> void retryOperation(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Predicate<Throwable> retryPredicate,
final Executor executor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationFuture = operation.get();
operationFuture.whenCompleteAsync(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
throwable = ExceptionUtils.stripExecutionException(throwable);
if (!retryPredicate.test(throwable)) {
resultFuture.completeExceptionally(
new RetryException(
"Stopped retrying the operation because the error is not "
+ "retryable.",
throwable));
} else {
if (retries > 0) {
retryOperation(
resultFuture,
operation,
retries - 1,
retryPredicate,
executor);
} else {
resultFuture.completeExceptionally(
new RetryException(
"Could not complete the operation. Number of retries "
+ "has been exhausted.",
throwable));
}
}
}
} else {
resultFuture.complete(t);
}
},
executor);
resultFuture.whenComplete((t, throwable) -> operationFuture.cancel(false));
}
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retries number of retries
* @param retryDelay delay between retries
* @param retryPredicate Predicate to test whether an exception is retryable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Time retryDelay,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(
operation,
new FixedRetryStrategy(retries, Duration.ofMillis(retryDelay.toMilliseconds())),
retryPredicate,
scheduledExecutor);
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retryStrategy the RetryStrategy
* @param retryPredicate Predicate to test whether an exception is retryable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retryOperationWithDelay(
resultFuture, operation, retryStrategy, retryPredicate, scheduledExecutor);
return resultFuture;
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retries number of retries
* @param retryDelay delay between retries
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Time retryDelay,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(
operation,
new FixedRetryStrategy(retries, Duration.ofMillis(retryDelay.toMilliseconds())),
scheduledExecutor);
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retryStrategy the RetryStrategy
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(operation, retryStrategy, (throwable) -> true, scheduledExecutor);
}
/**
* Schedule the operation with the given delay.
*
* @param operation to schedule
* @param delay delay to schedule
* @param scheduledExecutor executor to be used for the operation
* @return Future which schedules the given operation with given delay.
*/
public static CompletableFuture<Void> scheduleWithDelay(
final Runnable operation, final Time delay, final ScheduledExecutor scheduledExecutor) {
Supplier<Void> operationSupplier =
() -> {
operation.run();
return null;
};
return scheduleWithDelay(operationSupplier, delay, scheduledExecutor);
}
/**
* Schedule the operation with the given delay.
*
* @param operation to schedule
* @param delay delay to schedule
* @param scheduledExecutor executor to be used for the operation
* @param <T> type of the result
* @return Future which schedules the given operation with given delay.
*/
public static <T> CompletableFuture<T> scheduleWithDelay(
final Supplier<T> operation,
final Time delay,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
() -> {
try {
resultFuture.complete(operation.get());
} catch (Throwable t) {
resultFuture.completeExceptionally(t);
}
},
delay.getSize(),
delay.getUnit());
resultFuture.whenComplete(
(t, throwable) -> {
if (!scheduledFuture.isDone()) {
scheduledFuture.cancel(false);
}
});
return resultFuture;
}
private static <T> void retryOperationWithDelay(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationResultFuture = operation.get();
operationResultFuture.whenComplete(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
throwable = ExceptionUtils.stripExecutionException(throwable);
if (!retryPredicate.test(throwable)) {
resultFuture.completeExceptionally(throwable);
} else if (retryStrategy.getNumRemainingRetries() > 0) {
long retryDelayMillis =
retryStrategy.getRetryDelay().toMillis();
final ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
(Runnable)
() ->
retryOperationWithDelay(
resultFuture,
operation,
retryStrategy
.getNextRetryStrategy(),
retryPredicate,
scheduledExecutor),
retryDelayMillis,
TimeUnit.MILLISECONDS);
resultFuture.whenComplete(
(innerT, innerThrowable) ->
scheduledFuture.cancel(false));
} else {
RetryException retryException =
new RetryException(
"Could not complete the operation. Number of retries has been exhausted.",
throwable);
resultFuture.completeExceptionally(retryException);
}
}
} else {
resultFuture.complete(t);
}
});
resultFuture.whenComplete((t, throwable) -> operationResultFuture.cancel(false));
}
}
/**
* Retry the given operation with the given delay in between successful completions where the
* result does not match a given predicate.
*
* @param operation to retry
* @param retryDelay delay between retries
* @param deadline A deadline that specifies at what point we should stop retrying
* @param acceptancePredicate Predicate to test whether the result is acceptable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case the predicate isn't matched
*/
public static <T> CompletableFuture<T> retrySuccessfulWithDelay(
final Supplier<CompletableFuture<T>> operation,
final Time retryDelay,
final Deadline deadline,
final Predicate<T> acceptancePredicate,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retrySuccessfulOperationWithDelay(
resultFuture,
operation,
retryDelay,
deadline,
acceptancePredicate,
scheduledExecutor);
return resultFuture;
}
private static <T> void retrySuccessfulOperationWithDelay(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final Time retryDelay,
final Deadline deadline,
final Predicate<T> acceptancePredicate,
final ScheduledExecutor scheduledExecutor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationResultFuture = operation.get();
operationResultFuture.whenComplete(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
resultFuture.completeExceptionally(throwable);
}
} else {
if (acceptancePredicate.test(t)) {
resultFuture.complete(t);
} else if (deadline.hasTimeLeft()) {
final ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
(Runnable)
() ->
retrySuccessfulOperationWithDelay(
resultFuture,
operation,
retryDelay,
deadline,
acceptancePredicate,
scheduledExecutor),
retryDelay.toMilliseconds(),
TimeUnit.MILLISECONDS);
resultFuture.whenComplete(
(innerT, innerThrowable) -> scheduledFuture.cancel(false));
} else {
resultFuture.completeExceptionally(
new RetryException(
"Could not satisfy the predicate within the allowed time."));
}
}
});
resultFuture.whenComplete((t, throwable) -> operationResultFuture.cancel(false));
}
}
/**
* Exception with which the returned future is completed if the {@link #retry(Supplier, int,
* Executor)} operation fails.
*/
public static class RetryException extends Exception {
private static final long serialVersionUID = 3613470781274141862L;
public RetryException(String message) {
super(message);
}
public RetryException(String message, Throwable cause) {
super(message, cause);
}
public RetryException(Throwable cause) {
super(cause);
}
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future, long timeout, TimeUnit timeUnit) {
return orTimeout(future, timeout, timeUnit, Executors.directExecutor(), null);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutMsg timeout message for exception
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
@Nullable String timeoutMsg) {
return orTimeout(future, timeout, timeUnit, Executors.directExecutor(), timeoutMsg);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutFailExecutor executor that will complete the future exceptionally after the
* timeout is reached
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
Executor timeoutFailExecutor) {
return orTimeout(future, timeout, timeUnit, timeoutFailExecutor, null);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutFailExecutor executor that will complete the future exceptionally after the
* timeout is reached
* @param timeoutMsg timeout message for exception
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
Executor timeoutFailExecutor,
@Nullable String timeoutMsg) {
if (!future.isDone()) {
final ScheduledFuture<?> timeoutFuture =
Delayer.delay(
() -> timeoutFailExecutor.execute(new Timeout(future, timeoutMsg)),
timeout,
timeUnit);
future.whenComplete(
(T value, Throwable throwable) -> {
if (!timeoutFuture.isDone()) {
timeoutFuture.cancel(false);
}
});
}
return future;
}
// ------------------------------------------------------------------------
// Future actions
// ------------------------------------------------------------------------
/**
* Run the given {@code RunnableFuture} if it is not done, and then retrieves its result.
*
* @param future to run if not done and get
* @param <T> type of the result
* @return the result after running the future
* @throws ExecutionException if a problem occurred
* @throws InterruptedException if the current thread has been interrupted
*/
public static <T> T runIfNotDoneAndGet(RunnableFuture<T> future)
throws ExecutionException, InterruptedException {
if (null == future) {
return null;
}
if (!future.isDone()) {
future.run();
}
return future.get();
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwards(
CompletableFuture<?> future, RunnableWithException runnable) {
return runAfterwardsAsync(future, runnable, Executors.directExecutor());
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwardsAsync(
CompletableFuture<?> future, RunnableWithException runnable) {
return runAfterwardsAsync(future, runnable, ForkJoinPool.commonPool());
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @param executor to run the given action
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwardsAsync(
CompletableFuture<?> future, RunnableWithException runnable, Executor executor) {
final CompletableFuture<Void> resultFuture = new CompletableFuture<>();
future.whenCompleteAsync(
(Object ignored, Throwable throwable) -> {
try {
runnable.run();
} catch (Throwable e) {
throwable = ExceptionUtils.firstOrSuppressed(e, throwable);
}
if (throwable != null) {
resultFuture.completeExceptionally(throwable);
} else {
resultFuture.complete(null);
}
},
executor);
return resultFuture;
}
/**
* Run the given asynchronous action after the completion of the given future. The given future
* can be completed normally or exceptionally. In case of an exceptional completion, the
* asynchronous action's exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param composedAction asynchronous action which is triggered after the future's completion
* @return Future which is completed after the asynchronous action has completed. This future
* can contain an exception if an error occurred in the given future or asynchronous action.
*/
public static CompletableFuture<Void> composeAfterwards(
CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction) {
final CompletableFuture<Void> resultFuture = new CompletableFuture<>();
future.whenComplete(
(Object outerIgnored, Throwable outerThrowable) -> {
final CompletableFuture<?> composedActionFuture = composedAction.get();
composedActionFuture.whenComplete(
(Object innerIgnored, Throwable innerThrowable) -> {
if (innerThrowable != null) {
resultFuture.completeExceptionally(
ExceptionUtils.firstOrSuppressed(
innerThrowable, outerThrowable));
} else if (outerThrowable != null) {
resultFuture.completeExceptionally(outerThrowable);
} else {
resultFuture.complete(null);
}
});
});
return resultFuture;
}
// ------------------------------------------------------------------------
// composing futures
// ------------------------------------------------------------------------
/**
* Creates a future that is complete once multiple other futures completed. The future fails
* (completes exceptionally) once one of the futures in the conjunction fails. Upon successful
* completion, the future returns the collection of the futures' results.
*
* <p>The ConjunctFuture gives access to how many Futures in the conjunction have already
* completed successfully, via {@link ConjunctFuture#getNumFuturesCompleted()}.
*
* @param futures The futures that make up the conjunction. No null entries are allowed.
* @return The ConjunctFuture that completes once all given futures are complete (or one fails).
*/
public static <T> ConjunctFuture<Collection<T>> combineAll(
Collection<? extends CompletableFuture<? extends T>> futures) {
checkNotNull(futures, "futures");
return new ResultConjunctFuture<>(futures);
}
/**
* Creates a future that is complete once all of the given futures have completed. The future
* fails (completes exceptionally) once one of the given futures fails.
*
* <p>The ConjunctFuture gives access to how many Futures have already completed successfully,
* via {@link ConjunctFuture#getNumFuturesCompleted()}.
*
* @param futures The futures to wait on. No null entries are allowed.
* @return The WaitingFuture that completes once all given futures are complete (or one fails).
*/
public static ConjunctFuture<Void> waitForAll(
Collection<? extends CompletableFuture<?>> futures) {
checkNotNull(futures, "futures");
return new WaitingConjunctFuture(futures);
}
/**
* A future that is complete once multiple other futures completed. The futures are not
* necessarily of the same type. The ConjunctFuture fails (completes exceptionally) once one of
* the Futures in the conjunction fails.
*
* <p>The advantage of using the ConjunctFuture over chaining all the futures (such as via
* {@link CompletableFuture#thenCombine(CompletionStage, BiFunction)} )}) is that ConjunctFuture
* also tracks how many of the Futures are already complete.
*/
public abstract static class ConjunctFuture<T> extends CompletableFuture<T> {
/**
* Gets the total number of Futures in the conjunction.
*
* @return The total number of Futures in the conjunction.
*/
public abstract int getNumFuturesTotal();
/**
* Gets the number of Futures in the conjunction that are already complete.
*
* @return The number of Futures in the conjunction that are already complete
*/
public abstract int getNumFuturesCompleted();
}
/**
* The implementation of the {@link ConjunctFuture} which returns its Futures' result as a
* collection.
*/
private static class ResultConjunctFuture<T> extends ConjunctFuture<Collection<T>> {
/** The total number of futures in the conjunction. */
private final int numTotal;
/** The number of futures in the conjunction that are already complete. */
private final AtomicInteger numCompleted = new AtomicInteger(0);
/** The set of collected results so far. */
private final T[] results;
/**
* The function that is attached to all futures in the conjunction. Once a future is
* complete, this function tracks the completion or fails the conjunct.
*/
private void handleCompletedFuture(int index, T value, Throwable throwable) {
if (throwable != null) {
completeExceptionally(throwable);
} else {
/**
* This {@link #results} update itself is not synchronised in any way and it's fine
* because:
*
* <ul>
* <li>There is a happens-before relationship for each thread (that is completing
* the future) between setting {@link #results} and incrementing {@link
* #numCompleted}.
* <li>Each thread is updating uniquely different field of the {@link #results}
* array.
* <li>There is a happens-before relationship between all of the writing threads
* and the last one thread (thanks to the {@code
* numCompleted.incrementAndGet() == numTotal} check.
* <li>The last thread will be completing the future, so it has transitively
* happens-before relationship with all of preceding updated/writes to {@link
* #results}.
* <li>{@link AtomicInteger#incrementAndGet} is an equivalent of both volatile
* read & write
* </ul>
*/
results[index] = value;
if (numCompleted.incrementAndGet() == numTotal) {
complete(Arrays.asList(results));
}
}
}
@SuppressWarnings("unchecked")
ResultConjunctFuture(Collection<? extends CompletableFuture<? extends T>> resultFutures) {
this.numTotal = resultFutures.size();
results = (T[]) new Object[numTotal];
if (resultFutures.isEmpty()) {
complete(Collections.emptyList());
} else {
int counter = 0;
for (CompletableFuture<? extends T> future : resultFutures) {
final int index = counter;
counter++;
future.whenComplete(
(value, throwable) -> handleCompletedFuture(index, value, throwable));
}
}
}
@Override
public int getNumFuturesTotal() {
return numTotal;
}
@Override
public int getNumFuturesCompleted() {
return numCompleted.get();
}
}
/**
* Implementation of the {@link ConjunctFuture} interface which waits only for the completion of
* its futures and does not return their values.
*/
private static final class WaitingConjunctFuture extends ConjunctFuture<Void> {
/** Number of completed futures. */
private final AtomicInteger numCompleted = new AtomicInteger(0);
/** Total number of futures to wait on. */
private final int numTotal;
/**
* Method which increments the atomic completion counter and completes or fails the
* WaitingFutureImpl.
*/
private void handleCompletedFuture(Object ignored, Throwable throwable) {
if (throwable == null) {
if (numTotal == numCompleted.incrementAndGet()) {
complete(null);
}
} else {
completeExceptionally(throwable);
}
}
private WaitingConjunctFuture(Collection<? extends CompletableFuture<?>> futures) {
this.numTotal = futures.size();
if (futures.isEmpty()) {
complete(null);
} else {
for (java.util.concurrent.CompletableFuture<?> future : futures) {
future.whenComplete(this::handleCompletedFuture);
}
}
}
@Override
public int getNumFuturesTotal() {
return numTotal;
}
@Override
public int getNumFuturesCompleted() {
return numCompleted.get();
}
}
/**
* Creates a {@link ConjunctFuture} which is only completed after all given futures have
* completed. Unlike {@link FutureUtils#waitForAll(Collection)}, the resulting future won't be
* completed directly if one of the given futures is completed exceptionally. Instead, all
* occurring exception will be collected and combined to a single exception. If at least on
* exception occurs, then the resulting future will be completed exceptionally.
*
* @param futuresToComplete futures to complete
* @return Future which is completed after all given futures have been completed.
*/
public static ConjunctFuture<Void> completeAll(
Collection<? extends CompletableFuture<?>> futuresToComplete) {
return new CompletionConjunctFuture(futuresToComplete);
}
/**
* {@link ConjunctFuture} implementation which is completed after all the given futures have
* been completed. Exceptional completions of the input futures will be recorded but it won't
* trigger the early completion of this future.
*/
private static final class CompletionConjunctFuture extends ConjunctFuture<Void> {
private final Object lock = new Object();
private final int numFuturesTotal;
private int futuresCompleted;
private Throwable globalThrowable;
private CompletionConjunctFuture(
Collection<? extends CompletableFuture<?>> futuresToComplete) {
numFuturesTotal = futuresToComplete.size();
futuresCompleted = 0;
globalThrowable = null;
if (futuresToComplete.isEmpty()) {
complete(null);
} else {
for (CompletableFuture<?> completableFuture : futuresToComplete) {
completableFuture.whenComplete(this::completeFuture);
}
}
}
private void completeFuture(Object ignored, Throwable throwable) {
synchronized (lock) {
futuresCompleted++;
if (throwable != null) {
globalThrowable = ExceptionUtils.firstOrSuppressed(throwable, globalThrowable);
}
if (futuresCompleted == numFuturesTotal) {
if (globalThrowable != null) {
completeExceptionally(globalThrowable);
} else {
complete(null);
}
}
}
}
@Override
public int getNumFuturesTotal() {
return numFuturesTotal;
}
@Override
public int getNumFuturesCompleted() {
synchronized (lock) {
return futuresCompleted;
}
}
}
// ------------------------------------------------------------------------
// Helper methods
// ------------------------------------------------------------------------
/**
* Returns an exceptionally completed {@link CompletableFuture}.
*
* @param cause to complete the future with
* @param <T> type of the future
* @return An exceptionally completed CompletableFuture
*/
public static <T> CompletableFuture<T> completedExceptionally(Throwable cause) {
CompletableFuture<T> result = new CompletableFuture<>();
result.completeExceptionally(cause);
return result;
}
/**
* Returns a future which is completed with the result of the {@link SupplierWithException}.
*
* @param supplier to provide the future's value
* @param executor to execute the supplier
* @param <T> type of the result
* @return Future which is completed with the value of the supplier
*/
public static <T> CompletableFuture<T> supplyAsync(
SupplierWithException<T, ?> supplier, Executor executor) {
return CompletableFuture.supplyAsync(
() -> {
try {
return supplier.get();
} catch (Throwable e) {
throw new CompletionException(e);
}
},
executor);
}
/**
* Converts Flink time into a {@link Duration}.
*
* @param time to convert into a Duration
* @return Duration with the length of the given time
*/
public static Duration toDuration(Time time) {
return Duration.ofMillis(time.toMilliseconds());
}
// ------------------------------------------------------------------------
// Converting futures
// ------------------------------------------------------------------------
/**
* Converts a Scala {@link Future} to a {@link CompletableFuture}.
*
* @param scalaFuture to convert to a Java 8 CompletableFuture
* @param <T> type of the future value
* @param <U> type of the original future
* @return Java 8 CompletableFuture
*/
public static <T, U extends T> CompletableFuture<T> toJava(Future<U> scalaFuture) {
final CompletableFuture<T> result = new CompletableFuture<>();
scalaFuture.onComplete(
new OnComplete<U>() {
@Override
public void onComplete(Throwable failure, U success) {
if (failure != null) {
result.completeExceptionally(failure);
} else {
result.complete(success);
}
}
},
Executors.directExecutionContext());
return result;
}
/**
* This function takes a {@link CompletableFuture} and a function to apply to this future. If
* the input future is already done, this function returns {@link
* CompletableFuture#thenApply(Function)}. Otherwise, the return value is {@link
* CompletableFuture#thenApplyAsync(Function, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to apply.
* @param executor the executor to run the apply function if the future is not yet done.
* @param applyFun the function to apply.
* @param <IN> type of the input future.
* @param <OUT> type of the output future.
* @return a completable future that is applying the given function to the input future.
*/
public static <IN, OUT> CompletableFuture<OUT> thenApplyAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Function<? super IN, ? extends OUT> applyFun) {
return completableFuture.isDone()
? completableFuture.thenApply(applyFun)
: completableFuture.thenApplyAsync(applyFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a function to compose with this future.
* If the input future is already done, this function returns {@link
* CompletableFuture#thenCompose(Function)}. Otherwise, the return value is {@link
* CompletableFuture#thenComposeAsync(Function, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to compose.
* @param executor the executor to run the compose function if the future is not yet done.
* @param composeFun the function to compose.
* @param <IN> type of the input future.
* @param <OUT> type of the output future.
* @return a completable future that is a composition of the input future and the function.
*/
public static <IN, OUT> CompletableFuture<OUT> thenComposeAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Function<? super IN, ? extends CompletionStage<OUT>> composeFun) {
return completableFuture.isDone()
? completableFuture.thenCompose(composeFun)
: completableFuture.thenComposeAsync(composeFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a bi-consumer to call on completion of
* this future. If the input future is already done, this function returns {@link
* CompletableFuture#whenComplete(BiConsumer)}. Otherwise, the return value is {@link
* CompletableFuture#whenCompleteAsync(BiConsumer, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #whenComplete.
* @param executor the executor to run the whenComplete function if the future is not yet done.
* @param whenCompleteFun the bi-consumer function to call when the future is completed.
* @param <IN> type of the input future.
* @return the new completion stage.
*/
public static <IN> CompletableFuture<IN> whenCompleteAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
BiConsumer<? super IN, ? super Throwable> whenCompleteFun) {
return completableFuture.isDone()
? completableFuture.whenComplete(whenCompleteFun)
: completableFuture.whenCompleteAsync(whenCompleteFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a consumer to accept the result of this
* future. If the input future is already done, this function returns {@link
* CompletableFuture#thenAccept(Consumer)}. Otherwise, the return value is {@link
* CompletableFuture#thenAcceptAsync(Consumer, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #thenAccept.
* @param executor the executor to run the thenAccept function if the future is not yet done.
* @param consumer the consumer function to call when the future is completed.
* @param <IN> type of the input future.
* @return the new completion stage.
*/
public static <IN> CompletableFuture<Void> thenAcceptAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Consumer<? super IN> consumer) {
return completableFuture.isDone()
? completableFuture.thenAccept(consumer)
: completableFuture.thenAcceptAsync(consumer, executor);
}
/**
* This function takes a {@link CompletableFuture} and a handler function for the result of this
* future. If the input future is already done, this function returns {@link
* CompletableFuture#handle(BiFunction)}. Otherwise, the return value is {@link
* CompletableFuture#handleAsync(BiFunction, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #handle.
* @param executor the executor to run the handle function if the future is not yet done.
* @param handler the handler function to call when the future is completed.
* @param <IN> type of the handler input argument.
* @param <OUT> type of the handler return value.
* @return the new completion stage.
*/
public static <IN, OUT> CompletableFuture<OUT> handleAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
BiFunction<? super IN, Throwable, ? extends OUT> handler) {
return completableFuture.isDone()
? completableFuture.handle(handler)
: completableFuture.handleAsync(handler, executor);
}
/** @return true if future has completed normally, false otherwise. */
public static boolean isCompletedNormally(CompletableFuture<?> future) {
return future.isDone() && !future.isCompletedExceptionally();
}
/**
* Perform check state that future has completed normally and return the result.
*
* @return the result of completable future.
* @throws IllegalStateException Thrown, if future has not completed or it has completed
* exceptionally.
*/
public static <T> T checkStateAndGet(CompletableFuture<T> future) {
checkCompletedNormally(future);
return getWithoutException(future);
}
/**
* Gets the result of a completable future without any exception thrown.
*
* @param future the completable future specified.
* @param <T> the type of result
* @return the result of completable future, or null if it's unfinished or finished
* exceptionally
*/
@Nullable
public static <T> T getWithoutException(CompletableFuture<T> future) {
if (isCompletedNormally(future)) {
try {
return future.get();
} catch (InterruptedException | ExecutionException ignored) {
}
}
return null;
}
/**
* @return the result of completable future, or the defaultValue if it has not yet completed.
*/
public static <T> T getOrDefault(CompletableFuture<T> future, T defaultValue) {
T value = getWithoutException(future);
return value == null ? defaultValue : value;
}
/** Runnable to complete the given future with a {@link TimeoutException}. */
private static final class Timeout implements Runnable {
private final CompletableFuture<?> future;
private final String timeoutMsg;
private Timeout(CompletableFuture<?> future, @Nullable String timeoutMsg) {
this.future = checkNotNull(future);
this.timeoutMsg = timeoutMsg;
}
@Override
public void run() {
future.completeExceptionally(new TimeoutException(timeoutMsg));
}
}
/**
* Delay scheduler used to timeout futures.
*
* <p>This class creates a singleton scheduler used to run the provided actions.
*/
private enum Delayer {
;
static final ScheduledThreadPoolExecutor DELAYER =
new ScheduledThreadPoolExecutor(
1, new ExecutorThreadFactory("FlinkCompletableFutureDelayScheduler"));
/**
* Delay the given action by the given delay.
*
* @param runnable to execute after the given delay
* @param delay after which to execute the runnable
* @param timeUnit time unit of the delay
* @return Future of the scheduled action
*/
private static ScheduledFuture<?> delay(Runnable runnable, long delay, TimeUnit timeUnit) {
checkNotNull(runnable);
checkNotNull(timeUnit);
return DELAYER.schedule(runnable, delay, timeUnit);
}
}
/**
* Asserts that the given {@link CompletableFuture} is not completed exceptionally. If the
* future is completed exceptionally, then it will call the {@link FatalExitExceptionHandler}.
*
* @param completableFuture to assert for no exceptions
*/
public static void assertNoException(CompletableFuture<?> completableFuture) {
handleUncaughtException(completableFuture, FatalExitExceptionHandler.INSTANCE);
}
/**
* Checks that the given {@link CompletableFuture} is not completed exceptionally. If the future
* is completed exceptionally, then it will call the given uncaught exception handler.
*
* @param completableFuture to assert for no exceptions
* @param uncaughtExceptionHandler to call if the future is completed exceptionally
*/
public static void handleUncaughtException(
CompletableFuture<?> completableFuture,
Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
checkNotNull(completableFuture)
.whenComplete(
(ignored, throwable) -> {
if (throwable != null) {
uncaughtExceptionHandler.uncaughtException(
Thread.currentThread(), throwable);
}
});
}
/**
* Forwards the value from the source future to the target future.
*
* @param source future to forward the value from
* @param target future to forward the value to
* @param <T> type of the value
*/
public static <T> void forward(CompletableFuture<T> source, CompletableFuture<T> target) {
source.whenComplete(forwardTo(target));
}
/**
* Forwards the value from the source future to the target future using the provided executor.
*
* @param source future to forward the value from
* @param target future to forward the value to
* @param executor executor to forward the source value to the target future
* @param <T> type of the value
*/
public static <T> void forwardAsync(
CompletableFuture<T> source, CompletableFuture<T> target, Executor executor) {
source.whenCompleteAsync(forwardTo(target), executor);
}
/**
* Throws the causing exception if the given future is completed exceptionally, otherwise do
* nothing.
*
* @param future the future to check.
* @throws Exception when the future is completed exceptionally.
*/
public static void throwIfCompletedExceptionally(CompletableFuture<?> future) throws Exception {
if (future.isCompletedExceptionally()) {
future.get();
}
}
private static <T> BiConsumer<T, Throwable> forwardTo(CompletableFuture<T> target) {
return (value, throwable) -> {
if (throwable != null) {
target.completeExceptionally(throwable);
} else {
target.complete(value);
}
};
}
}
| flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.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.flink.runtime.concurrent;
import org.apache.flink.api.common.time.Deadline;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.runtime.util.FatalExitExceptionHandler;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.function.RunnableWithException;
import org.apache.flink.util.function.SupplierWithException;
import akka.dispatch.OnComplete;
import javax.annotation.Nullable;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import scala.concurrent.Future;
import static org.apache.flink.util.Preconditions.checkCompletedNormally;
import static org.apache.flink.util.Preconditions.checkNotNull;
/** A collection of utilities that expand the usage of {@link CompletableFuture}. */
public class FutureUtils {
private static final CompletableFuture<Void> COMPLETED_VOID_FUTURE =
CompletableFuture.completedFuture(null);
/**
* Returns a completed future of type {@link Void}.
*
* @return a completed future of type {@link Void}
*/
public static CompletableFuture<Void> completedVoidFuture() {
return COMPLETED_VOID_FUTURE;
}
/**
* Fakes asynchronous execution by immediately executing the operation and completing the
* supplied future either noramlly or exceptionally.
*
* @param operation to executed
* @param <T> type of the result
*/
public static <T> void completeFromCallable(
CompletableFuture<T> future, Callable<T> operation) {
try {
future.complete(operation.call());
} catch (Exception e) {
future.completeExceptionally(e);
}
}
// ------------------------------------------------------------------------
// retrying operations
// ------------------------------------------------------------------------
/**
* Retry the given operation the given number of times in case of a failure.
*
* @param operation to executed
* @param retries if the operation failed
* @param executor to use to run the futures
* @param <T> type of the result
* @return Future containing either the result of the operation or a {@link RetryException}
*/
public static <T> CompletableFuture<T> retry(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Executor executor) {
return retry(operation, retries, ignore -> true, executor);
}
/**
* Retry the given operation the given number of times in case of a failure only when an
* exception is retryable.
*
* @param operation to executed
* @param retries if the operation failed
* @param retryPredicate Predicate to test whether an exception is retryable
* @param executor to use to run the futures
* @param <T> type of the result
* @return Future containing either the result of the operation or a {@link RetryException}
*/
public static <T> CompletableFuture<T> retry(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Predicate<Throwable> retryPredicate,
final Executor executor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retryOperation(resultFuture, operation, retries, retryPredicate, executor);
return resultFuture;
}
/**
* Helper method which retries the provided operation in case of a failure.
*
* @param resultFuture to complete
* @param operation to retry
* @param retries until giving up
* @param retryPredicate Predicate to test whether an exception is retryable
* @param executor to run the futures
* @param <T> type of the future's result
*/
private static <T> void retryOperation(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Predicate<Throwable> retryPredicate,
final Executor executor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationFuture = operation.get();
operationFuture.whenCompleteAsync(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
throwable = ExceptionUtils.stripExecutionException(throwable);
if (!retryPredicate.test(throwable)) {
resultFuture.completeExceptionally(
new RetryException(
"Stopped retrying the operation because the error is not "
+ "retryable.",
throwable));
} else {
if (retries > 0) {
retryOperation(
resultFuture,
operation,
retries - 1,
retryPredicate,
executor);
} else {
resultFuture.completeExceptionally(
new RetryException(
"Could not complete the operation. Number of retries "
+ "has been exhausted.",
throwable));
}
}
}
} else {
resultFuture.complete(t);
}
},
executor);
resultFuture.whenComplete((t, throwable) -> operationFuture.cancel(false));
}
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retries number of retries
* @param retryDelay delay between retries
* @param retryPredicate Predicate to test whether an exception is retryable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Time retryDelay,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(
operation,
new FixedRetryStrategy(retries, Duration.ofMillis(retryDelay.toMilliseconds())),
retryPredicate,
scheduledExecutor);
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retryStrategy the RetryStrategy
* @param retryPredicate Predicate to test whether an exception is retryable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retryOperationWithDelay(
resultFuture, operation, retryStrategy, retryPredicate, scheduledExecutor);
return resultFuture;
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retries number of retries
* @param retryDelay delay between retries
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final int retries,
final Time retryDelay,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(
operation,
new FixedRetryStrategy(retries, Duration.ofMillis(retryDelay.toMilliseconds())),
scheduledExecutor);
}
/**
* Retry the given operation with the given delay in between failures.
*
* @param operation to retry
* @param retryStrategy the RetryStrategy
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case of failures
*/
public static <T> CompletableFuture<T> retryWithDelay(
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final ScheduledExecutor scheduledExecutor) {
return retryWithDelay(operation, retryStrategy, (throwable) -> true, scheduledExecutor);
}
/**
* Schedule the operation with the given delay.
*
* @param operation to schedule
* @param delay delay to schedule
* @param scheduledExecutor executor to be used for the operation
* @return Future which schedules the given operation with given delay.
*/
public static CompletableFuture<Void> scheduleWithDelay(
final Runnable operation, final Time delay, final ScheduledExecutor scheduledExecutor) {
Supplier<Void> operationSupplier =
() -> {
operation.run();
return null;
};
return scheduleWithDelay(operationSupplier, delay, scheduledExecutor);
}
/**
* Schedule the operation with the given delay.
*
* @param operation to schedule
* @param delay delay to schedule
* @param scheduledExecutor executor to be used for the operation
* @param <T> type of the result
* @return Future which schedules the given operation with given delay.
*/
public static <T> CompletableFuture<T> scheduleWithDelay(
final Supplier<T> operation,
final Time delay,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
() -> {
try {
resultFuture.complete(operation.get());
} catch (Throwable t) {
resultFuture.completeExceptionally(t);
}
},
delay.getSize(),
delay.getUnit());
resultFuture.whenComplete(
(t, throwable) -> {
if (!scheduledFuture.isDone()) {
scheduledFuture.cancel(false);
}
});
return resultFuture;
}
private static <T> void retryOperationWithDelay(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final RetryStrategy retryStrategy,
final Predicate<Throwable> retryPredicate,
final ScheduledExecutor scheduledExecutor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationResultFuture = operation.get();
operationResultFuture.whenComplete(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
throwable = ExceptionUtils.stripExecutionException(throwable);
if (!retryPredicate.test(throwable)) {
resultFuture.completeExceptionally(throwable);
} else if (retryStrategy.getNumRemainingRetries() > 0) {
long retryDelayMillis =
retryStrategy.getRetryDelay().toMillis();
final ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
(Runnable)
() ->
retryOperationWithDelay(
resultFuture,
operation,
retryStrategy
.getNextRetryStrategy(),
retryPredicate,
scheduledExecutor),
retryDelayMillis,
TimeUnit.MILLISECONDS);
resultFuture.whenComplete(
(innerT, innerThrowable) ->
scheduledFuture.cancel(false));
} else {
RetryException retryException =
new RetryException(
"Could not complete the operation. Number of retries has been exhausted.",
throwable);
resultFuture.completeExceptionally(retryException);
}
}
} else {
resultFuture.complete(t);
}
});
resultFuture.whenComplete((t, throwable) -> operationResultFuture.cancel(false));
}
}
/**
* Retry the given operation with the given delay in between successful completions where the
* result does not match a given predicate.
*
* @param operation to retry
* @param retryDelay delay between retries
* @param deadline A deadline that specifies at what point we should stop retrying
* @param acceptancePredicate Predicate to test whether the result is acceptable
* @param scheduledExecutor executor to be used for the retry operation
* @param <T> type of the result
* @return Future which retries the given operation a given amount of times and delays the retry
* in case the predicate isn't matched
*/
public static <T> CompletableFuture<T> retrySuccessfulWithDelay(
final Supplier<CompletableFuture<T>> operation,
final Time retryDelay,
final Deadline deadline,
final Predicate<T> acceptancePredicate,
final ScheduledExecutor scheduledExecutor) {
final CompletableFuture<T> resultFuture = new CompletableFuture<>();
retrySuccessfulOperationWithDelay(
resultFuture,
operation,
retryDelay,
deadline,
acceptancePredicate,
scheduledExecutor);
return resultFuture;
}
private static <T> void retrySuccessfulOperationWithDelay(
final CompletableFuture<T> resultFuture,
final Supplier<CompletableFuture<T>> operation,
final Time retryDelay,
final Deadline deadline,
final Predicate<T> acceptancePredicate,
final ScheduledExecutor scheduledExecutor) {
if (!resultFuture.isDone()) {
final CompletableFuture<T> operationResultFuture = operation.get();
operationResultFuture.whenComplete(
(t, throwable) -> {
if (throwable != null) {
if (throwable instanceof CancellationException) {
resultFuture.completeExceptionally(
new RetryException(
"Operation future was cancelled.", throwable));
} else {
resultFuture.completeExceptionally(throwable);
}
} else {
if (acceptancePredicate.test(t)) {
resultFuture.complete(t);
} else if (deadline.hasTimeLeft()) {
final ScheduledFuture<?> scheduledFuture =
scheduledExecutor.schedule(
(Runnable)
() ->
retrySuccessfulOperationWithDelay(
resultFuture,
operation,
retryDelay,
deadline,
acceptancePredicate,
scheduledExecutor),
retryDelay.toMilliseconds(),
TimeUnit.MILLISECONDS);
resultFuture.whenComplete(
(innerT, innerThrowable) -> scheduledFuture.cancel(false));
} else {
resultFuture.completeExceptionally(
new RetryException(
"Could not satisfy the predicate within the allowed time."));
}
}
});
resultFuture.whenComplete((t, throwable) -> operationResultFuture.cancel(false));
}
}
/**
* Exception with which the returned future is completed if the {@link #retry(Supplier, int,
* Executor)} operation fails.
*/
public static class RetryException extends Exception {
private static final long serialVersionUID = 3613470781274141862L;
public RetryException(String message) {
super(message);
}
public RetryException(String message, Throwable cause) {
super(message, cause);
}
public RetryException(Throwable cause) {
super(cause);
}
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future, long timeout, TimeUnit timeUnit) {
return orTimeout(future, timeout, timeUnit, Executors.directExecutor(), null);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutMsg timeout message for exception
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
@Nullable String timeoutMsg) {
return orTimeout(future, timeout, timeUnit, Executors.directExecutor(), timeoutMsg);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutFailExecutor executor that will complete the future exceptionally after the
* timeout is reached
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
Executor timeoutFailExecutor) {
return orTimeout(future, timeout, timeUnit, timeoutFailExecutor, null);
}
/**
* Times the given future out after the timeout.
*
* @param future to time out
* @param timeout after which the given future is timed out
* @param timeUnit time unit of the timeout
* @param timeoutFailExecutor executor that will complete the future exceptionally after the
* timeout is reached
* @param timeoutMsg timeout message for exception
* @param <T> type of the given future
* @return The timeout enriched future
*/
public static <T> CompletableFuture<T> orTimeout(
CompletableFuture<T> future,
long timeout,
TimeUnit timeUnit,
Executor timeoutFailExecutor,
@Nullable String timeoutMsg) {
if (!future.isDone()) {
final ScheduledFuture<?> timeoutFuture =
Delayer.delay(
() -> timeoutFailExecutor.execute(new Timeout(future, timeoutMsg)),
timeout,
timeUnit);
future.whenComplete(
(T value, Throwable throwable) -> {
if (!timeoutFuture.isDone()) {
timeoutFuture.cancel(false);
}
});
}
return future;
}
// ------------------------------------------------------------------------
// Future actions
// ------------------------------------------------------------------------
/**
* Run the given {@code RunnableFuture} if it is not done, and then retrieves its result.
*
* @param future to run if not done and get
* @param <T> type of the result
* @return the result after running the future
* @throws ExecutionException if a problem occurred
* @throws InterruptedException if the current thread has been interrupted
*/
public static <T> T runIfNotDoneAndGet(RunnableFuture<T> future)
throws ExecutionException, InterruptedException {
if (null == future) {
return null;
}
if (!future.isDone()) {
future.run();
}
return future.get();
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwards(
CompletableFuture<?> future, RunnableWithException runnable) {
return runAfterwardsAsync(future, runnable, Executors.directExecutor());
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwardsAsync(
CompletableFuture<?> future, RunnableWithException runnable) {
return runAfterwardsAsync(future, runnable, ForkJoinPool.commonPool());
}
/**
* Run the given action after the completion of the given future. The given future can be
* completed normally or exceptionally. In case of an exceptional completion the, the action's
* exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param runnable action which is triggered after the future's completion
* @param executor to run the given action
* @return Future which is completed after the action has completed. This future can contain an
* exception, if an error occurred in the given future or action.
*/
public static CompletableFuture<Void> runAfterwardsAsync(
CompletableFuture<?> future, RunnableWithException runnable, Executor executor) {
final CompletableFuture<Void> resultFuture = new CompletableFuture<>();
future.whenCompleteAsync(
(Object ignored, Throwable throwable) -> {
try {
runnable.run();
} catch (Throwable e) {
throwable = ExceptionUtils.firstOrSuppressed(e, throwable);
}
if (throwable != null) {
resultFuture.completeExceptionally(throwable);
} else {
resultFuture.complete(null);
}
},
executor);
return resultFuture;
}
/**
* Run the given asynchronous action after the completion of the given future. The given future
* can be completed normally or exceptionally. In case of an exceptional completion, the
* asynchronous action's exception will be added to the initial exception.
*
* @param future to wait for its completion
* @param composedAction asynchronous action which is triggered after the future's completion
* @return Future which is completed after the asynchronous action has completed. This future
* can contain an exception if an error occurred in the given future or asynchronous action.
*/
public static CompletableFuture<Void> composeAfterwards(
CompletableFuture<?> future, Supplier<CompletableFuture<?>> composedAction) {
final CompletableFuture<Void> resultFuture = new CompletableFuture<>();
future.whenComplete(
(Object outerIgnored, Throwable outerThrowable) -> {
final CompletableFuture<?> composedActionFuture = composedAction.get();
composedActionFuture.whenComplete(
(Object innerIgnored, Throwable innerThrowable) -> {
if (innerThrowable != null) {
resultFuture.completeExceptionally(
ExceptionUtils.firstOrSuppressed(
innerThrowable, outerThrowable));
} else if (outerThrowable != null) {
resultFuture.completeExceptionally(outerThrowable);
} else {
resultFuture.complete(null);
}
});
});
return resultFuture;
}
// ------------------------------------------------------------------------
// composing futures
// ------------------------------------------------------------------------
/**
* Creates a future that is complete once multiple other futures completed. The future fails
* (completes exceptionally) once one of the futures in the conjunction fails. Upon successful
* completion, the future returns the collection of the futures' results.
*
* <p>The ConjunctFuture gives access to how many Futures in the conjunction have already
* completed successfully, via {@link ConjunctFuture#getNumFuturesCompleted()}.
*
* @param futures The futures that make up the conjunction. No null entries are allowed.
* @return The ConjunctFuture that completes once all given futures are complete (or one fails).
*/
public static <T> ConjunctFuture<Collection<T>> combineAll(
Collection<? extends CompletableFuture<? extends T>> futures) {
checkNotNull(futures, "futures");
return new ResultConjunctFuture<>(futures);
}
/**
* Creates a future that is complete once all of the given futures have completed. The future
* fails (completes exceptionally) once one of the given futures fails.
*
* <p>The ConjunctFuture gives access to how many Futures have already completed successfully,
* via {@link ConjunctFuture#getNumFuturesCompleted()}.
*
* @param futures The futures to wait on. No null entries are allowed.
* @return The WaitingFuture that completes once all given futures are complete (or one fails).
*/
public static ConjunctFuture<Void> waitForAll(
Collection<? extends CompletableFuture<?>> futures) {
checkNotNull(futures, "futures");
return new WaitingConjunctFuture(futures);
}
/**
* A future that is complete once multiple other futures completed. The futures are not
* necessarily of the same type. The ConjunctFuture fails (completes exceptionally) once one of
* the Futures in the conjunction fails.
*
* <p>The advantage of using the ConjunctFuture over chaining all the futures (such as via
* {@link CompletableFuture#thenCombine(CompletionStage, BiFunction)} )}) is that ConjunctFuture
* also tracks how many of the Futures are already complete.
*/
public abstract static class ConjunctFuture<T> extends CompletableFuture<T> {
/**
* Gets the total number of Futures in the conjunction.
*
* @return The total number of Futures in the conjunction.
*/
public abstract int getNumFuturesTotal();
/**
* Gets the number of Futures in the conjunction that are already complete.
*
* @return The number of Futures in the conjunction that are already complete
*/
public abstract int getNumFuturesCompleted();
}
/**
* The implementation of the {@link ConjunctFuture} which returns its Futures' result as a
* collection.
*/
private static class ResultConjunctFuture<T> extends ConjunctFuture<Collection<T>> {
/** The total number of futures in the conjunction. */
private final int numTotal;
/** The number of futures in the conjunction that are already complete. */
private final AtomicInteger numCompleted = new AtomicInteger(0);
/** The set of collected results so far. */
private volatile T[] results;
/**
* The function that is attached to all futures in the conjunction. Once a future is
* complete, this function tracks the completion or fails the conjunct.
*/
private void handleCompletedFuture(int index, T value, Throwable throwable) {
if (throwable != null) {
completeExceptionally(throwable);
} else {
results[index] = value;
if (numCompleted.incrementAndGet() == numTotal) {
complete(Arrays.asList(results));
}
}
}
@SuppressWarnings("unchecked")
ResultConjunctFuture(Collection<? extends CompletableFuture<? extends T>> resultFutures) {
this.numTotal = resultFutures.size();
results = (T[]) new Object[numTotal];
if (resultFutures.isEmpty()) {
complete(Collections.emptyList());
} else {
int counter = 0;
for (CompletableFuture<? extends T> future : resultFutures) {
final int index = counter;
counter++;
future.whenComplete(
(value, throwable) -> handleCompletedFuture(index, value, throwable));
}
}
}
@Override
public int getNumFuturesTotal() {
return numTotal;
}
@Override
public int getNumFuturesCompleted() {
return numCompleted.get();
}
}
/**
* Implementation of the {@link ConjunctFuture} interface which waits only for the completion of
* its futures and does not return their values.
*/
private static final class WaitingConjunctFuture extends ConjunctFuture<Void> {
/** Number of completed futures. */
private final AtomicInteger numCompleted = new AtomicInteger(0);
/** Total number of futures to wait on. */
private final int numTotal;
/**
* Method which increments the atomic completion counter and completes or fails the
* WaitingFutureImpl.
*/
private void handleCompletedFuture(Object ignored, Throwable throwable) {
if (throwable == null) {
if (numTotal == numCompleted.incrementAndGet()) {
complete(null);
}
} else {
completeExceptionally(throwable);
}
}
private WaitingConjunctFuture(Collection<? extends CompletableFuture<?>> futures) {
this.numTotal = futures.size();
if (futures.isEmpty()) {
complete(null);
} else {
for (java.util.concurrent.CompletableFuture<?> future : futures) {
future.whenComplete(this::handleCompletedFuture);
}
}
}
@Override
public int getNumFuturesTotal() {
return numTotal;
}
@Override
public int getNumFuturesCompleted() {
return numCompleted.get();
}
}
/**
* Creates a {@link ConjunctFuture} which is only completed after all given futures have
* completed. Unlike {@link FutureUtils#waitForAll(Collection)}, the resulting future won't be
* completed directly if one of the given futures is completed exceptionally. Instead, all
* occurring exception will be collected and combined to a single exception. If at least on
* exception occurs, then the resulting future will be completed exceptionally.
*
* @param futuresToComplete futures to complete
* @return Future which is completed after all given futures have been completed.
*/
public static ConjunctFuture<Void> completeAll(
Collection<? extends CompletableFuture<?>> futuresToComplete) {
return new CompletionConjunctFuture(futuresToComplete);
}
/**
* {@link ConjunctFuture} implementation which is completed after all the given futures have
* been completed. Exceptional completions of the input futures will be recorded but it won't
* trigger the early completion of this future.
*/
private static final class CompletionConjunctFuture extends ConjunctFuture<Void> {
private final Object lock = new Object();
private final int numFuturesTotal;
private int futuresCompleted;
private Throwable globalThrowable;
private CompletionConjunctFuture(
Collection<? extends CompletableFuture<?>> futuresToComplete) {
numFuturesTotal = futuresToComplete.size();
futuresCompleted = 0;
globalThrowable = null;
if (futuresToComplete.isEmpty()) {
complete(null);
} else {
for (CompletableFuture<?> completableFuture : futuresToComplete) {
completableFuture.whenComplete(this::completeFuture);
}
}
}
private void completeFuture(Object ignored, Throwable throwable) {
synchronized (lock) {
futuresCompleted++;
if (throwable != null) {
globalThrowable = ExceptionUtils.firstOrSuppressed(throwable, globalThrowable);
}
if (futuresCompleted == numFuturesTotal) {
if (globalThrowable != null) {
completeExceptionally(globalThrowable);
} else {
complete(null);
}
}
}
}
@Override
public int getNumFuturesTotal() {
return numFuturesTotal;
}
@Override
public int getNumFuturesCompleted() {
synchronized (lock) {
return futuresCompleted;
}
}
}
// ------------------------------------------------------------------------
// Helper methods
// ------------------------------------------------------------------------
/**
* Returns an exceptionally completed {@link CompletableFuture}.
*
* @param cause to complete the future with
* @param <T> type of the future
* @return An exceptionally completed CompletableFuture
*/
public static <T> CompletableFuture<T> completedExceptionally(Throwable cause) {
CompletableFuture<T> result = new CompletableFuture<>();
result.completeExceptionally(cause);
return result;
}
/**
* Returns a future which is completed with the result of the {@link SupplierWithException}.
*
* @param supplier to provide the future's value
* @param executor to execute the supplier
* @param <T> type of the result
* @return Future which is completed with the value of the supplier
*/
public static <T> CompletableFuture<T> supplyAsync(
SupplierWithException<T, ?> supplier, Executor executor) {
return CompletableFuture.supplyAsync(
() -> {
try {
return supplier.get();
} catch (Throwable e) {
throw new CompletionException(e);
}
},
executor);
}
/**
* Converts Flink time into a {@link Duration}.
*
* @param time to convert into a Duration
* @return Duration with the length of the given time
*/
public static Duration toDuration(Time time) {
return Duration.ofMillis(time.toMilliseconds());
}
// ------------------------------------------------------------------------
// Converting futures
// ------------------------------------------------------------------------
/**
* Converts a Scala {@link Future} to a {@link CompletableFuture}.
*
* @param scalaFuture to convert to a Java 8 CompletableFuture
* @param <T> type of the future value
* @param <U> type of the original future
* @return Java 8 CompletableFuture
*/
public static <T, U extends T> CompletableFuture<T> toJava(Future<U> scalaFuture) {
final CompletableFuture<T> result = new CompletableFuture<>();
scalaFuture.onComplete(
new OnComplete<U>() {
@Override
public void onComplete(Throwable failure, U success) {
if (failure != null) {
result.completeExceptionally(failure);
} else {
result.complete(success);
}
}
},
Executors.directExecutionContext());
return result;
}
/**
* This function takes a {@link CompletableFuture} and a function to apply to this future. If
* the input future is already done, this function returns {@link
* CompletableFuture#thenApply(Function)}. Otherwise, the return value is {@link
* CompletableFuture#thenApplyAsync(Function, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to apply.
* @param executor the executor to run the apply function if the future is not yet done.
* @param applyFun the function to apply.
* @param <IN> type of the input future.
* @param <OUT> type of the output future.
* @return a completable future that is applying the given function to the input future.
*/
public static <IN, OUT> CompletableFuture<OUT> thenApplyAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Function<? super IN, ? extends OUT> applyFun) {
return completableFuture.isDone()
? completableFuture.thenApply(applyFun)
: completableFuture.thenApplyAsync(applyFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a function to compose with this future.
* If the input future is already done, this function returns {@link
* CompletableFuture#thenCompose(Function)}. Otherwise, the return value is {@link
* CompletableFuture#thenComposeAsync(Function, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to compose.
* @param executor the executor to run the compose function if the future is not yet done.
* @param composeFun the function to compose.
* @param <IN> type of the input future.
* @param <OUT> type of the output future.
* @return a completable future that is a composition of the input future and the function.
*/
public static <IN, OUT> CompletableFuture<OUT> thenComposeAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Function<? super IN, ? extends CompletionStage<OUT>> composeFun) {
return completableFuture.isDone()
? completableFuture.thenCompose(composeFun)
: completableFuture.thenComposeAsync(composeFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a bi-consumer to call on completion of
* this future. If the input future is already done, this function returns {@link
* CompletableFuture#whenComplete(BiConsumer)}. Otherwise, the return value is {@link
* CompletableFuture#whenCompleteAsync(BiConsumer, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #whenComplete.
* @param executor the executor to run the whenComplete function if the future is not yet done.
* @param whenCompleteFun the bi-consumer function to call when the future is completed.
* @param <IN> type of the input future.
* @return the new completion stage.
*/
public static <IN> CompletableFuture<IN> whenCompleteAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
BiConsumer<? super IN, ? super Throwable> whenCompleteFun) {
return completableFuture.isDone()
? completableFuture.whenComplete(whenCompleteFun)
: completableFuture.whenCompleteAsync(whenCompleteFun, executor);
}
/**
* This function takes a {@link CompletableFuture} and a consumer to accept the result of this
* future. If the input future is already done, this function returns {@link
* CompletableFuture#thenAccept(Consumer)}. Otherwise, the return value is {@link
* CompletableFuture#thenAcceptAsync(Consumer, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #thenAccept.
* @param executor the executor to run the thenAccept function if the future is not yet done.
* @param consumer the consumer function to call when the future is completed.
* @param <IN> type of the input future.
* @return the new completion stage.
*/
public static <IN> CompletableFuture<Void> thenAcceptAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
Consumer<? super IN> consumer) {
return completableFuture.isDone()
? completableFuture.thenAccept(consumer)
: completableFuture.thenAcceptAsync(consumer, executor);
}
/**
* This function takes a {@link CompletableFuture} and a handler function for the result of this
* future. If the input future is already done, this function returns {@link
* CompletableFuture#handle(BiFunction)}. Otherwise, the return value is {@link
* CompletableFuture#handleAsync(BiFunction, Executor)} with the given executor.
*
* @param completableFuture the completable future for which we want to call #handle.
* @param executor the executor to run the handle function if the future is not yet done.
* @param handler the handler function to call when the future is completed.
* @param <IN> type of the handler input argument.
* @param <OUT> type of the handler return value.
* @return the new completion stage.
*/
public static <IN, OUT> CompletableFuture<OUT> handleAsyncIfNotDone(
CompletableFuture<IN> completableFuture,
Executor executor,
BiFunction<? super IN, Throwable, ? extends OUT> handler) {
return completableFuture.isDone()
? completableFuture.handle(handler)
: completableFuture.handleAsync(handler, executor);
}
/** @return true if future has completed normally, false otherwise. */
public static boolean isCompletedNormally(CompletableFuture<?> future) {
return future.isDone() && !future.isCompletedExceptionally();
}
/**
* Perform check state that future has completed normally and return the result.
*
* @return the result of completable future.
* @throws IllegalStateException Thrown, if future has not completed or it has completed
* exceptionally.
*/
public static <T> T checkStateAndGet(CompletableFuture<T> future) {
checkCompletedNormally(future);
return getWithoutException(future);
}
/**
* Gets the result of a completable future without any exception thrown.
*
* @param future the completable future specified.
* @param <T> the type of result
* @return the result of completable future, or null if it's unfinished or finished
* exceptionally
*/
@Nullable
public static <T> T getWithoutException(CompletableFuture<T> future) {
if (isCompletedNormally(future)) {
try {
return future.get();
} catch (InterruptedException | ExecutionException ignored) {
}
}
return null;
}
/**
* @return the result of completable future, or the defaultValue if it has not yet completed.
*/
public static <T> T getOrDefault(CompletableFuture<T> future, T defaultValue) {
T value = getWithoutException(future);
return value == null ? defaultValue : value;
}
/** Runnable to complete the given future with a {@link TimeoutException}. */
private static final class Timeout implements Runnable {
private final CompletableFuture<?> future;
private final String timeoutMsg;
private Timeout(CompletableFuture<?> future, @Nullable String timeoutMsg) {
this.future = checkNotNull(future);
this.timeoutMsg = timeoutMsg;
}
@Override
public void run() {
future.completeExceptionally(new TimeoutException(timeoutMsg));
}
}
/**
* Delay scheduler used to timeout futures.
*
* <p>This class creates a singleton scheduler used to run the provided actions.
*/
private enum Delayer {
;
static final ScheduledThreadPoolExecutor DELAYER =
new ScheduledThreadPoolExecutor(
1, new ExecutorThreadFactory("FlinkCompletableFutureDelayScheduler"));
/**
* Delay the given action by the given delay.
*
* @param runnable to execute after the given delay
* @param delay after which to execute the runnable
* @param timeUnit time unit of the delay
* @return Future of the scheduled action
*/
private static ScheduledFuture<?> delay(Runnable runnable, long delay, TimeUnit timeUnit) {
checkNotNull(runnable);
checkNotNull(timeUnit);
return DELAYER.schedule(runnable, delay, timeUnit);
}
}
/**
* Asserts that the given {@link CompletableFuture} is not completed exceptionally. If the
* future is completed exceptionally, then it will call the {@link FatalExitExceptionHandler}.
*
* @param completableFuture to assert for no exceptions
*/
public static void assertNoException(CompletableFuture<?> completableFuture) {
handleUncaughtException(completableFuture, FatalExitExceptionHandler.INSTANCE);
}
/**
* Checks that the given {@link CompletableFuture} is not completed exceptionally. If the future
* is completed exceptionally, then it will call the given uncaught exception handler.
*
* @param completableFuture to assert for no exceptions
* @param uncaughtExceptionHandler to call if the future is completed exceptionally
*/
public static void handleUncaughtException(
CompletableFuture<?> completableFuture,
Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
checkNotNull(completableFuture)
.whenComplete(
(ignored, throwable) -> {
if (throwable != null) {
uncaughtExceptionHandler.uncaughtException(
Thread.currentThread(), throwable);
}
});
}
/**
* Forwards the value from the source future to the target future.
*
* @param source future to forward the value from
* @param target future to forward the value to
* @param <T> type of the value
*/
public static <T> void forward(CompletableFuture<T> source, CompletableFuture<T> target) {
source.whenComplete(forwardTo(target));
}
/**
* Forwards the value from the source future to the target future using the provided executor.
*
* @param source future to forward the value from
* @param target future to forward the value to
* @param executor executor to forward the source value to the target future
* @param <T> type of the value
*/
public static <T> void forwardAsync(
CompletableFuture<T> source, CompletableFuture<T> target, Executor executor) {
source.whenCompleteAsync(forwardTo(target), executor);
}
/**
* Throws the causing exception if the given future is completed exceptionally, otherwise do
* nothing.
*
* @param future the future to check.
* @throws Exception when the future is completed exceptionally.
*/
public static void throwIfCompletedExceptionally(CompletableFuture<?> future) throws Exception {
if (future.isCompletedExceptionally()) {
future.get();
}
}
private static <T> BiConsumer<T, Throwable> forwardTo(CompletableFuture<T> target) {
return (value, throwable) -> {
if (throwable != null) {
target.completeExceptionally(throwable);
} else {
target.complete(value);
}
};
}
}
| [FLINK-21365][runtime] Document and make the contract of FutureUtils.ResultConjunctFuture more explicit
Add an explanation why is the current solution working and also
clean it up a little bit (dropping unecessary volatile and adding final keyword).
| flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java | [FLINK-21365][runtime] Document and make the contract of FutureUtils.ResultConjunctFuture more explicit | <ide><path>link-runtime/src/main/java/org/apache/flink/runtime/concurrent/FutureUtils.java
<ide> private final AtomicInteger numCompleted = new AtomicInteger(0);
<ide>
<ide> /** The set of collected results so far. */
<del> private volatile T[] results;
<add> private final T[] results;
<ide>
<ide> /**
<ide> * The function that is attached to all futures in the conjunction. Once a future is
<ide> if (throwable != null) {
<ide> completeExceptionally(throwable);
<ide> } else {
<add> /**
<add> * This {@link #results} update itself is not synchronised in any way and it's fine
<add> * because:
<add> *
<add> * <ul>
<add> * <li>There is a happens-before relationship for each thread (that is completing
<add> * the future) between setting {@link #results} and incrementing {@link
<add> * #numCompleted}.
<add> * <li>Each thread is updating uniquely different field of the {@link #results}
<add> * array.
<add> * <li>There is a happens-before relationship between all of the writing threads
<add> * and the last one thread (thanks to the {@code
<add> * numCompleted.incrementAndGet() == numTotal} check.
<add> * <li>The last thread will be completing the future, so it has transitively
<add> * happens-before relationship with all of preceding updated/writes to {@link
<add> * #results}.
<add> * <li>{@link AtomicInteger#incrementAndGet} is an equivalent of both volatile
<add> * read & write
<add> * </ul>
<add> */
<ide> results[index] = value;
<ide>
<ide> if (numCompleted.incrementAndGet() == numTotal) { |
|
Java | apache-2.0 | 7076b7408f06bc8a277f58e7bb6c2ec3372d5d6f | 0 | apache/commons-lang,MarkDacek/commons-lang,britter/commons-lang,britter/commons-lang,apache/commons-lang,britter/commons-lang,apache/commons-lang,MarkDacek/commons-lang,MarkDacek/commons-lang | /*
* 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.commons.lang3;
import java.io.Serializable;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* <p>A contiguous range of characters, optionally negated.</p>
*
* <p>Instances are immutable.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
*/
// TODO: This is no longer public and will be removed later as CharSet is moved
// to depend on Range.
final class CharRange implements Iterable<Character>, Serializable {
/**
* Required for serialization support. Lang version 2.0.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 8270183163158333422L;
/** The first character, inclusive, in the range. */
private final char start;
/** The last character, inclusive, in the range. */
private final char end;
/** True if the range is everything except the characters specified. */
private final boolean negated;
/** Cached toString. */
private transient String iToString;
/**
* <p>Constructs a {@code CharRange} over a set of characters,
* optionally negating the range.</p>
*
* <p>A negated range includes everything except that defined by the
* start and end characters.</p>
*
* <p>If start and end are in the wrong order, they are reversed.
* Thus {@code a-e} is the same as {@code e-a}.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @param negated true to express everything except the range
*/
private CharRange(char start, char end, final boolean negated) {
super();
if (start > end) {
final char temp = start;
start = end;
end = temp;
}
this.start = start;
this.end = end;
this.negated = negated;
}
/**
* <p>Constructs a {@code CharRange} over a single character.</p>
*
* @param ch only character in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange is(final char ch) {
return new CharRange(ch, ch, false);
}
/**
* <p>Constructs a negated {@code CharRange} over a single character.</p>
*
* @param ch only character in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isNot(final char ch) {
return new CharRange(ch, ch, true);
}
/**
* <p>Constructs a {@code CharRange} over a set of characters.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isIn(final char start, final char end) {
return new CharRange(start, end, false);
}
/**
* <p>Constructs a negated {@code CharRange} over a set of characters.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isNotIn(final char start, final char end) {
return new CharRange(start, end, true);
}
// Accessors
//-----------------------------------------------------------------------
/**
* <p>Gets the start character for this character range.</p>
*
* @return the start char (inclusive)
*/
public char getStart() {
return this.start;
}
/**
* <p>Gets the end character for this character range.</p>
*
* @return the end char (inclusive)
*/
public char getEnd() {
return this.end;
}
/**
* <p>Is this {@code CharRange} negated.</p>
*
* <p>A negated range includes everything except that defined by the
* start and end characters.</p>
*
* @return {@code true} if negated
*/
public boolean isNegated() {
return negated;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Is the character specified contained in this range.</p>
*
* @param ch the character to check
* @return {@code true} if this range contains the input character
*/
public boolean contains(final char ch) {
return (ch >= start && ch <= end) != negated;
}
/**
* <p>Are all the characters of the passed in range contained in
* this range.</p>
*
* @param range the range to check against
* @return {@code true} if this range entirely contains the input range
* @throws IllegalArgumentException if {@code null} input
*/
public boolean contains(final CharRange range) {
Validate.isTrue(range != null, "The Range must not be null");
if (negated) {
if (range.negated) {
return start >= range.start && end <= range.end;
}
return range.end < start || range.start > end;
}
if (range.negated) {
return start == 0 && end == Character.MAX_VALUE;
}
return start <= range.start && end >= range.end;
}
// Basics
//-----------------------------------------------------------------------
/**
* <p>Compares two CharRange objects, returning true if they represent
* exactly the same range of characters defined in the same way.</p>
*
* @param obj the object to compare to
* @return true if equal
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CharRange)) {
return false;
}
final CharRange other = (CharRange) obj;
return start == other.start && end == other.end && negated == other.negated;
}
/**
* <p>Gets a hashCode compatible with the equals method.</p>
*
* @return a suitable hashCode
*/
@Override
public int hashCode() {
return 83 + start + 7 * end + (negated ? 1 : 0);
}
/**
* <p>Gets a string representation of the character range.</p>
*
* @return string representation of this range
*/
@Override
public String toString() {
if (iToString == null) {
final StringBuilder buf = new StringBuilder(4);
if (isNegated()) {
buf.append('^');
}
buf.append(start);
if (start != end) {
buf.append('-');
buf.append(end);
}
iToString = buf.toString();
}
return iToString;
}
// Expansions
//-----------------------------------------------------------------------
/**
* <p>Returns an iterator which can be used to walk through the characters described by this range.</p>
*
* <p>#NotThreadSafe# the iterator is not thread-safe</p>
* @return an iterator to the chars represented by this range
* @since 2.5
*/
@Override
public Iterator<Character> iterator() {
return new CharacterIterator(this);
}
/**
* Character {@link Iterator}.
* <p>#NotThreadSafe#</p>
*/
private static class CharacterIterator implements Iterator<Character> {
/** The current character */
private char current;
private final CharRange range;
private boolean hasNext;
/**
* Construct a new iterator for the character range.
*
* @param r The character range
*/
private CharacterIterator(final CharRange r) {
range = r;
hasNext = true;
if (range.negated) {
if (range.start == 0) {
if (range.end == Character.MAX_VALUE) {
// This range is an empty set
hasNext = false;
} else {
current = (char) (range.end + 1);
}
} else {
current = 0;
}
} else {
current = range.start;
}
}
/**
* Prepare the next character in the range.
*/
private void prepareNext() {
if (range.negated) {
if (current == Character.MAX_VALUE) {
hasNext = false;
} else if (current + 1 == range.start) {
if (range.end == Character.MAX_VALUE) {
hasNext = false;
} else {
current = (char) (range.end + 1);
}
} else {
current = (char) (current + 1);
}
} else if (current < range.end) {
current = (char) (current + 1);
} else {
hasNext = false;
}
}
/**
* Has the iterator not reached the end character yet?
*
* @return {@code true} if the iterator has yet to reach the character date
*/
@Override
public boolean hasNext() {
return hasNext;
}
/**
* Return the next character in the iteration
*
* @return {@code Character} for the next character
*/
@Override
public Character next() {
if (!hasNext) {
throw new NoSuchElementException();
}
final char cur = current;
prepareNext();
return Character.valueOf(cur);
}
/**
* Always throws UnsupportedOperationException.
*
* @throws UnsupportedOperationException
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| src/main/java/org/apache/commons/lang3/CharRange.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.commons.lang3;
import java.io.Serializable;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* <p>A contiguous range of characters, optionally negated.</p>
*
* <p>Instances are immutable.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
*/
// TODO: This is no longer public and will be removed later as CharSet is moved
// to depend on Range.
final class CharRange implements Iterable<Character>, Serializable {
/**
* Required for serialization support. Lang version 2.0.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 8270183163158333422L;
/** The first character, inclusive, in the range. */
private final char start;
/** The last character, inclusive, in the range. */
private final char end;
/** True if the range is everything except the characters specified. */
private final boolean negated;
/** Cached toString. */
private transient String iToString;
/**
* <p>Constructs a {@code CharRange} over a set of characters,
* optionally negating the range.</p>
*
* <p>A negated range includes everything except that defined by the
* start and end characters.</p>
*
* <p>If start and end are in the wrong order, they are reversed.
* Thus {@code a-e} is the same as {@code e-a}.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @param negated true to express everything except the range
*/
private CharRange(char start, char end, final boolean negated) {
super();
if (start > end) {
final char temp = start;
start = end;
end = temp;
}
this.start = start;
this.end = end;
this.negated = negated;
}
/**
* <p>Constructs a {@code CharRange} over a single character.</p>
*
* @param ch only character in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange is(final char ch) {
return new CharRange(ch, ch, false);
}
/**
* <p>Constructs a negated {@code CharRange} over a single character.</p>
*
* @param ch only character in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isNot(final char ch) {
return new CharRange(ch, ch, true);
}
/**
* <p>Constructs a {@code CharRange} over a set of characters.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isIn(final char start, final char end) {
return new CharRange(start, end, false);
}
/**
* <p>Constructs a negated {@code CharRange} over a set of characters.</p>
*
* @param start first character, inclusive, in this range
* @param end last character, inclusive, in this range
* @return the new CharRange object
* @see CharRange#CharRange(char, char, boolean)
* @since 2.5
*/
public static CharRange isNotIn(final char start, final char end) {
return new CharRange(start, end, true);
}
// Accessors
//-----------------------------------------------------------------------
/**
* <p>Gets the start character for this character range.</p>
*
* @return the start char (inclusive)
*/
public char getStart() {
return this.start;
}
/**
* <p>Gets the end character for this character range.</p>
*
* @return the end char (inclusive)
*/
public char getEnd() {
return this.end;
}
/**
* <p>Is this {@code CharRange} negated.</p>
*
* <p>A negated range includes everything except that defined by the
* start and end characters.</p>
*
* @return {@code true} if negated
*/
public boolean isNegated() {
return negated;
}
// Contains
//-----------------------------------------------------------------------
/**
* <p>Is the character specified contained in this range.</p>
*
* @param ch the character to check
* @return {@code true} if this range contains the input character
*/
public boolean contains(final char ch) {
return (ch >= start && ch <= end) != negated;
}
/**
* <p>Are all the characters of the passed in range contained in
* this range.</p>
*
* @param range the range to check against
* @return {@code true} if this range entirely contains the input range
* @throws IllegalArgumentException if {@code null} input
*/
public boolean contains(final CharRange range) {
Validate.isTrue(range != null, "The Range must not be null");
if (negated) {
if (range.negated) {
return start >= range.start && end <= range.end;
}
return range.end < start || range.start > end;
}
if (range.negated) {
return start == 0 && end == Character.MAX_VALUE;
}
return start <= range.start && end >= range.end;
}
// Basics
//-----------------------------------------------------------------------
/**
* <p>Compares two CharRange objects, returning true if they represent
* exactly the same range of characters defined in the same way.</p>
*
* @param obj the object to compare to
* @return true if equal
*/
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof CharRange == false) {
return false;
}
final CharRange other = (CharRange) obj;
return start == other.start && end == other.end && negated == other.negated;
}
/**
* <p>Gets a hashCode compatible with the equals method.</p>
*
* @return a suitable hashCode
*/
@Override
public int hashCode() {
return 83 + start + 7 * end + (negated ? 1 : 0);
}
/**
* <p>Gets a string representation of the character range.</p>
*
* @return string representation of this range
*/
@Override
public String toString() {
if (iToString == null) {
final StringBuilder buf = new StringBuilder(4);
if (isNegated()) {
buf.append('^');
}
buf.append(start);
if (start != end) {
buf.append('-');
buf.append(end);
}
iToString = buf.toString();
}
return iToString;
}
// Expansions
//-----------------------------------------------------------------------
/**
* <p>Returns an iterator which can be used to walk through the characters described by this range.</p>
*
* <p>#NotThreadSafe# the iterator is not thread-safe</p>
* @return an iterator to the chars represented by this range
* @since 2.5
*/
@Override
public Iterator<Character> iterator() {
return new CharacterIterator(this);
}
/**
* Character {@link Iterator}.
* <p>#NotThreadSafe#</p>
*/
private static class CharacterIterator implements Iterator<Character> {
/** The current character */
private char current;
private final CharRange range;
private boolean hasNext;
/**
* Construct a new iterator for the character range.
*
* @param r The character range
*/
private CharacterIterator(final CharRange r) {
range = r;
hasNext = true;
if (range.negated) {
if (range.start == 0) {
if (range.end == Character.MAX_VALUE) {
// This range is an empty set
hasNext = false;
} else {
current = (char) (range.end + 1);
}
} else {
current = 0;
}
} else {
current = range.start;
}
}
/**
* Prepare the next character in the range.
*/
private void prepareNext() {
if (range.negated) {
if (current == Character.MAX_VALUE) {
hasNext = false;
} else if (current + 1 == range.start) {
if (range.end == Character.MAX_VALUE) {
hasNext = false;
} else {
current = (char) (range.end + 1);
}
} else {
current = (char) (current + 1);
}
} else if (current < range.end) {
current = (char) (current + 1);
} else {
hasNext = false;
}
}
/**
* Has the iterator not reached the end character yet?
*
* @return {@code true} if the iterator has yet to reach the character date
*/
@Override
public boolean hasNext() {
return hasNext;
}
/**
* Return the next character in the iteration
*
* @return {@code Character} for the next character
*/
@Override
public Character next() {
if (hasNext == false) {
throw new NoSuchElementException();
}
final char cur = current;
prepareNext();
return Character.valueOf(cur);
}
/**
* Always throws UnsupportedOperationException.
*
* @throws UnsupportedOperationException
* @see java.util.Iterator#remove()
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| Boolean comparisons in CharRange (closes #289)
Cleaned up comparisons to false to just use the boolean negation
operator (!).
| src/main/java/org/apache/commons/lang3/CharRange.java | Boolean comparisons in CharRange (closes #289) | <ide><path>rc/main/java/org/apache/commons/lang3/CharRange.java
<ide> if (obj == this) {
<ide> return true;
<ide> }
<del> if (obj instanceof CharRange == false) {
<add> if (!(obj instanceof CharRange)) {
<ide> return false;
<ide> }
<ide> final CharRange other = (CharRange) obj;
<ide> */
<ide> @Override
<ide> public Character next() {
<del> if (hasNext == false) {
<add> if (!hasNext) {
<ide> throw new NoSuchElementException();
<ide> }
<ide> final char cur = current; |
|
Java | apache-2.0 | 810218298156c61f1f3a2c4f51ebafebf196243d | 0 | dimbleby/JGroups,vjuranek/JGroups,rhusar/JGroups,Sanne/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,pferraro/JGroups,rvansa/JGroups,ligzy/JGroups,pruivo/JGroups,rhusar/JGroups,belaban/JGroups,deepnarsay/JGroups,pferraro/JGroups,tristantarrant/JGroups,danberindei/JGroups,rhusar/JGroups,Sanne/JGroups,danberindei/JGroups,pruivo/JGroups,dimbleby/JGroups,pruivo/JGroups,belaban/JGroups,kedzie/JGroups,Sanne/JGroups,danberindei/JGroups,TarantulaTechnology/JGroups,vjuranek/JGroups,deepnarsay/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,slaskawi/JGroups,kedzie/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,deepnarsay/JGroups,rpelisse/JGroups,ligzy/JGroups,slaskawi/JGroups,rpelisse/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,tristantarrant/JGroups,slaskawi/JGroups,kedzie/JGroups,rvansa/JGroups |
package org.jgroups.tests;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.blocks.TCPConnectionMap;
import org.jgroups.util.DefaultThreadFactory;
import org.jgroups.util.Util;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Bela Ban
*/
@Test(groups=Global.FUNCTIONAL,sequential=true)
public class ConnectionMapUnitTest {
TCPConnectionMap ct1, ct2;
static final int port1=15555, port2=16666;
@BeforeMethod
protected void setUp() throws Exception {
ct1=new TCPConnectionMap("TCPConnectionMap1",
new DefaultThreadFactory(Util.getGlobalThreadGroup(), "test", true),
null, null, null, null, port1, port1);
ct1.setUseSendQueues(false);
ct1.start();
ct2=new TCPConnectionMap("TCPConnectionMap2",
new DefaultThreadFactory(Util.getGlobalThreadGroup(), "test", true),
null, null, null, null, port2, port2);
ct2.setUseSendQueues(false);
ct2.start();
}
@AfterMethod
void tearDown() throws Exception {
if(ct1 != null) {
ct1.stop();
ct1=null;
}
if(ct2 != null) {
ct2.stop();
ct2=null;
}
}
public void testSetup() {
Assert.assertNotSame(ct1.getLocalAddress(), ct2.getLocalAddress());
}
public void testSendToNullReceiver() throws Exception {
byte[] data=new byte[0];
ct1.send(null, data, 0, data.length);
}
public void testSendEmptyData() throws Exception {
byte[] data=new byte[0];
Address myself=ct1.getLocalAddress();
ct1.setReceiver(new TCPConnectionMap.Receiver() {
public void receive(Address sender, byte[] data, int offset, int length) {}
});
ct1.send(myself, data, 0, data.length);
}
public void testSendNullData() throws Exception {
Address myself=ct1.getLocalAddress();
ct1.send(myself, null, 0, 0);
}
public void testSendToSelf() throws Exception {
long NUM=1000, total_time;
Address myself=ct1.getLocalAddress();
MyReceiver r=new MyReceiver(ct1, NUM, false);
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct1.setReceiver(r);
for(int i=0; i < NUM; i++) {
ct1.send(myself, data, 0, 0);
}
log("sent " + NUM + " msgs");
r.waitForCompletion();
total_time=r.stop_time - r.start_time;
log("number expected=" + r.getNumExpected() + ", number received=" + r.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r.getNumReceived() + " ms/msg)");
Assert.assertEquals(r.getNumExpected(), r.getNumReceived());
}
public void testSendToOther() throws Exception {
long NUM=1000, total_time;
Address other=ct2.getLocalAddress();
MyReceiver r=new MyReceiver(ct2, NUM, false);
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct2.setReceiver(r);
for(int i=0; i < NUM; i++) {
ct1.send(other, data, 0, 0);
}
log("sent " + NUM + " msgs");
r.waitForCompletion();
total_time=r.stop_time - r.start_time;
log("number expected=" + r.getNumExpected() + ", number received=" + r.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r.getNumReceived() + " ms/msg)");
Assert.assertEquals(r.getNumExpected(), r.getNumReceived());
}
public void testSendToOtherGetResponse() throws Exception {
long NUM=1000, total_time;
Address other=ct2.getLocalAddress();
MyReceiver r1=new MyReceiver(ct1, NUM, false);
MyReceiver r2=new MyReceiver(ct2, NUM, true); // send response
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct1.setReceiver(r1);
ct2.setReceiver(r2);
for(int i=0; i < NUM; i++) {
ct1.send(other, data, 0, 0);
}
log("sent " + NUM + " msgs");
r1.waitForCompletion();
total_time=r1.stop_time - r1.start_time;
log("number expected=" + r1.getNumExpected() + ", number received=" + r1.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r1.getNumReceived() + " ms/msg)");
Assert.assertEquals(r1.getNumExpected(), r1.getNumReceived());
}
static void log(String msg) {
System.out.println("-- [" + Thread.currentThread() + "]: " + msg);
}
static class MyReceiver implements TCPConnectionMap.Receiver {
long num_expected=0, num_received=0, start_time=0, stop_time=0;
boolean done=false, send_response=false;
long modulo;
TCPConnectionMap ct;
MyReceiver(TCPConnectionMap ct, long num_expected, boolean send_response) {
this.ct=ct;
this.num_expected=num_expected;
this.send_response=send_response;
start_time=System.currentTimeMillis();
modulo=num_expected / 10;
}
public long getNumReceived() {
return num_received;
}
public long getNumExpected() {
return num_expected;
}
public void receive(Address sender, byte[] data, int offset, int length) {
num_received++;
if(num_received % modulo == 0)
log("received msg# " + num_received);
if(send_response) {
if(ct != null) {
try {
byte[] rsp=new byte[0];
ct.send(sender, rsp, 0, 0);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
if(num_received >= num_expected) {
synchronized(this) {
if(!done) {
done=true;
stop_time=System.currentTimeMillis();
notifyAll();
}
}
}
}
public void waitForCompletion() {
synchronized(this) {
while(!done) {
try {
wait();
}
catch(InterruptedException e) {
}
}
}
}
}
}
| tests/junit-functional/org/jgroups/tests/ConnectionMapUnitTest.java |
package org.jgroups.tests;
import org.jgroups.Address;
import org.jgroups.Global;
import org.jgroups.blocks.TCPConnectionMap;
import org.jgroups.util.DefaultThreadFactory;
import org.jgroups.util.Util;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Bela Ban
*/
@Test(groups=Global.FUNCTIONAL,sequential=true)
public class ConnectionMapUnitTest {
TCPConnectionMap ct1, ct2;
static final int port1=5555, port2=6666;
@BeforeMethod
protected void setUp() throws Exception {
ct1=new TCPConnectionMap("TCPConnectionMap1",
new DefaultThreadFactory(Util.getGlobalThreadGroup(), "test", true),
null, null, null, null, port1, port1);
ct1.setUseSendQueues(false);
ct1.start();
ct2=new TCPConnectionMap("TCPConnectionMap2",
new DefaultThreadFactory(Util.getGlobalThreadGroup(), "test", true),
null, null, null, null, port2, port2);
ct2.setUseSendQueues(false);
ct2.start();
}
@AfterMethod
void tearDown() throws Exception {
if(ct1 != null) {
ct1.stop();
ct1=null;
}
if(ct2 != null) {
ct2.stop();
ct2=null;
}
}
public void testSetup() {
Assert.assertNotSame(ct1.getLocalAddress(), ct2.getLocalAddress());
}
public void testSendToNullReceiver() throws Exception {
byte[] data=new byte[0];
ct1.send(null, data, 0, data.length);
}
public void testSendEmptyData() throws Exception {
byte[] data=new byte[0];
Address myself=ct1.getLocalAddress();
ct1.setReceiver(new TCPConnectionMap.Receiver() {
public void receive(Address sender, byte[] data, int offset, int length) {}
});
ct1.send(myself, data, 0, data.length);
}
public void testSendNullData() throws Exception {
Address myself=ct1.getLocalAddress();
ct1.send(myself, null, 0, 0);
}
public void testSendToSelf() throws Exception {
long NUM=1000, total_time;
Address myself=ct1.getLocalAddress();
MyReceiver r=new MyReceiver(ct1, NUM, false);
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct1.setReceiver(r);
for(int i=0; i < NUM; i++) {
ct1.send(myself, data, 0, 0);
}
log("sent " + NUM + " msgs");
r.waitForCompletion();
total_time=r.stop_time - r.start_time;
log("number expected=" + r.getNumExpected() + ", number received=" + r.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r.getNumReceived() + " ms/msg)");
Assert.assertEquals(r.getNumExpected(), r.getNumReceived());
}
public void testSendToOther() throws Exception {
long NUM=1000, total_time;
Address other=ct2.getLocalAddress();
MyReceiver r=new MyReceiver(ct2, NUM, false);
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct2.setReceiver(r);
for(int i=0; i < NUM; i++) {
ct1.send(other, data, 0, 0);
}
log("sent " + NUM + " msgs");
r.waitForCompletion();
total_time=r.stop_time - r.start_time;
log("number expected=" + r.getNumExpected() + ", number received=" + r.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r.getNumReceived() + " ms/msg)");
Assert.assertEquals(r.getNumExpected(), r.getNumReceived());
}
public void testSendToOtherGetResponse() throws Exception {
long NUM=1000, total_time;
Address other=ct2.getLocalAddress();
MyReceiver r1=new MyReceiver(ct1, NUM, false);
MyReceiver r2=new MyReceiver(ct2, NUM, true); // send response
byte[] data=new byte[] {'b', 'e', 'l', 'a'};
ct1.setReceiver(r1);
ct2.setReceiver(r2);
for(int i=0; i < NUM; i++) {
ct1.send(other, data, 0, 0);
}
log("sent " + NUM + " msgs");
r1.waitForCompletion();
total_time=r1.stop_time - r1.start_time;
log("number expected=" + r1.getNumExpected() + ", number received=" + r1.getNumReceived() +
", total time=" + total_time + " (" + (double)total_time / r1.getNumReceived() + " ms/msg)");
Assert.assertEquals(r1.getNumExpected(), r1.getNumReceived());
}
static void log(String msg) {
System.out.println("-- [" + Thread.currentThread() + "]: " + msg);
}
static class MyReceiver implements TCPConnectionMap.Receiver {
long num_expected=0, num_received=0, start_time=0, stop_time=0;
boolean done=false, send_response=false;
long modulo;
TCPConnectionMap ct;
MyReceiver(TCPConnectionMap ct, long num_expected, boolean send_response) {
this.ct=ct;
this.num_expected=num_expected;
this.send_response=send_response;
start_time=System.currentTimeMillis();
modulo=num_expected / 10;
}
public long getNumReceived() {
return num_received;
}
public long getNumExpected() {
return num_expected;
}
public void receive(Address sender, byte[] data, int offset, int length) {
num_received++;
if(num_received % modulo == 0)
log("received msg# " + num_received);
if(send_response) {
if(ct != null) {
try {
byte[] rsp=new byte[0];
ct.send(sender, rsp, 0, 0);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
if(num_received >= num_expected) {
synchronized(this) {
if(!done) {
done=true;
stop_time=System.currentTimeMillis();
notifyAll();
}
}
}
}
public void waitForCompletion() {
synchronized(this) {
while(!done) {
try {
wait();
}
catch(InterruptedException e) {
}
}
}
}
}
}
| changed ports from 5555 to 15555 and 6666 to 16666 (conflicts with IntelliJ ports)
| tests/junit-functional/org/jgroups/tests/ConnectionMapUnitTest.java | changed ports from 5555 to 15555 and 6666 to 16666 (conflicts with IntelliJ ports) | <ide><path>ests/junit-functional/org/jgroups/tests/ConnectionMapUnitTest.java
<ide> @Test(groups=Global.FUNCTIONAL,sequential=true)
<ide> public class ConnectionMapUnitTest {
<ide> TCPConnectionMap ct1, ct2;
<del> static final int port1=5555, port2=6666;
<add> static final int port1=15555, port2=16666;
<ide>
<ide>
<ide> |
|
Java | apache-2.0 | e6c1aca23c396502136b31f743af8ed18b9d3743 | 0 | d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor,d3sw/conductor | package com.netflix.conductor.aurora;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.netflix.conductor.common.metadata.events.EventExecution;
import com.netflix.conductor.common.metadata.events.EventPublished;
import com.netflix.conductor.common.metadata.tasks.PollData;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.dao.ExecutionDAO;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.MetadataDAO;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class AuroraExecutionDAO extends AuroraBaseDAO implements ExecutionDAO {
private MetadataDAO metadata;
private IndexDAO indexer;
@Inject
public AuroraExecutionDAO(DataSource dataSource, ObjectMapper mapper,
MetadataDAO metadata, IndexDAO indexer) {
super(dataSource, mapper);
this.metadata = metadata;
this.indexer = indexer;
}
@Override
@Deprecated // Not used by core engine
public List<Task> getPendingTasksByWorkflow(String taskName, String workflowId) {
String SQL = "SELECT t.json_data FROM task_in_progress tip " +
"INNER JOIN task t ON t.task_id = tip.task_id " +
"WHERE tip.task_def_name = ? AND tip.workflow_id = ?";
return queryWithTransaction(SQL, q -> q.addParameter(taskName)
.addParameter(workflowId)
.executeAndFetch(Task.class));
}
@Override
public List<Task> getPendingTasksForTaskType(String taskType) {
String SQL = "SELECT t.json_data FROM task_in_progress tip " +
"INNER JOIN task t ON t.task_id = tip.task_id " +
"WHERE tip.task_def_name = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(taskType).executeAndFetch(Task.class));
}
@Override
public List<Task> getPendingSystemTasks(String taskType) {
String SQL = "SELECT json_data FROM task WHERE task_type = ? AND task_status = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(taskType)
.addParameter("IN_PROGRESS")
.executeAndFetch(Task.class));
}
@Override
public List<Task> getTasks(String taskType, String startKey, int count) {
List<Task> tasks = Lists.newLinkedList();
List<Task> pendingTasks = getPendingTasksForTaskType(taskType);
boolean startKeyFound = startKey == null;
int foundCount = 0;
for (Task pendingTask : pendingTasks) {
if (!startKeyFound) {
if (pendingTask.getTaskId().equals(startKey)) {
startKeyFound = true;
continue;
}
}
if (startKeyFound && foundCount < count) {
tasks.add(pendingTask);
foundCount++;
}
}
return tasks;
}
@Override
public List<Task> createTasks(List<Task> tasks) {
List<Task> created = Lists.newLinkedList();
withTransaction(tx -> {
for (Task task : tasks) {
Preconditions.checkNotNull(task, "task object cannot be null");
Preconditions.checkNotNull(task.getTaskId(), "Task id cannot be null");
Preconditions.checkNotNull(task.getWorkflowInstanceId(), "Workflow instance id cannot be null");
Preconditions.checkNotNull(task.getReferenceTaskName(), "Task reference name cannot be null");
boolean taskAdded = addScheduledTask(tx, task);
if (!taskAdded) {
String taskKey = task.getReferenceTaskName() + task.getRetryCount();
logger.debug("Task already scheduled, skipping the run " + task.getTaskId() +
", ref=" + task.getReferenceTaskName() + ", key=" + taskKey);
continue;
}
// Set schedule time here, after task was added to schedule table (it does not contain schedule time)
task.setScheduledTime(System.currentTimeMillis());
//The flag is boolean object, setting it to false so workflow executor can properly determine the state
task.setStarted(false);
addTaskInProgress(tx, task);
updateTask(tx, task);
created.add(task);
}
});
return created;
}
@Override
public void updateTask(Task task) {
withTransaction(tx -> updateTask(tx, task));
}
@Override
public boolean exceedsInProgressLimit(Task task) {
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef == null) {
return false;
}
int limit = taskDef.concurrencyLimit();
if (limit <= 0) {
return false;
}
long current = getInProgressTaskCount(task.getTaskDefName());
if (current >= limit) {
return true;
}
logger.debug("Task execution count for {}: limit={}, current={}", task.getTaskDefName(), limit, current);
String SQL = "SELECT task_id FROM task_in_progress WHERE task_def_name = ? ORDER BY id LIMIT ?";
List<String> taskIds = queryWithTransaction(SQL,
q -> q.addParameter(task.getTaskDefName()).addParameter(limit).executeScalarList(String.class));
boolean rateLimited = !taskIds.contains(task.getTaskId());
if (rateLimited) {
logger.debug("Task execution count limited. {}, limit {}, current {}", task.getTaskDefName(), limit, current);
}
return rateLimited;
}
@Override
public boolean exceedsRateLimitPerFrequency(Task task) {
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef == null) {
return false;
}
Integer rateLimitPerFrequency = taskDef.getRateLimitPerFrequency();
Integer rateLimitFrequencyInSeconds = taskDef.getRateLimitFrequencyInSeconds();
if (rateLimitPerFrequency == null || rateLimitPerFrequency <= 0 ||
rateLimitFrequencyInSeconds == null || rateLimitFrequencyInSeconds <= 0) {
return false;
}
logger.debug("Evaluating rate limiting for Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds);
long currentTimeEpochMillis = System.currentTimeMillis();
long currentTimeEpochMinusRateLimitBucket = currentTimeEpochMillis - (rateLimitFrequencyInSeconds * 1000);
// Delete the expired records first
String SQL = "DELETE FROM task_rate_limit WHERE task_def_name = ? AND created_on < ?";
executeWithTransaction(SQL, q -> q
.addParameter(taskDef.getName())
.addTimestampParameter(currentTimeEpochMinusRateLimitBucket)
.executeDelete());
// Count how many left between currentTimeEpochMinusRateLimitBucket and currentTimeEpochMillis
SQL = "SELECT COUNT(*) FROM task_rate_limit WHERE task_def_name = ? AND created_on BETWEEN ? AND ?";
long currentBucketCount = queryWithTransaction(SQL, q -> q
.addParameter(taskDef.getName())
.addTimestampParameter(currentTimeEpochMinusRateLimitBucket)
.addTimestampParameter(currentTimeEpochMillis)
.executeScalar(Long.class));
// Within the rate limit
if (currentBucketCount < rateLimitPerFrequency) {
SQL = "INSERT INTO task_rate_limit(created_on,expires_on,task_def_name) VALUES (?,?,?)";
executeWithTransaction(SQL, q -> q
.addTimestampParameter(currentTimeEpochMillis)
.addTimestampParameter(System.currentTimeMillis() + (rateLimitFrequencyInSeconds * 1000))
.addParameter(taskDef.getName())
.executeUpdate());
logger.debug("Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {} within the rate limit with current count {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds, ++currentBucketCount);
return false;
}
logger.debug("Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {} is out of bounds of rate limit with current count {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds, currentBucketCount);
return true;
}
@Override
public void updateTasks(List<Task> tasks) {
withTransaction(tx -> {
for (Task task : tasks) {
updateTask(tx, task);
}
});
}
@Override
public void addTaskExecLog(List<TaskExecLog> log) {
indexer.add(log);
}
@Override
public void removeTask(String taskId) {
Task task = getTask(taskId);
if (task == null) {
logger.debug("No such task found by id {}", taskId);
return;
}
withTransaction(tx -> removeTask(tx, task));
}
@Override
public void removeTask(Task task) {
withTransaction(tx -> removeTask(tx, task));
}
@Override
public Task getTask(String taskId) {
return getWithTransaction(tx -> getTask(tx, taskId));
}
@Override
public Task getTask(String workflowId, String taskRefName) {
String GET_TASK = "SELECT json_data FROM task WHERE workflow_id = ? and task_refname = ? ORDER BY id DESC";
return queryWithTransaction(GET_TASK, q -> q
.addParameter(workflowId)
.addParameter(taskRefName)
.executeAndFetchFirst(Task.class));
}
@Override
public List<Task> getTasks(List<String> taskIds) {
if (taskIds == null || taskIds.isEmpty()) {
return Lists.newArrayList();
}
return getWithTransaction(tx -> taskIds.stream()
.map(id -> getTask(tx, id))
.filter(Objects::nonNull)
.collect(Collectors.toList()));
}
@Override
public List<Task> getTasksForWorkflow(String workflowId) {
String SQL = "SELECT task_id FROM task WHERE workflow_id = ?";
List<String> taskIds = getWithTransaction(tx -> query(tx, SQL, q -> q.addParameter(workflowId).executeScalarList(String.class)));
return getTasks(taskIds);
}
private Task getTask(Connection tx, String taskId) {
String GET_TASK = "SELECT json_data FROM task WHERE task_id = ?";
return query(tx, GET_TASK, q -> q.addParameter(taskId).executeAndFetchFirst(Task.class));
}
@Override
public String createWorkflow(Workflow workflow) {
return insertOrUpdateWorkflow(workflow, false);
}
@Override
public String updateWorkflow(Workflow workflow) {
return insertOrUpdateWorkflow(workflow, true);
}
@Override
public void removeWorkflow(String workflowId) {
Workflow workflow = getWorkflow(workflowId, true);
if (workflow == null)
return;
withTransaction(tx -> {
for (Task task : workflow.getTasks()) {
removeTask(tx, task);
}
removeWorkflow(tx, workflowId);
});
}
@Override
@Deprecated
public void removeFromPendingWorkflow(String workflowType, String workflowId) {
// not in use any more. See references
}
@Override
public Workflow getWorkflow(String workflowId) {
return getWorkflow(workflowId, true);
}
@Override
public Workflow getWorkflow(String workflowId, boolean includeTasks) {
Workflow workflow = getWithTransaction(tx -> readWorkflow(tx, workflowId));
if (workflow != null) {
if (includeTasks) {
List<Task> tasks = getTasksForWorkflow(workflowId);
tasks.sort(Comparator.comparingLong(Task::getScheduledTime).thenComparingInt(Task::getSeq));
workflow.setTasks(tasks);
}
return workflow;
}
return null;
}
@Override
public List<String> getRunningWorkflowIds(String workflowName) {
return getWithTransaction(tx -> getRunningWorkflowIds(tx, workflowName));
}
private List<String> getRunningWorkflowIds(Connection tx, String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
String SQL = "SELECT workflow_id FROM workflow WHERE workflow_type = ? AND workflow_status IN ('RUNNING','PAUSED')";
return query(tx, SQL, q -> q.addParameter(workflowName).executeScalarList(String.class));
}
@Override
public List<Workflow> getPendingWorkflowsByType(String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
List<String> workflowIds = getWithTransaction(tx -> getRunningWorkflowIds(tx, workflowName));
return workflowIds.stream()
.map(id -> getWorkflow(id, true))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public long getPendingWorkflowCount(String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
String SQL = "SELECT COUNT(*) FROM workflow WHERE workflow_type = ? AND workflow_status IN ('RUNNING','PAUSED')";
return queryWithTransaction(SQL, q -> q.addParameter(workflowName).executeCount());
}
@Override
public long getInProgressTaskCount(String taskDefName) {
String SQL = "SELECT COUNT(*) FROM task_in_progress WHERE task_def_name = ? AND in_progress = true";
return queryWithTransaction(SQL, q -> q.addParameter(taskDefName).executeCount());
}
@Override
public List<Workflow> getWorkflowsByType(String workflowName, Long startTime, Long endTime) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
Preconditions.checkNotNull(startTime, "startTime cannot be null");
Preconditions.checkNotNull(endTime, "endTime cannot be null");
List<Workflow> workflows = new LinkedList<>();
withTransaction(tx -> {
String SQL = "SELECT workflow_id FROM workflow WHERE workflow_type = ? AND date_str BETWEEN ? AND ?";
List<String> workflowIds = query(tx, SQL, q -> q.addParameter(workflowName)
.addParameter(dateStr(startTime)).addParameter(dateStr(endTime)).executeScalarList(String.class));
workflowIds.forEach(workflowId -> {
try {
Workflow wf = getWorkflow(workflowId);
if (wf.getCreateTime() >= startTime && wf.getCreateTime() <= endTime) {
workflows.add(wf);
}
} catch (Exception e) {
logger.error("Unable to load workflow id {} with name {}", workflowId, workflowName, e);
}
});
});
return workflows;
}
@Override
public List<Workflow> getWorkflowsByCorrelationId(String correlationId) {
Preconditions.checkNotNull(correlationId, "correlationId cannot be null");
String SQL = "SELECT workflow_id FROM workflow WHERE correlation_id = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(correlationId).executeScalarList(String.class).stream()
.map(this::getWorkflow).collect(Collectors.toList()));
}
@Override
public boolean addEventExecution(EventExecution ee) {
return getWithTransaction(tx -> insertEventExecution(tx, ee));
}
@Override
public void updateEventExecution(EventExecution ee) {
withTransaction(tx -> updateEventExecution(tx, ee));
}
@Override
@Deprecated
public List<EventExecution> getEventExecutions(String eventHandlerName, String eventName, String messageId, int max) {
// not in use any more. See references
return Collections.emptyList();
}
@Override
public void addMessage(String queue, Message msg) {
indexer.addMessage(queue, msg);
}
@Override
public void updateLastPoll(String taskDefName, String domain, String workerId) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
PollData pollData = new PollData(taskDefName, domain, workerId, System.currentTimeMillis());
String effectiveDomain = (domain == null) ? "DEFAULT" : domain;
withTransaction(tx -> insertOrUpdatePollData(tx, pollData, effectiveDomain));
}
@Override
public PollData getPollData(String taskDefName, String domain) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
String effectiveDomain = (domain == null) ? "DEFAULT" : domain;
return getWithTransaction(tx -> readPollData(tx, taskDefName, effectiveDomain));
}
@Override
public List<PollData> getPollData(String taskDefName) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
return readAllPollData(taskDefName);
}
@Override
public void addEventPublished(EventPublished ep) {
getWithTransaction(tx -> insertEventPublished(tx, ep));
}
/**
* Function to find tasks in the workflows which associated with given tags
* <p>
* Includes task into result if:
* workflow.tags contains ALL values from the tags parameter
* and task type matches the given task type
* and the task status is IN_PROGRESS
*
* @param tags A set of tags
* @return List of tasks
*/
@Override
public List<Task> getPendingTasksByTags(String taskType, Set<String> tags) {
String SQL = "SELECT t.json_data FROM task t " +
"INNER JOIN workflow w ON w.workflow_id = t.workflow_id " +
"WHERE t.task_type = ? AND t.task_status = ? AND w.tags @> ?";
return queryWithTransaction(SQL, q -> q.addParameter(taskType)
.addParameter("IN_PROGRESS")
.addParameter(tags)
.executeAndFetch(Task.class));
}
/**
* Function to check is there any workflows associated with given tags
* Returns true if workflow.tags contains ALL values from the tags parameter
* Otherwise returns false
*
* @param tags A set of tags
* @return Either true or false
*/
@Override
public boolean anyRunningWorkflowsByTags(Set<String> tags) {
String SQL = "SELECT COUNT(*) FROM workflow WHERE tags @> ?";
return queryWithTransaction(SQL, q -> q.addParameter(tags).executeScalar(Long.class) > 0);
}
@Override
public void resetStartTime(Task task, boolean updateOutput) {
Map<String, Object> payload = new HashMap<>();
payload.put("startTime", task.getStartTime());
payload.put("endTime", task.getEndTime());
if (updateOutput) {
payload.put("outputData", task.getOutputData());
}
String SQL = "UPDATE task SET json_data = (json_data::jsonb || ?::jsonb)::text WHERE task_id = ?";
executeWithTransaction(SQL, q -> q
.addJsonParameter(payload)
.addParameter(task.getTaskId())
.executeUpdate());
}
private static int dateStr(Long timeInMs) {
Date date = new Date(timeInMs);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return Integer.parseInt(format.format(date));
}
private boolean addScheduledTask(Connection tx, Task task) {
String taskKey = task.getReferenceTaskName() + task.getRetryCount();
final String CHECK_SQL = "SELECT true FROM task_scheduled WHERE workflow_id = ? AND task_key = ?";
boolean exists = query(tx, CHECK_SQL, q -> q
.addParameter(task.getWorkflowInstanceId())
.addParameter(taskKey)
.executeScalar(Boolean.class));
// Return task not scheduled (false) if it is already exists
if (exists) {
return false;
}
// Warning! Constraint name is also unique index name
final String ADD_SQL = "INSERT INTO task_scheduled (workflow_id, task_key, task_id) " +
"VALUES (?, ?, ?) ON CONFLICT ON CONSTRAINT task_scheduled_wf_task DO NOTHING";
int count = query(tx, ADD_SQL, q -> q
.addParameter(task.getWorkflowInstanceId())
.addParameter(taskKey)
.addParameter(task.getTaskId())
.executeUpdate());
return count > 0;
}
private void removeTask(Connection tx, Task task) {
final String taskKey = task.getReferenceTaskName() + task.getRetryCount();
removeScheduledTask(tx, task, taskKey);
removeTaskInProgress(tx, task);
removeTaskData(tx, task);
}
private void insertOrUpdateTask(Connection tx, Task task) {
// Warning! Constraint name is also unique index name
String SQL = "INSERT INTO task (task_id, task_type, task_refname, task_status, json_data, workflow_id, " +
"start_time, end_time, input, output) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT ON CONSTRAINT task_task_id DO " +
"UPDATE SET modified_on=now(), task_status=?, json_data=?, input = ?, output = ?, start_time = ?, end_time = ?";
execute(tx, SQL, q -> q
.addParameter(task.getTaskId())
.addParameter(task.getTaskType())
.addParameter(task.getReferenceTaskName())
.addParameter(task.getStatus().name())
.addJsonParameter(task)
.addParameter(task.getWorkflowInstanceId())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime())
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addParameter(task.getStatus().name())
.addJsonParameter(task)
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime())
.executeUpdate());
}
private void updateTask(Connection tx, Task task) {
task.setUpdateTime(System.currentTimeMillis());
if (task.getStatus() != null && task.getStatus().isTerminal()) {
task.setEndTime(System.currentTimeMillis());
}
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef != null && taskDef.concurrencyLimit() > 0) {
updateInProgressStatus(tx, task);
}
insertOrUpdateTask(tx, task);
if (task.getStatus() != null && task.getStatus().isTerminal()) {
removeTaskInProgress(tx, task);
}
}
private String insertOrUpdateWorkflow(Workflow workflow, boolean update) {
Preconditions.checkNotNull(workflow, "workflow object cannot be null");
if (workflow.getStatus().isTerminal()) {
workflow.setEndTime(System.currentTimeMillis());
}
List<Task> tasks = workflow.getTasks();
workflow.setTasks(Lists.newLinkedList());
withTransaction(tx -> {
if (update) {
updateWorkflow(tx, workflow);
} else {
addWorkflow(tx, workflow);
}
});
workflow.setTasks(tasks);
return workflow.getWorkflowId();
}
private void addWorkflow(Connection tx, Workflow workflow) {
String SQL = "INSERT INTO workflow (workflow_id, parent_workflow_id, workflow_type, workflow_status, " +
"correlation_id, tags, input, json_data, date_str, start_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
execute(tx, SQL, q -> q.addParameter(workflow.getWorkflowId())
.addParameter(workflow.getParentWorkflowId())
.addParameter(workflow.getWorkflowType())
.addParameter(workflow.getStatus().name())
.addParameter(workflow.getCorrelationId())
.addParameter(workflow.getTags())
.addJsonParameter(workflow.getInput())
.addJsonParameter(workflow)
.addParameter(dateStr(workflow.getCreateTime()))
.addTimestampParameter(workflow.getStartTime())
.executeUpdate());
}
private void updateWorkflow(Connection tx, Workflow workflow) {
String SQL = "UPDATE workflow SET json_data = ?, workflow_status = ?, output = ?, end_time = ?, " +
"tags = ?, modified_on = now() WHERE workflow_id = ?";
// We must not delete tags for RESET as it must be restarted right away
Set<String> tags;
if (workflow.getStatus().isTerminal() && workflow.getStatus() != Workflow.WorkflowStatus.RESET) {
tags = Collections.emptySet();
} else {
tags = workflow.getTags();
}
execute(tx, SQL,
q -> q.addJsonParameter(workflow)
.addParameter(workflow.getStatus().name())
.addJsonParameter(workflow.getOutput())
.addTimestampParameter(workflow.getEndTime())
.addParameter(tags)
.addParameter(workflow.getWorkflowId())
.executeUpdate());
}
private Workflow readWorkflow(Connection tx, String workflowId) {
String SQL = "SELECT json_data FROM workflow WHERE workflow_id = ?";
return query(tx, SQL, q -> q.addParameter(workflowId).executeAndFetchFirst(Workflow.class));
}
private void removeWorkflow(Connection tx, String workflowId) {
String SQL = "DELETE FROM workflow WHERE workflow_id = ?";
execute(tx, SQL, q -> q.addParameter(workflowId).executeDelete());
}
private void addTaskInProgress(Connection tx, Task task) {
String SQL = "INSERT INTO task_in_progress (task_def_name, task_id, workflow_id) VALUES (?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT task_in_progress_fields DO NOTHING";
execute(tx, SQL, q -> q.addParameter(task.getTaskDefName())
.addParameter(task.getTaskId())
.addParameter(task.getWorkflowInstanceId())
.executeUpdate());
}
private void removeTaskInProgress(Connection tx, Task task) {
String SQL = "DELETE FROM task_in_progress WHERE task_def_name = ? AND task_id = ?";
execute(tx, SQL,
q -> q.addParameter(task.getTaskDefName()).addParameter(task.getTaskId()).executeUpdate());
}
private void updateInProgressStatus(Connection tx, Task task) {
boolean inProgress = Task.Status.IN_PROGRESS.equals(task.getStatus());
String SQL = "UPDATE task_in_progress SET in_progress = ?, modified_on = now() "
+ "WHERE task_def_name = ? AND task_id = ?";
execute(tx, SQL, q -> q.addParameter(inProgress)
.addParameter(task.getTaskDefName()).addParameter(task.getTaskId()).executeUpdate());
}
private void removeScheduledTask(Connection tx, Task task, String taskKey) {
String SQL = "DELETE FROM task_scheduled WHERE workflow_id = ? AND task_key = ?";
execute(tx, SQL,
q -> q.addParameter(task.getWorkflowInstanceId()).addParameter(taskKey).executeDelete());
}
private void removeTaskData(Connection tx, Task task) {
String SQL = "DELETE FROM task WHERE task_id = ?";
execute(tx, SQL, q -> q.addParameter(task.getTaskId()).executeDelete());
}
private boolean insertEventExecution(Connection tx, EventExecution ee) {
String SQL = "INSERT INTO event_execution" +
"(handler_name, event_name, message_id, execution_id, status, subject, received_on, accepted_on) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT event_execution_fields DO NOTHING";
int count = query(tx, SQL, q -> q.addParameter(ee.getName())
.addParameter(ee.getEvent())
.addParameter(ee.getMessageId())
.addParameter(ee.getId())
.addParameter(ee.getStatus().name())
.addParameter(ee.getSubject())
.addTimestampParameter(ee.getReceived())
.addTimestampParameter(ee.getAccepted())
.executeUpdate());
return count > 0;
}
private void updateEventExecution(Connection tx, EventExecution ee) {
String SQL = "UPDATE event_execution SET " +
"modified_on = now(), status = ?, started_on = ?, processed_on = ?" +
"WHERE handler_name = ? AND event_name = ? " +
"AND message_id = ? AND execution_id = ?";
execute(tx, SQL, q -> q.addParameter(ee.getStatus().name())
.addTimestampParameter(ee.getStarted())
.addTimestampParameter(ee.getProcessed())
.addParameter(ee.getName())
.addParameter(ee.getEvent())
.addParameter(ee.getMessageId())
.addParameter(ee.getId())
.executeUpdate());
}
private boolean insertEventPublished(Connection tx, EventPublished ep) {
String SQL = "INSERT INTO event_published" +
"(json_data, message_id, subject, published_on) " +
"VALUES (?, ?, ?, ?)";
int count = query(tx, SQL, q -> q.addJsonParameter(ep)
.addParameter(ep.getId())
.addParameter(ep.getSubject())
.addTimestampParameter(ep.getPublished())
.executeUpdate());
return count > 0;
}
private void insertOrUpdatePollData(Connection tx, PollData pollData, String domain) {
// Warning! Constraint name is also unique index name
String SQL = "INSERT INTO poll_data (queue_name, domain, json_data) VALUES (?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT poll_data_fields DO UPDATE SET json_data=?, modified_on=now()";
execute(tx, SQL, q -> q.addParameter(pollData.getQueueName())
.addParameter(domain)
.addJsonParameter(pollData)
.addJsonParameter(pollData)
.executeUpdate());
}
private PollData readPollData(Connection tx, String queueName, String domain) {
String SQL = "SELECT json_data FROM poll_data WHERE queue_name = ? AND domain = ?";
return query(tx, SQL,
q -> q.addParameter(queueName).addParameter(domain).executeAndFetchFirst(PollData.class));
}
private List<PollData> readAllPollData(String queueName) {
String SQL = "SELECT json_data FROM poll_data WHERE queue_name = ?";
return queryWithTransaction(SQL, q -> q.addParameter(queueName).executeAndFetch(PollData.class));
}
}
| postgresql-persistence/src/main/java/com/netflix/conductor/aurora/AuroraExecutionDAO.java | package com.netflix.conductor.aurora;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.netflix.conductor.common.metadata.events.EventExecution;
import com.netflix.conductor.common.metadata.events.EventPublished;
import com.netflix.conductor.common.metadata.tasks.PollData;
import com.netflix.conductor.common.metadata.tasks.Task;
import com.netflix.conductor.common.metadata.tasks.TaskDef;
import com.netflix.conductor.common.metadata.tasks.TaskExecLog;
import com.netflix.conductor.common.run.Workflow;
import com.netflix.conductor.core.events.queue.Message;
import com.netflix.conductor.dao.ExecutionDAO;
import com.netflix.conductor.dao.IndexDAO;
import com.netflix.conductor.dao.MetadataDAO;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class AuroraExecutionDAO extends AuroraBaseDAO implements ExecutionDAO {
private MetadataDAO metadata;
private IndexDAO indexer;
@Inject
public AuroraExecutionDAO(DataSource dataSource, ObjectMapper mapper,
MetadataDAO metadata, IndexDAO indexer) {
super(dataSource, mapper);
this.metadata = metadata;
this.indexer = indexer;
}
@Override
@Deprecated // Not used by core engine
public List<Task> getPendingTasksByWorkflow(String taskName, String workflowId) {
String SQL = "SELECT t.json_data FROM task_in_progress tip " +
"INNER JOIN task t ON t.task_id = tip.task_id " +
"WHERE tip.task_def_name = ? AND tip.workflow_id = ?";
return queryWithTransaction(SQL, q -> q.addParameter(taskName)
.addParameter(workflowId)
.executeAndFetch(Task.class));
}
@Override
public List<Task> getPendingTasksForTaskType(String taskType) {
String SQL = "SELECT t.json_data FROM task_in_progress tip " +
"INNER JOIN task t ON t.task_id = tip.task_id " +
"WHERE tip.task_def_name = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(taskType).executeAndFetch(Task.class));
}
@Override
public List<Task> getPendingSystemTasks(String taskType) {
String SQL = "SELECT json_data FROM task WHERE task_type = ? AND task_status = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(taskType)
.addParameter("IN_PROGRESS")
.executeAndFetch(Task.class));
}
@Override
public List<Task> getTasks(String taskType, String startKey, int count) {
List<Task> tasks = Lists.newLinkedList();
List<Task> pendingTasks = getPendingTasksForTaskType(taskType);
boolean startKeyFound = startKey == null;
int foundCount = 0;
for (Task pendingTask : pendingTasks) {
if (!startKeyFound) {
if (pendingTask.getTaskId().equals(startKey)) {
startKeyFound = true;
continue;
}
}
if (startKeyFound && foundCount < count) {
tasks.add(pendingTask);
foundCount++;
}
}
return tasks;
}
@Override
public List<Task> createTasks(List<Task> tasks) {
List<Task> created = Lists.newLinkedList();
withTransaction(tx -> {
for (Task task : tasks) {
Preconditions.checkNotNull(task, "task object cannot be null");
Preconditions.checkNotNull(task.getTaskId(), "Task id cannot be null");
Preconditions.checkNotNull(task.getWorkflowInstanceId(), "Workflow instance id cannot be null");
Preconditions.checkNotNull(task.getReferenceTaskName(), "Task reference name cannot be null");
boolean taskAdded = addScheduledTask(tx, task);
if (!taskAdded) {
String taskKey = task.getReferenceTaskName() + task.getRetryCount();
logger.debug("Task already scheduled, skipping the run " + task.getTaskId() +
", ref=" + task.getReferenceTaskName() + ", key=" + taskKey);
continue;
}
// Set schedule time here, after task was added to schedule table (it does not contain schedule time)
task.setScheduledTime(System.currentTimeMillis());
//The flag is boolean object, setting it to false so workflow executor can properly determine the state
task.setStarted(false);
addTaskInProgress(tx, task);
updateTask(tx, task);
created.add(task);
}
});
return created;
}
@Override
public void updateTask(Task task) {
withTransaction(tx -> updateTask(tx, task));
}
@Override
public boolean exceedsInProgressLimit(Task task) {
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef == null) {
return false;
}
int limit = taskDef.concurrencyLimit();
if (limit <= 0) {
return false;
}
long current = getInProgressTaskCount(task.getTaskDefName());
if (current >= limit) {
return true;
}
logger.debug("Task execution count for {}: limit={}, current={}", task.getTaskDefName(), limit, current);
String SQL = "SELECT task_id FROM task_in_progress WHERE task_def_name = ? ORDER BY id LIMIT ?";
List<String> taskIds = queryWithTransaction(SQL,
q -> q.addParameter(task.getTaskDefName()).addParameter(limit).executeScalarList(String.class));
boolean rateLimited = !taskIds.contains(task.getTaskId());
if (rateLimited) {
logger.debug("Task execution count limited. {}, limit {}, current {}", task.getTaskDefName(), limit, current);
}
return rateLimited;
}
@Override
public boolean exceedsRateLimitPerFrequency(Task task) {
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef == null) {
return false;
}
Integer rateLimitPerFrequency = taskDef.getRateLimitPerFrequency();
Integer rateLimitFrequencyInSeconds = taskDef.getRateLimitFrequencyInSeconds();
if (rateLimitPerFrequency == null || rateLimitPerFrequency <= 0 ||
rateLimitFrequencyInSeconds == null || rateLimitFrequencyInSeconds <= 0) {
return false;
}
logger.debug("Evaluating rate limiting for Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds);
long currentTimeEpochMillis = System.currentTimeMillis();
long currentTimeEpochMinusRateLimitBucket = currentTimeEpochMillis - (rateLimitFrequencyInSeconds * 1000);
// Delete the expired records first
String SQL = "DELETE FROM task_rate_limit WHERE task_def_name = ? AND created_on < ?";
executeWithTransaction(SQL, q -> q
.addParameter(taskDef.getName())
.addTimestampParameter(currentTimeEpochMinusRateLimitBucket)
.executeDelete());
// Count how many left between currentTimeEpochMinusRateLimitBucket and currentTimeEpochMillis
SQL = "SELECT COUNT(*) FROM task_rate_limit WHERE task_def_name = ? AND created_on BETWEEN ? AND ?";
long currentBucketCount = queryWithTransaction(SQL, q -> q
.addParameter(taskDef.getName())
.addTimestampParameter(currentTimeEpochMinusRateLimitBucket)
.addTimestampParameter(currentTimeEpochMillis)
.executeScalar(Long.class));
// Within the rate limit
if (currentBucketCount < rateLimitPerFrequency) {
SQL = "INSERT INTO task_rate_limit(created_on,expires_on,task_def_name) VALUES (?,?,?)";
executeWithTransaction(SQL, q -> q
.addTimestampParameter(currentTimeEpochMillis)
.addTimestampParameter(System.currentTimeMillis() + (rateLimitFrequencyInSeconds * 1000))
.addParameter(taskDef.getName())
.executeUpdate());
logger.debug("Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {} within the rate limit with current count {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds, ++currentBucketCount);
return false;
}
logger.debug("Task: {} with rateLimitPerFrequency: {} and rateLimitFrequencyInSeconds: {} is out of bounds of rate limit with current count {}",
task, rateLimitPerFrequency, rateLimitFrequencyInSeconds, currentBucketCount);
return true;
}
@Override
public void updateTasks(List<Task> tasks) {
withTransaction(tx -> {
for (Task task : tasks) {
updateTask(tx, task);
}
});
}
@Override
public void addTaskExecLog(List<TaskExecLog> log) {
indexer.add(log);
}
@Override
public void removeTask(String taskId) {
Task task = getTask(taskId);
if (task == null) {
logger.debug("No such task found by id {}", taskId);
return;
}
withTransaction(tx -> removeTask(tx, task));
}
@Override
public void removeTask(Task task) {
withTransaction(tx -> removeTask(tx, task));
}
@Override
public Task getTask(String taskId) {
return getWithTransaction(tx -> getTask(tx, taskId));
}
@Override
public Task getTask(String workflowId, String taskRefName) {
String GET_TASK = "SELECT json_data FROM task WHERE workflow_id = ? and task_refname = ? ORDER BY id DESC";
return queryWithTransaction(GET_TASK, q -> q
.addParameter(workflowId)
.addParameter(taskRefName)
.executeAndFetchFirst(Task.class));
}
@Override
public List<Task> getTasks(List<String> taskIds) {
if (taskIds == null || taskIds.isEmpty()) {
return Lists.newArrayList();
}
return getWithTransaction(tx -> taskIds.stream().map(id -> getTask(tx, id)))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public List<Task> getTasksForWorkflow(String workflowId) {
String SQL = "SELECT task_id FROM task WHERE workflow_id = ?";
List<String> taskIds = getWithTransaction(tx -> query(tx, SQL, q -> q.addParameter(workflowId).executeScalarList(String.class)));
return getTasks(taskIds);
}
private Task getTask(Connection tx, String taskId) {
String GET_TASK = "SELECT json_data FROM task WHERE task_id = ?";
return query(tx, GET_TASK, q -> q.addParameter(taskId).executeAndFetchFirst(Task.class));
}
@Override
public String createWorkflow(Workflow workflow) {
return insertOrUpdateWorkflow(workflow, false);
}
@Override
public String updateWorkflow(Workflow workflow) {
return insertOrUpdateWorkflow(workflow, true);
}
@Override
public void removeWorkflow(String workflowId) {
Workflow workflow = getWorkflow(workflowId, true);
if (workflow == null)
return;
withTransaction(tx -> {
for (Task task : workflow.getTasks()) {
removeTask(tx, task);
}
removeWorkflow(tx, workflowId);
});
}
@Override
@Deprecated
public void removeFromPendingWorkflow(String workflowType, String workflowId) {
// not in use any more. See references
}
@Override
public Workflow getWorkflow(String workflowId) {
return getWorkflow(workflowId, true);
}
@Override
public Workflow getWorkflow(String workflowId, boolean includeTasks) {
Workflow workflow = getWithTransaction(tx -> readWorkflow(tx, workflowId));
if (workflow != null) {
if (includeTasks) {
List<Task> tasks = getTasksForWorkflow(workflowId);
tasks.sort(Comparator.comparingLong(Task::getScheduledTime).thenComparingInt(Task::getSeq));
workflow.setTasks(tasks);
}
return workflow;
}
return null;
}
@Override
public List<String> getRunningWorkflowIds(String workflowName) {
return getWithTransaction(tx -> getRunningWorkflowIds(tx, workflowName));
}
private List<String> getRunningWorkflowIds(Connection tx, String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
String SQL = "SELECT workflow_id FROM workflow WHERE workflow_type = ? AND workflow_status IN ('RUNNING','PAUSED')";
return query(tx, SQL, q -> q.addParameter(workflowName).executeScalarList(String.class));
}
@Override
public List<Workflow> getPendingWorkflowsByType(String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
List<String> workflowIds = getWithTransaction(tx -> getRunningWorkflowIds(tx, workflowName));
return workflowIds.stream()
.map(id -> getWorkflow(id, true))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
@Override
public long getPendingWorkflowCount(String workflowName) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
String SQL = "SELECT COUNT(*) FROM workflow WHERE workflow_type = ? AND workflow_status IN ('RUNNING','PAUSED')";
return queryWithTransaction(SQL, q -> q.addParameter(workflowName).executeCount());
}
@Override
public long getInProgressTaskCount(String taskDefName) {
String SQL = "SELECT COUNT(*) FROM task_in_progress WHERE task_def_name = ? AND in_progress = true";
return queryWithTransaction(SQL, q -> q.addParameter(taskDefName).executeCount());
}
@Override
public List<Workflow> getWorkflowsByType(String workflowName, Long startTime, Long endTime) {
Preconditions.checkNotNull(workflowName, "workflowName cannot be null");
Preconditions.checkNotNull(startTime, "startTime cannot be null");
Preconditions.checkNotNull(endTime, "endTime cannot be null");
List<Workflow> workflows = new LinkedList<>();
withTransaction(tx -> {
String SQL = "SELECT workflow_id FROM workflow WHERE workflow_type = ? AND date_str BETWEEN ? AND ?";
List<String> workflowIds = query(tx, SQL, q -> q.addParameter(workflowName)
.addParameter(dateStr(startTime)).addParameter(dateStr(endTime)).executeScalarList(String.class));
workflowIds.forEach(workflowId -> {
try {
Workflow wf = getWorkflow(workflowId);
if (wf.getCreateTime() >= startTime && wf.getCreateTime() <= endTime) {
workflows.add(wf);
}
} catch (Exception e) {
logger.error("Unable to load workflow id {} with name {}", workflowId, workflowName, e);
}
});
});
return workflows;
}
@Override
public List<Workflow> getWorkflowsByCorrelationId(String correlationId) {
Preconditions.checkNotNull(correlationId, "correlationId cannot be null");
String SQL = "SELECT workflow_id FROM workflow WHERE correlation_id = ?";
return queryWithTransaction(SQL,
q -> q.addParameter(correlationId).executeScalarList(String.class).stream()
.map(this::getWorkflow).collect(Collectors.toList()));
}
@Override
public boolean addEventExecution(EventExecution ee) {
return getWithTransaction(tx -> insertEventExecution(tx, ee));
}
@Override
public void updateEventExecution(EventExecution ee) {
withTransaction(tx -> updateEventExecution(tx, ee));
}
@Override
@Deprecated
public List<EventExecution> getEventExecutions(String eventHandlerName, String eventName, String messageId, int max) {
// not in use any more. See references
return Collections.emptyList();
}
@Override
public void addMessage(String queue, Message msg) {
indexer.addMessage(queue, msg);
}
@Override
public void updateLastPoll(String taskDefName, String domain, String workerId) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
PollData pollData = new PollData(taskDefName, domain, workerId, System.currentTimeMillis());
String effectiveDomain = (domain == null) ? "DEFAULT" : domain;
withTransaction(tx -> insertOrUpdatePollData(tx, pollData, effectiveDomain));
}
@Override
public PollData getPollData(String taskDefName, String domain) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
String effectiveDomain = (domain == null) ? "DEFAULT" : domain;
return getWithTransaction(tx -> readPollData(tx, taskDefName, effectiveDomain));
}
@Override
public List<PollData> getPollData(String taskDefName) {
Preconditions.checkNotNull(taskDefName, "taskDefName name cannot be null");
return readAllPollData(taskDefName);
}
@Override
public void addEventPublished(EventPublished ep) {
getWithTransaction(tx -> insertEventPublished(tx, ep));
}
/**
* Function to find tasks in the workflows which associated with given tags
* <p>
* Includes task into result if:
* workflow.tags contains ALL values from the tags parameter
* and task type matches the given task type
* and the task status is IN_PROGRESS
*
* @param tags A set of tags
* @return List of tasks
*/
@Override
public List<Task> getPendingTasksByTags(String taskType, Set<String> tags) {
String SQL = "SELECT t.json_data FROM task t " +
"INNER JOIN workflow w ON w.workflow_id = t.workflow_id " +
"WHERE t.task_type = ? AND t.task_status = ? AND w.tags @> ?";
return queryWithTransaction(SQL, q -> q.addParameter(taskType)
.addParameter("IN_PROGRESS")
.addParameter(tags)
.executeAndFetch(Task.class));
}
/**
* Function to check is there any workflows associated with given tags
* Returns true if workflow.tags contains ALL values from the tags parameter
* Otherwise returns false
*
* @param tags A set of tags
* @return Either true or false
*/
@Override
public boolean anyRunningWorkflowsByTags(Set<String> tags) {
String SQL = "SELECT COUNT(*) FROM workflow WHERE tags @> ?";
return queryWithTransaction(SQL, q -> q.addParameter(tags).executeScalar(Long.class) > 0);
}
@Override
public void resetStartTime(Task task, boolean updateOutput) {
Map<String, Object> payload = new HashMap<>();
payload.put("startTime", task.getStartTime());
payload.put("endTime", task.getEndTime());
if (updateOutput) {
payload.put("outputData", task.getOutputData());
}
String SQL = "UPDATE task SET json_data = (json_data::jsonb || ?::jsonb)::text WHERE task_id = ?";
executeWithTransaction(SQL, q -> q
.addJsonParameter(payload)
.addParameter(task.getTaskId())
.executeUpdate());
}
private static int dateStr(Long timeInMs) {
Date date = new Date(timeInMs);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
return Integer.parseInt(format.format(date));
}
private boolean addScheduledTask(Connection tx, Task task) {
String taskKey = task.getReferenceTaskName() + task.getRetryCount();
final String CHECK_SQL = "SELECT true FROM task_scheduled WHERE workflow_id = ? AND task_key = ?";
boolean exists = query(tx, CHECK_SQL, q -> q
.addParameter(task.getWorkflowInstanceId())
.addParameter(taskKey)
.executeScalar(Boolean.class));
// Return task not scheduled (false) if it is already exists
if (exists) {
return false;
}
// Warning! Constraint name is also unique index name
final String ADD_SQL = "INSERT INTO task_scheduled (workflow_id, task_key, task_id) " +
"VALUES (?, ?, ?) ON CONFLICT ON CONSTRAINT task_scheduled_wf_task DO NOTHING";
int count = query(tx, ADD_SQL, q -> q
.addParameter(task.getWorkflowInstanceId())
.addParameter(taskKey)
.addParameter(task.getTaskId())
.executeUpdate());
return count > 0;
}
private void removeTask(Connection tx, Task task) {
final String taskKey = task.getReferenceTaskName() + task.getRetryCount();
removeScheduledTask(tx, task, taskKey);
removeTaskInProgress(tx, task);
removeTaskData(tx, task);
}
private void insertOrUpdateTask(Connection tx, Task task) {
// Warning! Constraint name is also unique index name
String SQL = "INSERT INTO task (task_id, task_type, task_refname, task_status, json_data, workflow_id, " +
"start_time, end_time, input, output) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT ON CONSTRAINT task_task_id DO " +
"UPDATE SET modified_on=now(), task_status=?, json_data=?, input = ?, output = ?, start_time = ?, end_time = ?";
execute(tx, SQL, q -> q
.addParameter(task.getTaskId())
.addParameter(task.getTaskType())
.addParameter(task.getReferenceTaskName())
.addParameter(task.getStatus().name())
.addJsonParameter(task)
.addParameter(task.getWorkflowInstanceId())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime())
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addParameter(task.getStatus().name())
.addJsonParameter(task)
.addJsonParameter(task.getInputData())
.addJsonParameter(task.getOutputData())
.addTimestampParameter(task.getStartTime())
.addTimestampParameter(task.getEndTime())
.executeUpdate());
}
private void updateTask(Connection tx, Task task) {
task.setUpdateTime(System.currentTimeMillis());
if (task.getStatus() != null && task.getStatus().isTerminal()) {
task.setEndTime(System.currentTimeMillis());
}
TaskDef taskDef = metadata.getTaskDef(task.getTaskDefName());
if (taskDef != null && taskDef.concurrencyLimit() > 0) {
updateInProgressStatus(tx, task);
}
insertOrUpdateTask(tx, task);
if (task.getStatus() != null && task.getStatus().isTerminal()) {
removeTaskInProgress(tx, task);
}
}
private String insertOrUpdateWorkflow(Workflow workflow, boolean update) {
Preconditions.checkNotNull(workflow, "workflow object cannot be null");
if (workflow.getStatus().isTerminal()) {
workflow.setEndTime(System.currentTimeMillis());
}
List<Task> tasks = workflow.getTasks();
workflow.setTasks(Lists.newLinkedList());
withTransaction(tx -> {
if (update) {
updateWorkflow(tx, workflow);
} else {
addWorkflow(tx, workflow);
}
});
workflow.setTasks(tasks);
return workflow.getWorkflowId();
}
private void addWorkflow(Connection tx, Workflow workflow) {
String SQL = "INSERT INTO workflow (workflow_id, parent_workflow_id, workflow_type, workflow_status, " +
"correlation_id, tags, input, json_data, date_str, start_time) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
execute(tx, SQL, q -> q.addParameter(workflow.getWorkflowId())
.addParameter(workflow.getParentWorkflowId())
.addParameter(workflow.getWorkflowType())
.addParameter(workflow.getStatus().name())
.addParameter(workflow.getCorrelationId())
.addParameter(workflow.getTags())
.addJsonParameter(workflow.getInput())
.addJsonParameter(workflow)
.addParameter(dateStr(workflow.getCreateTime()))
.addTimestampParameter(workflow.getStartTime())
.executeUpdate());
}
private void updateWorkflow(Connection tx, Workflow workflow) {
String SQL = "UPDATE workflow SET json_data = ?, workflow_status = ?, output = ?, end_time = ?, " +
"tags = ?, modified_on = now() WHERE workflow_id = ?";
// We must not delete tags for RESET as it must be restarted right away
Set<String> tags;
if (workflow.getStatus().isTerminal() && workflow.getStatus() != Workflow.WorkflowStatus.RESET) {
tags = Collections.emptySet();
} else {
tags = workflow.getTags();
}
execute(tx, SQL,
q -> q.addJsonParameter(workflow)
.addParameter(workflow.getStatus().name())
.addJsonParameter(workflow.getOutput())
.addTimestampParameter(workflow.getEndTime())
.addParameter(tags)
.addParameter(workflow.getWorkflowId())
.executeUpdate());
}
private Workflow readWorkflow(Connection tx, String workflowId) {
String SQL = "SELECT json_data FROM workflow WHERE workflow_id = ?";
return query(tx, SQL, q -> q.addParameter(workflowId).executeAndFetchFirst(Workflow.class));
}
private void removeWorkflow(Connection tx, String workflowId) {
String SQL = "DELETE FROM workflow WHERE workflow_id = ?";
execute(tx, SQL, q -> q.addParameter(workflowId).executeDelete());
}
private void addTaskInProgress(Connection tx, Task task) {
String SQL = "INSERT INTO task_in_progress (task_def_name, task_id, workflow_id) VALUES (?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT task_in_progress_fields DO NOTHING";
execute(tx, SQL, q -> q.addParameter(task.getTaskDefName())
.addParameter(task.getTaskId())
.addParameter(task.getWorkflowInstanceId())
.executeUpdate());
}
private void removeTaskInProgress(Connection tx, Task task) {
String SQL = "DELETE FROM task_in_progress WHERE task_def_name = ? AND task_id = ?";
execute(tx, SQL,
q -> q.addParameter(task.getTaskDefName()).addParameter(task.getTaskId()).executeUpdate());
}
private void updateInProgressStatus(Connection tx, Task task) {
boolean inProgress = Task.Status.IN_PROGRESS.equals(task.getStatus());
String SQL = "UPDATE task_in_progress SET in_progress = ?, modified_on = now() "
+ "WHERE task_def_name = ? AND task_id = ?";
execute(tx, SQL, q -> q.addParameter(inProgress)
.addParameter(task.getTaskDefName()).addParameter(task.getTaskId()).executeUpdate());
}
private void removeScheduledTask(Connection tx, Task task, String taskKey) {
String SQL = "DELETE FROM task_scheduled WHERE workflow_id = ? AND task_key = ?";
execute(tx, SQL,
q -> q.addParameter(task.getWorkflowInstanceId()).addParameter(taskKey).executeDelete());
}
private void removeTaskData(Connection tx, Task task) {
String SQL = "DELETE FROM task WHERE task_id = ?";
execute(tx, SQL, q -> q.addParameter(task.getTaskId()).executeDelete());
}
private boolean insertEventExecution(Connection tx, EventExecution ee) {
String SQL = "INSERT INTO event_execution" +
"(handler_name, event_name, message_id, execution_id, status, subject, received_on, accepted_on) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT event_execution_fields DO NOTHING";
int count = query(tx, SQL, q -> q.addParameter(ee.getName())
.addParameter(ee.getEvent())
.addParameter(ee.getMessageId())
.addParameter(ee.getId())
.addParameter(ee.getStatus().name())
.addParameter(ee.getSubject())
.addTimestampParameter(ee.getReceived())
.addTimestampParameter(ee.getAccepted())
.executeUpdate());
return count > 0;
}
private void updateEventExecution(Connection tx, EventExecution ee) {
String SQL = "UPDATE event_execution SET " +
"modified_on = now(), status = ?, started_on = ?, processed_on = ?" +
"WHERE handler_name = ? AND event_name = ? " +
"AND message_id = ? AND execution_id = ?";
execute(tx, SQL, q -> q.addParameter(ee.getStatus().name())
.addTimestampParameter(ee.getStarted())
.addTimestampParameter(ee.getProcessed())
.addParameter(ee.getName())
.addParameter(ee.getEvent())
.addParameter(ee.getMessageId())
.addParameter(ee.getId())
.executeUpdate());
}
private boolean insertEventPublished(Connection tx, EventPublished ep) {
String SQL = "INSERT INTO event_published" +
"(json_data, message_id, subject, published_on) " +
"VALUES (?, ?, ?, ?)";
int count = query(tx, SQL, q -> q.addJsonParameter(ep)
.addParameter(ep.getId())
.addParameter(ep.getSubject())
.addTimestampParameter(ep.getPublished())
.executeUpdate());
return count > 0;
}
private void insertOrUpdatePollData(Connection tx, PollData pollData, String domain) {
// Warning! Constraint name is also unique index name
String SQL = "INSERT INTO poll_data (queue_name, domain, json_data) VALUES (?, ?, ?) " +
"ON CONFLICT ON CONSTRAINT poll_data_fields DO UPDATE SET json_data=?, modified_on=now()";
execute(tx, SQL, q -> q.addParameter(pollData.getQueueName())
.addParameter(domain)
.addJsonParameter(pollData)
.addJsonParameter(pollData)
.executeUpdate());
}
private PollData readPollData(Connection tx, String queueName, String domain) {
String SQL = "SELECT json_data FROM poll_data WHERE queue_name = ? AND domain = ?";
return query(tx, SQL,
q -> q.addParameter(queueName).addParameter(domain).executeAndFetchFirst(PollData.class));
}
private List<PollData> readAllPollData(String queueName) {
String SQL = "SELECT json_data FROM poll_data WHERE queue_name = ?";
return queryWithTransaction(SQL, q -> q.addParameter(queueName).executeAndFetch(PollData.class));
}
}
| ONECOND-1557 PgHero conductor code refactoring
| postgresql-persistence/src/main/java/com/netflix/conductor/aurora/AuroraExecutionDAO.java | ONECOND-1557 PgHero conductor code refactoring | <ide><path>ostgresql-persistence/src/main/java/com/netflix/conductor/aurora/AuroraExecutionDAO.java
<ide> return Lists.newArrayList();
<ide> }
<ide>
<del> return getWithTransaction(tx -> taskIds.stream().map(id -> getTask(tx, id)))
<add> return getWithTransaction(tx -> taskIds.stream()
<add> .map(id -> getTask(tx, id))
<ide> .filter(Objects::nonNull)
<del> .collect(Collectors.toList());
<add> .collect(Collectors.toList()));
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 8b3202ae492a72e6366dc0a8337ab584843cdd5c | 0 | Elorri/PopularMovies | package com.example.android.popularmovies;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Elorri-user on 28/09/2015.
*/
public class TmdbAccess {
private static final String LOG_TAG = TmdbAccess.class.getSimpleName();
private final String API_KEY = "real_api_key_here";
public Movie[] getMoviesSortBy(String sortBy) {
URL url = constructMovieListQuery(sortBy);
String popularMoviesJsonStr = getJsonString(url);
try {
return getMoviesFromJson(popularMoviesJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
return null;
}
}
public Movie getMovieById(String id){
URL url = constructMovieDetailQuery(id);
String popularMoviesJsonStr = getJsonString(url);
try {
return getOneMovieFromJson(popularMoviesJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
return null;
}
}
public URL constructPosterImageURL(String posterName) {
try {
final String BASE_URL = "http://image.tmdb.org/t/p/";
final String SIZE = "w185";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath(SIZE)
.appendPath(posterName)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private URL constructMovieListQuery(String sortByValue) {
try {
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORTBY_PARAM = "sort_by";
final String KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(SORTBY_PARAM, sortByValue)
.appendQueryParameter(KEY_PARAM, API_KEY)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private URL constructMovieDetailQuery(String id) {
try {
final String BASE_URL = "http://api.themoviedb.org/3/movie/";
final String KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath(id)
.appendQueryParameter(KEY_PARAM, API_KEY)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private String getJsonString(URL url) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String jsonStr = null;
try {
// Create the request http, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
jsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return jsonStr;
}
private Movie[] getMoviesFromJson(String moviesJsonStr) throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String RESULTS = "results";
final String ID = "id";
final String TITLE="title";
final String POSTER_PATH = "poster_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray moviesArray = moviesJson.getJSONArray(RESULTS);
Movie[] moviesList = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
// Get the JSON object representing the movie
JSONObject aMovie = moviesArray.getJSONObject(i);
// Create Movie Object
String id = aMovie.getString(ID);
String title =aMovie.getString(TITLE);
String posterPath = aMovie.getString(POSTER_PATH);
String posterName = null;
if (!posterPath.equals("null"))
posterName = posterPath.split("/")[1]; //To remove the unwanted '/' given by the api
moviesList[i] = new Movie(id, title, posterName);
}
return moviesList;
}
private Movie getOneMovieFromJson(String theMovieJsonStr) throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String ID = "id";
final String TITLE="title";
final String POSTER_PATH = "poster_path";
final String OVERVIEW = "overview";
final String VOTE_AVERAGE = "vote_average";
final String RELEASE_DATE = "release_date";
final String DURATION = "runtime";
JSONObject movieJson = new JSONObject(theMovieJsonStr);
String id = movieJson.getString(ID);
String title =movieJson.getString(TITLE);
String posterPath = movieJson.getString(POSTER_PATH);
String posterName = null;
if (!posterPath.equals("null"))
posterName = posterPath.split("/")[1]; //To remove the unwanted '/' given by the api
String releaseDate =movieJson.getString(RELEASE_DATE);
String duration =movieJson.getString(DURATION);
String voteAverage =movieJson.getString(VOTE_AVERAGE);
String overview =movieJson.getString(OVERVIEW);
return new Movie(id, title, posterName, releaseDate, duration, voteAverage, overview);
}
}
| app/src/main/java/com/example/android/popularmovies/TmdbAccess.java | package com.example.android.popularmovies;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Elorri-user on 28/09/2015.
*/
public class TmdbAccess {
private static final String LOG_TAG = TmdbAccess.class.getSimpleName();
private final String API_KEY = "4691965cfc3e6f0591bc595986e92e84";
public Movie[] getMoviesSortBy(String sortBy) {
URL url = constructMovieListQuery(sortBy);
String popularMoviesJsonStr = getJsonString(url);
try {
return getMoviesFromJson(popularMoviesJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
return null;
}
}
public Movie getMovieById(String id){
URL url = constructMovieDetailQuery(id);
String popularMoviesJsonStr = getJsonString(url);
try {
return getOneMovieFromJson(popularMoviesJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
return null;
}
}
public URL constructPosterImageURL(String posterName) {
try {
final String BASE_URL = "http://image.tmdb.org/t/p/";
final String SIZE = "w185";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath(SIZE)
.appendPath(posterName)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private URL constructMovieListQuery(String sortByValue) {
try {
final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORTBY_PARAM = "sort_by";
final String KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(SORTBY_PARAM, sortByValue)
.appendQueryParameter(KEY_PARAM, API_KEY)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private URL constructMovieDetailQuery(String id) {
try {
final String BASE_URL = "http://api.themoviedb.org/3/movie/";
final String KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendPath(id)
.appendQueryParameter(KEY_PARAM, API_KEY)
.build();
return new URL(builtUri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error " + e);
return null;
}
}
private String getJsonString(URL url) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String jsonStr = null;
try {
// Create the request http, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
jsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return jsonStr;
}
private Movie[] getMoviesFromJson(String moviesJsonStr) throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String RESULTS = "results";
final String ID = "id";
final String TITLE="title";
final String POSTER_PATH = "poster_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray moviesArray = moviesJson.getJSONArray(RESULTS);
Movie[] moviesList = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
// Get the JSON object representing the movie
JSONObject aMovie = moviesArray.getJSONObject(i);
// Create Movie Object
String id = aMovie.getString(ID);
String title =aMovie.getString(TITLE);
String posterPath = aMovie.getString(POSTER_PATH);
String posterName = null;
if (!posterPath.equals("null"))
posterName = posterPath.split("/")[1]; //To remove the unwanted '/' given by the api
moviesList[i] = new Movie(id, title, posterName);
}
return moviesList;
}
private Movie getOneMovieFromJson(String theMovieJsonStr) throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String ID = "id";
final String TITLE="title";
final String POSTER_PATH = "poster_path";
final String OVERVIEW = "overview";
final String VOTE_AVERAGE = "vote_average";
final String RELEASE_DATE = "release_date";
final String DURATION = "runtime";
JSONObject movieJson = new JSONObject(theMovieJsonStr);
String id = movieJson.getString(ID);
String title =movieJson.getString(TITLE);
String posterPath = movieJson.getString(POSTER_PATH);
String posterName = null;
if (!posterPath.equals("null"))
posterName = posterPath.split("/")[1]; //To remove the unwanted '/' given by the api
String releaseDate =movieJson.getString(RELEASE_DATE);
String duration =movieJson.getString(DURATION);
String voteAverage =movieJson.getString(VOTE_AVERAGE);
String overview =movieJson.getString(OVERVIEW);
return new Movie(id, title, posterName, releaseDate, duration, voteAverage, overview);
}
}
| Remove API key before pushing on github
| app/src/main/java/com/example/android/popularmovies/TmdbAccess.java | Remove API key before pushing on github | <ide><path>pp/src/main/java/com/example/android/popularmovies/TmdbAccess.java
<ide>
<ide>
<ide> private static final String LOG_TAG = TmdbAccess.class.getSimpleName();
<del> private final String API_KEY = "4691965cfc3e6f0591bc595986e92e84";
<add> private final String API_KEY = "real_api_key_here";
<ide>
<ide> public Movie[] getMoviesSortBy(String sortBy) {
<ide> URL url = constructMovieListQuery(sortBy); |
|
Java | apache-2.0 | 9e90fa3d37a846e4acd5e86356f9e7a82f884ce8 | 0 | helyho/Voovan,helyho/Voovan,helyho/Voovan | package org.voovan.tools.reflect;
import org.voovan.tools.TDateTime;
import org.voovan.tools.TObject;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.json.annotation.NotJSON;
import org.voovan.tools.reflect.annotation.NotSerialization;
import java.lang.reflect.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
/**
* 反射工具类
*
* @author helyho
*
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TReflect {
private static Map<String, Field> fields = new HashMap<String ,Field>();
private static Map<String, Method> methods = new HashMap<String ,Method>();
private static Map<String, Field[]> fieldArrays = new HashMap<String ,Field[]>();
private static Map<String, Method[]> methodArrays = new HashMap<String ,Method[]>();
/**
* 获得类所有的Field
*
* @param clazz 类对象
* @return Field数组
*/
public static Field[] getFields(Class<?> clazz) {
String mark = clazz.getCanonicalName();
Field[] fields = null;
if(fieldArrays.containsKey(mark)){
fields = fieldArrays.get(mark);
}else {
ArrayList<Field> fieldArray = new ArrayList<Field>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
Field[] tmpFields = clazz.getDeclaredFields();
fieldArray.addAll(Arrays.asList(tmpFields));
}
fields = fieldArray.toArray(new Field[]{});
fieldArrays.put(mark, fields);
fieldArray.clear();
}
return fields;
}
/**
* 查找类特定的Field
*
* @param clazz 类对象
* @param fieldName field 名称
* @return field 对象
* @throws NoSuchFieldException 无 Field 异常
* @throws SecurityException 安全性异常
*/
public static Field findField(Class<?> clazz, String fieldName)
throws ReflectiveOperationException {
String mark = clazz.getCanonicalName()+"#"+fieldName;
try {
if(fields.containsKey(mark)){
return fields.get(mark);
}else {
Field field = clazz.getDeclaredField(fieldName);
fields.put(mark, field);
return field;
}
}catch(NoSuchFieldException ex){
Class superClazz = clazz.getSuperclass();
if( superClazz != Object.class ) {
return findField(clazz.getSuperclass(), fieldName);
}else{
return null;
}
}
}
/**
* 查找类特定的Field
* 不区分大小写,并且替换掉特殊字符
* @param clazz 类对象
* @param fieldName Field 名称
* @return Field 对象
* @throws ReflectiveOperationException 反射异常
*/
public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName)
throws ReflectiveOperationException{
String mark = clazz.getCanonicalName()+"#"+fieldName;
if(fields.containsKey(mark)){
return fields.get(mark);
}else {
for (Field field : getFields(clazz)) {
if (field.getName().equalsIgnoreCase(fieldName)) {
fields.put(mark, field);
return field;
}
}
}
return null;
}
/**
* 获取 Field 的范型类型
* @param field field 对象
* @return 返回范型类型数组
* @throws ClassNotFoundException 类找不到异常
*/
public static Class[] getFieldGenericType(Field field) throws ClassNotFoundException {
Class[] result = null;
Type fieldType = field.getGenericType();
if(fieldType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)fieldType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
* 获取类中指定Field的值
* @param <T> 范型
* @param obj 对象
* @param fieldName Field 名称
* @return Field 的值
* @throws ReflectiveOperationException 反射异常
*/
@SuppressWarnings("unchecked")
static public <T> T getFieldValue(Object obj, String fieldName)
throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
return (T) field.get(obj);
}
/**
* 更新对象中指定的Field的值
* 注意:对 private 等字段有效
*
* @param obj 对象
* @param fieldName field 名称
* @param fieldValue field 值
* @throws ReflectiveOperationException 反射异常
*/
public static void setFieldValue(Object obj, String fieldName,
Object fieldValue) throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
field.set(obj, fieldValue);
}
/**
* 将对象中的field和其值组装成Map 静态字段(static修饰的)不包括
*
* @param obj 对象
* @return 所有 field 名称-值拼装的 Map
* @throws ReflectiveOperationException 反射异常
*/
public static Map<Field, Object> getFieldValues(Object obj)
throws ReflectiveOperationException {
HashMap<Field, Object> result = new HashMap<Field, Object>();
Field[] fields = getFields(obj.getClass());
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers()) &&
field.getAnnotation(NotJSON.class)==null &&
field.getAnnotation(NotSerialization.class)==null) {
Object value = getFieldValue(obj, field.getName());
result.put(field, value);
}
}
return result;
}
/**
* 查找类中的方法
* @param clazz 类对象
* @param name 方法名
* @param paramTypes 参数类型
* @return 方法对象
* @throws ReflectiveOperationException 反射异常
*/
public static Method findMethod(Class<?> clazz, String name,
Class<?>... paramTypes) throws ReflectiveOperationException {
String mark = clazz.getCanonicalName()+"#"+name;
for(Class<?> paramType : paramTypes){
mark = mark + "$" + paramType.getCanonicalName();
}
if(methods.containsKey(mark)){
return methods.get(mark);
}else {
Method method = clazz.getDeclaredMethod(name, paramTypes);
methods.put(mark, method);
return method;
}
}
/**
* 查找类中的方法(使用参数数量)
* @param clazz 类对象
* @param name 方法名
* @param paramCount 参数数量
* @return 方法对象
* @throws ReflectiveOperationException 反射异常
*/
public static Method[] findMethod(Class<?> clazz, String name,
int paramCount) throws ReflectiveOperationException {
Method[] methods = null;
String mark = clazz.getCanonicalName()+"#"+name+"@"+paramCount;
if(methodArrays.containsKey(mark)){
return methodArrays.get(mark);
} else {
ArrayList<Method> methodList = new ArrayList<Method>();
Method[] allMethods = getMethods(clazz, name);
for (Method method : allMethods) {
if (method.getParameters().length == paramCount) {
methodList.add(method);
}
}
methods = methodList.toArray(new Method[]{});
methodArrays.put(mark,methods);
methodList.clear();
}
return methods;
}
/**
* 获取类的方法集合
* @param clazz 类对象
* @return Method 对象数组
*/
public static Method[] getMethods(Class<?> clazz) {
Method[] methods = null;
String mark = clazz.getCanonicalName();
if(methodArrays.containsKey(mark)){
return methodArrays.get(mark);
} else {
List<Method> methodList = new ArrayList<Method>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
Method[] tmpMethods = clazz.getDeclaredMethods();
methodList.addAll(Arrays.asList(tmpMethods));
}
methods = methodList.toArray(new Method[]{});
methodList.clear();
methodArrays.put(mark,methods);
}
return methods;
}
/**
* 获取类的特定方法的集合
* 类中可能存在同名方法
* @param clazz 类对象
* @param name 方法名
* @return Method 对象数组
*/
public static Method[] getMethods(Class<?> clazz,String name) {
Method[] methods = null;
String mark = clazz.getCanonicalName()+"#"+name;
if(methodArrays.containsKey(mark)){
return methodArrays.get(mark);
} else {
ArrayList<Method> methodList = new ArrayList<Method>();
Method[] allMethods = getMethods(clazz);
for (Method method : allMethods) {
if (method.getName().equals(name))
methodList.add(method);
}
methods = methodList.toArray(new Method[0]);
methodList.clear();
methodArrays.put(mark,methods);
}
return methods;
}
/**
* 获取方法的参数返回值的范型类型
* @param method method 对象
* @param parameterIndex 参数索引(大于0)参数索引位置[第一个参数为0,以此类推], (-1) 返回值
* @return 返回范型类型数组
* @throws ClassNotFoundException 类找不到异常
*/
public static Class[] getMethodParameterGenericType(Method method,int parameterIndex) throws ClassNotFoundException {
Class[] result = null;
Type parameterType;
if(parameterIndex == -1){
parameterType = method.getGenericReturnType();
}else{
parameterType = method.getGenericParameterTypes()[parameterIndex];
}
if(parameterType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)parameterType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
* 使用对象执行它的一个方法
* 对对象执行一个指定Method对象的方法
* @param obj 执行方法的对象
* @param method 方法对象
* @param parameters 多个参数
* @return 方法返回结果
* @throws ReflectiveOperationException 反射异常
*/
public static Object invokeMethod(Object obj, Method method, Object... parameters)
throws ReflectiveOperationException {
return method.invoke(obj, parameters);
}
/**
* 使用对象执行方法
* 推荐使用的方法,这个方法会自动寻找参数匹配度最好的方法并执行
* 对对象执行一个通过 方法名和参数列表选择的方法
* @param obj 执行方法的对象,如果调用静态方法直接传 Class 类型的对象
* @param name 执行方法名
* @param parameters 方法参数
* @return 方法返回结果
* @throws ReflectiveOperationException 反射异常
*/
public static Object invokeMethod(Object obj, String name, Object... parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Method method = null;
Class objClass = (obj instanceof Class) ? (Class)obj : obj.getClass();
try {
method = findMethod(objClass, name, parameterTypes);
method.setAccessible(true);
return method.invoke(obj, parameters);
}catch(Exception e){
Exception lastExecption = e;
//找到这个名称的所有方法
Method[] methods = findMethod(objClass,name,parameterTypes.length);
for(Method similarMethod : methods){
Parameter[] methodParams = similarMethod.getParameters();
//匹配参数数量相等的方法
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
//参数类型转换
String value = "";
Class parameterClass = parameters[i].getClass();
//复杂的对象通过 JSON转换成字符串,再转换成特定类型的对象
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
method = similarMethod;
try{
method.setAccessible(true);
return method.invoke(obj, convertedParams);
}catch(Exception ex){
lastExecption = (Exception) ex.getCause();
continue;
}
}
}
if ( !(lastExecption instanceof ReflectiveOperationException) ) {
lastExecption = new ReflectiveOperationException(lastExecption);
}
throw (ReflectiveOperationException)lastExecption;
}
}
/**
* 构造新的对象
* 通过参数中的构造参数对象parameters,选择特定的构造方法构造
* @param <T> 范型
* @param clazz 类对象
* @param parameters 构造方法参数
* @return 新的对象
* @throws ReflectiveOperationException 反射异常
*/
public static <T> T newInstance(Class<T> clazz, Object ...parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Constructor<T> constructor = null;
try {
if (parameters.length == 0) {
constructor = clazz.getConstructor();
} else {
constructor = clazz.getConstructor(parameterTypes);
}
return constructor.newInstance(parameters);
}catch(Exception e){
Constructor[] constructors = clazz.getConstructors();
for(Constructor similarConstructor : constructors){
Parameter[] methodParams = similarConstructor.getParameters();
//匹配参数数量相等的方法
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
//参数类型转换
String value = "";
Class parameterClass = parameters[i].getClass();
//复杂的对象通过 JSON转换成字符串,再转换成特定类型的对象
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
constructor = similarConstructor;
try{
return constructor.newInstance(convertedParams);
}catch(Exception ex){
continue;
}
}
}
throw e;
}
}
/**
* 构造新的对象
* @param <T> 范型
* @param className 类名称
* @param parameters 构造方法参数
* @return 新的对象
* @throws ReflectiveOperationException 反射异常
*/
public static <T> T newInstance(String className, Object ...parameters) throws ReflectiveOperationException {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) Class.forName(className);
return newInstance(clazz,parameters);
}
/**
* 将对象数组转换成,对象类型的数组
* @param objs 对象类型数组
* @return 类数组
*/
public static Class<?>[] getArrayClasses(Object[] objs){
Class<?>[] parameterTypes= new Class<?>[objs.length];
for(int i=0;i<objs.length;i++){
parameterTypes[i] = objs[i].getClass();
}
return parameterTypes;
}
/**
* 将Map转换成指定的对象
*
* @param clazz 类对象
* @param mapArg Map 对象
* @param ignoreCase 匹配属性名是否不区分大小写
* @return 转换后的对象
* @throws ReflectiveOperationException 反射异常
* @throws ParseException 解析异常
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getObjectFromMap(Class<?> clazz,
Map<String, ?> mapArg,boolean ignoreCase) throws ReflectiveOperationException, ParseException {
Object obj = null;
if(mapArg==null){
return obj;
}
if(mapArg.isEmpty()){
return TReflect.newInstance(clazz,new Object[]{});
}
Object singleValue = mapArg.values().iterator().next();
// java标准对象
if (clazz.isPrimitive() || clazz == Object.class){
obj = singleValue;
}
//java 日期对象
else if(isExtendsByClass(clazz,Date.class)){
//取 Map.Values 里的递第一个值
String value = singleValue==null?null:singleValue.toString();
SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE);
obj = singleValue!=null?dateFormat.parse(value.toString()):null;
}
//Map 类型
else if(isImpByInterface(clazz,Map.class)){
//不可构造的类型使用最常用的类型
if(Modifier.isAbstract(clazz.getModifiers()) && Modifier.isInterface(clazz.getModifiers())){
clazz = HashMap.class;
}
Map mapObject = TObject.cast(newInstance(clazz));
mapObject.putAll(mapArg);
obj = mapObject;
}
//Collection 类型
else if(isImpByInterface(clazz,Collection.class)){
//不可构造的类型使用最常用的类型
if(Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())){
clazz = ArrayList.class;
}
Collection listObject = TObject.cast(newInstance(clazz));
if(singleValue!=null){
listObject.addAll((Collection) TObject.cast(singleValue));
}
obj = listObject;
}
//Array 类型
else if(clazz.isArray()){
Class arrayClass = clazz.getComponentType();
Object tempArrayObj = Array.newInstance(arrayClass, 0);
return ((Collection)singleValue).toArray((Object[])tempArrayObj);
}
//java基本对象
else if (clazz.getName().startsWith("java.lang")) {
//取 Map.Values 里的递第一个值
String value = singleValue==null?null:singleValue.toString();
obj = singleValue==null?null:newInstance(clazz, value);
}
// 复杂对象
else {
obj = newInstance(clazz);
for(Entry<String,?> argEntry : mapArg.entrySet()){
String key = argEntry.getKey();
Object value = argEntry.getValue();
Field field = null;
if(ignoreCase) {
//忽略大小写匹配
field = findFieldIgnoreCase(clazz, key);
}else{
//精确匹配属性
field = findField(clazz, key);
}
if(field!=null) {
String fieldName = field.getName();
Class fieldType = field.getType();
try {
if(value != null) {
//对于 对象类型为 Map 的属性进行处理,查找范型,并转换为范型定义的类型
if (isImpByInterface(fieldType, Map.class) && value instanceof Map) {
Class[] mapGenericTypes = getFieldGenericType(field);
if (mapGenericTypes != null) {
if (fieldType == Map.class) {
fieldType = HashMap.class;
}
Map result = (Map) TReflect.newInstance(fieldType);
Map mapValue = (Map) value;
Iterator iterator = mapValue.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
Map keyOfMap = null;
Map valueOfMap = null;
if (entry.getKey() instanceof Map) {
keyOfMap = (Map) entry.getKey();
} else {
keyOfMap = TObject.newMap("value", entry.getKey());
}
if (entry.getValue() instanceof Map) {
valueOfMap = (Map) entry.getValue();
} else {
valueOfMap = TObject.newMap("value", entry.getValue());
}
Object keyObj = getObjectFromMap(mapGenericTypes[0], keyOfMap, ignoreCase);
Object valueObj = getObjectFromMap(mapGenericTypes[1], valueOfMap, ignoreCase);
result.put(keyObj, valueObj);
}
value = result;
}
}
//对于 对象类型为 Collection 的属性进行处理,查找范型,并转换为范型定义的类型
else if (isImpByInterface(fieldType, Collection.class) && value instanceof Collection) {
Class[] listGenericTypes = getFieldGenericType(field);
if (listGenericTypes != null) {
if (fieldType == List.class) {
fieldType = ArrayList.class;
}
List result = (List) TReflect.newInstance(fieldType);
List listValue = (List) value;
for (Object listItem : listValue) {
Map valueOfMap = null;
if (listItem instanceof Map) {
valueOfMap = (Map) listItem;
} else {
valueOfMap = TObject.newMap("value", listItem);
}
Object item = getObjectFromMap(listGenericTypes[0], valueOfMap, ignoreCase);
result.add(item);
}
value = result;
}
} else if (value instanceof Map) {
value = getObjectFromMap(fieldType, (Map<String, ?>) value, ignoreCase);
} else {
value = getObjectFromMap(fieldType, TObject.newMap("value", value), ignoreCase);
}
}
setFieldValue(obj, fieldName, value);
}catch(Exception e){
throw new ReflectiveOperationException("Fill object " + obj.getClass().getCanonicalName() +
"#"+fieldName+" failed",e);
}
}
}
}
return obj;
}
/**
* 将对象转换成 Map
* key 对象属性名称
* value 对象属性值
* @param obj 待转换的对象
* @return 转后的 Map
* @throws ReflectiveOperationException 反射异常
*/
public static Map<String, Object> getMapfromObject(Object obj) throws ReflectiveOperationException{
Map<String, Object> mapResult = new HashMap<String, Object>();
Map<Field, Object> fieldValues = TReflect.getFieldValues(obj);
//如果是 java 标准类型
if(obj.getClass().getName().startsWith("java.lang")
|| obj.getClass().isPrimitive()){
mapResult.put("value", obj);
}
//对 Collection 类型的处理
else if(obj instanceof Collection){
Collection collection = (Collection) newInstance(obj.getClass());
for(Object collectionItem : (Collection)obj) {
collection.add(getMapfromObject(collectionItem));
}
mapResult.put("value", collection);
}
//对 Map 类型的处理
else if(obj instanceof Map){
Map mapObject = (Map)obj;
Map map = (Map)newInstance(obj.getClass());
for(Object key : mapObject.keySet()) {
map.put(getMapfromObject(key),getMapfromObject(mapObject.get(key)));
}
mapResult.put("value", map);
}
//复杂对象类型
else{
for(Entry<Field,Object> entry : fieldValues.entrySet()){
String key = entry.getKey().getName();
Object value = entry.getValue();
if(value == null){
mapResult.put(key, value);
}else if(!key.contains("$")){
String valueClass = entry.getValue().getClass().getName();
if(valueClass.startsWith("java")){
mapResult.put(key, value);
}else {
//如果是复杂类型则递归调用
Map resultMap = getMapfromObject(value);
if(resultMap.size()==1 && resultMap.containsKey("value")){
mapResult.put(key, resultMap.values().iterator().next());
}else{
mapResult.put(key,resultMap);
}
}
}
}
}
return mapResult;
}
/**
* 判断某个类型是否实现了某个接口
* 包括判断其父接口
* @param type 被判断的类型
* @param interfaceClass 检查是否实现了次类的接口
* @return 是否实现某个接口
*/
public static boolean isImpByInterface(Class<?> type,Class<?> interfaceClass){
if(type==interfaceClass){
return true;
}
Class<?>[] interfaces= type.getInterfaces();
for (Class<?> interfaceItem : interfaces) {
if (interfaceItem.equals(interfaceClass)) {
return true;
}
else{
return isImpByInterface(interfaceItem,interfaceClass);
}
}
return false;
}
/**
* 判断某个类型是否继承于某个类
* 包括判断其父类
* @param type 判断的类型
* @param extendsClass 用于判断的父类类型
* @return 是否继承于某个类
*/
public static boolean isExtendsByClass(Class<?> type,Class<?> extendsClass){
if(extendsClass == type){
return true;
}
Class<?> superClass = type;
do{
if(superClass.equals(extendsClass)){
return true;
}
superClass = superClass.getSuperclass();
}while(superClass!=null && !superClass.equals(extendsClass) && !superClass.equals(Object.class));
return false;
}
/**
* 获取类的继承树上的所有父类
* @param type 类型 Class
* @return 所有父类
*/
public static Class[] getAllExtendAndInterfaceClass(Class<?> type){
if(type == null){
return null;
}
ArrayList<Class> classes = new ArrayList<Class>();
Class<?> superClass = type;
do{
superClass = superClass.getSuperclass();
classes.addAll(Arrays.asList(superClass.getInterfaces()));
classes.add(superClass);
}while(!Object.class.equals(superClass));
return classes.toArray(new Class[]{});
}
/**
* 获取类的 json 形式的描述
* @param clazz Class 类型对象
* @return 类的 json 形式的描述
*/
public static String getClazzJSONModel(Class clazz){
StringBuilder jsonStrBuilder = new StringBuilder();
if(clazz.getName().startsWith("java") || clazz.isPrimitive()){
jsonStrBuilder.append(clazz.getName());
} else if(clazz.getName().startsWith("[L")){
String clazzName = clazz.getName();
clazzName = clazzName.substring(clazzName.lastIndexOf(".")+1,clazzName.length()-2)+"[]";
jsonStrBuilder.append(clazzName);
} else {
jsonStrBuilder.append("{");
for (Field field : TReflect.getFields(clazz)) {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(field.getName());
jsonStrBuilder.append("\":");
String filedValueModel = getClazzJSONModel(field.getType());
if(filedValueModel.startsWith("{") && filedValueModel.endsWith("}")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else if(filedValueModel.startsWith("[") && filedValueModel.endsWith("]")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append("\",");
}
}
jsonStrBuilder.deleteCharAt(jsonStrBuilder.length()-1);
jsonStrBuilder.append("}");
}
return jsonStrBuilder.toString();
}
}
| src/main/java/org/voovan/tools/reflect/TReflect.java | package org.voovan.tools.reflect;
import org.voovan.tools.TDateTime;
import org.voovan.tools.TObject;
import org.voovan.tools.TString;
import org.voovan.tools.json.JSON;
import org.voovan.tools.json.annotation.NotJSON;
import org.voovan.tools.reflect.annotation.NotSerialization;
import java.lang.reflect.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
/**
* 反射工具类
*
* @author helyho
*
* Voovan Framework.
* WebSite: https://github.com/helyho/Voovan
* Licence: Apache v2 License
*/
public class TReflect {
private static Map<String, Field> fields = new HashMap<String ,Field>();
private static Map<String, Method> methods = new HashMap<String ,Method>();
/**
* 获得类所有的Field
*
* @param clazz 类对象
* @return Field数组
*/
public static Field[] getFields(Class<?> clazz) {
List<Field> fields = new ArrayList<Field>();
for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
Field[] tmpFields = clazz.getDeclaredFields();
fields.addAll(Arrays.asList(tmpFields));
}
return fields.toArray(new Field[]{});
}
/**
* 查找类特定的Field
*
* @param clazz 类对象
* @param fieldName field 名称
* @return field 对象
* @throws NoSuchFieldException 无 Field 异常
* @throws SecurityException 安全性异常
*/
public static Field findField(Class<?> clazz, String fieldName)
throws ReflectiveOperationException {
String fieldMark = clazz.getCanonicalName()+"#"+fieldName;
try {
if(fields.containsKey(fieldMark)){
return fields.get(fieldMark);
}else {
Field field = clazz.getDeclaredField(fieldName);
fields.put(fieldMark, field);
return field;
}
}catch(NoSuchFieldException ex){
Class superClazz = clazz.getSuperclass();
if( superClazz != Object.class ) {
return findField(clazz.getSuperclass(), fieldName);
}else{
return null;
}
}
}
/**
* 查找类特定的Field
* 不区分大小写,并且替换掉特殊字符
* @param clazz 类对象
* @param fieldName Field 名称
* @return Field 对象
* @throws ReflectiveOperationException 反射异常
*/
public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName)
throws ReflectiveOperationException{
String fieldMark = clazz.getCanonicalName()+"#"+fieldName;
if(fields.containsKey(fieldMark)){
return fields.get(fieldMark);
}else {
for (Field field : getFields(clazz)) {
if (field.getName().equalsIgnoreCase(fieldName)) {
fields.put(fieldMark, field);
return field;
}
}
}
return null;
}
/**
* 获取 Field 的范型类型
* @param field field 对象
* @return 返回范型类型数组
* @throws ClassNotFoundException 类找不到异常
*/
public static Class[] getFieldGenericType(Field field) throws ClassNotFoundException {
Class[] result = null;
Type fieldType = field.getGenericType();
if(fieldType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)fieldType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
* 获取类中指定Field的值
* @param <T> 范型
* @param obj 对象
* @param fieldName Field 名称
* @return Field 的值
* @throws ReflectiveOperationException 反射异常
*/
@SuppressWarnings("unchecked")
static public <T> T getFieldValue(Object obj, String fieldName)
throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
return (T) field.get(obj);
}
/**
* 更新对象中指定的Field的值
* 注意:对 private 等字段有效
*
* @param obj 对象
* @param fieldName field 名称
* @param fieldValue field 值
* @throws ReflectiveOperationException 反射异常
*/
public static void setFieldValue(Object obj, String fieldName,
Object fieldValue) throws ReflectiveOperationException {
Field field = findField(obj.getClass(), fieldName);
field.setAccessible(true);
field.set(obj, fieldValue);
}
/**
* 将对象中的field和其值组装成Map 静态字段(static修饰的)不包括
*
* @param obj 对象
* @return 所有 field 名称-值拼装的 Map
* @throws ReflectiveOperationException 反射异常
*/
public static Map<Field, Object> getFieldValues(Object obj)
throws ReflectiveOperationException {
HashMap<Field, Object> result = new HashMap<Field, Object>();
Field[] fields = getFields(obj.getClass());
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers()) &&
field.getAnnotation(NotJSON.class)==null &&
field.getAnnotation(NotSerialization.class)==null) {
Object value = getFieldValue(obj, field.getName());
result.put(field, value);
}
}
return result;
}
/**
* 查找类中的方法
* @param clazz 类对象
* @param name 方法名
* @param paramTypes 参数类型
* @return 方法对象
* @throws ReflectiveOperationException 反射异常
*/
public static Method findMethod(Class<?> clazz, String name,
Class<?>... paramTypes) throws ReflectiveOperationException {
String methodMark = clazz.getCanonicalName()+"#"+name;
for(Class<?> paramType : paramTypes){
methodMark = methodMark + "$" + paramType.getCanonicalName();
}
if(methods.containsKey(methodMark)){
return methods.get(methodMark);
}else {
Method method = clazz.getDeclaredMethod(name, paramTypes);
methods.put(methodMark, method);
return method;
}
}
/**
* 查找类中的方法(使用参数数量)
* @param clazz 类对象
* @param name 方法名
* @param paramCount 参数数量
* @return 方法对象
* @throws ReflectiveOperationException 反射异常
*/
public static Method[] findMethod(Class<?> clazz, String name,
int paramCount) throws ReflectiveOperationException {
ArrayList<Method> result = new ArrayList<Method>();
Method[] methods = getMethods(clazz,name);
for(Method method : methods){
if(method.getParameters().length == paramCount){
result.add(method);
}
}
return result.toArray(new Method[]{});
}
/**
* 获取类的方法集合
* @param clazz 类对象
* @return Method 对象数组
*/
public static Method[] getMethods(Class<?> clazz) {
List<Method> methods = new ArrayList<Method>();
for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
Method[] tmpMethods = clazz.getDeclaredMethods();
methods.addAll(Arrays.asList(tmpMethods));
}
return methods.toArray(new Method[]{});
}
/**
* 获取类的特定方法的集合
* 类中可能存在同名方法
* @param clazz 类对象
* @param name 方法名
* @return Method 对象数组
*/
public static Method[] getMethods(Class<?> clazz,String name) {
ArrayList<Method> methods = new ArrayList<Method>();
Method[] allMethod = getMethods(clazz);
for(Method method : allMethod){
if(method.getName().equals(name) )
methods.add(method);
}
return methods.toArray(new Method[0]);
}
/**
* 获取方法的参数返回值的范型类型
* @param method method 对象
* @param parameterIndex 参数索引(大于0)参数索引位置[第一个参数为0,以此类推], (-1) 返回值
* @return 返回范型类型数组
* @throws ClassNotFoundException 类找不到异常
*/
public static Class[] getMethodParameterGenericType(Method method,int parameterIndex) throws ClassNotFoundException {
Class[] result = null;
Type parameterType;
if(parameterIndex == -1){
parameterType = method.getGenericReturnType();
}else{
parameterType = method.getGenericParameterTypes()[parameterIndex];
}
if(parameterType instanceof ParameterizedType){
ParameterizedType parameterizedFieldType = (ParameterizedType)parameterType;
Type[] actualType = parameterizedFieldType.getActualTypeArguments();
result = new Class[actualType.length];
for(int i=0;i<actualType.length;i++){
result[i] = Class.forName(actualType[i].getTypeName());
}
return result;
}
return null;
}
/**
* 使用对象执行它的一个方法
* 对对象执行一个指定Method对象的方法
* @param obj 执行方法的对象
* @param method 方法对象
* @param parameters 多个参数
* @return 方法返回结果
* @throws ReflectiveOperationException 反射异常
*/
public static Object invokeMethod(Object obj, Method method, Object... parameters)
throws ReflectiveOperationException {
return method.invoke(obj, parameters);
}
/**
* 使用对象执行方法
* 推荐使用的方法,这个方法会自动寻找参数匹配度最好的方法并执行
* 对对象执行一个通过 方法名和参数列表选择的方法
* @param obj 执行方法的对象,如果调用静态方法直接传 Class 类型的对象
* @param name 执行方法名
* @param parameters 方法参数
* @return 方法返回结果
* @throws ReflectiveOperationException 反射异常
*/
public static Object invokeMethod(Object obj, String name, Object... parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Method method = null;
Class objClass = (obj instanceof Class) ? (Class)obj : obj.getClass();
try {
method = findMethod(objClass, name, parameterTypes);
method.setAccessible(true);
return method.invoke(obj, parameters);
}catch(Exception e){
Exception lastExecption = e;
//找到这个名称的所有方法
Method[] methods = findMethod(objClass,name,parameterTypes.length);
for(Method similarMethod : methods){
Parameter[] methodParams = similarMethod.getParameters();
//匹配参数数量相等的方法
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
//参数类型转换
String value = "";
Class parameterClass = parameters[i].getClass();
//复杂的对象通过 JSON转换成字符串,再转换成特定类型的对象
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
method = similarMethod;
try{
method.setAccessible(true);
return method.invoke(obj, convertedParams);
}catch(Exception ex){
lastExecption = (Exception) ex.getCause();
continue;
}
}
}
if ( !(lastExecption instanceof ReflectiveOperationException) ) {
lastExecption = new ReflectiveOperationException(lastExecption);
}
throw (ReflectiveOperationException)lastExecption;
}
}
/**
* 构造新的对象
* 通过参数中的构造参数对象parameters,选择特定的构造方法构造
* @param <T> 范型
* @param clazz 类对象
* @param parameters 构造方法参数
* @return 新的对象
* @throws ReflectiveOperationException 反射异常
*/
public static <T> T newInstance(Class<T> clazz, Object ...parameters)
throws ReflectiveOperationException {
Class<?>[] parameterTypes = getArrayClasses(parameters);
Constructor<T> constructor = null;
try {
if (parameters.length == 0) {
constructor = clazz.getConstructor();
} else {
constructor = clazz.getConstructor(parameterTypes);
}
return constructor.newInstance(parameters);
}catch(Exception e){
Constructor[] constructors = clazz.getConstructors();
for(Constructor similarConstructor : constructors){
Parameter[] methodParams = similarConstructor.getParameters();
//匹配参数数量相等的方法
if(methodParams.length == parameters.length){
Object[] convertedParams = new Object[parameters.length];
for(int i=0;i<methodParams.length;i++){
Parameter parameter = methodParams[i];
//参数类型转换
String value = "";
Class parameterClass = parameters[i].getClass();
//复杂的对象通过 JSON转换成字符串,再转换成特定类型的对象
if(parameters[i] instanceof Collection ||
parameters[i] instanceof Map ||
parameterClass.isArray() ||
!parameterClass.getCanonicalName().startsWith("java.lang")){
value = JSON.toJSON(parameters[i]);
}else{
value = parameters[i].toString();
}
convertedParams[i] = TString.toObject(value, parameter.getType());
}
constructor = similarConstructor;
try{
return constructor.newInstance(convertedParams);
}catch(Exception ex){
continue;
}
}
}
throw e;
}
}
/**
* 构造新的对象
* @param <T> 范型
* @param className 类名称
* @param parameters 构造方法参数
* @return 新的对象
* @throws ReflectiveOperationException 反射异常
*/
public static <T> T newInstance(String className, Object ...parameters) throws ReflectiveOperationException {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) Class.forName(className);
return newInstance(clazz,parameters);
}
/**
* 将对象数组转换成,对象类型的数组
* @param objs 对象类型数组
* @return 类数组
*/
public static Class<?>[] getArrayClasses(Object[] objs){
Class<?>[] parameterTypes= new Class<?>[objs.length];
for(int i=0;i<objs.length;i++){
parameterTypes[i] = objs[i].getClass();
}
return parameterTypes;
}
/**
* 将Map转换成指定的对象
*
* @param clazz 类对象
* @param mapArg Map 对象
* @param ignoreCase 匹配属性名是否不区分大小写
* @return 转换后的对象
* @throws ReflectiveOperationException 反射异常
* @throws ParseException 解析异常
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getObjectFromMap(Class<?> clazz,
Map<String, ?> mapArg,boolean ignoreCase) throws ReflectiveOperationException, ParseException {
Object obj = null;
if(mapArg==null){
return obj;
}
if(mapArg.isEmpty()){
return TReflect.newInstance(clazz,new Object[]{});
}
Object singleValue = mapArg.values().iterator().next();
// java标准对象
if (clazz.isPrimitive() || clazz == Object.class){
obj = singleValue;
}
//java 日期对象
else if(isExtendsByClass(clazz,Date.class)){
//取 Map.Values 里的递第一个值
String value = singleValue==null?null:singleValue.toString();
SimpleDateFormat dateFormat = new SimpleDateFormat(TDateTime.STANDER_DATETIME_TEMPLATE);
obj = singleValue!=null?dateFormat.parse(value.toString()):null;
}
//Map 类型
else if(isImpByInterface(clazz,Map.class)){
//不可构造的类型使用最常用的类型
if(Modifier.isAbstract(clazz.getModifiers()) && Modifier.isInterface(clazz.getModifiers())){
clazz = HashMap.class;
}
Map mapObject = TObject.cast(newInstance(clazz));
mapObject.putAll(mapArg);
obj = mapObject;
}
//Collection 类型
else if(isImpByInterface(clazz,Collection.class)){
//不可构造的类型使用最常用的类型
if(Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())){
clazz = ArrayList.class;
}
Collection listObject = TObject.cast(newInstance(clazz));
if(singleValue!=null){
listObject.addAll((Collection) TObject.cast(singleValue));
}
obj = listObject;
}
//Array 类型
else if(clazz.isArray()){
Class arrayClass = clazz.getComponentType();
Object tempArrayObj = Array.newInstance(arrayClass, 0);
return ((Collection)singleValue).toArray((Object[])tempArrayObj);
}
//java基本对象
else if (clazz.getName().startsWith("java.lang")) {
//取 Map.Values 里的递第一个值
String value = singleValue==null?null:singleValue.toString();
obj = singleValue==null?null:newInstance(clazz, value);
}
// 复杂对象
else {
obj = newInstance(clazz);
for(Entry<String,?> argEntry : mapArg.entrySet()){
String key = argEntry.getKey();
Object value = argEntry.getValue();
Field field = null;
if(ignoreCase) {
//忽略大小写匹配
field = findFieldIgnoreCase(clazz, key);
}else{
//精确匹配属性
field = findField(clazz, key);
}
if(field!=null) {
String fieldName = field.getName();
Class fieldType = field.getType();
try {
if(value != null) {
//对于 对象类型为 Map 的属性进行处理,查找范型,并转换为范型定义的类型
if (isImpByInterface(fieldType, Map.class) && value instanceof Map) {
Class[] mapGenericTypes = getFieldGenericType(field);
if (mapGenericTypes != null) {
if (fieldType == Map.class) {
fieldType = HashMap.class;
}
Map result = (Map) TReflect.newInstance(fieldType);
Map mapValue = (Map) value;
Iterator iterator = mapValue.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
Map keyOfMap = null;
Map valueOfMap = null;
if (entry.getKey() instanceof Map) {
keyOfMap = (Map) entry.getKey();
} else {
keyOfMap = TObject.newMap("value", entry.getKey());
}
if (entry.getValue() instanceof Map) {
valueOfMap = (Map) entry.getValue();
} else {
valueOfMap = TObject.newMap("value", entry.getValue());
}
Object keyObj = getObjectFromMap(mapGenericTypes[0], keyOfMap, ignoreCase);
Object valueObj = getObjectFromMap(mapGenericTypes[1], valueOfMap, ignoreCase);
result.put(keyObj, valueObj);
}
value = result;
}
}
//对于 对象类型为 Collection 的属性进行处理,查找范型,并转换为范型定义的类型
else if (isImpByInterface(fieldType, Collection.class) && value instanceof Collection) {
Class[] listGenericTypes = getFieldGenericType(field);
if (listGenericTypes != null) {
if (fieldType == List.class) {
fieldType = ArrayList.class;
}
List result = (List) TReflect.newInstance(fieldType);
List listValue = (List) value;
for (Object listItem : listValue) {
Map valueOfMap = null;
if (listItem instanceof Map) {
valueOfMap = (Map) listItem;
} else {
valueOfMap = TObject.newMap("value", listItem);
}
Object item = getObjectFromMap(listGenericTypes[0], valueOfMap, ignoreCase);
result.add(item);
}
value = result;
}
} else if (value instanceof Map) {
value = getObjectFromMap(fieldType, (Map<String, ?>) value, ignoreCase);
} else {
value = getObjectFromMap(fieldType, TObject.newMap("value", value), ignoreCase);
}
}
setFieldValue(obj, fieldName, value);
}catch(Exception e){
throw new ReflectiveOperationException("Fill object " + obj.getClass().getCanonicalName() +
"#"+fieldName+" failed",e);
}
}
}
}
return obj;
}
/**
* 将对象转换成 Map
* key 对象属性名称
* value 对象属性值
* @param obj 待转换的对象
* @return 转后的 Map
* @throws ReflectiveOperationException 反射异常
*/
public static Map<String, Object> getMapfromObject(Object obj) throws ReflectiveOperationException{
Map<String, Object> mapResult = new HashMap<String, Object>();
Map<Field, Object> fieldValues = TReflect.getFieldValues(obj);
//如果是 java 标准类型
if(obj.getClass().getName().startsWith("java.lang")
|| obj.getClass().isPrimitive()){
mapResult.put("value", obj);
}
//对 Collection 类型的处理
else if(obj instanceof Collection){
Collection collection = (Collection) newInstance(obj.getClass());
for(Object collectionItem : (Collection)obj) {
collection.add(getMapfromObject(collectionItem));
}
mapResult.put("value", collection);
}
//对 Map 类型的处理
else if(obj instanceof Map){
Map mapObject = (Map)obj;
Map map = (Map)newInstance(obj.getClass());
for(Object key : mapObject.keySet()) {
map.put(getMapfromObject(key),getMapfromObject(mapObject.get(key)));
}
mapResult.put("value", map);
}
//复杂对象类型
else{
for(Entry<Field,Object> entry : fieldValues.entrySet()){
String key = entry.getKey().getName();
Object value = entry.getValue();
if(value == null){
mapResult.put(key, value);
}else if(!key.contains("$")){
String valueClass = entry.getValue().getClass().getName();
if(valueClass.startsWith("java")){
mapResult.put(key, value);
}else {
//如果是复杂类型则递归调用
Map resultMap = getMapfromObject(value);
if(resultMap.size()==1 && resultMap.containsKey("value")){
mapResult.put(key, resultMap.values().iterator().next());
}else{
mapResult.put(key,resultMap);
}
}
}
}
}
return mapResult;
}
/**
* 判断某个类型是否实现了某个接口
* 包括判断其父接口
* @param type 被判断的类型
* @param interfaceClass 检查是否实现了次类的接口
* @return 是否实现某个接口
*/
public static boolean isImpByInterface(Class<?> type,Class<?> interfaceClass){
if(type==interfaceClass){
return true;
}
Class<?>[] interfaces= type.getInterfaces();
for (Class<?> interfaceItem : interfaces) {
if (interfaceItem.equals(interfaceClass)) {
return true;
}
else{
return isImpByInterface(interfaceItem,interfaceClass);
}
}
return false;
}
/**
* 判断某个类型是否继承于某个类
* 包括判断其父类
* @param type 判断的类型
* @param extendsClass 用于判断的父类类型
* @return 是否继承于某个类
*/
public static boolean isExtendsByClass(Class<?> type,Class<?> extendsClass){
if(extendsClass == type){
return true;
}
Class<?> superClass = type;
do{
if(superClass.equals(extendsClass)){
return true;
}
superClass = superClass.getSuperclass();
}while(superClass!=null && !superClass.equals(extendsClass) && !superClass.equals(Object.class));
return false;
}
/**
* 获取类的继承树上的所有父类
* @param type 类型 Class
* @return 所有父类
*/
public static Class[] getAllExtendAndInterfaceClass(Class<?> type){
if(type == null){
return null;
}
ArrayList<Class> classes = new ArrayList<Class>();
Class<?> superClass = type;
do{
superClass = superClass.getSuperclass();
classes.addAll(Arrays.asList(superClass.getInterfaces()));
classes.add(superClass);
}while(!Object.class.equals(superClass));
return classes.toArray(new Class[]{});
}
/**
* 获取类的 json 形式的描述
* @param clazz Class 类型对象
* @return 类的 json 形式的描述
*/
public static String getClazzJSONModel(Class clazz){
StringBuilder jsonStrBuilder = new StringBuilder();
if(clazz.getName().startsWith("java") || clazz.isPrimitive()){
jsonStrBuilder.append(clazz.getName());
} else if(clazz.getName().startsWith("[L")){
String clazzName = clazz.getName();
clazzName = clazzName.substring(clazzName.lastIndexOf(".")+1,clazzName.length()-2)+"[]";
jsonStrBuilder.append(clazzName);
} else {
jsonStrBuilder.append("{");
for (Field field : TReflect.getFields(clazz)) {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(field.getName());
jsonStrBuilder.append("\":");
String filedValueModel = getClazzJSONModel(field.getType());
if(filedValueModel.startsWith("{") && filedValueModel.endsWith("}")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else if(filedValueModel.startsWith("[") && filedValueModel.endsWith("]")) {
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append(",");
} else {
jsonStrBuilder.append("\"");
jsonStrBuilder.append(filedValueModel);
jsonStrBuilder.append("\",");
}
}
jsonStrBuilder.deleteCharAt(jsonStrBuilder.length()-1);
jsonStrBuilder.append("}");
}
return jsonStrBuilder.toString();
}
}
| imp: 优化反射工具类的性能
| src/main/java/org/voovan/tools/reflect/TReflect.java | imp: 优化反射工具类的性能 | <ide><path>rc/main/java/org/voovan/tools/reflect/TReflect.java
<ide>
<ide> private static Map<String, Field> fields = new HashMap<String ,Field>();
<ide> private static Map<String, Method> methods = new HashMap<String ,Method>();
<add> private static Map<String, Field[]> fieldArrays = new HashMap<String ,Field[]>();
<add> private static Map<String, Method[]> methodArrays = new HashMap<String ,Method[]>();
<ide>
<ide> /**
<ide> * 获得类所有的Field
<ide> * @return Field数组
<ide> */
<ide> public static Field[] getFields(Class<?> clazz) {
<del> List<Field> fields = new ArrayList<Field>();
<del> for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
<del> Field[] tmpFields = clazz.getDeclaredFields();
<del> fields.addAll(Arrays.asList(tmpFields));
<del> }
<del> return fields.toArray(new Field[]{});
<add> String mark = clazz.getCanonicalName();
<add> Field[] fields = null;
<add>
<add> if(fieldArrays.containsKey(mark)){
<add> fields = fieldArrays.get(mark);
<add> }else {
<add> ArrayList<Field> fieldArray = new ArrayList<Field>();
<add> for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
<add> Field[] tmpFields = clazz.getDeclaredFields();
<add> fieldArray.addAll(Arrays.asList(tmpFields));
<add> }
<add> fields = fieldArray.toArray(new Field[]{});
<add> fieldArrays.put(mark, fields);
<add> fieldArray.clear();
<add> }
<add>
<add> return fields;
<ide> }
<ide>
<ide> /**
<ide> public static Field findField(Class<?> clazz, String fieldName)
<ide> throws ReflectiveOperationException {
<ide>
<del> String fieldMark = clazz.getCanonicalName()+"#"+fieldName;
<add> String mark = clazz.getCanonicalName()+"#"+fieldName;
<ide>
<ide> try {
<del> if(fields.containsKey(fieldMark)){
<del> return fields.get(fieldMark);
<add> if(fields.containsKey(mark)){
<add> return fields.get(mark);
<ide> }else {
<ide> Field field = clazz.getDeclaredField(fieldName);
<del> fields.put(fieldMark, field);
<add> fields.put(mark, field);
<ide> return field;
<ide> }
<ide>
<ide> public static Field findFieldIgnoreCase(Class<?> clazz, String fieldName)
<ide> throws ReflectiveOperationException{
<ide>
<del> String fieldMark = clazz.getCanonicalName()+"#"+fieldName;
<del>
<del> if(fields.containsKey(fieldMark)){
<del> return fields.get(fieldMark);
<add> String mark = clazz.getCanonicalName()+"#"+fieldName;
<add>
<add> if(fields.containsKey(mark)){
<add> return fields.get(mark);
<ide> }else {
<ide> for (Field field : getFields(clazz)) {
<ide> if (field.getName().equalsIgnoreCase(fieldName)) {
<del> fields.put(fieldMark, field);
<add> fields.put(mark, field);
<ide> return field;
<ide> }
<ide> }
<ide> */
<ide> public static Method findMethod(Class<?> clazz, String name,
<ide> Class<?>... paramTypes) throws ReflectiveOperationException {
<del>
<del>
<del>
<del> String methodMark = clazz.getCanonicalName()+"#"+name;
<add> String mark = clazz.getCanonicalName()+"#"+name;
<ide> for(Class<?> paramType : paramTypes){
<del> methodMark = methodMark + "$" + paramType.getCanonicalName();
<del> }
<del>
<del> if(methods.containsKey(methodMark)){
<del> return methods.get(methodMark);
<add> mark = mark + "$" + paramType.getCanonicalName();
<add> }
<add>
<add> if(methods.containsKey(mark)){
<add> return methods.get(mark);
<ide> }else {
<ide> Method method = clazz.getDeclaredMethod(name, paramTypes);
<del> methods.put(methodMark, method);
<add> methods.put(mark, method);
<ide> return method;
<ide> }
<ide> }
<ide> */
<ide> public static Method[] findMethod(Class<?> clazz, String name,
<ide> int paramCount) throws ReflectiveOperationException {
<del> ArrayList<Method> result = new ArrayList<Method>();
<del> Method[] methods = getMethods(clazz,name);
<del> for(Method method : methods){
<del> if(method.getParameters().length == paramCount){
<del> result.add(method);
<del> }
<del> }
<del>
<del> return result.toArray(new Method[]{});
<add> Method[] methods = null;
<add>
<add> String mark = clazz.getCanonicalName()+"#"+name+"@"+paramCount;
<add>
<add> if(methodArrays.containsKey(mark)){
<add> return methodArrays.get(mark);
<add> } else {
<add> ArrayList<Method> methodList = new ArrayList<Method>();
<add> Method[] allMethods = getMethods(clazz, name);
<add> for (Method method : allMethods) {
<add> if (method.getParameters().length == paramCount) {
<add> methodList.add(method);
<add> }
<add> }
<add> methods = methodList.toArray(new Method[]{});
<add> methodArrays.put(mark,methods);
<add> methodList.clear();
<add> }
<add>
<add> return methods;
<ide> }
<ide>
<ide> /**
<ide> * @return Method 对象数组
<ide> */
<ide> public static Method[] getMethods(Class<?> clazz) {
<del> List<Method> methods = new ArrayList<Method>();
<del> for( ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
<del> Method[] tmpMethods = clazz.getDeclaredMethods();
<del> methods.addAll(Arrays.asList(tmpMethods));
<del> }
<del> return methods.toArray(new Method[]{});
<add>
<add> Method[] methods = null;
<add>
<add> String mark = clazz.getCanonicalName();
<add>
<add> if(methodArrays.containsKey(mark)){
<add> return methodArrays.get(mark);
<add> } else {
<add> List<Method> methodList = new ArrayList<Method>();
<add> for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
<add> Method[] tmpMethods = clazz.getDeclaredMethods();
<add> methodList.addAll(Arrays.asList(tmpMethods));
<add> }
<add> methods = methodList.toArray(new Method[]{});
<add> methodList.clear();
<add> methodArrays.put(mark,methods);
<add> }
<add> return methods;
<ide> }
<ide>
<ide> /**
<ide> * @return Method 对象数组
<ide> */
<ide> public static Method[] getMethods(Class<?> clazz,String name) {
<del> ArrayList<Method> methods = new ArrayList<Method>();
<del> Method[] allMethod = getMethods(clazz);
<del>
<del> for(Method method : allMethod){
<del> if(method.getName().equals(name) )
<del> methods.add(method);
<del> }
<del> return methods.toArray(new Method[0]);
<add>
<add> Method[] methods = null;
<add>
<add> String mark = clazz.getCanonicalName()+"#"+name;
<add>
<add> if(methodArrays.containsKey(mark)){
<add> return methodArrays.get(mark);
<add> } else {
<add> ArrayList<Method> methodList = new ArrayList<Method>();
<add> Method[] allMethods = getMethods(clazz);
<add> for (Method method : allMethods) {
<add> if (method.getName().equals(name))
<add> methodList.add(method);
<add> }
<add> methods = methodList.toArray(new Method[0]);
<add> methodList.clear();
<add> methodArrays.put(mark,methods);
<add> }
<add> return methods;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | a30a9cdab7354b0012fb2c87d534dda684828315 | 0 | tasomaniac/OpenLinkWith,tasomaniac/OpenLinkWith,tasomaniac/OpenLinkWith | package com.tasomaniac.openwith.homescreen;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import com.tasomaniac.android.widget.DelayedProgressBar;
import com.tasomaniac.openwith.R;
import com.tasomaniac.openwith.resolver.DisplayResolveInfo;
import com.tasomaniac.openwith.util.Intents;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindBitmap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import static android.os.Build.VERSION_CODES.M;
@TargetApi(M)
public class AddToHomeScreenDialogFragment extends AppCompatDialogFragment
implements DialogInterface.OnClickListener {
private static final String KEY_DRI = "dri";
private static final String KEY_INTENT = "intent";
private final OkHttpClient client = new OkHttpClient();
@BindView(R.id.add_to_home_screen_title)
EditText titleView;
@BindView(R.id.add_to_home_screen_progress)
DelayedProgressBar progressBar;
@BindBitmap(R.drawable.ic_star_mark)
Bitmap shortcutMark;
private DisplayResolveInfo dri;
private ShortcutIconCreator shortcutIconCreator;
private Intent intent;
private Call call;
public static AddToHomeScreenDialogFragment newInstance(DisplayResolveInfo dri, Intent intent) {
AddToHomeScreenDialogFragment fragment = new AddToHomeScreenDialogFragment();
Bundle args = new Bundle();
args.putParcelable(KEY_DRI, dri);
args.putParcelable(KEY_INTENT, intent);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dri = getArguments().getParcelable(KEY_DRI);
intent = getArguments().getParcelable(KEY_INTENT);
}
@Override
public void onStart() {
super.onStart();
onTitleChanged(titleView.getText());
shortcutIconCreator = new ShortcutIconCreator(shortcutMark);
if (TextUtils.isEmpty(titleView.getText())) {
showProgressBar();
fetchTitle();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.cancel();
}
}
private void fetchTitle() {
if (call != null) {
call.cancel();
}
call = client.newCall(new Request.Builder().url(intent.getDataString()).build());
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
hideProgressBar();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
hideProgressBar();
if (!response.isSuccessful()) {
return;
}
if (!TextUtils.isEmpty(titleView.getText())) {
return;
}
try (ResponseBody body = response.body()) {
final String title = extractTitle(body);
titleView.post(new Runnable() {
@Override
public void run() {
if (title !=null && TextUtils.isEmpty(titleView.getText())) {
titleView.append(title);
}
}
});
}
}
});
}
private static String extractTitle(ResponseBody body) throws IOException {
BufferedSource source = body.source();
Pattern pattern = Pattern.compile("<title>(.+)</title>");
String line;
//noinspection MethodCallInLoopCondition
while ((line = source.readUtf8Line()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return matcher.group(1);
}
}
return null;
}
private void showProgressBar() {
progressBar.post(new Runnable() {
@Override
public void run() {
progressBar.show();
}
});
}
private void hideProgressBar() {
progressBar.post(new Runnable() {
@Override
public void run() {
progressBar.hide(true);
}
});
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_add_to_home_screen, (ViewGroup) getView(), false);
ButterKnife.bind(this, view);
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.add, this)
.setNegativeButton(R.string.cancel, null)
.setView(view)
.setTitle(R.string.add_to_homescreen)
.create();
forceKeyboardVisible(dialog);
return dialog;
}
private static void forceKeyboardVisible(AlertDialog dialog) {
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
);
}
@Override
public void onClick(DialogInterface dialog, int which) {
createShortcutFor(dri);
Intents.launchHomeScreen(getActivity());
}
@OnEditorAction(R.id.add_to_home_screen_title)
boolean onKeyboardDoneClicked(int actionId) {
if (EditorInfo.IME_ACTION_GO == actionId) {
createShortcutFor(dri);
Intents.launchHomeScreen(getActivity());
return true;
}
return false;
}
@OnTextChanged(R.id.add_to_home_screen_title)
void onTitleChanged(CharSequence title) {
AlertDialog dialog = (AlertDialog) getDialog();
dialog.getButton(DialogInterface.BUTTON_POSITIVE)
.setEnabled(!TextUtils.isEmpty(title));
}
private void createShortcutFor(DisplayResolveInfo dri) {
Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, titleView.getText().toString());
shortcutIntent.putExtra(
Intent.EXTRA_SHORTCUT_ICON,
shortcutIconCreator.createShortcutIconFor((BitmapDrawable) dri.getDisplayIcon())
);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
shortcutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getActivity().sendBroadcast(Intents.fixIntents(getContext(), shortcutIntent));
}
public void show(FragmentManager fragmentManager) {
show(fragmentManager, "AddToHomeScreen");
}
}
| app/src/main/java/com/tasomaniac/openwith/homescreen/AddToHomeScreenDialogFragment.java | package com.tasomaniac.openwith.homescreen;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import com.tasomaniac.android.widget.DelayedProgressBar;
import com.tasomaniac.openwith.R;
import com.tasomaniac.openwith.resolver.DisplayResolveInfo;
import com.tasomaniac.openwith.util.Intents;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindBitmap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;
import static android.os.Build.VERSION_CODES.M;
@TargetApi(M)
public class AddToHomeScreenDialogFragment extends AppCompatDialogFragment
implements DialogInterface.OnClickListener {
private static final String KEY_DRI = "dri";
private static final String KEY_INTENT = "intent";
private final OkHttpClient client = new OkHttpClient();
@BindView(R.id.add_to_home_screen_title)
EditText titleView;
@BindView(R.id.add_to_home_screen_progress)
DelayedProgressBar progressBar;
@BindBitmap(R.drawable.ic_star_mark)
Bitmap shortcutMark;
private DisplayResolveInfo dri;
private ShortcutIconCreator shortcutIconCreator;
private Intent intent;
private Call call;
public static AddToHomeScreenDialogFragment newInstance(DisplayResolveInfo dri, Intent intent) {
AddToHomeScreenDialogFragment fragment = new AddToHomeScreenDialogFragment();
Bundle args = new Bundle();
args.putParcelable(KEY_DRI, dri);
args.putParcelable(KEY_INTENT, intent);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dri = getArguments().getParcelable(KEY_DRI);
intent = getArguments().getParcelable(KEY_INTENT);
}
@Override
public void onStart() {
super.onStart();
onTitleChanged(titleView.getText());
shortcutIconCreator = new ShortcutIconCreator(shortcutMark);
if (TextUtils.isEmpty(titleView.getText())) {
showProgressBar();
fetchTitle();
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (call != null) {
call.cancel();
}
}
private void fetchTitle() {
if (call != null) {
call.cancel();
}
call = client.newCall(new Request.Builder().url(intent.getDataString()).build());
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
hideProgressBar();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
hideProgressBar();
if (!response.isSuccessful()) {
return;
}
if (!TextUtils.isEmpty(titleView.getText())) {
return;
}
try (ResponseBody body = response.body()) {
final String title = extractTitle(body);
titleView.post(new Runnable() {
@Override
public void run() {
if (title !=null && TextUtils.isEmpty(titleView.getText())) {
titleView.append(title);
}
}
});
}
}
});
}
private void showProgressBar() {
progressBar.post(new Runnable() {
@Override
public void run() {
progressBar.show();
}
});
}
private void hideProgressBar() {
progressBar.post(new Runnable() {
@Override
public void run() {
progressBar.hide(true);
}
});
}
private static String extractTitle(ResponseBody body) throws IOException {
BufferedSource source = body.source();
Pattern pattern = Pattern.compile("<title>(.+)</title>");
String line;
//noinspection MethodCallInLoopCondition
while ((line = source.readUtf8Line()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return matcher.group(1);
}
}
return null;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_add_to_home_screen, (ViewGroup) getView(), false);
ButterKnife.bind(this, view);
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.add, this)
.setNegativeButton(R.string.cancel, null)
.setView(view)
.setTitle(R.string.add_to_homescreen)
.create();
dialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
);
return dialog;
}
@Override
public void onClick(DialogInterface dialog, int which) {
createShortcutFor(dri);
Intents.launchHomeScreen(getActivity());
}
@OnEditorAction(R.id.add_to_home_screen_title)
boolean onKeyboardDoneClicked(int actionId) {
if (EditorInfo.IME_ACTION_GO == actionId) {
createShortcutFor(dri);
Intents.launchHomeScreen(getActivity());
return true;
}
return false;
}
@OnTextChanged(R.id.add_to_home_screen_title)
void onTitleChanged(CharSequence title) {
AlertDialog dialog = (AlertDialog) getDialog();
dialog.getButton(DialogInterface.BUTTON_POSITIVE)
.setEnabled(!TextUtils.isEmpty(title));
}
private void createShortcutFor(DisplayResolveInfo dri) {
Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, titleView.getText().toString());
shortcutIntent.putExtra(
Intent.EXTRA_SHORTCUT_ICON,
shortcutIconCreator.createShortcutIconFor((BitmapDrawable) dri.getDisplayIcon())
);
shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
shortcutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getActivity().sendBroadcast(Intents.fixIntents(getContext(), shortcutIntent));
}
public void show(FragmentManager fragmentManager) {
show(fragmentManager, "AddToHomeScreen");
}
}
| Extract method for better readibility
| app/src/main/java/com/tasomaniac/openwith/homescreen/AddToHomeScreenDialogFragment.java | Extract method for better readibility | <ide><path>pp/src/main/java/com/tasomaniac/openwith/homescreen/AddToHomeScreenDialogFragment.java
<ide> });
<ide> }
<ide>
<del> private void showProgressBar() {
<del> progressBar.post(new Runnable() {
<del> @Override
<del> public void run() {
<del> progressBar.show();
<del> }
<del> });
<del> }
<del>
<del> private void hideProgressBar() {
<del> progressBar.post(new Runnable() {
<del> @Override
<del> public void run() {
<del> progressBar.hide(true);
<del> }
<del> });
<del> }
<del>
<ide> private static String extractTitle(ResponseBody body) throws IOException {
<ide> BufferedSource source = body.source();
<ide>
<ide> return null;
<ide> }
<ide>
<add> private void showProgressBar() {
<add> progressBar.post(new Runnable() {
<add> @Override
<add> public void run() {
<add> progressBar.show();
<add> }
<add> });
<add> }
<add>
<add> private void hideProgressBar() {
<add> progressBar.post(new Runnable() {
<add> @Override
<add> public void run() {
<add> progressBar.hide(true);
<add> }
<add> });
<add> }
<add>
<ide> @NonNull
<ide> @Override
<ide> public Dialog onCreateDialog(Bundle savedInstanceState) {
<ide> .setView(view)
<ide> .setTitle(R.string.add_to_homescreen)
<ide> .create();
<add> forceKeyboardVisible(dialog);
<add> return dialog;
<add> }
<add>
<add> private static void forceKeyboardVisible(AlertDialog dialog) {
<ide> dialog.getWindow().setSoftInputMode(
<ide> WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
<ide> | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
<ide> );
<del> return dialog;
<ide> }
<ide>
<ide> @Override |
|
Java | mit | 40b3005f5a51d8b57720d14fa607701b2b21e2cc | 0 | PrinceOfAmber/CyclicMagic,PrinceOfAmber/Cyclic | package com.lothrazar.cyclicmagic.component.hydrator;
import com.lothrazar.cyclicmagic.block.base.TileEntityBaseMachineInvo;
import com.lothrazar.cyclicmagic.gui.ITileRedstoneToggle;
import com.lothrazar.cyclicmagic.util.UtilItemStack;
import com.lothrazar.cyclicmagic.util.UtilWorld;
import net.minecraft.init.Blocks;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
public class TileEntityHydrator extends TileEntityBaseMachineInvo implements ITileRedstoneToggle, ITickable {
public TileEntityHydrator() {
super(9);
}
//vazkii wanted simple block breaker and block placer. already have the BlockBuilder for placing :D
//of course this isnt standalone and hes probably found some other mod by now but doing it anyway https://twitter.com/Vazkii/status/767569090483552256
// fake player idea ??? https://gitlab.prok.pw/Mirrors/minecraftforge/commit/f6ca556a380440ededce567f719d7a3301676ed0
private static final String NBT_REDST = "redstone";
private int needsRedstone = 1;
public static enum Fields {
REDSTONE
}
@Override
public int[] getFieldOrdinals() {
return super.getFieldArray(Fields.values().length);
}
@Override
public void update() {
if (isRunning()) {
this.spawnParticlesAbove();
}
this.shiftAllUp();
ItemStack s = this.getStackInSlot(0);
if (OreDictionary.itemMatches(s, new ItemStack(Blocks.DIRT), false)) {
sendOutput(new ItemStack(Blocks.FARMLAND));
s.shrink(1);
}
else if (OreDictionary.itemMatches(s, new ItemStack(Blocks.HARDENED_CLAY), false)) {
sendOutput(new ItemStack(Blocks.CLAY));
s.shrink(1);
}
else if (s.isItemEqual(new ItemStack(Blocks.CONCRETE_POWDER, 1, EnumDyeColor.BLACK.getMetadata()) )) {
sendOutput(new ItemStack(Blocks.CONCRETE, 1, EnumDyeColor.BLACK.getMetadata()));
s.shrink(1);
}
}
public void sendOutput(ItemStack out) {
UtilItemStack.dropItemStackInWorld(this.world, this.getPos(), out);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
tagCompound.setInteger(NBT_REDST, this.needsRedstone);
return super.writeToNBT(tagCompound);
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
this.needsRedstone = tagCompound.getInteger(NBT_REDST);
}
@Override
public int[] getSlotsForFace(EnumFacing side) {
return new int[] {};
}
@Override
public int getField(int id) {
switch (Fields.values()[id]) {
case REDSTONE:
return this.needsRedstone;
}
return -1;
}
@Override
public void setField(int id, int value) {
switch (Fields.values()[id]) {
case REDSTONE:
this.needsRedstone = value;
break;
}
}
@Override
public int getFieldCount() {
return Fields.values().length;
}
@Override
public void toggleNeedsRedstone() {
int val = this.needsRedstone + 1;
if (val > 1) {
val = 0;//hacky lazy way
}
this.setField(Fields.REDSTONE.ordinal(), val);
}
public boolean onlyRunIfPowered() {
return this.needsRedstone == 1;
}
}
| src/main/java/com/lothrazar/cyclicmagic/component/hydrator/TileEntityHydrator.java | package com.lothrazar.cyclicmagic.component.hydrator;
import com.lothrazar.cyclicmagic.block.base.TileEntityBaseMachineInvo;
import com.lothrazar.cyclicmagic.gui.ITileRedstoneToggle;
import com.lothrazar.cyclicmagic.util.UtilItemStack;
import com.lothrazar.cyclicmagic.util.UtilWorld;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.world.World;
import net.minecraftforge.oredict.OreDictionary;
public class TileEntityHydrator extends TileEntityBaseMachineInvo implements ITileRedstoneToggle, ITickable {
public TileEntityHydrator() {
super(9);
}
//vazkii wanted simple block breaker and block placer. already have the BlockBuilder for placing :D
//of course this isnt standalone and hes probably found some other mod by now but doing it anyway https://twitter.com/Vazkii/status/767569090483552256
// fake player idea ??? https://gitlab.prok.pw/Mirrors/minecraftforge/commit/f6ca556a380440ededce567f719d7a3301676ed0
private static final String NBT_REDST = "redstone";
private int needsRedstone = 1;
public static enum Fields {
REDSTONE
}
@Override
public int[] getFieldOrdinals() {
return super.getFieldArray(Fields.values().length);
}
@Override
public void update() {
if (isRunning()) {
this.spawnParticlesAbove();
}
this.shiftAllUp();
ItemStack s = this.getStackInSlot(0);
if(OreDictionary.itemMatches(s, new ItemStack(Blocks.DIRT), false)){
sendOutput( new ItemStack( Blocks.FARMLAND));
s.shrink(1);
}
else if(OreDictionary.itemMatches(s, new ItemStack(Blocks.HARDENED_CLAY), false)){
sendOutput(new ItemStack( Blocks.CLAY) );
s.shrink(1);
}
}
public void sendOutput(ItemStack out ) {
UtilItemStack.dropItemStackInWorld(this.world, this.getPos(), out);
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {
tagCompound.setInteger(NBT_REDST, this.needsRedstone);
return super.writeToNBT(tagCompound);
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
super.readFromNBT(tagCompound);
this.needsRedstone = tagCompound.getInteger(NBT_REDST);
}
@Override
public int[] getSlotsForFace(EnumFacing side) {
return new int[] {};
}
@Override
public int getField(int id) {
switch (Fields.values()[id]) {
case REDSTONE:
return this.needsRedstone;
}
return -1;
}
@Override
public void setField(int id, int value) {
switch (Fields.values()[id]) {
case REDSTONE:
this.needsRedstone = value;
break;
}
}
@Override
public int getFieldCount() {
return Fields.values().length;
}
@Override
public void toggleNeedsRedstone() {
int val = this.needsRedstone + 1;
if (val > 1) {
val = 0;//hacky lazy way
}
this.setField(Fields.REDSTONE.ordinal(), val);
}
public boolean onlyRunIfPowered() {
return this.needsRedstone == 1;
}
}
| proof of concept : concrete
| src/main/java/com/lothrazar/cyclicmagic/component/hydrator/TileEntityHydrator.java | proof of concept : concrete | <ide><path>rc/main/java/com/lothrazar/cyclicmagic/component/hydrator/TileEntityHydrator.java
<ide> import com.lothrazar.cyclicmagic.util.UtilItemStack;
<ide> import com.lothrazar.cyclicmagic.util.UtilWorld;
<ide> import net.minecraft.init.Blocks;
<add>import net.minecraft.item.EnumDyeColor;
<ide> import net.minecraft.item.ItemStack;
<ide> import net.minecraft.nbt.NBTTagCompound;
<ide> import net.minecraft.util.EnumFacing;
<ide> //of course this isnt standalone and hes probably found some other mod by now but doing it anyway https://twitter.com/Vazkii/status/767569090483552256
<ide> // fake player idea ??? https://gitlab.prok.pw/Mirrors/minecraftforge/commit/f6ca556a380440ededce567f719d7a3301676ed0
<ide> private static final String NBT_REDST = "redstone";
<del>
<ide> private int needsRedstone = 1;
<ide> public static enum Fields {
<ide> REDSTONE
<ide> if (isRunning()) {
<ide> this.spawnParticlesAbove();
<ide> }
<del>
<ide> this.shiftAllUp();
<del>
<ide> ItemStack s = this.getStackInSlot(0);
<del>
<del> if(OreDictionary.itemMatches(s, new ItemStack(Blocks.DIRT), false)){
<del> sendOutput( new ItemStack( Blocks.FARMLAND));
<add> if (OreDictionary.itemMatches(s, new ItemStack(Blocks.DIRT), false)) {
<add> sendOutput(new ItemStack(Blocks.FARMLAND));
<ide> s.shrink(1);
<ide> }
<del> else if(OreDictionary.itemMatches(s, new ItemStack(Blocks.HARDENED_CLAY), false)){
<del> sendOutput(new ItemStack( Blocks.CLAY) );
<add> else if (OreDictionary.itemMatches(s, new ItemStack(Blocks.HARDENED_CLAY), false)) {
<add> sendOutput(new ItemStack(Blocks.CLAY));
<ide> s.shrink(1);
<ide> }
<del>
<add> else if (s.isItemEqual(new ItemStack(Blocks.CONCRETE_POWDER, 1, EnumDyeColor.BLACK.getMetadata()) )) {
<add> sendOutput(new ItemStack(Blocks.CONCRETE, 1, EnumDyeColor.BLACK.getMetadata()));
<add> s.shrink(1);
<add> }
<ide> }
<del> public void sendOutput(ItemStack out ) {
<add> public void sendOutput(ItemStack out) {
<ide> UtilItemStack.dropItemStackInWorld(this.world, this.getPos(), out);
<ide> }
<ide> @Override |
|
Java | apache-2.0 | c368821a7f51aa03e256c6683d9f6dfa6f8f6982 | 0 | thymeleaf/thymeleaf,thymeleaf/thymeleaf | /*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.standard;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.dialect.IExecutionAttributeDialect;
import org.thymeleaf.dialect.IExpressionObjectDialect;
import org.thymeleaf.expression.IExpressionObjectFactory;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.expression.IStandardConversionService;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.IStandardVariableExpressionEvaluator;
import org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator;
import org.thymeleaf.standard.expression.StandardConversionService;
import org.thymeleaf.standard.expression.StandardExpressionObjectFactory;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.standard.processor.StandardActionTagProcessor;
import org.thymeleaf.standard.processor.StandardAltTitleTagProcessor;
import org.thymeleaf.standard.processor.StandardAssertTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrappendTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrprependTagProcessor;
import org.thymeleaf.standard.processor.StandardBlockTagProcessor;
import org.thymeleaf.standard.processor.StandardCaseTagProcessor;
import org.thymeleaf.standard.processor.StandardClassappendTagProcessor;
import org.thymeleaf.standard.processor.StandardConditionalCommentProcessor;
import org.thymeleaf.standard.processor.StandardConditionalFixedValueTagProcessor;
import org.thymeleaf.standard.processor.StandardDOMEventAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardDefaultAttributesTagProcessor;
import org.thymeleaf.standard.processor.StandardEachTagProcessor;
import org.thymeleaf.standard.processor.StandardFragmentTagProcessor;
import org.thymeleaf.standard.processor.StandardHrefTagProcessor;
import org.thymeleaf.standard.processor.StandardIfTagProcessor;
import org.thymeleaf.standard.processor.StandardIncludeTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineEnablementTemplateBoundariesProcessor;
import org.thymeleaf.standard.processor.StandardInlineHTMLTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineTextualTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineXMLTagProcessor;
import org.thymeleaf.standard.processor.StandardInliningCDATASectionProcessor;
import org.thymeleaf.standard.processor.StandardInliningCommentProcessor;
import org.thymeleaf.standard.processor.StandardInliningTextProcessor;
import org.thymeleaf.standard.processor.StandardInsertTagProcessor;
import org.thymeleaf.standard.processor.StandardLangXmlLangTagProcessor;
import org.thymeleaf.standard.processor.StandardMethodTagProcessor;
import org.thymeleaf.standard.processor.StandardNonRemovableAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardObjectTagProcessor;
import org.thymeleaf.standard.processor.StandardRefAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardRemovableAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardRemoveTagProcessor;
import org.thymeleaf.standard.processor.StandardReplaceTagProcessor;
import org.thymeleaf.standard.processor.StandardSrcTagProcessor;
import org.thymeleaf.standard.processor.StandardStyleappendTagProcessor;
import org.thymeleaf.standard.processor.StandardSubstituteByTagProcessor;
import org.thymeleaf.standard.processor.StandardSwitchTagProcessor;
import org.thymeleaf.standard.processor.StandardTextTagProcessor;
import org.thymeleaf.standard.processor.StandardTranslationDocTypeProcessor;
import org.thymeleaf.standard.processor.StandardUnlessTagProcessor;
import org.thymeleaf.standard.processor.StandardUtextTagProcessor;
import org.thymeleaf.standard.processor.StandardValueTagProcessor;
import org.thymeleaf.standard.processor.StandardWithTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlBaseTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlLangTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlNsTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlSpaceTagProcessor;
import org.thymeleaf.standard.serializer.IStandardCSSSerializer;
import org.thymeleaf.standard.serializer.IStandardJavaScriptSerializer;
import org.thymeleaf.standard.serializer.StandardCSSSerializer;
import org.thymeleaf.standard.serializer.StandardJavaScriptSerializer;
import org.thymeleaf.standard.serializer.StandardSerializers;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.util.Validate;
/**
* <p>
* Standard Dialect. This is the class containing the implementation of Thymeleaf Standard Dialect, including all
* <tt>th:*</tt> processors, expression objects, etc.
* </p>
* <p>
* Note this dialect uses <strong>OGNL</strong> as an expression language. There is a Spring-integrated version
* of the Standard Dialect called the <em>SpringStandard Dialect</em> at the <tt>thymeleaf-spring*</tt> packages,
* which uses SpringEL as an expression language.
* </p>
* <p>
* Note a class with this name existed since 1.0, but it was completely reimplemented
* in Thymeleaf 3.0
* </p>
*
* @author Daniel Fernández
*
* @since 3.0.0
*
*/
public class StandardDialect
extends AbstractProcessorDialect
implements IExecutionAttributeDialect, IExpressionObjectDialect {
public static final String NAME = "Standard";
public static final String PREFIX = "th";
public static final int PROCESSOR_PRECEDENCE = 1000;
private final IExpressionObjectFactory STANDARD_EXPRESSION_OBJECTS_FACTORY = new StandardExpressionObjectFactory();
// We will avoid setting this variableExpressionEvaluator variable to "OgnlVariableExpressionEvaluator.INSTANCE"
// in order to not cause this OGNL-related class to initialize, therefore introducing a forced dependency on OGNL
// to Spring users (who don't need OGNL at all).
private IStandardVariableExpressionEvaluator variableExpressionEvaluator = null;
private IStandardExpressionParser expressionParser = new StandardExpressionParser();
private IStandardConversionService conversionService = new StandardConversionService();
private IStandardJavaScriptSerializer javaScriptSerializer = new StandardJavaScriptSerializer(true);
private IStandardCSSSerializer cssSerializer = new StandardCSSSerializer();
public StandardDialect() {
super(NAME, PREFIX, PROCESSOR_PRECEDENCE);
}
/*
* Meant to be overridden by dialects that do almost the same as this, changing bits here and there
* (e.g. SpringStandardDialect)
*/
protected StandardDialect(final String name, final String prefix, final int processorPrecedence) {
super(name, prefix, processorPrecedence);
}
/**
* <p>
* Returns the variable expression evaluator (implementation of {@link IStandardVariableExpressionEvaluator})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This is used for executing all ${...} and *{...} expressions in Thymeleaf Standard Expressions.
* </p>
* <p>
* This will be {@link OGNLVariableExpressionEvaluator} by default. When using the Spring Standard
* Dialect, this will be a SpringEL-based implementation.
* </p>
*
* @return the Standard Variable Expression Evaluator object.
*/
public IStandardVariableExpressionEvaluator getVariableExpressionEvaluator() {
if (this.variableExpressionEvaluator == null) {
this.variableExpressionEvaluator = new OGNLVariableExpressionEvaluator(true);
}
return this.variableExpressionEvaluator;
}
/**
* <p>
* Sets the variable expression evaluator (implementation of {@link IStandardVariableExpressionEvaluator})
* that should be used at this instance of the Standard Dialect.
* </p>
* <p>
* This is used for executing all ${...} and *{...} expressions in Thymeleaf Standard Expressions.
* </p>
* <p>
* This will be an {@link OGNLVariableExpressionEvaluator} by default. When using the Spring Standard
* Dialect, this will be a SpringEL-based implementation.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param variableExpressionEvaluator the new Standard Variable Expression Evaluator object. Cannot be null.
*/
public void setVariableExpressionEvaluator(final IStandardVariableExpressionEvaluator variableExpressionEvaluator) {
Validate.notNull(variableExpressionEvaluator, "Standard Variable Expression Evaluator cannot be null");
this.variableExpressionEvaluator = variableExpressionEvaluator;
}
/**
* <p>
* Returns the Thymeleaf Standard Expression parser (implementation of {@link IStandardExpressionParser})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardExpressionParser} by default.
* </p>
*
* @return the Standard Expression Parser object.
*/
public IStandardExpressionParser getExpressionParser() {
return this.expressionParser;
}
/**
* <p>
* Sets the Thymeleaf Standard Expression parser (implementation of {@link IStandardExpressionParser})
* that should be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardExpressionParser} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param expressionParser the Standard Expression Parser object to be used. Cannot be null.
*/
public void setExpressionParser(final IStandardExpressionParser expressionParser) {
Validate.notNull(expressionParser, "Standard Expression Parser cannot be null");
this.expressionParser = expressionParser;
}
/**
* <p>
* Returns the Standard Conversion Service (implementation of {@link IStandardConversionService})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardConversionService} by default. In Spring environments, this will default
* to an implementation delegating on Spring's own ConversionService implementation.
* </p>
*
* @return the Standard Conversion Service object.
*/
public IStandardConversionService getConversionService() {
return this.conversionService;
}
/**
* <p>
* Sets the Standard Conversion Service (implementation of {@link IStandardConversionService})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardConversionService} by default. In Spring environments, this will default
* to an implementation delegating on Spring's own ConversionService implementation.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param conversionService the Standard ConversionService object to be used. Cannot be null.
*/
public void setConversionService(final IStandardConversionService conversionService) {
Validate.notNull(conversionService, "Standard Conversion Service cannot be null");
this.conversionService = conversionService;
}
/**
* <p>
* Returns the Standard JavaScript Serializer (implementation of {@link IStandardJavaScriptSerializer})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardJavaScriptSerializer} by default.
* </p>
*
* @return the Standard JavaScript Serializer object.
*/
public IStandardJavaScriptSerializer getJavaScriptSerializer() {
return this.javaScriptSerializer;
}
/**
* <p>
* Sets the Standard JavaScript Serializer (implementation of {@link IStandardJavaScriptSerializer})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardJavaScriptSerializer} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param javaScriptSerializer the Standard JavaScript Serializer object to be used. Cannot be null.
*/
public void setJavaScriptSerializer(final IStandardJavaScriptSerializer javaScriptSerializer) {
Validate.notNull(javaScriptSerializer, "Standard JavaScript Serializer cannot be null");
this.javaScriptSerializer = javaScriptSerializer;
}
/**
* <p>
* Returns the Standard CSS Serializer (implementation of {@link IStandardCSSSerializer})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardCSSSerializer} by default.
* </p>
*
* @return the Standard CSS Serializer object.
*/
public IStandardCSSSerializer getCSSSerializer() {
return this.cssSerializer;
}
/**
* <p>
* Sets the Standard CSS Serializer (implementation of {@link IStandardCSSSerializer})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardCSSSerializer} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param cssSerializer the Standard CSS Serializer object to be used. Cannot be null.
*/
public void setCSSSerializer(final IStandardCSSSerializer cssSerializer) {
Validate.notNull(cssSerializer, "Standard CSS Serializer cannot be null");
this.cssSerializer = cssSerializer;
}
public Map<String, Object> getExecutionAttributes() {
final Map<String,Object> executionAttributes = new HashMap<String, Object>(5, 1.0f);
executionAttributes.put(
StandardExpressions.STANDARD_VARIABLE_EXPRESSION_EVALUATOR_ATTRIBUTE_NAME, getVariableExpressionEvaluator());
executionAttributes.put(
StandardExpressions.STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME, getExpressionParser());
executionAttributes.put(
StandardExpressions.STANDARD_CONVERSION_SERVICE_ATTRIBUTE_NAME, getConversionService());
executionAttributes.put(
StandardSerializers.STANDARD_JAVASCRIPT_SERIALIZER_ATTRIBUTE_NAME, getJavaScriptSerializer());
executionAttributes.put(
StandardSerializers.STANDARD_CSS_SERIALIZER_ATTRIBUTE_NAME, getCSSSerializer());
return executionAttributes;
}
public IExpressionObjectFactory getExpressionObjectFactory() {
return STANDARD_EXPRESSION_OBJECTS_FACTORY;
}
public Set<IProcessor> getProcessors(final String dialectPrefix) {
return createStandardProcessorsSet(dialectPrefix);
}
/**
* <p>
* Create a the set of Standard processors, all of them freshly instanced.
* </p>
*
* @param dialectPrefix the prefix established for the Standard Dialect, needed for initialization
* @return the set of Standard processors.
*/
public static Set<IProcessor> createStandardProcessorsSet(final String dialectPrefix) {
/*
* It is important that we create new instances here because, if there are
* several dialects in the TemplateEngine that extend StandardDialect, they should
* not be returning the exact same instances for their processors in order
* to allow specific instances to be directly linked with their owner dialect.
*/
final Set<IProcessor> processors = new LinkedHashSet<IProcessor>();
/*
* ------------------------
* ------------------------
* HTML TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* HTML: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardActionTagProcessor(dialectPrefix));
processors.add(new StandardAltTitleTagProcessor(dialectPrefix));
processors.add(new StandardAssertTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrappendTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrprependTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardClassappendTagProcessor(dialectPrefix));
for (final String attrName : StandardConditionalFixedValueTagProcessor.ATTR_NAMES) {
processors.add(new StandardConditionalFixedValueTagProcessor(dialectPrefix, attrName));
}
for (final String attrName : StandardDOMEventAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardEachTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardFragmentTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardHrefTagProcessor(dialectPrefix));
processors.add(new StandardIfTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardIncludeTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardInlineHTMLTagProcessor(dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardLangXmlLangTagProcessor(dialectPrefix));
processors.add(new StandardMethodTagProcessor(dialectPrefix));
for (final String attrName : StandardNonRemovableAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardNonRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardObjectTagProcessor(TemplateMode.HTML, dialectPrefix));
for (final String attrName : StandardRemovableAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardRemoveTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardSrcTagProcessor(dialectPrefix));
processors.add(new StandardStyleappendTagProcessor(dialectPrefix));
processors.add(new StandardSubstituteByTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardSwitchTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardValueTagProcessor(dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardXmlBaseTagProcessor(dialectPrefix));
processors.add(new StandardXmlLangTagProcessor(dialectPrefix));
processors.add(new StandardXmlSpaceTagProcessor(dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardRefAttributeTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardDefaultAttributesTagProcessor(TemplateMode.HTML, dialectPrefix));
/*
* HTML: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.HTML, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
/*
* HTML: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each
* template mode in the StandardDialect (see AbstractStandardInliner for details). So if new processors
* are added here, it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.HTML));
/*
* HTML: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.HTML));
/*
* HTML: DOCTYPE PROCESSORS
*/
processors.add(new StandardTranslationDocTypeProcessor());
/*
* HTML: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.HTML));
processors.add(new StandardConditionalCommentProcessor());
/*
* HTML: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.HTML));
/*
* ------------------------
* ------------------------
* XML TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* XML: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrappendTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrprependTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardFragmentTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardIfTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardIncludeTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardInlineXMLTagProcessor(dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardSubstituteByTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardSwitchTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardRefAttributeTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardDefaultAttributesTagProcessor(TemplateMode.XML, dialectPrefix));
/*
* XML: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.XML, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
/*
* XML: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.XML));
/*
* XML: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.XML));
/*
* XML: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.XML));
/*
* XML: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.XML));
/*
* ------------------------
* ------------------------
* TEXT TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* TEXT: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.TEXT, dialectPrefix));
/*
* TEXT: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.TEXT, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.TEXT, null, "")); // With no name, will process [# th....] elements
/*
* TEXT: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.TEXT));
/*
* TEXT: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.TEXT));
/*
* ------------------------
* ------------------------
* JAVASCRIPT TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* JAVASCRIPT: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
/*
* JAVASCRIPT: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.JAVASCRIPT, null, "")); // With no name, will process [# th....] elements
/*
* JAVASCRIPT: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.JAVASCRIPT));
/*
* JAVASCRIPT: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.JAVASCRIPT));
/*
* ------------------------
* ------------------------
* CSS TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* CSS: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.CSS, dialectPrefix));
/*
* CSS: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.CSS, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.CSS, null, "")); // With no name, will process [# th....] elements
/*
* CSS: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.CSS));
/*
* CSS: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.CSS));
/*
* ------------------------
* ------------------------
* RAW TEMPLATE MODE
* ------------------------
* ------------------------
*/
// No processors defined for template mode. Note only TextProcessors would be possible in this template mode,
// given the entire templates are considered Text.
return processors;
}
}
| src/main/java/org/thymeleaf/standard/StandardDialect.java | /*
* =============================================================================
*
* Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.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.thymeleaf.standard;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.dialect.IExecutionAttributeDialect;
import org.thymeleaf.dialect.IExpressionObjectDialect;
import org.thymeleaf.expression.IExpressionObjectFactory;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.expression.IStandardConversionService;
import org.thymeleaf.standard.expression.IStandardExpressionParser;
import org.thymeleaf.standard.expression.IStandardVariableExpressionEvaluator;
import org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator;
import org.thymeleaf.standard.expression.StandardConversionService;
import org.thymeleaf.standard.expression.StandardExpressionObjectFactory;
import org.thymeleaf.standard.expression.StandardExpressionParser;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.standard.processor.StandardActionTagProcessor;
import org.thymeleaf.standard.processor.StandardAltTitleTagProcessor;
import org.thymeleaf.standard.processor.StandardAssertTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrappendTagProcessor;
import org.thymeleaf.standard.processor.StandardAttrprependTagProcessor;
import org.thymeleaf.standard.processor.StandardBlockTagProcessor;
import org.thymeleaf.standard.processor.StandardCaseTagProcessor;
import org.thymeleaf.standard.processor.StandardClassappendTagProcessor;
import org.thymeleaf.standard.processor.StandardConditionalCommentProcessor;
import org.thymeleaf.standard.processor.StandardConditionalFixedValueTagProcessor;
import org.thymeleaf.standard.processor.StandardDOMEventAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardDefaultAttributesTagProcessor;
import org.thymeleaf.standard.processor.StandardEachTagProcessor;
import org.thymeleaf.standard.processor.StandardFragmentTagProcessor;
import org.thymeleaf.standard.processor.StandardHrefTagProcessor;
import org.thymeleaf.standard.processor.StandardIfTagProcessor;
import org.thymeleaf.standard.processor.StandardIncludeTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineEnablementTemplateBoundariesProcessor;
import org.thymeleaf.standard.processor.StandardInlineHTMLTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineTextualTagProcessor;
import org.thymeleaf.standard.processor.StandardInlineXMLTagProcessor;
import org.thymeleaf.standard.processor.StandardInliningCDATASectionProcessor;
import org.thymeleaf.standard.processor.StandardInliningCommentProcessor;
import org.thymeleaf.standard.processor.StandardInliningTextProcessor;
import org.thymeleaf.standard.processor.StandardInsertTagProcessor;
import org.thymeleaf.standard.processor.StandardLangXmlLangTagProcessor;
import org.thymeleaf.standard.processor.StandardMethodTagProcessor;
import org.thymeleaf.standard.processor.StandardNonRemovableAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardObjectTagProcessor;
import org.thymeleaf.standard.processor.StandardRefAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardRemovableAttributeTagProcessor;
import org.thymeleaf.standard.processor.StandardRemoveTagProcessor;
import org.thymeleaf.standard.processor.StandardReplaceTagProcessor;
import org.thymeleaf.standard.processor.StandardSrcTagProcessor;
import org.thymeleaf.standard.processor.StandardStyleappendTagProcessor;
import org.thymeleaf.standard.processor.StandardSubstituteByTagProcessor;
import org.thymeleaf.standard.processor.StandardSwitchTagProcessor;
import org.thymeleaf.standard.processor.StandardTextTagProcessor;
import org.thymeleaf.standard.processor.StandardTranslationDocTypeProcessor;
import org.thymeleaf.standard.processor.StandardUnlessTagProcessor;
import org.thymeleaf.standard.processor.StandardUtextTagProcessor;
import org.thymeleaf.standard.processor.StandardValueTagProcessor;
import org.thymeleaf.standard.processor.StandardWithTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlBaseTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlLangTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlNsTagProcessor;
import org.thymeleaf.standard.processor.StandardXmlSpaceTagProcessor;
import org.thymeleaf.standard.serializer.IStandardCSSSerializer;
import org.thymeleaf.standard.serializer.IStandardJavaScriptSerializer;
import org.thymeleaf.standard.serializer.StandardCSSSerializer;
import org.thymeleaf.standard.serializer.StandardJavaScriptSerializer;
import org.thymeleaf.standard.serializer.StandardSerializers;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.util.Validate;
/**
* <p>
* Standard Dialect. This is the class containing the implementation of Thymeleaf Standard Dialect, including all
* <tt>th:*</tt> processors, expression objects, etc.
* </p>
* <p>
* Note this dialect uses <strong>OGNL</strong> as an expression language. There is a Spring-integrated version
* of the Standard Dialect called the <em>SpringStandard Dialect</em> at the <tt>thymeleaf-spring*</tt> packages,
* which uses SpringEL as an expression language.
* </p>
* <p>
* Note a class with this name existed since 1.0, but it was completely reimplemented
* in Thymeleaf 3.0
* </p>
*
* @author Daniel Fernández
*
* @since 3.0.0
*
*/
public class StandardDialect
extends AbstractProcessorDialect
implements IExecutionAttributeDialect, IExpressionObjectDialect {
public static final String NAME = "Standard";
public static final String PREFIX = "th";
public static final int PROCESSOR_PRECEDENCE = 1000;
private final IExpressionObjectFactory STANDARD_EXPRESSION_OBJECTS_FACTORY = new StandardExpressionObjectFactory();
// We will avoid setting this variableExpressionEvaluator variable to "OgnlVariableExpressionEvaluator.INSTANCE"
// in order to not cause this OGNL-related class to initialize, therefore introducing a forced dependency on OGNL
// to Spring users (who don't need OGNL at all).
private IStandardVariableExpressionEvaluator variableExpressionEvaluator = null;
private IStandardExpressionParser expressionParser = new StandardExpressionParser();
private IStandardConversionService conversionService = new StandardConversionService();
private IStandardJavaScriptSerializer javaScriptSerializer = new StandardJavaScriptSerializer(true);
private IStandardCSSSerializer cssSerializer = new StandardCSSSerializer();
public StandardDialect() {
super(NAME, PREFIX, PROCESSOR_PRECEDENCE);
}
/*
* Meant to be overridden by dialects that do almost the same as this, changing bits here and there
* (e.g. SpringStandardDialect)
*/
protected StandardDialect(final String name, final String prefix, final int processorPrecedence) {
super(name, prefix, processorPrecedence);
}
/**
* <p>
* Returns the variable expression evaluator (implementation of {@link IStandardVariableExpressionEvaluator})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This is used for executing all ${...} and *{...} expressions in Thymeleaf Standard Expressions.
* </p>
* <p>
* This will be {@link OGNLVariableExpressionEvaluator} by default. When using the Spring Standard
* Dialect, this will be a SpringEL-based implementation.
* </p>
*
* @return the Standard Variable Expression Evaluator object.
*/
public IStandardVariableExpressionEvaluator getVariableExpressionEvaluator() {
if (this.variableExpressionEvaluator == null) {
this.variableExpressionEvaluator = new OGNLVariableExpressionEvaluator(true);
}
return this.variableExpressionEvaluator;
}
/**
* <p>
* Sets the variable expression evaluator (implementation of {@link IStandardVariableExpressionEvaluator})
* that should be used at this instance of the Standard Dialect.
* </p>
* <p>
* This is used for executing all ${...} and *{...} expressions in Thymeleaf Standard Expressions.
* </p>
* <p>
* This will be an {@link OGNLVariableExpressionEvaluator} by default. When using the Spring Standard
* Dialect, this will be a SpringEL-based implementation.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param variableExpressionEvaluator the new Standard Variable Expression Evaluator object. Cannot be null.
*/
public void setVariableExpressionEvaluator(final IStandardVariableExpressionEvaluator variableExpressionEvaluator) {
Validate.notNull(variableExpressionEvaluator, "Standard Variable Expression Evaluator cannot be null");
this.variableExpressionEvaluator = variableExpressionEvaluator;
}
/**
* <p>
* Returns the Thymeleaf Standard Expression parser (implementation of {@link IStandardExpressionParser})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardExpressionParser} by default.
* </p>
*
* @return the Standard Expression Parser object.
*/
public IStandardExpressionParser getExpressionParser() {
return this.expressionParser;
}
/**
* <p>
* Sets the Thymeleaf Standard Expression parser (implementation of {@link IStandardExpressionParser})
* that should be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardExpressionParser} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param expressionParser the Standard Expression Parser object to be used. Cannot be null.
*/
public void setExpressionParser(final IStandardExpressionParser expressionParser) {
Validate.notNull(expressionParser, "Standard Expression Parser cannot be null");
this.expressionParser = expressionParser;
}
/**
* <p>
* Returns the Standard Conversion Service (implementation of {@link IStandardConversionService})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardConversionService} by default. In Spring environments, this will default
* to an implementation delegating on Spring's own ConversionService implementation.
* </p>
*
* @return the Standard Conversion Service object.
*/
public IStandardConversionService getConversionService() {
return this.conversionService;
}
/**
* <p>
* Sets the Standard Conversion Service (implementation of {@link IStandardConversionService})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardConversionService} by default. In Spring environments, this will default
* to an implementation delegating on Spring's own ConversionService implementation.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param conversionService the Standard ConversionService object to be used. Cannot be null.
*/
public void setConversionService(final IStandardConversionService conversionService) {
Validate.notNull(conversionService, "Standard Conversion Service cannot be null");
this.conversionService = conversionService;
}
/**
* <p>
* Returns the Standard JavaScript Serializer (implementation of {@link IStandardJavaScriptSerializer})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardJavaScriptSerializer} by default.
* </p>
*
* @return the Standard JavaScript Serializer object.
*/
public IStandardJavaScriptSerializer getJavaScriptSerializer() {
return this.javaScriptSerializer;
}
/**
* <p>
* Sets the Standard JavaScript Serializer (implementation of {@link IStandardJavaScriptSerializer})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardJavaScriptSerializer} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param javaScriptSerializer the Standard JavaScript Serializer object to be used. Cannot be null.
*/
public void setJavaScriptSerializer(final IStandardJavaScriptSerializer javaScriptSerializer) {
Validate.notNull(javaScriptSerializer, "Standard JavaScript Serializer cannot be null");
this.javaScriptSerializer = javaScriptSerializer;
}
/**
* <p>
* Returns the Standard CSS Serializer (implementation of {@link IStandardCSSSerializer})
* that is configured to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardCSSSerializer} by default.
* </p>
*
* @return the Standard CSS Serializer object.
*/
public IStandardCSSSerializer getCSSSerializer() {
return this.cssSerializer;
}
/**
* <p>
* Sets the Standard CSS Serializer (implementation of {@link IStandardCSSSerializer})
* that should to be used at this instance of the Standard Dialect.
* </p>
* <p>
* This will be {@link StandardCSSSerializer} by default.
* </p>
* <p>
* This method has no effect once the Template Engine has been initialized.
* </p>
* <p>
* Objects set here should be <b>thread-safe</b>.
* </p>
*
* @param cssSerializer the Standard CSS Serializer object to be used. Cannot be null.
*/
public void setCSSSerializer(final IStandardCSSSerializer cssSerializer) {
Validate.notNull(cssSerializer, "Standard CSS Serializer cannot be null");
this.cssSerializer = cssSerializer;
}
public Map<String, Object> getExecutionAttributes() {
final Map<String,Object> executionAttributes = new HashMap<String, Object>(5, 1.0f);
executionAttributes.put(
StandardExpressions.STANDARD_VARIABLE_EXPRESSION_EVALUATOR_ATTRIBUTE_NAME, getVariableExpressionEvaluator());
executionAttributes.put(
StandardExpressions.STANDARD_EXPRESSION_PARSER_ATTRIBUTE_NAME, getExpressionParser());
executionAttributes.put(
StandardExpressions.STANDARD_CONVERSION_SERVICE_ATTRIBUTE_NAME, getConversionService());
executionAttributes.put(
StandardSerializers.STANDARD_JAVASCRIPT_SERIALIZER_ATTRIBUTE_NAME, getJavaScriptSerializer());
executionAttributes.put(
StandardSerializers.STANDARD_CSS_SERIALIZER_ATTRIBUTE_NAME, getCSSSerializer());
return executionAttributes;
}
public IExpressionObjectFactory getExpressionObjectFactory() {
return STANDARD_EXPRESSION_OBJECTS_FACTORY;
}
public Set<IProcessor> getProcessors(final String dialectPrefix) {
return createStandardProcessorsSet(dialectPrefix);
}
/**
* <p>
* Create a the set of Standard processors, all of them freshly instanced.
* </p>
*
* @param dialectPrefix the prefix established for the Standard Dialect, needed for initialization
* @return the set of Standard processors.
*/
public static Set<IProcessor> createStandardProcessorsSet(final String dialectPrefix) {
/*
* It is important that we create new instances here because, if there are
* several dialects in the TemplateEngine that extend StandardDialect, they should
* not be returning the exact same instances for their processors in order
* to allow specific instances to be directly linked with their owner dialect.
*/
final Set<IProcessor> processors = new LinkedHashSet<IProcessor>();
/*
* ------------------------
* ------------------------
* HTML TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* HTML: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardActionTagProcessor(dialectPrefix));
processors.add(new StandardAltTitleTagProcessor(dialectPrefix));
processors.add(new StandardAssertTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrappendTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardAttrprependTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardClassappendTagProcessor(dialectPrefix));
for (final String attrName : StandardConditionalFixedValueTagProcessor.ATTR_NAMES) {
processors.add(new StandardConditionalFixedValueTagProcessor(dialectPrefix, attrName));
}
for (final String attrName : StandardDOMEventAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardEachTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardFragmentTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardHrefTagProcessor(dialectPrefix));
processors.add(new StandardIfTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardIncludeTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardInlineHTMLTagProcessor(dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardLangXmlLangTagProcessor(dialectPrefix));
processors.add(new StandardMethodTagProcessor(dialectPrefix));
for (final String attrName : StandardNonRemovableAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardNonRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardObjectTagProcessor(TemplateMode.HTML, dialectPrefix));
for (final String attrName : StandardRemovableAttributeTagProcessor.ATTR_NAMES) {
processors.add(new StandardRemovableAttributeTagProcessor(dialectPrefix, attrName));
}
processors.add(new StandardRemoveTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardSrcTagProcessor(dialectPrefix));
processors.add(new StandardStyleappendTagProcessor(dialectPrefix));
processors.add(new StandardSubstituteByTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardSwitchTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardValueTagProcessor(dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardXmlBaseTagProcessor(dialectPrefix));
processors.add(new StandardXmlLangTagProcessor(dialectPrefix));
processors.add(new StandardXmlSpaceTagProcessor(dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardRefAttributeTagProcessor(TemplateMode.HTML, dialectPrefix));
processors.add(new StandardDefaultAttributesTagProcessor(TemplateMode.HTML, dialectPrefix));
/*
* HTML: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.HTML, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
/*
* HTML: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each
* template mode in the StandardDialect (see AbstractStandardInliner for details). So if new processors
* are added here, it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.HTML));
/*
* HTML: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.HTML));
/*
* HTML: DOCTYPE PROCESSORS
*/
processors.add(new StandardTranslationDocTypeProcessor());
/*
* HTML: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.HTML));
processors.add(new StandardConditionalCommentProcessor());
/*
* HTML: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.HTML));
/*
* ------------------------
* ------------------------
* XML TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* XML: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrappendTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardAttrprependTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardFragmentTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardIfTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardIncludeTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardInlineXMLTagProcessor(dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardSubstituteByTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardSwitchTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardXmlNsTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardRefAttributeTagProcessor(TemplateMode.XML, dialectPrefix));
processors.add(new StandardDefaultAttributesTagProcessor(TemplateMode.XML, dialectPrefix));
/*
* XML: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.XML, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
/*
* XML: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.XML));
/*
* XML: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.XML));
/*
* XML: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.XML));
/*
* XML: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.XML));
/*
* ------------------------
* ------------------------
* TEXT TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* TEXT: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.TEXT, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.TEXT, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.TEXT, dialectPrefix));
/*
* TEXT: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.TEXT, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.TEXT, null, "")); // With no name, will process [# th....] elements
/*
* TEXT: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.TEXT));
/*
* TEXT: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.TEXT));
/*
* TEXT: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.TEXT));
/*
* TEXT: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.TEXT));
/*
* ------------------------
* ------------------------
* JAVASCRIPT TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* JAVASCRIPT: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix));
/*
* JAVASCRIPT: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.JAVASCRIPT, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.JAVASCRIPT, null, "")); // With no name, will process [# th....] elements
/*
* JAVASCRIPT: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.JAVASCRIPT));
/*
* JAVASCRIPT: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.JAVASCRIPT));
/*
* JAVASCRIPT: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.JAVASCRIPT));
/*
* JAVASCRIPT: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.JAVASCRIPT));
/*
* ------------------------
* ------------------------
* CSS TEMPLATE MODE
* ------------------------
* ------------------------
*/
/*
* CSS: ATTRIBUTE TAG PROCESSORS
*/
processors.add(new StandardAssertTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardCaseTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardEachTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:fragment attribute in text modes: no fragment selection available!
processors.add(new StandardIfTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:include to be added here, as it is already deprecated since 3.0
processors.add(new StandardInlineTextualTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardInsertTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardObjectTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardRemoveTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardReplaceTagProcessor(TemplateMode.CSS, dialectPrefix));
// No th:substituteby to be added here, as it is already deprecated since 2.1
processors.add(new StandardSwitchTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardTextTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardUnlessTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardUtextTagProcessor(TemplateMode.CSS, dialectPrefix));
processors.add(new StandardWithTagProcessor(TemplateMode.CSS, dialectPrefix));
/*
* CSS: ELEMENT TAG PROCESSORS
*/
processors.add(new StandardBlockTagProcessor(TemplateMode.CSS, dialectPrefix, StandardBlockTagProcessor.ELEMENT_NAME));
processors.add(new StandardBlockTagProcessor(TemplateMode.CSS, null, "")); // With no name, will process [# th....] elements
/*
* CSS: TEXT PROCESSORS
*
* NOTE the ability of the Standard Inlining mechanism to directly write to output instead of generating
* internal Strings relies on the fact that there is only ONE ITextProcessor instance for each template mode
* in the StandardDialect (see AbstractStandardInliner for details). So if new processors are added here,
* it should be for a really compelling reason.
*/
processors.add(new StandardInliningTextProcessor(TemplateMode.CSS));
/*
* CSS: CDATASection PROCESSORS
*/
processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.CSS));
/*
* CSS: COMMENT PROCESSORS
*/
processors.add(new StandardInliningCommentProcessor(TemplateMode.CSS));
/*
* CSS: TEMPLATE BOUNDARIES PROCESSORS
*/
processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.CSS));
/*
* ------------------------
* ------------------------
* RAW TEMPLATE MODE
* ------------------------
* ------------------------
*/
// No processors defined for template mode. Note only TextProcessors would be possible in this template mode,
// given the entire templates are considered Text.
return processors;
}
}
| Removed unneeded processors from StandardDialect (affecting events never fired in text template modes)
| src/main/java/org/thymeleaf/standard/StandardDialect.java | Removed unneeded processors from StandardDialect (affecting events never fired in text template modes) | <ide><path>rc/main/java/org/thymeleaf/standard/StandardDialect.java
<ide> processors.add(new StandardInliningTextProcessor(TemplateMode.TEXT));
<ide>
<ide> /*
<del> * TEXT: CDATASection PROCESSORS
<del> */
<del> processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.TEXT));
<del>
<del> /*
<del> * TEXT: COMMENT PROCESSORS
<del> */
<del> processors.add(new StandardInliningCommentProcessor(TemplateMode.TEXT));
<del>
<del> /*
<ide> * TEXT: TEMPLATE BOUNDARIES PROCESSORS
<ide> */
<ide> processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.TEXT));
<ide> processors.add(new StandardInliningTextProcessor(TemplateMode.JAVASCRIPT));
<ide>
<ide> /*
<del> * JAVASCRIPT: CDATASection PROCESSORS
<del> */
<del> processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.JAVASCRIPT));
<del>
<del> /*
<del> * JAVASCRIPT: COMMENT PROCESSORS
<del> */
<del> processors.add(new StandardInliningCommentProcessor(TemplateMode.JAVASCRIPT));
<del>
<del> /*
<ide> * JAVASCRIPT: TEMPLATE BOUNDARIES PROCESSORS
<ide> */
<ide> processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.JAVASCRIPT));
<ide> processors.add(new StandardInliningTextProcessor(TemplateMode.CSS));
<ide>
<ide> /*
<del> * CSS: CDATASection PROCESSORS
<del> */
<del> processors.add(new StandardInliningCDATASectionProcessor(TemplateMode.CSS));
<del>
<del> /*
<del> * CSS: COMMENT PROCESSORS
<del> */
<del> processors.add(new StandardInliningCommentProcessor(TemplateMode.CSS));
<del>
<del> /*
<ide> * CSS: TEMPLATE BOUNDARIES PROCESSORS
<ide> */
<ide> processors.add(new StandardInlineEnablementTemplateBoundariesProcessor(TemplateMode.CSS)); |
|
JavaScript | mit | 1c09aaa988172db310fdea9512c555e66b0f5e50 | 0 | boonmeelab/opendata-hackathon-2015,boonmeelab/opendata-hackathon-2015 |
// filter data
// [filter condition]
// year: { start: START_YEAR, end: END_YEAR} -> { start: 2008, end: 2009}
// sex: ARRAY -> 0 (unknown), 1 (female), 2 (male)
// age: ARRAY -> 0 (unknown), 1 (<=18), 2 (19-35), 3 (36-55), 4 (>=56)
// alcohol: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// safety: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// vehicle: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// hitBy: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// time: {start: [DAY, HOUR], end: [DAY, HOUR]}
// [Ex]
// {year: [2008, 2015], sex: [1], alcohol: [1, 2], safety: [1], vehicle: [1, 2, 3], hitBy: [1]}
function genericMapper(value, mapper) {
if (value in mapper) { return mapper[value]; }
return -1;
}
function findMatchWithArrayFilter(arrayFilter, entry) {
var bool = false;
for (var i = 0, len = arrayFilter.length; i < len; ++i) {
if (arrayFilter[i] === entry) {
bool = true;
break;
}
}
return bool;
}
function timeWrapper(day, hour) {
// Change to int.
day = parseInt(day); hour = parseInt(hour);
// Transform both to one time variable.
day = (day > 20)? (day - 31) : day;
hour = (hour === 24)? 0 : hour;
var time = day * 24 + hour;
return time;
}
function ageWrapper(age) {
if (age <= 18) return 1;
else if (age >= 19 && age <= 35) return 2;
else if (age >= 36 && age <= 55) return 3;
else if (age >= 56) return 4;
return -1;
}
function filterUtil(data, filter) {
// Check if all filters are specified. If not, error and return empty array.
if (!(filter.year && filter.year.start && filter.year.end &&
filter.time && filter.time.start && filter.time.end &&
filter.sex &&
filter.alcohol &&
filter.safety &&
filter.vehicle &&
filter.hitBy)) {
console.error('Please specify all filters. For now, we will just return empty result for you.');
return [];
}
var result = data.filter(function(d) {
var sex_map = {'unknown' : 0, 'หญิง' : 1, 'ชาย' : 2};
var alcohol_map = {'unknown' : 0, 'ไม่ดื่ม' : 1, 'ดื่ม' : 2};
var safety_map = {'unknown' : 0, 'ไม่ใส่' : 1, 'ใส่หมวก' : 2, 'เข็มขัด' : 2};
var vehicle_map = {
'unknown' : 0, 'อื่นๆ' : 0,
'ไม่มี/ล้มเอง' : 1,
'จักรยานยนต์' : 2,
'รถจักรยาน' : 3,
'รถเก๋ง/แท็กซี่' : 4, 'สามล้อเครื่อง' : 4, 'รถตู้' : 4, 'รถโดยสาร 4 ล้อ' : 4,
'รถบรรทุก' : 5, 'รถโดยสารใหญ่' : 5, 'ปิคอัพ' : 5,
};
var time = timeWrapper(d['วันที่เกิดเหตุ'], d['เวลาเกิดเหตุ']);
var time_filter_start = timeWrapper(filter.time.start[0], filter.time.start[1]);
var time_filter_end = timeWrapper(filter.time.end[0], filter.time.end[1]);
var time_filter = (time >= time_filter_start) && (time <= time_filter_end);
var year_filter = (d.year >= filter.year.start) && (d.year <= filter.year.end);
var sex_filter = findMatchWithArrayFilter(filter.sex, genericMapper(d['เพศ'], sex_map));
var age_filter = ageWrapper(d['อายุ']);
var alcohol_filter = findMatchWithArrayFilter(filter.alcohol, genericMapper(d['การดื่มสุรา'], alcohol_map));
var safety_filter = findMatchWithArrayFilter(filter.safety, genericMapper(d['มาตรการ'], safety_map));
var vehicle_filter = findMatchWithArrayFilter(filter.vehicle, genericMapper(d['รถผู้บาดเจ็บ'], vehicle_map));
var hitBy_filter = findMatchWithArrayFilter(filter.hitBy, genericMapper(d['รถคู่กรณี'], vehicle_map));
// console.log(d);
// console.log("year: " + year_filter +
// " time: " + time + " " + time_filter_start + " " + time_filter_end +
// " time reult: " + time_filter +
// " sex: " + sex_filter +
// " alcohol: " + alcohol_filter +
// " safety: " + safety_filter +
// " vehicle: " + vehicle_filter +
// " hitBy: " + hitBy_filter);
return year_filter && time_filter && sex_filter && age_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
});
return result;
}
function prefilterUtil(data) {
var result = {};
for (var i = 0, len = data.length; i < len; ++i) {
var day = parseInt(data[i]['วันที่เกิดเหตุ']);
var hour = parseInt(data[i]['เวลาเกิดเหตุ']);
hour = (hour === 24)? 0 : hour;
if (!(day in result)){
result[day] = {};
}
if (!(hour in result[day])) {
result[day][hour] = [];
}
result[day][hour].push(data[i]);
}
return result;
}
// // Global var for all loaded .csv data
// var dataset;
// d3.csv("/public/data/175_samples_all_newyear_casualties.csv", function(error, data) {
// if (error) { // when data is failed to load, do nothing.
// console.error(error);
// } else {
// // data is loaded successfully, we can start to visualize it.
// dataset = data;
// console.log("original");
// console.log(data);
// // call other functions here
// console.log("after filter");
// var myfilter = {
// year: {start: 2008, end: 2009},
// time: {start: [28, 0], end: [1, 1]},
// sex: [1],
// alcohol: [1],
// safety: [1],
// vehicle: [2],
// hitBy: [1,2,3,4,5],
// };
// console.log(filterUtil(data, myfilter));
// }
// });
| src/js/main-a.js |
// filter data
// [filter condition]
// year: { start: START_YEAR, end: END_YEAR} -> { start: 2008, end: 2009}
// sex: ARRAY -> 0 (unknown), 1 (female), 2 (male)
// age: ARRAY -> 0 (unknown), 1 (<=18), 2 (19-35), 3 (36-55), 4 (>=56)
// alcohol: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// safety: ARRAY -> 0 (unknown), 1 (no), 2 (yes)
// vehicle: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// hitBy: ARRAY -> 0 (unknown), 1 (no), 2 (motocycle), 3 (bicycle), 4 (car), 5 (pickup & truck)
// time: {start: [DAY, HOUR], end: [DAY, HOUR]}
// [Ex]
// {year: [2008, 2015], sex: [1], alcohol: [1, 2], safety: [1], vehicle: [1, 2, 3], hitBy: [1]}
function genericMapper(value, mapper) {
if (value in mapper) { return mapper[value]; }
return -1;
}
function findMatchWithArrayFilter(arrayFilter, entry) {
var bool = false;
for (var i = 0, len = arrayFilter.length; i < len; ++i) {
if (arrayFilter[i] === entry) {
bool = true;
break;
}
}
return bool;
}
function timeWrapper(day, hour) {
// Change to int.
day = parseInt(day); hour = parseInt(hour);
// Transform both to one time variable.
day = (day > 20)? (day - 31) : day;
hour = (hour === 24)? 0 : hour;
var time = day * 24 + hour;
return time;
}
function filterUtil(data, filter) {
// Check if all filters are specified. If not, error and return empty array.
if (!(filter.year && filter.year.start && filter.year.end &&
filter.time && filter.time.start && filter.time.end &&
filter.sex &&
filter.alcohol &&
filter.safety &&
filter.vehicle &&
filter.hitBy)) {
console.error('Please specify all filters. For now, we will just return empty result for you.');
return [];
}
var result = data.filter(function(d) {
var sex_map = {'unknown' : 0, 'หญิง' : 1, 'ชาย' : 2};
var alcohol_map = {'unknown' : 0, 'ไม่ดื่ม' : 1, 'ดื่ม' : 2};
var safety_map = {'unknown' : 0, 'ไม่ใส่' : 1, 'ใส่หมวก' : 2, 'เข็มขัด' : 2};
var vehicle_map = {
'unknown' : 0, 'อื่นๆ' : 0,
'ไม่มี/ล้มเอง' : 1,
'จักรยานยนต์' : 2,
'รถจักรยาน' : 3,
'รถเก๋ง/แท็กซี่' : 4, 'สามล้อเครื่อง' : 4, 'รถตู้' : 4, 'รถโดยสาร 4 ล้อ' : 4,
'รถบรรทุก' : 5, 'รถโดยสารใหญ่' : 5, 'ปิคอัพ' : 5,
};
var time = timeWrapper(d['วันที่เกิดเหตุ'], d['เวลาเกิดเหตุ']);
var time_filter_start = timeWrapper(filter.time.start[0], filter.time.start[1]);
var time_filter_end = timeWrapper(filter.time.end[0], filter.time.end[1]);
var time_filter = (time >= time_filter_start) && (time <= time_filter_end);
var year_filter = (d.year >= filter.year.start) && (d.year <= filter.year.end);
var sex_filter = findMatchWithArrayFilter(filter.sex, genericMapper(d['เพศ'], sex_map));
var alcohol_filter = findMatchWithArrayFilter(filter.alcohol, genericMapper(d['การดื่มสุรา'], alcohol_map));
var safety_filter = findMatchWithArrayFilter(filter.safety, genericMapper(d['มาตรการ'], safety_map));
var vehicle_filter = findMatchWithArrayFilter(filter.vehicle, genericMapper(d['รถผู้บาดเจ็บ'], vehicle_map));
var hitBy_filter = findMatchWithArrayFilter(filter.hitBy, genericMapper(d['รถคู่กรณี'], vehicle_map));
// console.log(d);
// console.log("year: " + year_filter +
// " time: " + time + " " + time_filter_start + " " + time_filter_end +
// " time reult: " + time_filter +
// " sex: " + sex_filter +
// " alcohol: " + alcohol_filter +
// " safety: " + safety_filter +
// " vehicle: " + vehicle_filter +
// " hitBy: " + hitBy_filter);
return year_filter && time_filter && sex_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
});
return result;
}
function prefilterUtil(data) {
var result = {};
for (var i = 0, len = data.length; i < len; ++i) {
var day = parseInt(data[i]['วันที่เกิดเหตุ']);
var hour = parseInt(data[i]['เวลาเกิดเหตุ']);
hour = (hour === 24)? 0 : hour;
if (!(day in result)){
result[day] = {};
}
if (!(hour in result[day])) {
result[day][hour] = [];
}
result[day][hour].push(data[i]);
}
return result;
}
// // Global var for all loaded .csv data
// var dataset;
// d3.csv("/public/data/175_samples_all_newyear_casualties.csv", function(error, data) {
// if (error) { // when data is failed to load, do nothing.
// console.error(error);
// } else {
// // data is loaded successfully, we can start to visualize it.
// dataset = data;
// console.log("original");
// console.log(data);
// // call other functions here
// console.log("after filter");
// var myfilter = {
// year: {start: 2008, end: 2009},
// time: {start: [28, 0], end: [1, 1]},
// sex: [1],
// alcohol: [1],
// safety: [1],
// vehicle: [2],
// hitBy: [1,2,3,4,5],
// };
// console.log(filterUtil(data, myfilter));
// }
// });
| Add age filter
| src/js/main-a.js | Add age filter | <ide><path>rc/js/main-a.js
<ide> return time;
<ide> }
<ide>
<add>function ageWrapper(age) {
<add> if (age <= 18) return 1;
<add> else if (age >= 19 && age <= 35) return 2;
<add> else if (age >= 36 && age <= 55) return 3;
<add> else if (age >= 56) return 4;
<add> return -1;
<add>}
<add>
<ide> function filterUtil(data, filter) {
<ide> // Check if all filters are specified. If not, error and return empty array.
<ide> if (!(filter.year && filter.year.start && filter.year.end &&
<ide> var time_filter = (time >= time_filter_start) && (time <= time_filter_end);
<ide> var year_filter = (d.year >= filter.year.start) && (d.year <= filter.year.end);
<ide> var sex_filter = findMatchWithArrayFilter(filter.sex, genericMapper(d['เพศ'], sex_map));
<add> var age_filter = ageWrapper(d['อายุ']);
<ide> var alcohol_filter = findMatchWithArrayFilter(filter.alcohol, genericMapper(d['การดื่มสุรา'], alcohol_map));
<ide> var safety_filter = findMatchWithArrayFilter(filter.safety, genericMapper(d['มาตรการ'], safety_map));
<ide> var vehicle_filter = findMatchWithArrayFilter(filter.vehicle, genericMapper(d['รถผู้บาดเจ็บ'], vehicle_map));
<ide> // " safety: " + safety_filter +
<ide> // " vehicle: " + vehicle_filter +
<ide> // " hitBy: " + hitBy_filter);
<del> return year_filter && time_filter && sex_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
<add> return year_filter && time_filter && sex_filter && age_filter && alcohol_filter && safety_filter && vehicle_filter && hitBy_filter;
<ide> });
<ide> return result;
<ide> } |
|
Java | apache-2.0 | 45112bf609e93559c49d7b1c400e1fd647c31b47 | 0 | YoungDigitalPlanet/empiria.player,YoungDigitalPlanet/empiria.player,YoungDigitalPlanet/empiria.player | package eu.ydp.empiria.player.client.gin;
import eu.ydp.gwtutil.client.components.exlistbox.ExListBoxDelays;
public class EmpiriaExListBoxDelay implements ExListBoxDelays {
@Override
public int getCloseDelay() {
return 0;
}
}
| src/eu/ydp/empiria/player/client/gin/EmpiriaExListBoxDelay.java | package eu.ydp.empiria.player.client.gin;
import eu.ydp.gwtutil.client.components.exlistbox.ExListBoxDelays;
public class EmpiriaExListBoxDelay implements ExListBoxDelays {
@Override
public int getAutoHideDelay() {
return 0;
}
@Override
public int getCloseDelay() {
return 0;
}
}
| [YPUB-6402] - interface containing one delay method
| src/eu/ydp/empiria/player/client/gin/EmpiriaExListBoxDelay.java | [YPUB-6402] - interface containing one delay method | <ide><path>rc/eu/ydp/empiria/player/client/gin/EmpiriaExListBoxDelay.java
<ide> public class EmpiriaExListBoxDelay implements ExListBoxDelays {
<ide>
<ide> @Override
<del> public int getAutoHideDelay() {
<del> return 0;
<del> }
<del>
<del> @Override
<ide> public int getCloseDelay() {
<ide> return 0;
<ide> } |
|
Java | apache-2.0 | 941afa4e81ee8c38ae3762692476d26e8e52d1ab | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NaturalOrderComparatorTest {
@Test
public void compare1() {
List<String> refVals = Stream.of("033_chr_0228_2d_r18", "034_chr_0228_2e_r18", "035_chr_0228_2f_r18", "036_chr_0229a_r18", "037_chr_0229b_r18", "038_chr_0229c_r18").collect(Collectors.toList());
List<String> testVals = new ArrayList<>(refVals);
testVals.sort(new NaturalOrderComparator());
for (int i = 0; i < refVals.size(); i++)
Assert.assertEquals(testVals.get(i), refVals.get(i));
}
@Test
public void compare2() {
List<String> refVals = Stream.of("1","2","10","11","20","21","100","101").collect(Collectors.toList());
List<String> testVals = new ArrayList<>(refVals);
testVals.sort(new NaturalOrderComparator());
for (int i = 0; i < refVals.size(); i++)
Assert.assertEquals(testVals.get(i), refVals.get(i));
}
@Test
public void compare3() {
List<String> refVals = Stream.of("season1episode1","season1episode10","season2episode1","season2episode10").collect(Collectors.toList());
List<String> testVals = new ArrayList<>(refVals);
testVals.sort(new NaturalOrderComparator());
for (int i = 0; i < refVals.size(); i++)
Assert.assertEquals(testVals.get(i), refVals.get(i));
}
} | app/src/test/java/me/devsaki/hentoid/util/NaturalOrderComparatorTest.java | package me.devsaki.hentoid.util;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NaturalOrderComparatorTest {
@Test
public void compare() {
List<String> refVals = Stream.of("033_chr_0228_2d_r18", "034_chr_0228_2e_r18", "035_chr_0228_2f_r18", "036_chr_0229a_r18", "037_chr_0229b_r18", "038_chr_0229c_r18").collect(Collectors.toList());
List<String> testVals = new ArrayList<>(refVals);
testVals.sort(new NaturalOrderComparator());
for (int i = 0; i < refVals.size(); i++)
Assert.assertEquals(testVals.get(i), refVals.get(i));
}
} | Even more tests
| app/src/test/java/me/devsaki/hentoid/util/NaturalOrderComparatorTest.java | Even more tests | <ide><path>pp/src/test/java/me/devsaki/hentoid/util/NaturalOrderComparatorTest.java
<ide> public class NaturalOrderComparatorTest {
<ide>
<ide> @Test
<del> public void compare() {
<add> public void compare1() {
<ide> List<String> refVals = Stream.of("033_chr_0228_2d_r18", "034_chr_0228_2e_r18", "035_chr_0228_2f_r18", "036_chr_0229a_r18", "037_chr_0229b_r18", "038_chr_0229c_r18").collect(Collectors.toList());
<ide> List<String> testVals = new ArrayList<>(refVals);
<ide>
<ide> for (int i = 0; i < refVals.size(); i++)
<ide> Assert.assertEquals(testVals.get(i), refVals.get(i));
<ide> }
<add>
<add> @Test
<add> public void compare2() {
<add> List<String> refVals = Stream.of("1","2","10","11","20","21","100","101").collect(Collectors.toList());
<add> List<String> testVals = new ArrayList<>(refVals);
<add>
<add> testVals.sort(new NaturalOrderComparator());
<add>
<add> for (int i = 0; i < refVals.size(); i++)
<add> Assert.assertEquals(testVals.get(i), refVals.get(i));
<add> }
<add>
<add> @Test
<add> public void compare3() {
<add> List<String> refVals = Stream.of("season1episode1","season1episode10","season2episode1","season2episode10").collect(Collectors.toList());
<add> List<String> testVals = new ArrayList<>(refVals);
<add>
<add> testVals.sort(new NaturalOrderComparator());
<add>
<add> for (int i = 0; i < refVals.size(); i++)
<add> Assert.assertEquals(testVals.get(i), refVals.get(i));
<add> }
<ide> } |
|
JavaScript | mit | 4da4c7cf197a5bba47971d438f6381a77cd19f7e | 0 | tprobinson/aersia,tprobinson/aersia,tprobinson/aersia | /////
// /*%= friendlyname */ v/*%= version */
//
//To do tags:
// CSS: Ongoing changes to the CSS.
// REWORK: Changes to do in the future.
// MOREFILE: Move this out into a compiled library file in the future
// FUTURE: Stuff to do much later.
/////
//"use strict";
/* jshint
maxerr:1000, eqeqeq: true, eqnull: false, unused: false, loopfunc: true
*/
/* jshint -W116 */
(function() {
//Initialize Angular app
var app = angular.module("aersia", [ ]);
app.controller("aersiaController", ['$scope','$http', function($scope,$http) {
this.friendlyname = "/*%= friendlyname */";
this.version = "/*%= version */";
// Create a bogus link to download stuff with
this.download = document.head.appendChild(document.createElement('a'));
this.download.style = "display:none;visibility:hidden;";
this.download.download = "aersiaStyle.json";
// Create a bogus file input to upload stuff with
this.upload = document.head.appendChild(document.createElement('input'));
this.upload.style = "display:none;visibility:hidden;";
this.upload.type = "file";
this.styleReader = new FileReader();
// Create x2js instance with default config
var x2js = new X2JS();
// Create the lightbox
this.lightbox = new Lightbox();
this.lightbox.load({
'preload': false,
'controls': false,
'nextOnClick': false
});
// Initialize the share button
var clipboard = new Clipboard(document.getElementById('copyBtn'), {
text: function(btn) {
this.success("Share link copied to clipboard.");
return window.location.href + '#' + encodeURIComponent( this.selectedPlaylist + '|' + this.curSong );
}.bind(this)
});
//Init logger
Logger.useDefaults({
logLevel: Logger.WARN,
formatter: function (messages, context) {
messages.unshift('[Aersia]');
if (context.name) messages.unshift('[' + context.name + ']');
}
});
Logger.get('internals').setLevel(Logger.ERROR);
Logger.get('player').setLevel(Logger.ERROR);
Logger.get('animation').setLevel(Logger.ERROR);
Logger.get('songart').setLevel(Logger.ERROR);
//Initialize variables
this.songs = [];
this.noShuffles = {};
this.curSong = 0;
this.autoplay = true;
this.playing = false;
this.playtries = 0;
this.prevVolume = 0;
this.history = [];
this.historyPosition = 0;
this.preferredFormats = [ "opus","ogg","m4a","mp3" ];
// UI variables
this.lastTimeText = '';
this.lastLoadText = '';
this.fullyLoaded = 0;
this.optionsBoxShown = false;
this.songArt = {
placeholder: true,
placeholdersrc: 'assets/img/placeholder.png',
rotating: false,
curArt: false,
nextArt: false,
timer: false,
period: 10000,
};
this.selectedLayout = "Classic";
this.layouts = {
"Classic": {
"class": "layout-classic",
"href": "layout-classic",
"features": ["controls","timeline","timeTextUpdate","progressUpdate","playlist","animations","options","songImg"]
},
"Touch": {
"class": "layout-touch",
"href": "layout-touch",
"features": ["controls","timeline","timeTextUpdate","progressUpdate","playlist","animations","options","songImg"]
},
"Streambox": {
"class": "layout-streambox",
"href": "layout-streambox",
"features": ["timeTextUpdate", "progressUpdate", "streambox","options","songImg"]
},
"Streambar": {
"class": "layout-streambar",
"href": "layout-streambar",
"features": ["controls","timeTextUpdate","progressUpdate","options"]
},
};
//js-cookie variables
this.cookieName = "aersia";
this.cookieConfig = { };
//Playlists
this.lastPlaylist = "";
this.selectedPlaylist = "VIP";
this.playlists = {
"VIP": {
"url": "/roster.json",
//"url": "http://vip.aersia.net/roster.xml",
"longName": "Vidya Intarweb Playlist",
},
"VIP - Source": {
"url": "http://vip.aersia.net/roster-source.xml",
"longName": "Vidya Intarweb Playlist - Source Edition",
},
"VIP - Exiled": {
"url": "http://vip.aersia.net/roster-exiled.xml",
"longName": "Vidya Intarweb Playlist - Exiled Edition",
},
"VIP - Mellow": {
"url": "http://vip.aersia.net/roster-mellow.xml",
"longName": "Vidya Intarweb Playlist - Mellow Edition",
},
"WAP": {
"url": "http://wap.aersia.net/roster.xml",
"longName": "Weeaboo Anime Playlist",
}
};
//Grab DOM elements
this.player = document.getElementsByTagName("audio")[0];
this.playlist = document.getElementById("playlist");
this.tabs = document.getElementsByClassName("effeckt-tabs")[0];
this.optionsbox = document.getElementsByClassName("optionsbox")[0];
this.layoutbox = document.getElementById("layoutbox");
this.streambox = document.getElementById("streambox");
this.mainControls = document.getElementById("mainControls");
this.playpause = document.getElementById("playpause");
this.timeText = document.getElementById("timeText");
this.timeline = document.getElementById("timeline");
this.timebox = document.getElementById("timebox");
this.controlsInfoBox = document.getElementById("controlsInfoBox");
this.loadBar = document.getElementById("loadBar");
this.playedBar = document.getElementById("playedBar");
this.playhead = document.getElementById("playhead");
this.loadPct = document.getElementById("loadPct");
this.volumeBar = document.getElementById("volumeBar");
this.messagebox = document.getElementById("messagebox");
this.toggleShuffleBtn = document.getElementById("toggleShuffle");
this.songUI = {
'Streambox': {
'title': document.getElementById("sboxSongTitle"),
'creator': document.getElementById("sboxSongCreator"),
'img': document.getElementById("sboxSongImg"),
},
'Streambar': {
'title': document.getElementById("controlsSongTitle"),
'creator': document.getElementById("controlsSongCreator"),
},
'default': {
'title': document.getElementById("oboxSongTitle"),
'creator': document.getElementById("oboxSongCreator"),
'img': document.getElementById("oboxSongImg"),
}
};
this.hookSongArtElement = function(el) {
addEvent(el, window.transitionEnd, function() {
if( classie.hasClass(el,"fadeout") )
{
if( ! this.songArt.rotating )
{
// If the rotation was cancelled for any reason, break out.
return;
}
// Grab the art in question
if( this.curSong == null || this.songArt.nextArt === false ||
this.songs[this.curSong] == null || this.songs[this.curSong].art == null ||
this.songs[this.curSong].art[this.songArt.nextArt] == null
)
{
Logger.get("songart").error("Faded out, but "+this.curSong+" + "+this.songArt.nextArt+" did not point to valid art!");
return;
}
Logger.get("songart").debug("Faded out, switched song art.");
this.songArt.placeholder = false;
el.src = 'http://mobygames.com'+this.songs[this.curSong].art[this.songArt.nextArt].thumbnail;
// Pick next art, wrap index if necessary.
this.songArt.curArt = this.songArt.nextArt;
this.songArt.nextArt++;
if( this.songArt.nextArt > this.songs[this.curSong].art.length - 1 )
{ this.songArt.nextArt = 0; }
}
}.bind(this));
// Fade back in whenever the image finishes loading.
addEvent(el,"load", function() {
Logger.get("songart").debug("Song art loaded, fading in.");
// Trigger the object-fit polyfill
objectFitImages(el);
classie.removeClass(el,"fadeout");
}.bind(this) );
addEvent(el,"error", function() {
Logger.get('songart').error("Unable to load song art, setting placeholder.");
this.stopSongArt();
}.bind(this) );
// Trigger the object-fit polyfill for the first time
objectFitImages(el);
// Load the image lightbox on click.
addEvent(el,'click',function(){
if( this.songArt.placeholder === true )
{ return; }
if(
this.curSong == null || this.songArt.curArt === false ||
this.songs[this.curSong] == null || this.songs[this.curSong].art == null ||
this.songs[this.curSong].art[this.songArt.curArt] == null
)
{ return; }
Logger.get("songart").debug("Opened full art Lightbox");
this.lightbox.open('http://mobygames.com'+this.songs[this.curSong].art[this.songArt.curArt].fullsize);
}.bind(this));
}.bind(this);
// Hook any layouts that have the songImg
Object.keys(this.songUI).forEach(function(val) {
if( this.songUI[val].img != null )
{ this.hookSongArtElement( this.songUI[val].img ); }
}.bind(this));
/////
//Styles and Presets
this.selectedPreset = "Aersia";
this.currentStyles = {};
this.styleNodes = {};
// Presets. This could be loaded from XHR later.
this.presetStyles = {
"Aersia": {
"focus": "#FF9148", // Orange
"background": "#183C63", // Lighter, main blue
"contrast": "#003366", // Dark, bordery color
"active": "#4687ef", // Bright, activey blue
"scrollbar": "#7f6157", // Dull orange, the back of the scrollbar
"loadbar": "#635d62", // Dull purple, for things like timeline bg
"controlsout": {"0%": "#c0ccd9", "100%": "#000c19"}, // The border around the controls
"controlsin": {"0%": "#3D6389", "100%": "#072d53"}, // The inside of the controls
},
//Styles from JSON files
/*%= includedstyles */
};
// CSS definitions of where all the colors go
this.styleCssText = {
"focus": [
"g, rect, path { fill: ","; }\n"+
".controls-container, .playlist-container, .optionsbox, #streambox { color: ","; }\n"+
"#playedBar, #playhead, .active-song, .ps-theme-vip>.ps-scrollbar-y-rail>.ps-scrollbar-y, .ps-theme-vip>.ps-scrollbar-x-rail>.ps-scrollbar-x { background-color: ","; }\n"+
"#volumeBar { border-color: transparent "," transparent transparent; }"
],
"background": [
".playlist-container, .optionsbox { background-color:","; }"
],
"contrast": [
".playlist>li:hover, .active-song { color: ","; }\n"+
".optionsbox, .sep, .playlist>li, section, .ps-theme-vip>.ps-scrollbar-y-rail, .ps-theme-vip>.ps-scrollbar-x-rail { border-color: ","; }\n"
],
"active": [
".playlist>li:hover, .ps-theme-vip:hover>.ps-scrollbar-y-rail:hover>.ps-scrollbar-y, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-y-rail>.ps-scrollbar-y, .ps-theme-vip:hover>.ps-scrollbar-x-rail:hover>.ps-scrollbar-x, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-x-rail:hover>.ps-scrollbar-x { background-color: ","; }"
],
"scrollbar": [
".ps-theme-vip>.ps-scrollbar-x-rail, .ps-theme-vip>.ps-scrollbar-y-rail { background-color: ","!important; }"
], // .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-x-rail, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-y-rail, .ps-theme-vip:hover>.ps-scrollbar-y-rail:hover, .ps-theme-vip:hover>.ps-scrollbar-x-rail:hover
"loadbar": [
"#loadBar { background-color: ","; }"
],
};
this.styleCssGradientText = {
"controlsout": ".controls-container, .effeckt-tabs",
"controlsin": ".controls-container>div, .effeckt-tabs>li, #streambox",
};
//Give each style its own stylesheet node.
Object.keys(this.styleCssText).forEach(function(val) {
this.styleNodes[val] = document.head.appendChild(document.createElement('style'));
}.bind(this));
Object.keys(this.styleCssGradientText).forEach(function(val) {
this.styleNodes[val] = document.head.appendChild(document.createElement('style'));
}.bind(this));
// Add a box for each layout in the layoutsbox.
Object.keys(this.layouts).forEach(function(key) {
var container = document.createElement("div");
classie.addClass(container,"vbox");
classie.addClass(container,"centertext");
var div = document.createElement("div");
container.appendChild(div);
//Why do I need a namespace for this, what is even the difference in the markup??
var svg = document.createElementNS("http://www.w3.org/2000/svg","svg");
svg.setAttribute("height","120px");
svg.setAttribute("width","120px");
div.appendChild(svg);
//Why do I need a namespace for this, what is even the difference in the markup??
var use = document.createElementNS("http://www.w3.org/2000/svg","use");
use.setAttributeNS('http://www.w3.org/1999/xlink', 'href',"#"+this.layouts[key].href);
svg.appendChild(use);
var name = document.createElement("div");
name.innerHTML = key;
container.appendChild(name);
this.layoutbox.appendChild(container);
container.onclick = function() {
this.switchLayout(key);
}.bind(this);
}.bind(this));
/////
// Initalize scrollbar
Ps.initialize(this.playlist, {
theme: 'vip',
minScrollbarLength: 20
});
//Bind it to update when window resizes.
addEvent(window,"resize", function() {
Ps.update(this.playlist);
}.bind(this));
/////
// Bind to check the hash when it updates
window.onhashchange = function() {
var hash = this.decodeHash();
if( hash[0] !== false ) {
this.loadPlaylist(hash[1]);
} else {
this.playSong(hash[1]);
}
// Consume the hash so it won't screw up reloads.
window.location.hash = '';
}.bind(this);
/////
// Mbox functions
this.closembox = function () { classie.addClass(this.messagebox,"hidden"); }.bind(this);
this.internalerror = function (str) { this.error("Internal error: "+str+" Please report this along with a screenshot to the webmaster."); }.bind(this);
this.success = function (str) { this._mbox_manip('mboxsuccess',str); }.bind(this);
this.error = function (str) { this._mbox_manip('mboxerror',str); }.bind(this);
this.info = function (str) { this._mbox_manip('mboxinfo',str); }.bind(this);
this._mbox_manip = function (destclass,str) {
classie.removeClass(this.messagebox,"hidden");
classie.removeClass(this.messagebox,"mboxerror");
classie.removeClass(this.messagebox,"mboxsuccess");
classie.removeClass(this.messagebox,"mboxinfo");
classie.addClass(this.messagebox,destclass);
this.messagebox.children[0].innerHTML = str;
}.bind(this);
this.mboxclosebutton = document.getElementById('mboxclose');
addEvent(this.mboxclosebutton,"click",this.closembox);
/////
// To enable layouts to swap functions on and off, here is an object of status and hooks.
this.features = {
"controls": {
"enable": function() {
classie.removeClass(this.mainControls,"hidden");
},
"disable": function() {
classie.addClass(this.mainControls,"hidden");
},
},
"timeline": {
"enable": function() {
classie.removeClass(this.timebox,"hidden");
classie.addClass(this.controlsInfoBox,"hidden");
this.timeText = document.getElementById("timeProgText");
this.loadPct = document.getElementById("timeLoadPct");
addEvent(this.player,"timeupdate", this.timelineUpdate);
this.timelineUpdate();
this.updateCurSongInfo();
},
"disable": function() {
classie.addClass(this.timebox,"hidden");
classie.removeClass(this.controlsInfoBox,"hidden");
this.timeText = document.getElementById("controlsProgText");
this.loadPct = document.getElementById("controlsLoadPct");
removeEvent(this.player,"timeupdate", this.timelineUpdate);
this.updateCurSongInfo();
},
},
"playlist": {
"enable": function() {
classie.removeClass(this.playlist,"hidden");
},
"disable": function() {
//here's where I would prevent a new playlist from loading up while this is disabled.
classie.addClass(this.playlist,"hidden");
},
},
"options": {
"enable": function() {
classie.removeClass(this.tabs,"hidden");
},
"disable": function() {
classie.addClass(this.tabs,"hidden");
this.toggleOptionsBox(false);
},
},
"streambox": {
"enable": function() {
classie.removeClass(this.streambox,"hidden");
},
"disable": function() {
classie.addClass(this.streambox,"hidden");
},
},
"timeTextUpdate": {
"enable": function() {
addEvent(this.player,"timeupdate", this.timeTextUpdate);
this.timeTextUpdate();
},
"disable": function() {
removeEvent(this.player,"timeupdate", this.timeTextUpdate);
},
},
"progressUpdate": {
"enable": function() {
addEvent(this.player,"timeupdate",this.progressUpdate); // not progress, it doesn't fire reliably
this.progressUpdate();
},
"disable": function() {
removeEvent(this.player,"timeupdate",this.progressUpdate);
},
},
"animations": {
"enable": function() {
// this.animationsEnabled = true;
},
"disable": function() {
// this.animationsEnabled = false;
},
},
"songImg": {
"enable": function() {
// this.animationsEnabled = true;
this.updateCurSongInfo();
},
"disable": function() {
// this.animationsEnabled = false;
},
},
};
// Forces a feature on or off regardless. This is only set by the user.
this.overrideFeatures = {};
this.enableFeature = function(feature) {
if( this.features[feature] != null && this.features[feature].enabled !== true )
{
if( this.features[feature].enable != null )
{ this.features[feature].enable.call(this); }
this.features[feature].enabled = true;
Logger.get("internals").info(feature+" enabled.");
}
}.bind(this);
this.disableFeature = function(feature) {
if( this.features[feature] != null && this.features[feature].enabled !== false )
{
if( this.features[feature].disable != null )
{ this.features[feature].disable.call(this); }
this.features[feature].enabled = false;
Logger.get("internals").info(feature+" disabled.");
}
}.bind(this);
this.toggleFeature = function(feature) {
if( this.features[feature] != null )
{
if( this.features[feature].enabled != null && this.features[feature].enabled )
{
this.disableFeature(feature);
} else {
this.enableFeature(feature);
}
}
}.bind(this);
/////
//Hook audio player
//This will be called whenever a song ends.
addEvent(this.player, "ended", function() {
if( this.autoplay )
{ this.shuffleSong(); }
}.bind(this));
// This will be called if the player breaks for any reason
addEvent(this.player, "error", function(ev) {
// Just retry. If this is called twice without a full playthrough, it will just stop.
this.playSong(this.curSong,true);
}.bind(this));
//This will be called every time a new song loads, and when the song is seeked and begins playing?
// addEvent(this.player,"canplaythrough", function () {
// Logger.get("internals").info('canplaythrough');
// }.bind(this));
//Makes timeline clickable
this.seekBar = function(e,amt) {
//Respond to either click or direct invocation
if( e !== '' )
{ amt = clickPercent(e,this.timeline); }
Logger.get("player").debug('Timeline seek: '+amt);
this.player.currentTime = this.player.duration * amt;
this.timeUpdate(e);
}.bind(this);
addEvent(this.timeline,"click", this.seekBar);
//This will be called as downloading progresses.
this.progressUpdate = function(e,amt) {
var newText = '';
//Respond to either click or direct invocation.
if( e !== '' )
{
var bufend = 0;
if( this.player.buffered.length > 0 ) { bufend = this.player.buffered.end(0); }
if( bufend === this.player.duration )
{
if( this.fullyLoaded === 0 )
{
amt = 100; // skip rounding
newText = "100%"; // show this for one tick.
this.fullyLoaded = 1;
}
else
{
//We are fully loaded. Show a timestamp instead.
newText = this.timeFormat(this.player.duration);
}
}
else // get normal percentage
{
amt = 100 * (bufend / this.player.duration);
newText = Math.round(amt) + '%';
}
}
else // use direct input
{
newText = Math.round(amt) + '%';
}
Logger.get("player").debug('Progress update: '+amt);
//Don't update the progress if it will look the same.
if( this.lastLoadText !== newText )
{
//Change loadPct text and store value
this.loadPct.textContent = newText;
this.lastLoadText = newText;
//Move loadBar in timeline
this.loadBar.style.right = (100 - amt) + '%'; // inverse percentage
}
}.bind(this);
//This will be called as the song progresses.
this.timeTextUpdate = function(e,amt) {
if( e != null && e !== '' )
{ amt = this.player.currentTime / this.player.duration; }
//Don't update the time if it will look the same.
var newTime = this.timeFormat(this.player.currentTime);
if( this.lastTimeText !== newTime )
{ this.timeText.textContent = newTime; this.lastTimeText = newTime; }
}.bind(this);
this.timelineUpdate = function(e,amt) {
if( e != null && e !== '' )
{ amt = this.player.currentTime / this.player.duration; }
Logger.get("player").debug('Time update: '+amt);
// //Move the playhead
// this.playhead.style.left = amt + "%";
//
// //Move the playedBar in the timeline
// this.playedBar.style.right = amt + "%";
//REWORK: somehow we need to cache the boundingrect, but for some reason if I don't use it every frame it gets off by a lot.
//This pixel-perfect version is just to achieve that one-pixel offset effect in the original .swf
//Move the playhead
var rect = this.timeline.getBoundingClientRect();
var clickpx = (rect.right - rect.left) * amt;
this.playhead.style.left = clickpx + "px";
//Move the playedBar in the timeline
this.playedBar.style.right = (((rect.right - rect.left) - clickpx) + 1) + "px";
}.bind(this);
//////////////////////
// Player functions //
//////////////////////
/////
// Playlist Management
this.loadPlaylist = function(start) {
if( this.selectedPlaylist == null || this.selectedPlaylist == "" ) { return; }
if( this.playlists[this.selectedPlaylist] == null ) { Logger.get("player").error("Playlist "+this.selectedPlaylist+" is invalid."); return; }
if( this.selectedPlaylist !== this.lastPlaylist )
{
// Loading a new playlist
//Stop the song.
this.pause();
this.resetControls();
$http.get(this.playlists[this.selectedPlaylist].url)
.then(function(res) {
// Prepare the playlist for use
var playlist = res.data;
//Convert it from XML to JSON if necessary
if( /.xml$/.test(this.playlists[this.selectedPlaylist].url) )
{
playlist = x2js.xml2js(playlist).playlist.trackList.track;
}
//Set the song list
this.songs = playlist;
this.lastPlaylist = this.selectedPlaylist;
// Update the window's title.
document.title = this.playlists[this.selectedPlaylist].longName + ' - ' + this.friendlyname + ' v' + this.version;
// If we're allowed, start playing.
if( this.autoplay )
{
// If we're supposed to start somewhere, do that. Otherwise, shuffle.
if( start != null && start !== false )
{ window.setTimeout(function() { this.playSong(start); }.bind(this),500); }
else
{ window.setTimeout(this.shuffleSong,500); }
// But give Angular's list a little time to update, since it's stupid.
}
}.bind(this),
function(res) {
//If the request fails for some reason
this.error("The playlist was not able to be loaded. Please try again or reload the page.");
}.bind(this)
);
}
else if( start != null && start !== false )
{
// Starting a song on this playlist without loading.
if( this.songs[start] == null ) { Logger.get("player").error("Requested song "+start+" is invalid."); return; }
this.playSong(start);
}
}.bind(this);
// Wrapper that updates cookie
this.changePlaylist = function() {
this.loadPlaylist();
this.setCookie();
}.bind(this);
// Keeps a list of previously played songs, up to 100.
this.historyTrack = function(idx) {
if( this.historyPosition < 0 && this.history[(this.history.length-1) + this.historyPosition] !== idx )
{
//I think this wipes too many things?
//We're backed up in the queue, but we're being asked to play a different song. Wipe out the queue so we can store the new one.
Logger.get("internals").info("History undo stack burst: "+this.history+" @ "+this.historyPosition);
while( this.historyPosition < 0 ) { this.history.pop(); this.historyPosition++; }
Logger.get("internals").info("History undo stack end: "+this.history+" @ "+this.historyPosition);
}
if( this.historyPosition === 0 )
{
// Cut the history list down if it's at capacity
while( this.history.length > 99 ) { this.history.shift(); }
this.history.push(idx);
Logger.get("internals").debug("History queue: "+this.history+" @ "+this.historyPosition);
}
}.bind(this);
// retry overrides attempting to play the same song.
this.playSong = function(index,retry) {
if( index == null || index === false ) { return; }
index = parseInt(index);
if( index === this.curSong && ( retry == null || retry === false )) { return; }
if( retry == null ) { retry = false; }
// Error handling
if( retry && this.playtries > 0 ) {
// If we've already retried for any reason, don't try again.
Logger.get("player").error("Cannot play song: "+this.songs[index].title);
return;
} else if ( retry ) {
// If this is our first retry, let's keep track of that.
this.playtries = 1;
} else {
// If we're being asked to play a song and this isn't a retry, let's reset our tries counter.
this.playtries = 0;
}
//Stop and unregister the old song.
this.pause();
this.player.src = '';
if( this.curSong != null && this.playlist.children[this.curSong] != null )
{ classie.removeClass(this.playlist.children[this.curSong],'active-song'); }
//log
if( retry )
{ Logger.get("player").error("Retrying song: "+this.songs[index].title); }
else
{ Logger.get("player").info("Playing song: "+this.songs[index].title); }
// Set the interface for the new song
this.curSong = index;
this.updateCurSongInfo();
this.fullyLoaded = 0;
// If this is a retry, we've already done this stuff and don't want to do it again.
if( ! retry )
{
// Set the shuffle control to reflect the disabled state
if( this.noShuffles[this.selectedPlaylist] != null && this.noShuffles[this.selectedPlaylist].indexOf(this.curSong) > -1 )
{ classie.addClass(this.toggleShuffleBtn, "toggled"); }
else
{ classie.removeClass(this.toggleShuffleBtn, "toggled"); }
// Highlight the active song
if( this.curSong != null && this.playlist.children[this.curSong] != null )
{ classie.addClass(this.playlist.children[this.curSong],'active-song'); }
// Put this song in history
this.historyTrack(this.curSong);
}
// Play
if( this.songs[this.curSong].formats != null )
{
var selFormat = '';
try {
this.preferredFormats.forEach(function(format) {
if( this.songs[this.curSong].formats[format] != null )
{ selFormat = format; throw BreakException; }
});
} catch(e) { // alert for now, use a message box later
if (e!==BreakException) throw e;
}
if( selFormat === '' )
{
Logger.get("player").error("Unable to use any of the provided file formats. Trying location.");
this.player.src = this.songs[this.curSong].location;
}
else {
Logger.get("player").debug("Selected format "+selFormat);
this.player.src = this.songs[this.curSong].formats[format];
}
}
else {
this.player.src = this.songs[this.curSong].location;
}
this.play();
//Trigger the playlist to scroll.
this.scrollToSong(index);
}.bind(this);
this.shuffleSong = function() {
//Generate a list of indexes we're allowed to play.
var list = [];
for ( var i=0; i<this.songs.length; i++ ) {
if
(
// Ensure we don't play the same song again and
i !== this.curSong &&
// it's not in our list of things not to shuffle
this.noShuffles[this.selectedPlaylist].indexOf(i) === -1
)
{
list.push(i);
}
}
var selected = Math.floor(Math.random() * list.length);
//Start our random song.
this.playSong( list[selected] );
}.bind(this);
// Forbids or allows a song to be played.
this.toggleShuffle = function() {
//If we haven't blocked anything on this playlist yet, give it the structure.
if( this.noShuffles[this.selectedPlaylist] == null ) { this.noShuffles[this.selectedPlaylist] = []; }
var pos = this.noShuffles[this.selectedPlaylist].indexOf(this.curSong);
if( pos === -1 )
{
Logger.get("player").info("Disabled shuffle for "+this.curSong);
this.noShuffles[this.selectedPlaylist].push(this.curSong);
classie.addClass(this.toggleShuffleBtn,"toggled");
} else {
Logger.get("player").info("Enabled shuffle for "+this.curSong);
this.noShuffles[this.selectedPlaylist].splice(pos,1);
classie.removeClass(this.toggleShuffleBtn,"toggled");
}
this.setCookie();
}.bind(this);
// Not used. Should remove.
this.isCurrentSong = function(index) {
return index === this.curSong;
}.bind(this);
/////
// Rating functions
this.rateUp = function() {
Logger.get("player").info("RateUp");
};
this.rateDown = function() {
Logger.get("player").info("RateDown");
};
/////
// HTML5 audio player control functions, in button order, then helper function order.
// Assistance from: http://www.alexkatz.me/html5-audio/building-a-custom-html5-audio-player-with-javascript/
this.play = function() {
//Reset the readouts
this.resetControls();
this.player.play();
this.playing = true;
classie.addClass(this.playpause,"toggled");
}.bind(this);
this.pause = function() {
this.player.pause();
this.playing = false;
classie.removeClass(this.playpause,"toggled");
}.bind(this);
this.togglePlay = function(bool) {
if( bool !== null ) { bool = !this.playing; }
if( bool ) { this.play(); }
else { this.pause(); }
}.bind(this);
// Traverses the history queue, or just plays a new song.
this.seek = function(amt) {
// var index = this.curSong + amt;
// if( index >= 0 && index <= this.songs.length )
// { this.playSong(index); }
if( amt < 0 )
{
if( (this.history.length-1) >= 0 -(this.historyPosition + amt) )
{
this.historyPosition += amt;
Logger.get("internals").debug("History rewind: "+this.history+" @ "+this.historyPosition);
this.playSong( // Play the song...
this.history[ // at history position...
(this.history.length-1) + this.historyPosition // offset by the end of the history queue.
]
);
}
}
else {
if( this.historyPosition === 0 )
{
this.shuffleSong();
}
else {
this.historyPosition += amt;
this.playSong( // Play the song...
this.history[ // at history position...
(this.history.length-1) + this.historyPosition // offset by the end of the history queue.
]
);
}
}
}.bind(this);
this.toggleOptionsBox = function(bool) {
if( bool == null ) { bool = !this.optionsBoxShown; }
this.optionsBoxShown = bool;
// Update the song info before we show the box, just in case
this.updateCurSongInfo();
// Toggle hidden class.
if( this.optionsBoxShown ) { classie.removeClass(this.optionsbox,"hidden"); } else { classie.addClass(this.optionsbox,"hidden"); }
//Trigger the scrollbar to fix itself.
Ps.update(this.playlist);
}.bind(this);
this.toggleFullscreen = function() {
toggleFullScreen();
}.bind(this);
this.toggleMute = function() {
//Toggle
var vol = this.player.volume;
this.volume('',this.prevVolume);
this.prevVolume = vol;
}.bind(this);
this.volume = function(e,amt) {
//Respond to either click or direct invocation
if( e !== '' ) { amt = clickPercent(e,this.volumeBar); }
amt = Math.pow(amt,2); //Human perception of volume is inverse-square.
Logger.get("player").info("Volume change: "+amt);
this.player.volume = amt;
}.bind(this);
this.timeFormat = function(sec) {
var min = Math.floor(sec/60);
sec = Math.floor(sec % 60);
return zeroPad(min,2)+':'+zeroPad(sec,2);
}.bind(this);
/////
// UI Functions
this.resetControls = function() {
this.timelineUpdate('',0);
this.timeTextUpdate('',0);
this.progressUpdate('',0);
}.bind(this);
this.toggleScrollSmooth = function() {
this.features.animations.enabled = !this.features.animations.enabled; // Angular changes the model before the change
this.toggleFeature("animations");
this.setCookie();
}.bind(this);
this.scrollToSong = function(index) {
// this function is called when the layout is set, which happens before the songs are even loaded once.
if( this.songs.length === 0 )
{ return; }
//Get the elements' height, since this could change.
var height = this.playlist.firstElementChild.offsetHeight;
var targetY = height * index;
// If this element would be closer to the end of the list than the viewport allows, just scroll to the bottom to avoid overflowing.
// The browser should realistically stop this, but every 'set' seems to move a pixel beyond the limit, and the smooth animation sets rapidly, causing a big overflow.
if( (height * this.songs.length) - targetY < this.playlist.offsetHeight )
{ targetY = (height * this.songs.length) - this.playlist.offsetHeight; }
Logger.get("animation").debug('Scroll event: '+this.playlist.scrollTop + ' by interval '+ height +' to '+targetY);
if( this.features.animations.enabled )
{
//Make the playlist scroll to the currently playing song.
scrollToSmooth(this.playlist, targetY, 600);
}
else
{
this.playlist.scrollTop = height * index;
}
}.bind(this);
this.setLayout = function(l) {
this.selectedLayout = l;
// Remove all the layouts
Object.keys(this.layouts).forEach(function(layout) { classie.removeClass(document.documentElement,this.layouts[layout].class); }.bind(this));
// Add the one we want.
classie.addClass(document.documentElement,this.layouts[this.selectedLayout].class);
// Enable all features of our layout, and disable everything else.
Object.keys(this.features).forEach(function(feature) {
if(
this.layouts[this.selectedLayout].features.indexOf(feature) > -1 && // layout is supposed to have it on
( this.overrideFeatures[feature] == null || this.overrideFeatures[feature] === true ) // and it's not forced off
)
{
this.enableFeature(feature);
} else {
this.disableFeature(feature);
}
}.bind(this));
// Trigger the playlist to scroll in case the layout is messed up
this.scrollToSong(this.curSong);
if( this.features.options.enabled )
{
// Open the optionsbox if it's hidden, re-adjust the tab, and set the optionsbox back the way it was.
// This is done because the tab height will probably have changed when the layout changes.
var orig = this.optionsBoxShown;
this.toggleOptionsBox(true);
var tab = document.getElementsByClassName("effeckt-tab active")[0];
if( tab != null )
{
window.setTimeout( function() {
Tabs.showTab(tab);
this.toggleOptionsBox(orig);
}.bind(this), 500 );
}
}
}.bind(this);
// Wrapper that updates cookie
this.switchLayout = function(l) {
this.setLayout(l);
this.setCookie();
}.bind(this);
this.styleSet = function(type) {
//Recompile the selected style's node
this.styleNodes[type].innerHTML = this.styleCssText[type].join(this.currentStyles[type]);
}.bind(this);
//Wrapper that updates cookie
this.changeStyle = function(type) {
this.styleSet(type);
this.setCookie();
}.bind(this);
this.gradientSet = function(type) {
//This is really bad. Maybe find a library for this later.
var begin = this.currentStyles[type]["0%"];
var end = this.currentStyles[type]["100%"];
this.styleNodes[type].innerHTML = this.styleCssGradientText[type] + " { \n"+
"background: "+begin+";\n"+ //Old browsers
"background: -moz-linear-gradient(top, "+begin+" 0%, "+end+" 100%);\n"+ // FF3.6-15
"background: -webkit-linear-gradient(top, "+begin+" 0%, "+end+" 100%);\n"+ // Chrome10-25,Safari5.1-6
"background: linear-gradient(to bottom, "+begin+" 0%, "+end+" 100%);\n"+ // W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+
"filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='"+begin+"', endColorstr='"+end+"',GradientType=0 );\n"+ // IE6-9
"}";
}.bind(this);
//Wrapper that updates cookie
this.changeGradient = function(type) {
this.gradientSet(type);
this.setCookie();
}.bind(this);
this.loadPreset = function() {
if( this.presetStyles[this.selectedPreset] != null )
{
Logger.get("internals").info("Setting preset to "+this.selectedPreset);
this.currentStyles = this.presetStyles[this.selectedPreset];
this.reloadStyle();
this.setCookie();
}
}.bind(this);
//Wrapper that calls them all
this.reloadStyle = function() {
Object.keys(this.styleCssText).forEach(function(val) { this.styleSet(val); }.bind(this));
Object.keys(this.styleCssGradientText).forEach(function(val) { this.gradientSet(val); }.bind(this));
}.bind(this);
/////
// Export and import styles
this.exportStyles = function() {
this.triggerDownload(this.currentStyles);
}.bind(this);
//This function is called when the FileReader loads, which is called when the file input changes, which is called when user picks file.
this.importStyles = function(event) {
Logger.get('internals').info('FileReader loaded file.');
var result;
try { result = JSON.parse(event.target.result); }
catch ( e ) { alert("File does not contain a valid style structure."); }
if( result != null )
{
// Check that all the right things are defined
try {
Object.keys(this.currentStyles).forEach(function(key) {
Logger.get('internals').debug(key);
if( result[key] == null ) { throw BreakException; }
}.bind(this));
this.currentStyles = result;
this.reloadStyle();
Logger.get('internals').info('Style imported successfully.');
this.setCookie();
} catch(e) { // alert for now, use a message box later
if (e!==BreakException) throw e;
alert("Imported style was not formatted correctly.");
}
}
}.bind(this);
this.upload.onchange = function() {
Logger.get('internals').info('File input changed.');
this.styleReader.readAsText(this.upload.files[0]);
}.bind(this);
this.styleReader.onload = this.importStyles;
/////
// Cookie functions
this.getCookie = function() {
var cookie = Cookies.getJSON(this.cookieName);
if( cookie == null ) {
// First launch, if this is a touch device, put it into touch mode by default.
if( isMobile.any() ) { this.switchLayout("Touch"); }
return 1;
}
// Directly mapped properties
['autoplay','selectedLayout','currentStyles','selectedPreset','selectedPlaylist','noShuffles']
.forEach(function(val) {
if( cookie[val] != null && this[val] != null )
{ this[val] = cookie[val]; }
}.bind(this));
// Unpacked properties
if( cookie.lastVolume != null ) { this.player.volume = cookie.lastVolume; }
if( cookie.features != null && cookie.features.animations != null && cookie.features.animations.enabled != null )
{ this.overrideFeatures.animations = cookie.features.animations.enabled; }
// Triggers
if( cookie.currentStyles != null ) { this.reloadStyle(); }
Logger.get("internals").info("Cookie read.");
}.bind(this);
this.setCookie = function() {
Cookies.set(this.cookieName, {
"autoplay": this.autoplay,
"features": { "animations": { "enabled": this.features.animations.enabled } },
"selectedLayout": this.selectedLayout,
"currentStyles": this.currentStyles,
"lastVolume": this.player.volume,
"selectedPreset": this.selectedPreset,
"selectedPlaylist": this.selectedPlaylist,
"noShuffles": this.noShuffles,
}, this.cookieConfig);
Logger.get("internals").info("Cookie written.");
}.bind(this);
/////
// File downloading and uploading
this.triggerDownload = function(data) {
if( typeof data === "object" )
{ data = JSON.stringify(data,null,'\t'); }
this.download.href = 'data:application/octet-stream;charset=utf-16le;base64,' + btoa(data);
this.download.dispatchEvent(new MouseEvent('click'));
Logger.get('internals').info('File download triggered.');
}.bind(this);
this.triggerLinkDownload = function(uri) {
this.download.href = uri;
this.download.dispatchEvent(new MouseEvent('click'));
Logger.get('internals').info('Link download triggered.');
}.bind(this);
this.triggerUpload = function() {
this.upload.dispatchEvent(new MouseEvent('click'));
}.bind(this);
// Reads the sharing links
this.decodeHash = function() {
var newPlaylist = false;
var newSong = false;
if( window.location.hash != null && window.location.hash !== '#' )
{
var bits = decodeURIComponent(window.location.hash).substr(1);
bits = bits.split('|');
if( this.playlists[bits[0]] != null )
{
newPlaylist = bits[0];
if( bits[1] != null )
{ newSong = bits[1]; }
}
}
Logger.get("internals").info("Hash decoded: "+newPlaylist+", "+newSong);
return [newPlaylist,newSong];
}.bind(this);
this.updateCurSongInfo = function() {
// Update the song panel
if( this.curSong != null && this.songs[this.curSong] != null && (
( (this.selectedLayout === "Classic" || this.selectedLayout === "Touch") && this.optionsBoxShown ) || // In Classic or Touch interface, don't update unless it's visible.
( this.selectedLayout === "Streambox" || this.selectedLayout === "Streambar" ) //In Streambox or Streambar, update.
)
){
this.getUIElement('title').innerHTML = this.songs[this.curSong].title;
this.getUIElement('creator').innerHTML = this.songs[this.curSong].creator;
// this.curSongRating.innerHTML = "0"; //this.songs[this.curSong].rating;
if( this.songs[this.curSong].art != null && this.songs[this.curSong].art.length > 0 )
{
this.setSongArt();
} else {
this.stopSongArt();
}
}
};
// Function to get the right elements from the current layouts
this.getUIElement = function(type) {
if( this.songUI[this.selectedLayout] != null && this.songUI[this.selectedLayout][type] != null )
{
return this.songUI[this.selectedLayout][type];
} else {
return this.songUI.default[type];
}
}.bind(this);
// Function to control the song rotation
this.setSongArt = function() {
this.stopSongArt();
this.rotateSongArt();
}.bind(this);
// Function to do the actual rotation
this.rotateSongArt = function() {
if( this.songArt.rotating === true )
{
// We don't need to do anything but trigger the next fade.
classie.addClass(this.getUIElement('img'),"fadeout");
}
else {
// Set up the cover art rotator. If it's set to placeholder, we'll stomp it immediately.
if( this.songArt.placeholder === true )
{
Logger.get("songart").debug("Stomping song art");
// Set these variables since we've already done the first rotation.
this.songArt.placeholder = false;
this.songArt.curArt = 0;
this.songArt.nextArt = 1;
this.getUIElement('img').src = 'http://mobygames.com'+this.songs[this.curSong].art[0].thumbnail;
}
else {
// Fade out. The rest will be triggered automatically.
Logger.get("songart").debug("Fading out song art.");
classie.addClass(this.getUIElement('img'),"fadeout");
}
if( this.songs[this.curSong].art.length > 1 )
{
this.songArt.rotating = true;
this.songArt.timer = window.setTimeout(this.rotateSongArt, this.songArt.rotateperiod);
}
}
}.bind(this);
this.stopSongArt = function() {
// Stop the timer, reset attributes, and show the placeholder.
window.clearTimeout(this.songArt.timer);
this.songArt.timer = false;
this.songArt.rotating = false;
this.songArt.curArt = false;
this.songArt.nextArt = 0;
this.songArt.placeholder = true;
this.getUIElement('img').src = this.songArt.placeholdersrc;
}.bind(this);
/////
// Initialization
this.init = function() {
// Assign the default preset to the "current style";
this.currentStyles = this.presetStyles[this.selectedPreset];
// Get any stored values that will override our defaults.
this.getCookie();
// Enable features in our currently selected layout
this.setLayout(this.selectedLayout);
// Detect browser support for file formats and remove any formats that are not supported
var formats = [];
this.preferredFormats.forEach(function(format) {
if( Modernizr.audio[format] != null && Modernizr.audio[format] !== "" )
{ formats.push(format); }
}.bind(this));
this.preferredFormats = formats;
// Check the window location for a share link. This overrides our starting playlist and song.
var hash = this.decodeHash();
if( hash[0] !== false ) { this.selectedPlaylist = hash[0]; }
//Load up our playlist, this is async and will start playing automatically.
this.loadPlaylist(hash[1]);
}.bind(this);
this.init();
}]);
})();
// Animation functions
function scrollToSmooth(el,targetScroll,duration) {
// const scrollHeight = window.scrollY,
var beginScroll = el.scrollTop,
beginTime = Date.now();
Logger.get('animation').info('Beginning animation: '+beginTime+' '+beginScroll+' to '+targetScroll);
requestAnimationFrame(step);
function step () {
setTimeout(function() {
//Get our time diff to scale against.
var now = Date.now();
if ( now <= beginTime + duration) {
//Queue the next frame ahead of time
requestAnimationFrame(step);
//This is probably overcomplicated, but this gets the amount we need to add to the initial scroll for our time
var mod = easeInOut( now, beginTime,duration, beginScroll,targetScroll );
Logger.get("animation").debug('anim: '+ (now-beginTime) +' + '+mod);
//Set the scroll absolutely
if( beginScroll < targetScroll ) { el.scrollTop = beginScroll + mod; }
else { el.scrollTop = beginScroll - mod; }
} else {
//Final frame, don't schedule another.
Logger.get("animation").debug('Ending animation: end:'+ (now > (beginTime + duration))+' s:'+el.scrollTop);
el.scrollTop = targetScroll;
}
}, 15 );
}
}
// function testEase(begin,duration,end) {
// var now = begin;
// var done = 0;
// var i = 0;
// while ( !done ) {
// i++;
// if (i > 1000 ) { done = 1;}
//
// var pct = (now-begin) / (end-begin);
//
// var mod =
// pct *
// //the cosine curve scaled by how far we are.
// ((Math.cos (
// Math.PI + //beginning at Pi to ease in
// (Math.PI * Math.abs(pct))
// ) + 1 ) / 2)
// ;
// var delta =
// now += mod;
// Logger.get('animations').debug('pct: '+pct+', now: '+now+', mod: '+mod);
// if( now >= end ) { done = 1; }
// }
// }
function easeInOut(now, beginX,targetX, beginY,targetY ) {
return ( -1 * Math.pow(((now - beginX) / targetX) - 1,2) + 1 ) // y = -x^2 + 1
* (Math.abs(targetY-beginY)); // scaled up to the amount that we need to move.
}
function addEvent(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
}
function removeEvent(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.removeEventListener) {
object.removeEventListener(type, callback, false);
} else if (object.detachEvent) {
object.detachEvent("on" + type, callback);
} else {
object["on"+type] = null;
}
}
// returns click as decimal (.77) of the total object's width
function clickPercent(e,obj) {
return (e.pageX - obj.getBoundingClientRect().left) / obj.offsetWidth;
}
//https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
function toggleFullScreen() {
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
//coderjoe: http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript
function zeroPad (num, numZeros) {
if( num === 0 ) { return zeroPadNonLog(num,numZeros); }
var an = Math.abs (num);
var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
if (digitCount >= numZeros) {
return num;
}
var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
return num < 0 ? '-' + zeroString + an : zeroString + an;
}
function zeroPadNonLog(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
//Test for SVG support and polyfill if no. https://css-tricks.com/svg-sprites-use-better-icon-fonts/
/MSIE|Trident/.test(navigator.userAgent) && document.addEventListener('DOMContentLoaded', function () {
[].forEach.call(document.querySelectorAll('svg'), function (svg) {
var use = svg.querySelector('use');
if (use) {
var object = document.createElement('object');
object.data = use.getAttribute('xlink:href');
object.className = svg.getAttribute('class');
svg.parentNode.replaceChild(object, svg);
}
});
});
//
// function easeOutBounce(t, b, c, d) {
// if ((t/=d) < (1/2.75)) {
// return c*(7.5625*t*t) + b;
// } else if (t < (2/2.75)) {
// return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
// } else if (t < (2.5/2.75)) {
// return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
// } else {
// return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
// }
// }
// http://stackoverflow.com/questions/12606245/detect-if-browser-is-running-on-an-android-or-ios-device
var isMobile = {
Windows: function() {
return /IEMobile/i.test(navigator.userAgent);
},
Android: function() {
return /Android/i.test(navigator.userAgent);
},
BlackBerry: function() {
return /BlackBerry/i.test(navigator.userAgent);
},
iOS: function() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
}
};
| js/main.js | /////
// /*%= friendlyname */ v/*%= version */
//
//To do tags:
// CSS: Ongoing changes to the CSS.
// REWORK: Changes to do in the future.
// MOREFILE: Move this out into a compiled library file in the future
// FUTURE: Stuff to do much later.
/////
//"use strict";
/* jshint
maxerr:1000, eqeqeq: true, eqnull: false, unused: false, loopfunc: true
*/
/* jshint -W116 */
(function() {
//Initialize Angular app
var app = angular.module("aersia", [ ]);
app.controller("aersiaController", ['$scope','$http', function($scope,$http) {
this.friendlyname = "/*%= friendlyname */";
this.version = "/*%= version */";
// Create a bogus link to download stuff with
this.download = document.head.appendChild(document.createElement('a'));
this.download.style = "display:none;visibility:hidden;";
this.download.download = "aersiaStyle.json";
// Create a bogus file input to upload stuff with
this.upload = document.head.appendChild(document.createElement('input'));
this.upload.style = "display:none;visibility:hidden;";
this.upload.type = "file";
this.styleReader = new FileReader();
// Create x2js instance with default config
var x2js = new X2JS();
// Create the lightbox
this.lightbox = new Lightbox();
this.lightbox.load({
'preload': false,
'controls': false,
'nextOnClick': false
});
// Initialize the share button
var clipboard = new Clipboard(document.getElementById('copyBtn'), {
text: function(btn) {
this.success("Share link copied to clipboard.");
return window.location.href + '#' + encodeURIComponent( this.selectedPlaylist + '|' + this.curSong );
}.bind(this)
});
//Init logger
Logger.useDefaults({
logLevel: Logger.WARN,
formatter: function (messages, context) {
messages.unshift('[Aersia]');
if (context.name) messages.unshift('[' + context.name + ']');
}
});
Logger.get('internals').setLevel(Logger.ERROR);
Logger.get('player').setLevel(Logger.ERROR);
Logger.get('animation').setLevel(Logger.ERROR);
Logger.get('songart').setLevel(Logger.ERROR);
//Initialize variables
this.songs = [];
this.noShuffles = {};
this.curSong = 0;
this.autoplay = true;
this.playing = false;
this.playtries = 0;
this.prevVolume = 0;
this.history = [];
this.historyPosition = 0;
this.preferredFormats = [ "opus","ogg","m4a","mp3" ];
// UI variables
this.lastTimeText = '';
this.lastLoadText = '';
this.fullyLoaded = 0;
this.optionsBoxShown = false;
this.songArt = {
placeholder: true,
placeholdersrc: 'assets/img/placeholder.png',
rotating: false,
curArt: false,
nextArt: false,
timer: false,
period: 10000,
};
this.selectedLayout = "Classic";
this.layouts = {
"Classic": {
"class": "layout-classic",
"href": "layout-classic",
"features": ["controls","timeline","timeTextUpdate","progressUpdate","playlist","animations","options","songImg"]
},
"Touch": {
"class": "layout-touch",
"href": "layout-touch",
"features": ["controls","timeline","timeTextUpdate","progressUpdate","playlist","animations","options","songImg"]
},
"Streambox": {
"class": "layout-streambox",
"href": "layout-streambox",
"features": ["timeTextUpdate", "progressUpdate", "streambox","options","songImg"]
},
"Streambar": {
"class": "layout-streambar",
"href": "layout-streambar",
"features": ["controls","timeTextUpdate","progressUpdate","options"]
},
};
//js-cookie variables
this.cookieName = "aersia";
this.cookieConfig = { };
//Playlists
this.lastPlaylist = "";
this.selectedPlaylist = "VIP";
this.playlists = {
"VIP": {
"url": "/roster.json",
//"url": "http://vip.aersia.net/roster.xml",
"longName": "Vidya Intarweb Playlist",
},
"VIP - Source": {
"url": "http://vip.aersia.net/roster-source.xml",
"longName": "Vidya Intarweb Playlist - Source Edition",
},
"VIP - Exiled": {
"url": "http://vip.aersia.net/roster-exiled.xml",
"longName": "Vidya Intarweb Playlist - Exiled Edition",
},
"VIP - Mellow": {
"url": "http://vip.aersia.net/roster-mellow.xml",
"longName": "Vidya Intarweb Playlist - Mellow Edition",
},
"WAP": {
"url": "http://wap.aersia.net/roster.xml",
"longName": "Weeaboo Anime Playlist",
}
};
//Grab DOM elements
this.player = document.getElementsByTagName("audio")[0];
this.playlist = document.getElementById("playlist");
this.tabs = document.getElementsByClassName("effeckt-tabs")[0];
this.optionsbox = document.getElementsByClassName("optionsbox")[0];
this.layoutbox = document.getElementById("layoutbox");
this.streambox = document.getElementById("streambox");
this.mainControls = document.getElementById("mainControls");
this.playpause = document.getElementById("playpause");
this.timeText = document.getElementById("timeText");
this.timeline = document.getElementById("timeline");
this.timebox = document.getElementById("timebox");
this.controlsInfoBox = document.getElementById("controlsInfoBox");
this.loadBar = document.getElementById("loadBar");
this.playedBar = document.getElementById("playedBar");
this.playhead = document.getElementById("playhead");
this.loadPct = document.getElementById("loadPct");
this.volumeBar = document.getElementById("volumeBar");
this.messagebox = document.getElementById("messagebox");
this.toggleShuffleBtn = document.getElementById("toggleShuffle");
this.songUI = {
'Streambox': {
'title': document.getElementById("sboxSongTitle"),
'creator': document.getElementById("sboxSongCreator"),
'img': document.getElementById("sboxSongImg"),
},
'Streambar': {
'title': document.getElementById("controlsSongTitle"),
'creator': document.getElementById("controlsSongCreator"),
},
'default': {
'title': document.getElementById("oboxSongTitle"),
'creator': document.getElementById("oboxSongCreator"),
'img': document.getElementById("oboxSongImg"),
}
};
this.hookSongArtElement = function(el) {
addEvent(el, window.transitionEnd, function() {
if( classie.hasClass(el,"fadeout") )
{
if( ! this.songArt.rotating )
{
// If the rotation was cancelled for any reason, break out.
return;
}
// Grab the art in question
if( this.curSong == null || this.songArt.nextArt === false ||
this.songs[this.curSong] == null || this.songs[this.curSong].art == null ||
this.songs[this.curSong].art[this.songArt.nextArt] == null
)
{
Logger.get("songart").error("Faded out, but "+this.curSong+" + "+this.songArt.nextArt+" did not point to valid art!");
return;
}
Logger.get("songart").debug("Faded out, switched song art.");
this.songArt.placeholder = false;
el.src = 'http://mobygames.com'+this.songs[this.curSong].art[this.songArt.nextArt].thumbnail;
// Pick next art, wrap index if necessary.
this.songArt.curArt = this.songArt.nextArt;
this.songArt.nextArt++;
if( this.songArt.nextArt > this.songs[this.curSong].art.length - 1 )
{ this.songArt.nextArt = 0; }
}
}.bind(this));
// Fade back in whenever the image finishes loading.
addEvent(el,"load", function() {
Logger.get("songart").debug("Song art loaded, fading in.");
// Trigger the object-fit polyfill
objectFitImages(el);
classie.removeClass(el,"fadeout");
}.bind(this) );
addEvent(el,"error", function() {
Logger.get('songart').error("Unable to load song art, setting placeholder.");
this.stopSongArt();
}.bind(this) );
// Trigger the object-fit polyfill for the first time
objectFitImages(el);
// Load the image lightbox on click.
addEvent(el,'click',function(){
if( this.songArt.placeholder === true )
{ return; }
if(
this.curSong == null || this.songArt.curArt === false ||
this.songs[this.curSong] == null || this.songs[this.curSong].art == null ||
this.songs[this.curSong].art[this.songArt.curArt] == null
)
{ return; }
Logger.get("songart").debug("Opened full art Lightbox");
this.lightbox.open('http://mobygames.com'+this.songs[this.curSong].art[this.songArt.curArt].fullsize);
}.bind(this));
}.bind(this);
// Hook any layouts that have the songImg
Object.keys(this.songUI).forEach(function(val) {
if( this.songUI[val].img != null )
{ this.hookSongArtElement( this.songUI[val].img ); }
}.bind(this));
/////
//Styles and Presets
this.selectedPreset = "Aersia";
this.currentStyles = {};
this.styleNodes = {};
// Presets. This could be loaded from XHR later.
this.presetStyles = {
"Aersia": {
"focus": "#FF9148", // Orange
"background": "#183C63", // Lighter, main blue
"contrast": "#003366", // Dark, bordery color
"active": "#4687ef", // Bright, activey blue
"scrollbar": "#7f6157", // Dull orange, the back of the scrollbar
"loadbar": "#635d62", // Dull purple, for things like timeline bg
"controlsout": {"0%": "#c0ccd9", "100%": "#000c19"}, // The border around the controls
"controlsin": {"0%": "#3D6389", "100%": "#072d53"}, // The inside of the controls
},
//Styles from JSON files
/*%= includedstyles */
};
// CSS definitions of where all the colors go
this.styleCssText = {
"focus": [
"g, rect, path { fill: ","; }\n"+
".controls-container, .playlist-container, .optionsbox, #streambox { color: ","; }\n"+
"#playedBar, #playhead, .active-song, .ps-theme-vip>.ps-scrollbar-y-rail>.ps-scrollbar-y, .ps-theme-vip>.ps-scrollbar-x-rail>.ps-scrollbar-x { background-color: ","; }\n"+
"#volumeBar { border-color: transparent "," transparent transparent; }"
],
"background": [
".playlist-container, .optionsbox { background-color:","; }"
],
"contrast": [
".playlist>li:hover, .active-song { color: ","; }\n"+
".optionsbox, .sep, .playlist>li, section, .ps-theme-vip>.ps-scrollbar-y-rail, .ps-theme-vip>.ps-scrollbar-x-rail { border-color: ","; }\n"
],
"active": [
".playlist>li:hover, .ps-theme-vip:hover>.ps-scrollbar-y-rail:hover>.ps-scrollbar-y, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-y-rail>.ps-scrollbar-y, .ps-theme-vip:hover>.ps-scrollbar-x-rail:hover>.ps-scrollbar-x, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-x-rail:hover>.ps-scrollbar-x { background-color: ","; }"
],
"scrollbar": [
".ps-theme-vip>.ps-scrollbar-x-rail, .ps-theme-vip>.ps-scrollbar-y-rail { background-color: ","!important; }"
], // .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-x-rail, .ps-theme-vip.ps-in-scrolling>.ps-scrollbar-y-rail, .ps-theme-vip:hover>.ps-scrollbar-y-rail:hover, .ps-theme-vip:hover>.ps-scrollbar-x-rail:hover
"loadbar": [
"#loadBar { background-color: ","; }"
],
};
this.styleCssGradientText = {
"controlsout": ".controls-container, .effeckt-tabs",
"controlsin": ".controls-container>div, .effeckt-tabs>li, #streambox",
};
//Give each style its own stylesheet node.
Object.keys(this.styleCssText).forEach(function(val) {
this.styleNodes[val] = document.head.appendChild(document.createElement('style'));
}.bind(this));
Object.keys(this.styleCssGradientText).forEach(function(val) {
this.styleNodes[val] = document.head.appendChild(document.createElement('style'));
}.bind(this));
// Add a box for each layout in the layoutsbox.
Object.keys(this.layouts).forEach(function(key) {
var container = document.createElement("div");
classie.addClass(container,"vbox");
classie.addClass(container,"centertext");
var div = document.createElement("div");
container.appendChild(div);
//Why do I need a namespace for this, what is even the difference in the markup??
var svg = document.createElementNS("http://www.w3.org/2000/svg","svg");
svg.setAttribute("height","120px");
svg.setAttribute("width","120px");
div.appendChild(svg);
//Why do I need a namespace for this, what is even the difference in the markup??
var use = document.createElementNS("http://www.w3.org/2000/svg","use");
use.setAttributeNS('http://www.w3.org/1999/xlink', 'href',"#"+this.layouts[key].href);
svg.appendChild(use);
var name = document.createElement("div");
name.innerHTML = key;
container.appendChild(name);
this.layoutbox.appendChild(container);
container.onclick = function() {
this.switchLayout(key);
}.bind(this);
}.bind(this));
/////
// Initalize scrollbar
Ps.initialize(this.playlist, {
theme: 'vip',
minScrollbarLength: 20
});
//Bind it to update when window resizes.
addEvent(window,"resize", function() {
Ps.update(this.playlist);
}.bind(this));
/////
// Bind to check the hash when it updates
window.onhashchange = function() {
var hash = this.decodeHash();
if( hash[0] !== false ) {
this.loadPlaylist(hash[1]);
} else {
this.playSong(hash[1]);
}
// Consume the hash so it won't screw up reloads.
window.location.hash = '';
}.bind(this);
/////
// Mbox functions
this.closembox = function () { classie.addClass(this.messagebox,"hidden"); }.bind(this);
this.internalerror = function (str) { this.error("Internal error: "+str+" Please report this along with a screenshot to the webmaster."); }.bind(this);
this.success = function (str) { this._mbox_manip('mboxsuccess',str); }.bind(this);
this.error = function (str) { this._mbox_manip('mboxerror',str); }.bind(this);
this.info = function (str) { this._mbox_manip('mboxinfo',str); }.bind(this);
this._mbox_manip = function (destclass,str) {
classie.removeClass(this.messagebox,"hidden");
classie.removeClass(this.messagebox,"mboxerror");
classie.removeClass(this.messagebox,"mboxsuccess");
classie.removeClass(this.messagebox,"mboxinfo");
classie.addClass(this.messagebox,destclass);
this.messagebox.children[0].innerHTML = str;
}.bind(this);
this.mboxclosebutton = document.getElementById('mboxclose');
addEvent(this.mboxclosebutton,"click",this.closembox);
/////
// To enable layouts to swap functions on and off, here is an object of status and hooks.
this.features = {
"controls": {
"enable": function() {
classie.removeClass(this.mainControls,"hidden");
},
"disable": function() {
classie.addClass(this.mainControls,"hidden");
},
},
"timeline": {
"enable": function() {
classie.removeClass(this.timebox,"hidden");
classie.addClass(this.controlsInfoBox,"hidden");
this.timeText = document.getElementById("timeProgText");
this.loadPct = document.getElementById("timeLoadPct");
addEvent(this.player,"timeupdate", this.timelineUpdate);
this.timelineUpdate();
this.updateCurSongInfo();
},
"disable": function() {
classie.addClass(this.timebox,"hidden");
classie.removeClass(this.controlsInfoBox,"hidden");
this.timeText = document.getElementById("controlsProgText");
this.loadPct = document.getElementById("controlsLoadPct");
removeEvent(this.player,"timeupdate", this.timelineUpdate);
this.updateCurSongInfo();
},
},
"playlist": {
"enable": function() {
classie.removeClass(this.playlist,"hidden");
},
"disable": function() {
//here's where I would prevent a new playlist from loading up while this is disabled.
classie.addClass(this.playlist,"hidden");
},
},
"options": {
"enable": function() {
classie.removeClass(this.tabs,"hidden");
},
"disable": function() {
classie.addClass(this.tabs,"hidden");
this.toggleOptionsBox(false);
},
},
"streambox": {
"enable": function() {
classie.removeClass(this.streambox,"hidden");
},
"disable": function() {
classie.addClass(this.streambox,"hidden");
},
},
"timeTextUpdate": {
"enable": function() {
addEvent(this.player,"timeupdate", this.timeTextUpdate);
this.timeTextUpdate();
},
"disable": function() {
removeEvent(this.player,"timeupdate", this.timeTextUpdate);
},
},
"progressUpdate": {
"enable": function() {
addEvent(this.player,"timeupdate",this.progressUpdate); // not progress, it doesn't fire reliably
this.progressUpdate();
},
"disable": function() {
removeEvent(this.player,"timeupdate",this.progressUpdate);
},
},
"animations": {
"enable": function() {
// this.animationsEnabled = true;
},
"disable": function() {
// this.animationsEnabled = false;
},
},
"songImg": {
"enable": function() {
// this.animationsEnabled = true;
this.updateCurSongInfo();
},
"disable": function() {
// this.animationsEnabled = false;
},
},
};
// Forces a feature on or off regardless. This is only set by the user.
this.overrideFeatures = {};
this.enableFeature = function(feature) {
if( this.features[feature] != null && this.features[feature].enabled !== true )
{
if( this.features[feature].enable != null )
{ this.features[feature].enable.call(this); }
this.features[feature].enabled = true;
Logger.get("internals").info(feature+" enabled.");
}
}.bind(this);
this.disableFeature = function(feature) {
if( this.features[feature] != null && this.features[feature].enabled !== false )
{
if( this.features[feature].disable != null )
{ this.features[feature].disable.call(this); }
this.features[feature].enabled = false;
Logger.get("internals").info(feature+" disabled.");
}
}.bind(this);
this.toggleFeature = function(feature) {
if( this.features[feature] != null )
{
if( this.features[feature].enabled != null && this.features[feature].enabled )
{
this.disableFeature(feature);
} else {
this.enableFeature(feature);
}
}
}.bind(this);
/////
//Hook audio player
//This will be called whenever a song ends.
addEvent(this.player, "ended", function() {
if( this.autoplay )
{ this.shuffleSong(); }
}.bind(this));
// This will be called if the player breaks for any reason
addEvent(this.player, "error", function(ev) {
// Just retry. If this is called twice without a full playthrough, it will just stop.
this.playSong(this.curSong,true);
}.bind(this));
//This will be called every time a new song loads, and when the song is seeked and begins playing?
// addEvent(this.player,"canplaythrough", function () {
// Logger.get("internals").info('canplaythrough');
// }.bind(this));
//Makes timeline clickable
this.seekBar = function(e,amt) {
//Respond to either click or direct invocation
if( e !== '' )
{ amt = clickPercent(e,this.timeline); }
Logger.get("player").debug('Timeline seek: '+amt);
this.player.currentTime = this.player.duration * amt;
this.timeUpdate(e);
}.bind(this);
addEvent(this.timeline,"click", this.seekBar);
//This will be called as downloading progresses.
this.progressUpdate = function(e,amt) {
var newText = '';
//Respond to either click or direct invocation.
if( e !== '' )
{
var bufend = 0;
if( this.player.buffered.length > 0 ) { bufend = this.player.buffered.end(0); }
if( bufend === this.player.duration )
{
if( this.fullyLoaded === 0 )
{
amt = 100; // skip rounding
newText = "100%"; // show this for one tick.
this.fullyLoaded = 1;
}
else
{
//We are fully loaded. Show a timestamp instead.
newText = this.timeFormat(this.player.duration);
}
}
else // get normal percentage
{
amt = 100 * (bufend / this.player.duration);
newText = Math.round(amt) + '%';
}
}
else // use direct input
{
newText = Math.round(amt) + '%';
}
Logger.get("player").debug('Progress update: '+amt);
//Don't update the progress if it will look the same.
if( this.lastLoadText !== newText )
{
//Change loadPct text and store value
this.loadPct.textContent = newText;
this.lastLoadText = newText;
//Move loadBar in timeline
this.loadBar.style.right = (100 - amt) + '%'; // inverse percentage
}
}.bind(this);
//This will be called as the song progresses.
this.timeTextUpdate = function(e,amt) {
if( e != null && e !== '' )
{ amt = this.player.currentTime / this.player.duration; }
//Don't update the time if it will look the same.
var newTime = this.timeFormat(this.player.currentTime);
if( this.lastTimeText !== newTime )
{ this.timeText.textContent = newTime; this.lastTimeText = newTime; }
}.bind(this);
this.timelineUpdate = function(e,amt) {
if( e != null && e !== '' )
{ amt = this.player.currentTime / this.player.duration; }
Logger.get("player").debug('Time update: '+amt);
// //Move the playhead
// this.playhead.style.left = amt + "%";
//
// //Move the playedBar in the timeline
// this.playedBar.style.right = amt + "%";
//REWORK: somehow we need to cache the boundingrect, but for some reason if I don't use it every frame it gets off by a lot.
//This pixel-perfect version is just to achieve that one-pixel offset effect in the original .swf
//Move the playhead
var rect = this.timeline.getBoundingClientRect();
var clickpx = (rect.right - rect.left) * amt;
this.playhead.style.left = clickpx + "px";
//Move the playedBar in the timeline
this.playedBar.style.right = (((rect.right - rect.left) - clickpx) + 1) + "px";
}.bind(this);
//////////////////////
// Player functions //
//////////////////////
/////
// Playlist Management
this.loadPlaylist = function(start) {
if( this.selectedPlaylist == null || this.selectedPlaylist == "" ) { return; }
if( this.playlists[this.selectedPlaylist] == null ) { Logger.get("player").error("Playlist "+this.selectedPlaylist+" is invalid."); return; }
if( this.selectedPlaylist !== this.lastPlaylist )
{
// Loading a new playlist
//Stop the song.
this.pause();
this.resetControls();
$http.get(this.playlists[this.selectedPlaylist].url)
.then(function(res) {
// Prepare the playlist for use
var playlist = res.data;
//Convert it from XML to JSON if necessary
if( /.xml$/.test(this.playlists[this.selectedPlaylist].url) )
{
playlist = x2js.xml2js(playlist).playlist.trackList.track;
}
//Set the song list
this.songs = playlist;
this.lastPlaylist = this.selectedPlaylist;
// Update the window's title.
document.title = this.playlists[this.selectedPlaylist].longName + ' - ' + this.friendlyname + ' v' + this.version;
// If we're allowed, start playing.
if( this.autoplay )
{
// If we're supposed to start somewhere, do that. Otherwise, shuffle.
if( start != null && start !== false )
{ window.setTimeout(function() { this.playSong(start); }.bind(this),500); }
else
{ window.setTimeout(this.shuffleSong,500); }
// But give Angular's list a little time to update, since it's stupid.
}
}.bind(this),
function(res) {
//If the request fails for some reason
this.error("The playlist was not able to be loaded. Please try again or reload the page.");
}.bind(this)
);
}
else if( start != null && start !== false )
{
// Starting a song on this playlist without loading.
if( this.songs[start] == null ) { Logger.get("player").error("Requested song "+start+" is invalid."); return; }
this.playSong(start);
}
}.bind(this);
// Wrapper that updates cookie
this.changePlaylist = function() {
this.loadPlaylist();
this.setCookie();
}.bind(this);
// Keeps a list of previously played songs, up to 100.
this.historyTrack = function(idx) {
if( this.historyPosition < 0 && this.history[(this.history.length-1) + this.historyPosition] !== idx )
{
//I think this wipes too many things?
//We're backed up in the queue, but we're being asked to play a different song. Wipe out the queue so we can store the new one.
Logger.get("internals").info("History undo stack burst: "+this.history+" @ "+this.historyPosition);
while( this.historyPosition < 0 ) { this.history.pop(); this.historyPosition++; }
Logger.get("internals").info("History undo stack end: "+this.history+" @ "+this.historyPosition);
}
if( this.historyPosition === 0 )
{
// Cut the history list down if it's at capacity
while( this.history.length > 99 ) { this.history.shift(); }
this.history.push(idx);
Logger.get("internals").debug("History queue: "+this.history+" @ "+this.historyPosition);
}
}.bind(this);
// retry overrides attempting to play the same song.
this.playSong = function(index,retry) {
if( index == null || index === false ) { return; }
index = parseInt(index);
if( index === this.curSong && ( retry == null || retry === false )) { return; }
if( retry == null ) { retry = false; }
// Error handling
if( retry && this.playtries > 0 ) {
// If we've already retried for any reason, don't try again.
Logger.get("player").error("Cannot play song: "+this.songs[index].title);
return;
} else if ( retry ) {
// If this is our first retry, let's keep track of that.
this.playtries = 1;
} else {
// If we're being asked to play a song and this isn't a retry, let's reset our tries counter.
this.playtries = 0;
}
//Stop and unregister the old song.
this.pause();
this.player.src = '';
if( this.curSong != null && this.playlist.children[this.curSong] != null )
{ classie.removeClass(this.playlist.children[this.curSong],'active-song'); }
//log
if( retry )
{ Logger.get("player").error("Retrying song: "+this.songs[index].title); }
else
{ Logger.get("player").info("Playing song: "+this.songs[index].title); }
// Set the interface for the new song
this.curSong = index;
this.updateCurSongInfo();
this.fullyLoaded = 0;
// If this is a retry, we've already done this stuff and don't want to do it again.
if( ! retry )
{
// Set the shuffle control to reflect the disabled state
if( this.noShuffles[this.selectedPlaylist] != null && this.noShuffles[this.selectedPlaylist].indexOf(this.curSong) > -1 )
{ classie.addClass(this.toggleShuffleBtn, "toggled"); }
else
{ classie.removeClass(this.toggleShuffleBtn, "toggled"); }
// Highlight the active song
if( this.curSong != null && this.playlist.children[this.curSong] != null )
{ classie.addClass(this.playlist.children[this.curSong],'active-song'); }
// Put this song in history
this.historyTrack(this.curSong);
}
// Play
if( this.songs[this.curSong].formats != null )
{
var selFormat = '';
try {
this.preferredFormats.forEach(function(format) {
if( this.songs[this.curSong].formats[format] != null )
{ selFormat = format; throw BreakException; }
});
} catch(e) { // alert for now, use a message box later
if (e!==BreakException) throw e;
}
if( selFormat === '' )
{
Logger.get("player").error("Unable to use any of the provided file formats. Trying location.");
this.player.src = this.songs[this.curSong].location;
}
else {
Logger.get("player").debug("Selected format "+selFormat);
this.player.src = this.songs[this.curSong].formats[format];
}
}
else {
this.player.src = this.songs[this.curSong].location;
}
this.play();
//Trigger the playlist to scroll.
this.scrollToSong(index);
}.bind(this);
this.shuffleSong = function() {
//Generate a list of songs we're allowed to play.
var list = clone(this.songs);
//Ensure we don't play the same song again.
list.splice(list.indexOf(this.curSong),1);
if( this.noShuffles[this.selectedPlaylist] != null )
{
this.noShuffles[this.selectedPlaylist].forEach(function(val){ list.splice(val,1); }.bind(this));
}
var selected = Math.floor(Math.random() * list.length);
//Start our random song.
this.playSong(selected);
}.bind(this);
// Forbids or allows a song to be played.
this.toggleShuffle = function() {
//If we haven't blocked anything on this playlist yet, give it the structure.
if( this.noShuffles[this.selectedPlaylist] == null ) { this.noShuffles[this.selectedPlaylist] = []; }
var pos = this.noShuffles[this.selectedPlaylist].indexOf(this.curSong);
if( pos === -1 )
{
Logger.get("player").info("Disabled shuffle for "+this.curSong);
this.noShuffles[this.selectedPlaylist].push(this.curSong);
classie.addClass(this.toggleShuffleBtn,"toggled");
} else {
Logger.get("player").info("Enabled shuffle for "+this.curSong);
this.noShuffles[this.selectedPlaylist].splice(pos,1);
classie.removeClass(this.toggleShuffleBtn,"toggled");
}
this.setCookie();
}.bind(this);
// Not used. Should remove.
this.isCurrentSong = function(index) {
return index === this.curSong;
}.bind(this);
/////
// Rating functions
this.rateUp = function() {
Logger.get("player").info("RateUp");
};
this.rateDown = function() {
Logger.get("player").info("RateDown");
};
/////
// HTML5 audio player control functions, in button order, then helper function order.
// Assistance from: http://www.alexkatz.me/html5-audio/building-a-custom-html5-audio-player-with-javascript/
this.play = function() {
//Reset the readouts
this.resetControls();
this.player.play();
this.playing = true;
classie.addClass(this.playpause,"toggled");
}.bind(this);
this.pause = function() {
this.player.pause();
this.playing = false;
classie.removeClass(this.playpause,"toggled");
}.bind(this);
this.togglePlay = function(bool) {
if( bool !== null ) { bool = !this.playing; }
if( bool ) { this.play(); }
else { this.pause(); }
}.bind(this);
// Traverses the history queue, or just plays a new song.
this.seek = function(amt) {
// var index = this.curSong + amt;
// if( index >= 0 && index <= this.songs.length )
// { this.playSong(index); }
if( amt < 0 )
{
if( (this.history.length-1) >= 0 -(this.historyPosition + amt) )
{
this.historyPosition += amt;
Logger.get("internals").debug("History rewind: "+this.history+" @ "+this.historyPosition);
this.playSong( // Play the song...
this.history[ // at history position...
(this.history.length-1) + this.historyPosition // offset by the end of the history queue.
]
);
}
}
else {
if( this.historyPosition === 0 )
{
this.shuffleSong();
}
else {
this.historyPosition += amt;
this.playSong( // Play the song...
this.history[ // at history position...
(this.history.length-1) + this.historyPosition // offset by the end of the history queue.
]
);
}
}
}.bind(this);
this.toggleOptionsBox = function(bool) {
if( bool == null ) { bool = !this.optionsBoxShown; }
this.optionsBoxShown = bool;
// Update the song info before we show the box, just in case
this.updateCurSongInfo();
// Toggle hidden class.
if( this.optionsBoxShown ) { classie.removeClass(this.optionsbox,"hidden"); } else { classie.addClass(this.optionsbox,"hidden"); }
//Trigger the scrollbar to fix itself.
Ps.update(this.playlist);
}.bind(this);
this.toggleFullscreen = function() {
toggleFullScreen();
}.bind(this);
this.toggleMute = function() {
//Toggle
var vol = this.player.volume;
this.volume('',this.prevVolume);
this.prevVolume = vol;
}.bind(this);
this.volume = function(e,amt) {
//Respond to either click or direct invocation
if( e !== '' ) { amt = clickPercent(e,this.volumeBar); }
amt = Math.pow(amt,2); //Human perception of volume is inverse-square.
Logger.get("player").info("Volume change: "+amt);
this.player.volume = amt;
}.bind(this);
this.timeFormat = function(sec) {
var min = Math.floor(sec/60);
sec = Math.floor(sec % 60);
return zeroPad(min,2)+':'+zeroPad(sec,2);
}.bind(this);
/////
// UI Functions
this.resetControls = function() {
this.timelineUpdate('',0);
this.timeTextUpdate('',0);
this.progressUpdate('',0);
}.bind(this);
this.toggleScrollSmooth = function() {
this.features.animations.enabled = !this.features.animations.enabled; // Angular changes the model before the change
this.toggleFeature("animations");
this.setCookie();
}.bind(this);
this.scrollToSong = function(index) {
// this function is called when the layout is set, which happens before the songs are even loaded once.
if( this.songs.length === 0 )
{ return; }
//Get the elements' height, since this could change.
var height = this.playlist.firstElementChild.offsetHeight;
var targetY = height * index;
// If this element would be closer to the end of the list than the viewport allows, just scroll to the bottom to avoid overflowing.
// The browser should realistically stop this, but every 'set' seems to move a pixel beyond the limit, and the smooth animation sets rapidly, causing a big overflow.
if( (height * this.songs.length) - targetY < this.playlist.offsetHeight )
{ targetY = (height * this.songs.length) - this.playlist.offsetHeight; }
Logger.get("animation").debug('Scroll event: '+this.playlist.scrollTop + ' by interval '+ height +' to '+targetY);
if( this.features.animations.enabled )
{
//Make the playlist scroll to the currently playing song.
scrollToSmooth(this.playlist, targetY, 600);
}
else
{
this.playlist.scrollTop = height * index;
}
}.bind(this);
this.setLayout = function(l) {
this.selectedLayout = l;
// Remove all the layouts
Object.keys(this.layouts).forEach(function(layout) { classie.removeClass(document.documentElement,this.layouts[layout].class); }.bind(this));
// Add the one we want.
classie.addClass(document.documentElement,this.layouts[this.selectedLayout].class);
// Enable all features of our layout, and disable everything else.
Object.keys(this.features).forEach(function(feature) {
if(
this.layouts[this.selectedLayout].features.indexOf(feature) > -1 && // layout is supposed to have it on
( this.overrideFeatures[feature] == null || this.overrideFeatures[feature] === true ) // and it's not forced off
)
{
this.enableFeature(feature);
} else {
this.disableFeature(feature);
}
}.bind(this));
// Trigger the playlist to scroll in case the layout is messed up
this.scrollToSong(this.curSong);
if( this.features.options.enabled )
{
// Open the optionsbox if it's hidden, re-adjust the tab, and set the optionsbox back the way it was.
// This is done because the tab height will probably have changed when the layout changes.
var orig = this.optionsBoxShown;
this.toggleOptionsBox(true);
var tab = document.getElementsByClassName("effeckt-tab active")[0];
if( tab != null )
{
window.setTimeout( function() {
Tabs.showTab(tab);
this.toggleOptionsBox(orig);
}.bind(this), 500 );
}
}
}.bind(this);
// Wrapper that updates cookie
this.switchLayout = function(l) {
this.setLayout(l);
this.setCookie();
}.bind(this);
this.styleSet = function(type) {
//Recompile the selected style's node
this.styleNodes[type].innerHTML = this.styleCssText[type].join(this.currentStyles[type]);
}.bind(this);
//Wrapper that updates cookie
this.changeStyle = function(type) {
this.styleSet(type);
this.setCookie();
}.bind(this);
this.gradientSet = function(type) {
//This is really bad. Maybe find a library for this later.
var begin = this.currentStyles[type]["0%"];
var end = this.currentStyles[type]["100%"];
this.styleNodes[type].innerHTML = this.styleCssGradientText[type] + " { \n"+
"background: "+begin+";\n"+ //Old browsers
"background: -moz-linear-gradient(top, "+begin+" 0%, "+end+" 100%);\n"+ // FF3.6-15
"background: -webkit-linear-gradient(top, "+begin+" 0%, "+end+" 100%);\n"+ // Chrome10-25,Safari5.1-6
"background: linear-gradient(to bottom, "+begin+" 0%, "+end+" 100%);\n"+ // W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+
"filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='"+begin+"', endColorstr='"+end+"',GradientType=0 );\n"+ // IE6-9
"}";
}.bind(this);
//Wrapper that updates cookie
this.changeGradient = function(type) {
this.gradientSet(type);
this.setCookie();
}.bind(this);
this.loadPreset = function() {
if( this.presetStyles[this.selectedPreset] != null )
{
Logger.get("internals").info("Setting preset to "+this.selectedPreset);
this.currentStyles = this.presetStyles[this.selectedPreset];
this.reloadStyle();
this.setCookie();
}
}.bind(this);
//Wrapper that calls them all
this.reloadStyle = function() {
Object.keys(this.styleCssText).forEach(function(val) { this.styleSet(val); }.bind(this));
Object.keys(this.styleCssGradientText).forEach(function(val) { this.gradientSet(val); }.bind(this));
}.bind(this);
/////
// Export and import styles
this.exportStyles = function() {
this.triggerDownload(this.currentStyles);
}.bind(this);
//This function is called when the FileReader loads, which is called when the file input changes, which is called when user picks file.
this.importStyles = function(event) {
Logger.get('internals').info('FileReader loaded file.');
var result;
try { result = JSON.parse(event.target.result); }
catch ( e ) { alert("File does not contain a valid style structure."); }
if( result != null )
{
// Check that all the right things are defined
try {
Object.keys(this.currentStyles).forEach(function(key) {
Logger.get('internals').debug(key);
if( result[key] == null ) { throw BreakException; }
}.bind(this));
this.currentStyles = result;
this.reloadStyle();
Logger.get('internals').info('Style imported successfully.');
this.setCookie();
} catch(e) { // alert for now, use a message box later
if (e!==BreakException) throw e;
alert("Imported style was not formatted correctly.");
}
}
}.bind(this);
this.upload.onchange = function() {
Logger.get('internals').info('File input changed.');
this.styleReader.readAsText(this.upload.files[0]);
}.bind(this);
this.styleReader.onload = this.importStyles;
/////
// Cookie functions
this.getCookie = function() {
var cookie = Cookies.getJSON(this.cookieName);
if( cookie == null ) {
// First launch, if this is a touch device, put it into touch mode by default.
if( isMobile.any() ) { this.switchLayout("Touch"); }
return 1;
}
// Directly mapped properties
['autoplay','selectedLayout','currentStyles','selectedPreset','selectedPlaylist','noShuffles']
.forEach(function(val) {
if( cookie[val] != null && this[val] != null )
{ this[val] = cookie[val]; }
}.bind(this));
// Unpacked properties
if( cookie.lastVolume != null ) { this.player.volume = cookie.lastVolume; }
if( cookie.features != null && cookie.features.animations != null && cookie.features.animations.enabled != null )
{ this.overrideFeatures.animations = cookie.features.animations.enabled; }
// Triggers
if( cookie.currentStyles != null ) { this.reloadStyle(); }
Logger.get("internals").info("Cookie read.");
}.bind(this);
this.setCookie = function() {
Cookies.set(this.cookieName, {
"autoplay": this.autoplay,
"features": { "animations": { "enabled": this.features.animations.enabled } },
"selectedLayout": this.selectedLayout,
"currentStyles": this.currentStyles,
"lastVolume": this.player.volume,
"selectedPreset": this.selectedPreset,
"selectedPlaylist": this.selectedPlaylist,
"noShuffles": this.noShuffles,
}, this.cookieConfig);
Logger.get("internals").info("Cookie written.");
}.bind(this);
/////
// File downloading and uploading
this.triggerDownload = function(data) {
if( typeof data === "object" )
{ data = JSON.stringify(data,null,'\t'); }
this.download.href = 'data:application/octet-stream;charset=utf-16le;base64,' + btoa(data);
this.download.dispatchEvent(new MouseEvent('click'));
Logger.get('internals').info('File download triggered.');
}.bind(this);
this.triggerLinkDownload = function(uri) {
this.download.href = uri;
this.download.dispatchEvent(new MouseEvent('click'));
Logger.get('internals').info('Link download triggered.');
}.bind(this);
this.triggerUpload = function() {
this.upload.dispatchEvent(new MouseEvent('click'));
}.bind(this);
// Reads the sharing links
this.decodeHash = function() {
var newPlaylist = false;
var newSong = false;
if( window.location.hash != null && window.location.hash !== '#' )
{
var bits = decodeURIComponent(window.location.hash).substr(1);
bits = bits.split('|');
if( this.playlists[bits[0]] != null )
{
newPlaylist = bits[0];
if( bits[1] != null )
{ newSong = bits[1]; }
}
}
Logger.get("internals").info("Hash decoded: "+newPlaylist+", "+newSong);
return [newPlaylist,newSong];
}.bind(this);
this.updateCurSongInfo = function() {
// Update the song panel
if( this.curSong != null && this.songs[this.curSong] != null && (
( (this.selectedLayout === "Classic" || this.selectedLayout === "Touch") && this.optionsBoxShown ) || // In Classic or Touch interface, don't update unless it's visible.
( this.selectedLayout === "Streambox" || this.selectedLayout === "Streambar" ) //In Streambox or Streambar, update.
)
){
this.getUIElement('title').innerHTML = this.songs[this.curSong].title;
this.getUIElement('creator').innerHTML = this.songs[this.curSong].creator;
// this.curSongRating.innerHTML = "0"; //this.songs[this.curSong].rating;
if( this.songs[this.curSong].art != null && this.songs[this.curSong].art.length > 0 )
{
this.setSongArt();
} else {
this.stopSongArt();
}
}
};
// Function to get the right elements from the current layouts
this.getUIElement = function(type) {
if( this.songUI[this.selectedLayout] != null && this.songUI[this.selectedLayout][type] != null )
{
return this.songUI[this.selectedLayout][type];
} else {
return this.songUI.default[type];
}
}.bind(this);
// Function to control the song rotation
this.setSongArt = function() {
this.stopSongArt();
this.rotateSongArt();
}.bind(this);
// Function to do the actual rotation
this.rotateSongArt = function() {
if( this.songArt.rotating === true )
{
// We don't need to do anything but trigger the next fade.
classie.addClass(this.getUIElement('img'),"fadeout");
}
else {
// Set up the cover art rotator. If it's set to placeholder, we'll stomp it immediately.
if( this.songArt.placeholder === true )
{
Logger.get("songart").debug("Stomping song art");
// Set these variables since we've already done the first rotation.
this.songArt.placeholder = false;
this.songArt.curArt = 0;
this.songArt.nextArt = 1;
this.getUIElement('img').src = 'http://mobygames.com'+this.songs[this.curSong].art[0].thumbnail;
}
else {
// Fade out. The rest will be triggered automatically.
Logger.get("songart").debug("Fading out song art.");
classie.addClass(this.getUIElement('img'),"fadeout");
}
if( this.songs[this.curSong].art.length > 1 )
{
this.songArt.rotating = true;
this.songArt.timer = window.setTimeout(this.rotateSongArt, this.songArt.rotateperiod);
}
}
}.bind(this);
this.stopSongArt = function() {
// Stop the timer, reset attributes, and show the placeholder.
window.clearTimeout(this.songArt.timer);
this.songArt.timer = false;
this.songArt.rotating = false;
this.songArt.curArt = false;
this.songArt.nextArt = 0;
this.songArt.placeholder = true;
this.getUIElement('img').src = this.songArt.placeholdersrc;
}.bind(this);
/////
// Initialization
this.init = function() {
// Assign the default preset to the "current style";
this.currentStyles = this.presetStyles[this.selectedPreset];
// Get any stored values that will override our defaults.
this.getCookie();
// Enable features in our currently selected layout
this.setLayout(this.selectedLayout);
// Detect browser support for file formats and remove any formats that are not supported
var formats = [];
this.preferredFormats.forEach(function(format) {
if( Modernizr.audio[format] != null && Modernizr.audio[format] !== "" )
{ formats.push(format); }
}.bind(this));
this.preferredFormats = formats;
// Check the window location for a share link. This overrides our starting playlist and song.
var hash = this.decodeHash();
if( hash[0] !== false ) { this.selectedPlaylist = hash[0]; }
//Load up our playlist, this is async and will start playing automatically.
this.loadPlaylist(hash[1]);
}.bind(this);
this.init();
}]);
})();
// Animation functions
function scrollToSmooth(el,targetScroll,duration) {
// const scrollHeight = window.scrollY,
var beginScroll = el.scrollTop,
beginTime = Date.now();
Logger.get('animation').info('Beginning animation: '+beginTime+' '+beginScroll+' to '+targetScroll);
requestAnimationFrame(step);
function step () {
setTimeout(function() {
//Get our time diff to scale against.
var now = Date.now();
if ( now <= beginTime + duration) {
//Queue the next frame ahead of time
requestAnimationFrame(step);
//This is probably overcomplicated, but this gets the amount we need to add to the initial scroll for our time
var mod = easeInOut( now, beginTime,duration, beginScroll,targetScroll );
Logger.get("animation").debug('anim: '+ (now-beginTime) +' + '+mod);
//Set the scroll absolutely
if( beginScroll < targetScroll ) { el.scrollTop = beginScroll + mod; }
else { el.scrollTop = beginScroll - mod; }
} else {
//Final frame, don't schedule another.
Logger.get("animation").debug('Ending animation: end:'+ (now > (beginTime + duration))+' s:'+el.scrollTop);
el.scrollTop = targetScroll;
}
}, 15 );
}
}
// function testEase(begin,duration,end) {
// var now = begin;
// var done = 0;
// var i = 0;
// while ( !done ) {
// i++;
// if (i > 1000 ) { done = 1;}
//
// var pct = (now-begin) / (end-begin);
//
// var mod =
// pct *
// //the cosine curve scaled by how far we are.
// ((Math.cos (
// Math.PI + //beginning at Pi to ease in
// (Math.PI * Math.abs(pct))
// ) + 1 ) / 2)
// ;
// var delta =
// now += mod;
// Logger.get('animations').debug('pct: '+pct+', now: '+now+', mod: '+mod);
// if( now >= end ) { done = 1; }
// }
// }
function easeInOut(now, beginX,targetX, beginY,targetY ) {
return ( -1 * Math.pow(((now - beginX) / targetX) - 1,2) + 1 ) // y = -x^2 + 1
* (Math.abs(targetY-beginY)); // scaled up to the amount that we need to move.
}
function addEvent(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
}
function removeEvent(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.removeEventListener) {
object.removeEventListener(type, callback, false);
} else if (object.detachEvent) {
object.detachEvent("on" + type, callback);
} else {
object["on"+type] = null;
}
}
// returns click as decimal (.77) of the total object's width
function clickPercent(e,obj) {
return (e.pageX - obj.getBoundingClientRect().left) / obj.offsetWidth;
}
//https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
function toggleFullScreen() {
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.msRequestFullscreen) {
document.documentElement.msRequestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}
//coderjoe: http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript
function zeroPad (num, numZeros) {
if( num === 0 ) { return zeroPadNonLog(num,numZeros); }
var an = Math.abs (num);
var digitCount = 1 + Math.floor (Math.log (an) / Math.LN10);
if (digitCount >= numZeros) {
return num;
}
var zeroString = Math.pow (10, numZeros - digitCount).toString ().substr (1);
return num < 0 ? '-' + zeroString + an : zeroString + an;
}
function zeroPadNonLog(num, numZeros) {
var n = Math.abs(num);
var zeros = Math.max(0, numZeros - Math.floor(n).toString().length );
var zeroString = Math.pow(10,zeros).toString().substr(1);
if( num < 0 ) {
zeroString = '-' + zeroString;
}
return zeroString+n;
}
//Test for SVG support and polyfill if no. https://css-tricks.com/svg-sprites-use-better-icon-fonts/
/MSIE|Trident/.test(navigator.userAgent) && document.addEventListener('DOMContentLoaded', function () {
[].forEach.call(document.querySelectorAll('svg'), function (svg) {
var use = svg.querySelector('use');
if (use) {
var object = document.createElement('object');
object.data = use.getAttribute('xlink:href');
object.className = svg.getAttribute('class');
svg.parentNode.replaceChild(object, svg);
}
});
});
//
// function easeOutBounce(t, b, c, d) {
// if ((t/=d) < (1/2.75)) {
// return c*(7.5625*t*t) + b;
// } else if (t < (2/2.75)) {
// return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
// } else if (t < (2.5/2.75)) {
// return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
// } else {
// return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
// }
// }
// http://stackoverflow.com/questions/12606245/detect-if-browser-is-running-on-an-android-or-ios-device
var isMobile = {
Windows: function() {
return /IEMobile/i.test(navigator.userAgent);
},
Android: function() {
return /Android/i.test(navigator.userAgent);
},
BlackBerry: function() {
return /BlackBerry/i.test(navigator.userAgent);
},
iOS: function() {
return /iPhone|iPad|iPod/i.test(navigator.userAgent);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
}
};
| Rather than splicing or using ES6 sets, just iterate once.
| js/main.js | Rather than splicing or using ES6 sets, just iterate once. | <ide><path>s/main.js
<ide> }.bind(this);
<ide>
<ide> this.shuffleSong = function() {
<del> //Generate a list of songs we're allowed to play.
<del> var list = clone(this.songs);
<del>
<del> //Ensure we don't play the same song again.
<del> list.splice(list.indexOf(this.curSong),1);
<del>
<del> if( this.noShuffles[this.selectedPlaylist] != null )
<del> {
<del> this.noShuffles[this.selectedPlaylist].forEach(function(val){ list.splice(val,1); }.bind(this));
<add>
<add> //Generate a list of indexes we're allowed to play.
<add> var list = [];
<add> for ( var i=0; i<this.songs.length; i++ ) {
<add> if
<add> (
<add> // Ensure we don't play the same song again and
<add> i !== this.curSong &&
<add>
<add> // it's not in our list of things not to shuffle
<add> this.noShuffles[this.selectedPlaylist].indexOf(i) === -1
<add> )
<add> {
<add> list.push(i);
<add> }
<ide> }
<ide>
<ide> var selected = Math.floor(Math.random() * list.length);
<ide>
<ide> //Start our random song.
<del> this.playSong(selected);
<add> this.playSong( list[selected] );
<ide> }.bind(this);
<ide>
<ide> // Forbids or allows a song to be played. |
|
Java | bsd-3-clause | 66bf3baa456957e585d4865664dfc0e94da4aa58 | 0 | wakatime/jetbrains-wakatime | /* ==========================================================
File: Dependencies.java
Description: Manages plugin dependencies.
Maintainer: WakaTime <[email protected]>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
===========================================================*/
package com.wakatime.intellij.plugin;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nullable;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.PasswordAuthentication;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static java.nio.file.attribute.PosixFilePermission.*;
class Response {
public int statusCode;
public String body;
public String etag;
public Response(int statusCode, String body, @Nullable String etag) {
this.statusCode = statusCode;
this.body = body;
this.etag = etag;
}
}
public class Dependencies {
private static String resourcesLocation = null;
private static String cliVersion = null;
private static Boolean alpha = null;
private static Boolean standalone = null;
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation != null) return Dependencies.resourcesLocation;
if (System.getenv("WAKATIME_HOME") != null && !System.getenv("WAKATIME_HOME").trim().isEmpty()) {
File resourcesFolder = new File(System.getenv("WAKATIME_HOME"));
if (resourcesFolder.exists()) {
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
WakaTime.log.debug("Using $WAKATIME_HOME for resources folder: " + Dependencies.resourcesLocation);
return Dependencies.resourcesLocation;
}
}
if (isWindows()) {
File windowsHome = new File(System.getenv("USERPROFILE"));
File resourcesFolder = new File(windowsHome, ".wakatime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
return Dependencies.resourcesLocation;
}
File userHomeDir = new File(System.getProperty("user.home"));
File resourcesFolder = new File(userHomeDir, ".wakatime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
return Dependencies.resourcesLocation;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return cli.exists();
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
WakaTime.log.debug("wakatime-cli local version output: \"" + output + "\"");
WakaTime.log.debug("wakatime-cli local version exit code: " + p.exitValue());
if (p.exitValue() == 0) {
String cliVersion = latestCliVersion();
WakaTime.log.debug("Latest wakatime-cli version: " + cliVersion);
if (isStandalone()) {
if (output.contains(cliVersion)) return false;
} else {
if (output.trim().equals(cliVersion)) return false;
}
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
return true;
}
public static String latestCliVersion() {
if (cliVersion != null) return cliVersion;
if (!isStandalone()) {
String url = Dependencies.githubReleasesApiUrl();
try {
Response resp = getUrlAsString(url, ConfigFile.get("internal", "cli_version_etag"));
if (resp == null) {
cliVersion = ConfigFile.get("internal", "cli_version").trim();
WakaTime.log.debug("Using cached wakatime-cli version from config: " + cliVersion);
return cliVersion;
}
Pattern p = Pattern.compile(".*\"tag_name\":\\s*\"([^\"]+)\",.*");
Matcher m = p.matcher(resp.body);
if (m.find()) {
cliVersion = m.group(1);
if (!isStandalone() && resp.etag != null) {
ConfigFile.set("internal", "cli_version_etag", resp.etag);
ConfigFile.set("internal", "cli_version", cliVersion);
}
return cliVersion;
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
cliVersion = "Unknown";
return cliVersion;
}
String url = Dependencies.s3BucketUrl() + "current_version.txt";
try {
Response resp = getUrlAsString(url, null);
Pattern p = Pattern.compile("([0-9]+\\.[0-9]+\\.[0-9]+)");
Matcher m = p.matcher(resp.body);
if (m.find()) {
cliVersion = m.group(1);
return cliVersion;
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
cliVersion = "Unknown";
return cliVersion;
}
public static String getCLILocation() {
String ext = isWindows() ? ".exe" : "";
if (!isStandalone()) {
return combinePaths(getResourcesLocation(), "wakatime-cli-" + platform() + "-" + architecture() + ext);
}
return combinePaths(getResourcesLocation(), "wakatime-cli", "wakatime-cli" + ext);
}
public static void installCLI() {
File resourceDir = new File(getResourcesLocation());
if (!resourceDir.exists()) resourceDir.mkdirs();
String url = getCLIDownloadUrl();
String zipFile = combinePaths(getResourcesLocation(), "wakatime-cli.zip");
if (downloadFile(url, zipFile)) {
if (isStandalone()) {
// Delete old wakatime-master directory if it exists
File dir = new File(combinePaths(getResourcesLocation(), "wakatime-cli"));
recursiveDelete(dir);
} else {
// Delete old wakatime-cli if it exists
File file = new File(getCLILocation());
recursiveDelete(file);
}
File outputDir = new File(getResourcesLocation());
try {
unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
if (!isWindows()) makeExecutable(getCLILocation());
} catch (IOException e) {
WakaTime.log.warn(e);
}
}
}
private static String getCLIDownloadUrl() {
if (isStandalone()) return s3BucketUrl() + "wakatime-cli.zip";
return "https://github.com/wakatime/wakatime-cli/releases/download/" + latestCliVersion() + "/wakatime-cli-" + platform() + "-" + architecture() + ".zip";
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
return true;
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
// try downloading without verifying SSL cert (https://github.com/wakatime/jetbrains-wakatime/issues/46)
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
InputStream inputStream = conn.getInputStream();
fos = new FileOutputStream(saveAs);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
fos.close();
return true;
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (IOException e) {
WakaTime.log.warn(e);
}
return false;
}
public static Response getUrlAsString(String url, @Nullable String etag) {
StringBuilder text = new StringBuilder();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
String responseEtag = null;
int statusCode = -1;
try {
HttpsURLConnection conn = (HttpsURLConnection) downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
if (etag != null && !etag.trim().equals("")) {
conn.setRequestProperty("If-None-Match", etag.trim());
}
statusCode = conn.getResponseCode();
if (statusCode == 304) return null;
InputStream inputStream = downloadUrl.openStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
if (conn.getResponseCode() == 200) responseEtag = conn.getHeaderField("ETag");
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
// try downloading without verifying SSL cert (https://github.com/wakatime/jetbrains-wakatime/issues/46)
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[]{new LocalSSLTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
if (etag != null && !etag.trim().equals("")) {
conn.setRequestProperty("If-None-Match", etag.trim());
}
statusCode = conn.getResponseCode();
if (statusCode == 304) return null;
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
if (conn.getResponseCode() == 200) responseEtag = conn.getHeaderField("ETag");
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (UnknownHostException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (UnknownHostException e) {
WakaTime.log.warn(e);
} catch (Exception e) {
WakaTime.log.warn(e);
}
return new Response(statusCode, text.toString(), responseEtag);
}
/**
* Configures a proxy if one is set in ~/.wakatime.cfg.
*/
public static void configureProxy() {
String proxyConfig = ConfigFile.get("settings", "proxy");
if (proxyConfig != null && !proxyConfig.trim().equals("")) {
try {
URL proxyUrl = new URL(proxyConfig);
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
final String user = userInfo.split(":")[0];
final String pass = userInfo.split(":")[1];
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pass.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
System.setProperty("https.proxyHost", proxyUrl.getHost());
System.setProperty("https.proxyPort", Integer.toString(proxyUrl.getPort()));
} catch (MalformedURLException e) {
WakaTime.log.error("Proxy string must follow https://user:pass@host:port format: " + proxyConfig);
}
}
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void recursiveDelete(File path) {
if(path.exists()) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recursiveDelete(files[i]);
} else {
files[i].delete();
}
}
}
path.delete();
}
}
public static boolean isAlpha() {
if (alpha != null) return alpha;
String setting = ConfigFile.get("settings", "alpha");
alpha = setting != null && setting.equals("true");
return alpha;
}
public static boolean isStandalone() {
if (standalone != null) return standalone;
String setting = ConfigFile.get("settings", "standalone");
standalone = setting == null || !setting.equals("false");
return standalone;
}
public static boolean is64bit() {
return System.getProperty("os.arch").indexOf("64") != -1;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
public static String platform() {
if (isWindows()) return "windows";
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("mac") || os.contains("darwin")) return "darwin";
if (os.contains("linux")) return "linux";
return os;
}
public static String architecture() {
String arch = System.getProperty("os.arch");
if (arch.contains("386") || arch.contains("32")) return "386";
if (arch.equals("aarch64")) return "arm64";
if (platform().equals("darwin") && arch.contains("arm")) return "arm64";
if (arch.contains("64")) return "amd64";
return arch;
}
public static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (arg != null) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
}
if (path == null)
return null;
return path.toString();
}
private static String githubReleasesApiUrl() {
if (isAlpha()) {
return "https://api.github.com/repos/wakatime/wakatime-cli/releases?per_page=1";
}
return "https://api.github.com/repos/wakatime/wakatime-cli/releases/latest";
}
private static String s3BucketUrl() {
String s3Prefix = "https://wakatime-cli.s3-us-west-2.amazonaws.com/";
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0) {
String arch = Dependencies.is64bit() ? "64" : "32";
return s3Prefix + "windows-x86-" + arch + "/";
} else if (os.indexOf("mac") >= 0 || os.indexOf("darwin") >= 0) {
return s3Prefix + "mac-x86-64/";
} else {
return s3Prefix + "linux-x86-64/";
}
}
private static void makeExecutable(String filePath) throws IOException {
File file = new File(filePath);
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(OWNER_READ);
perms.add(OWNER_WRITE);
perms.add(OWNER_EXECUTE);
perms.add(GROUP_READ);
perms.add(GROUP_EXECUTE);
perms.add(OTHERS_READ);
perms.add(OTHERS_EXECUTE);
Files.setPosixFilePermissions(file.toPath(), perms);
}
}
| src/com/wakatime/intellij/plugin/Dependencies.java | /* ==========================================================
File: Dependencies.java
Description: Manages plugin dependencies.
Maintainer: WakaTime <[email protected]>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
===========================================================*/
package com.wakatime.intellij.plugin;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.Nullable;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.PasswordAuthentication;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static java.nio.file.attribute.PosixFilePermission.*;
class Response {
public int statusCode;
public String body;
public String etag;
public Response(int statusCode, String body, @Nullable String etag) {
this.statusCode = statusCode;
this.body = body;
this.etag = etag;
}
}
public class Dependencies {
private static String resourcesLocation = null;
private static String cliVersion = null;
private static Boolean alpha = null;
private static Boolean standalone = null;
public static String getResourcesLocation() {
if (Dependencies.resourcesLocation == null) {
if (System.getenv("WAKATIME_HOME") != null && !System.getenv("WAKATIME_HOME").trim().isEmpty()) {
File resourcesFolder = new File(System.getenv("WAKATIME_HOME"));
if (resourcesFolder.exists()) {
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
WakaTime.log.debug("Using $WAKATIME_HOME for resources folder: " + Dependencies.resourcesLocation);
return Dependencies.resourcesLocation;
}
}
if (isWindows()) {
File appDataFolder = new File(System.getenv("APPDATA"));
File resourcesFolder = new File(appDataFolder, "WakaTime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
} else {
File userHomeDir = new File(System.getProperty("user.home"));
File resourcesFolder = new File(userHomeDir, ".wakatime");
Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
}
}
return Dependencies.resourcesLocation;
}
public static boolean isCLIInstalled() {
File cli = new File(Dependencies.getCLILocation());
return cli.exists();
}
public static boolean isCLIOld() {
if (!Dependencies.isCLIInstalled()) {
return false;
}
ArrayList<String> cmds = new ArrayList<String>();
cmds.add(Dependencies.getCLILocation());
cmds.add("--version");
try {
Process p = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
p.waitFor();
String output = "";
String s;
while ((s = stdInput.readLine()) != null) {
output += s;
}
while ((s = stdError.readLine()) != null) {
output += s;
}
WakaTime.log.debug("wakatime-cli local version output: \"" + output + "\"");
WakaTime.log.debug("wakatime-cli local version exit code: " + p.exitValue());
if (p.exitValue() == 0) {
String cliVersion = latestCliVersion();
WakaTime.log.debug("Latest wakatime-cli version: " + cliVersion);
if (isStandalone()) {
if (output.contains(cliVersion)) return false;
} else {
if (output.trim().equals(cliVersion)) return false;
}
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
return true;
}
public static String latestCliVersion() {
if (cliVersion != null) return cliVersion;
if (!isStandalone()) {
String url = Dependencies.githubReleasesApiUrl();
try {
Response resp = getUrlAsString(url, ConfigFile.get("internal", "cli_version_etag"));
if (resp == null) {
cliVersion = ConfigFile.get("internal", "cli_version").trim();
WakaTime.log.debug("Using cached wakatime-cli version from config: " + cliVersion);
return cliVersion;
}
Pattern p = Pattern.compile(".*\"tag_name\":\\s*\"([^\"]+)\",.*");
Matcher m = p.matcher(resp.body);
if (m.find()) {
cliVersion = m.group(1);
if (!isStandalone() && resp.etag != null) {
ConfigFile.set("internal", "cli_version_etag", resp.etag);
ConfigFile.set("internal", "cli_version", cliVersion);
}
return cliVersion;
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
cliVersion = "Unknown";
return cliVersion;
}
String url = Dependencies.s3BucketUrl() + "current_version.txt";
try {
Response resp = getUrlAsString(url, null);
Pattern p = Pattern.compile("([0-9]+\\.[0-9]+\\.[0-9]+)");
Matcher m = p.matcher(resp.body);
if (m.find()) {
cliVersion = m.group(1);
return cliVersion;
}
} catch (Exception e) {
WakaTime.log.warn(e);
}
cliVersion = "Unknown";
return cliVersion;
}
public static String getCLILocation() {
String ext = isWindows() ? ".exe" : "";
if (!isStandalone()) {
return combinePaths(getResourcesLocation(), "wakatime-cli-" + platform() + "-" + architecture() + ext);
}
return combinePaths(getResourcesLocation(), "wakatime-cli", "wakatime-cli" + ext);
}
public static void installCLI() {
File resourceDir = new File(getResourcesLocation());
if (!resourceDir.exists()) resourceDir.mkdirs();
String url = getCLIDownloadUrl();
String zipFile = combinePaths(getResourcesLocation(), "wakatime-cli.zip");
if (downloadFile(url, zipFile)) {
if (isStandalone()) {
// Delete old wakatime-master directory if it exists
File dir = new File(combinePaths(getResourcesLocation(), "wakatime-cli"));
recursiveDelete(dir);
} else {
// Delete old wakatime-cli if it exists
File file = new File(getCLILocation());
recursiveDelete(file);
}
File outputDir = new File(getResourcesLocation());
try {
unzip(zipFile, outputDir);
File oldZipFile = new File(zipFile);
oldZipFile.delete();
if (!isWindows()) makeExecutable(getCLILocation());
} catch (IOException e) {
WakaTime.log.warn(e);
}
}
}
private static String getCLIDownloadUrl() {
if (isStandalone()) return s3BucketUrl() + "wakatime-cli.zip";
return "https://github.com/wakatime/wakatime-cli/releases/download/" + latestCliVersion() + "/wakatime-cli-" + platform() + "-" + architecture() + ".zip";
}
public static boolean downloadFile(String url, String saveAs) {
File outFile = new File(saveAs);
// create output directory if does not exist
File outDir = outFile.getParentFile();
if (!outDir.exists())
outDir.mkdirs();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
rbc = Channels.newChannel(downloadUrl.openStream());
fos = new FileOutputStream(saveAs);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
return true;
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
// try downloading without verifying SSL cert (https://github.com/wakatime/jetbrains-wakatime/issues/46)
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection)downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
InputStream inputStream = conn.getInputStream();
fos = new FileOutputStream(saveAs);
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
fos.close();
return true;
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (IOException e) {
WakaTime.log.warn(e);
}
return false;
}
public static Response getUrlAsString(String url, @Nullable String etag) {
StringBuilder text = new StringBuilder();
URL downloadUrl = null;
try {
downloadUrl = new URL(url);
} catch (MalformedURLException e) { }
String responseEtag = null;
int statusCode = -1;
try {
HttpsURLConnection conn = (HttpsURLConnection) downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
if (etag != null && !etag.trim().equals("")) {
conn.setRequestProperty("If-None-Match", etag.trim());
}
statusCode = conn.getResponseCode();
if (statusCode == 304) return null;
InputStream inputStream = downloadUrl.openStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
if (conn.getResponseCode() == 200) responseEtag = conn.getHeaderField("ETag");
} catch (RuntimeException e) {
WakaTime.log.warn(e);
try {
// try downloading without verifying SSL cert (https://github.com/wakatime/jetbrains-wakatime/issues/46)
SSLContext SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[]{new LocalSSLTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(SSL_CONTEXT.getSocketFactory());
HttpsURLConnection conn = (HttpsURLConnection) downloadUrl.openConnection();
conn.setRequestProperty("User-Agent", "github.com/wakatime/jetbrains-wakatime");
if (etag != null && !etag.trim().equals("")) {
conn.setRequestProperty("If-None-Match", etag.trim());
}
statusCode = conn.getResponseCode();
if (statusCode == 304) return null;
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[4096];
while (inputStream.read(buffer) != -1) {
text.append(new String(buffer, "UTF-8"));
}
inputStream.close();
if (conn.getResponseCode() == 200) responseEtag = conn.getHeaderField("ETag");
} catch (NoSuchAlgorithmException e1) {
WakaTime.log.warn(e1);
} catch (KeyManagementException e1) {
WakaTime.log.warn(e1);
} catch (UnknownHostException e1) {
WakaTime.log.warn(e1);
} catch (IOException e1) {
WakaTime.log.warn(e1);
}
} catch (UnknownHostException e) {
WakaTime.log.warn(e);
} catch (Exception e) {
WakaTime.log.warn(e);
}
return new Response(statusCode, text.toString(), responseEtag);
}
/**
* Configures a proxy if one is set in ~/.wakatime.cfg.
*/
public static void configureProxy() {
String proxyConfig = ConfigFile.get("settings", "proxy");
if (proxyConfig != null && !proxyConfig.trim().equals("")) {
try {
URL proxyUrl = new URL(proxyConfig);
String userInfo = proxyUrl.getUserInfo();
if (userInfo != null) {
final String user = userInfo.split(":")[0];
final String pass = userInfo.split(":")[1];
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(user, pass.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
System.setProperty("https.proxyHost", proxyUrl.getHost());
System.setProperty("https.proxyPort", Integer.toString(proxyUrl.getPort()));
} catch (MalformedURLException e) {
WakaTime.log.error("Proxy string must follow https://user:pass@host:port format: " + proxyConfig);
}
}
}
private static void unzip(String zipFile, File outputDir) throws IOException {
if(!outputDir.exists())
outputDir.mkdirs();
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputDir, fileName);
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile.getAbsolutePath());
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
}
private static void recursiveDelete(File path) {
if(path.exists()) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recursiveDelete(files[i]);
} else {
files[i].delete();
}
}
}
path.delete();
}
}
public static boolean isAlpha() {
if (alpha != null) return alpha;
String setting = ConfigFile.get("settings", "alpha");
alpha = setting != null && setting.equals("true");
return alpha;
}
public static boolean isStandalone() {
if (standalone != null) return standalone;
String setting = ConfigFile.get("settings", "standalone");
standalone = setting == null || !setting.equals("false");
return standalone;
}
public static boolean is64bit() {
return System.getProperty("os.arch").indexOf("64") != -1;
}
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
public static String platform() {
if (isWindows()) return "windows";
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("mac") || os.contains("darwin")) return "darwin";
if (os.contains("linux")) return "linux";
return os;
}
public static String architecture() {
String arch = System.getProperty("os.arch");
if (arch.contains("386") || arch.contains("32")) return "386";
if (arch.equals("aarch64")) return "arm64";
if (platform().equals("darwin") && arch.contains("arm")) return "arm64";
if (arch.contains("64")) return "amd64";
return arch;
}
public static String combinePaths(String... args) {
File path = null;
for (String arg : args) {
if (arg != null) {
if (path == null)
path = new File(arg);
else
path = new File(path, arg);
}
}
if (path == null)
return null;
return path.toString();
}
private static String githubReleasesApiUrl() {
if (isAlpha()) {
return "https://api.github.com/repos/wakatime/wakatime-cli/releases?per_page=1";
}
return "https://api.github.com/repos/wakatime/wakatime-cli/releases/latest";
}
private static String s3BucketUrl() {
String s3Prefix = "https://wakatime-cli.s3-us-west-2.amazonaws.com/";
String os = System.getProperty("os.name").toLowerCase();
if (os.indexOf("win") >= 0) {
String arch = Dependencies.is64bit() ? "64" : "32";
return s3Prefix + "windows-x86-" + arch + "/";
} else if (os.indexOf("mac") >= 0 || os.indexOf("darwin") >= 0) {
return s3Prefix + "mac-x86-64/";
} else {
return s3Prefix + "linux-x86-64/";
}
}
private static void makeExecutable(String filePath) throws IOException {
File file = new File(filePath);
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(OWNER_READ);
perms.add(OWNER_WRITE);
perms.add(OWNER_EXECUTE);
perms.add(GROUP_READ);
perms.add(GROUP_EXECUTE);
perms.add(OTHERS_READ);
perms.add(OTHERS_EXECUTE);
Files.setPosixFilePermissions(file.toPath(), perms);
}
}
| use home folder for all wakatime files even on Windows platform
| src/com/wakatime/intellij/plugin/Dependencies.java | use home folder for all wakatime files even on Windows platform | <ide><path>rc/com/wakatime/intellij/plugin/Dependencies.java
<ide> private static Boolean standalone = null;
<ide>
<ide> public static String getResourcesLocation() {
<del> if (Dependencies.resourcesLocation == null) {
<del> if (System.getenv("WAKATIME_HOME") != null && !System.getenv("WAKATIME_HOME").trim().isEmpty()) {
<del> File resourcesFolder = new File(System.getenv("WAKATIME_HOME"));
<del> if (resourcesFolder.exists()) {
<del> Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
<del> WakaTime.log.debug("Using $WAKATIME_HOME for resources folder: " + Dependencies.resourcesLocation);
<del> return Dependencies.resourcesLocation;
<del> }
<del> }
<del>
<del> if (isWindows()) {
<del> File appDataFolder = new File(System.getenv("APPDATA"));
<del> File resourcesFolder = new File(appDataFolder, "WakaTime");
<add> if (Dependencies.resourcesLocation != null) return Dependencies.resourcesLocation;
<add>
<add> if (System.getenv("WAKATIME_HOME") != null && !System.getenv("WAKATIME_HOME").trim().isEmpty()) {
<add> File resourcesFolder = new File(System.getenv("WAKATIME_HOME"));
<add> if (resourcesFolder.exists()) {
<ide> Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
<del> } else {
<del> File userHomeDir = new File(System.getProperty("user.home"));
<del> File resourcesFolder = new File(userHomeDir, ".wakatime");
<del> Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
<del> }
<del> }
<add> WakaTime.log.debug("Using $WAKATIME_HOME for resources folder: " + Dependencies.resourcesLocation);
<add> return Dependencies.resourcesLocation;
<add> }
<add> }
<add>
<add> if (isWindows()) {
<add> File windowsHome = new File(System.getenv("USERPROFILE"));
<add> File resourcesFolder = new File(windowsHome, ".wakatime");
<add> Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
<add> return Dependencies.resourcesLocation;
<add> }
<add>
<add> File userHomeDir = new File(System.getProperty("user.home"));
<add> File resourcesFolder = new File(userHomeDir, ".wakatime");
<add> Dependencies.resourcesLocation = resourcesFolder.getAbsolutePath();
<ide> return Dependencies.resourcesLocation;
<ide> }
<ide> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.